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;
13pub mod metrics;
14mod nexus;
15pub mod pagination;
16mod query_authority;
17mod runtime_payloads;
18mod runtime_uploads;
19mod sticky_worker;
20mod sticky_workflow_cache;
21#[cfg(feature = "telemetry")]
22pub mod telemetry;
23pub mod testing;
24pub use pagination::{
25    PaginationError, WorkflowHistoryIterator, WorkflowHistoryOptions, WorkflowHistoryPage,
26    WorkflowIterator, WorkflowListOptions, WorkflowListPage, WorkflowSummary,
27};
28mod tls;
29mod worker_capacity;
30mod worker_session;
31mod workflow_hydration;
32
33pub use activity_error::ActivityError;
34pub use cancellation_context::{
35    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
36};
37pub use cancellation_scope::CancellationScopeOpenReceipt;
38#[doc(hidden)]
39pub use cancellation_scope_history::{
40    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
41};
42#[doc(hidden)]
43pub use cancellation_scope_replay::CancellationScopeRequested;
44
45pub use cooperative_cancellation::{
46    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
47    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
48    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
49    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
50};
51
52use std::{
53    any::{type_name, Any, TypeId},
54    collections::{BTreeMap, BTreeSet, HashMap},
55    future::Future,
56    io::{self, Read},
57    pin::Pin,
58    sync::{
59        atomic::{AtomicBool, Ordering},
60        Arc, Mutex, OnceLock,
61    },
62    task::{Context as TaskContext, Poll},
63    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
64};
65
66use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
67use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
68use chrono::DateTime;
69use futures_util::{future::OptionFuture, task::noop_waker_ref};
70pub use local_activity::LocalActivityOptions;
71use serde::{
72    de::DeserializeOwned,
73    ser::{SerializeMap, SerializeSeq},
74    Deserialize, Deserializer, Serialize, Serializer,
75};
76pub use serde_json::{json, Value};
77use sha2::{Digest, Sha256};
78pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
79use thiserror::Error;
80pub use uuid::Uuid;
81pub use worker_session::{WorkerSession, WorkerSessionOptions};
82
83pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
84pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
85
86/// Select the worker request protocol without enabling optional capabilities.
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
88#[non_exhaustive]
89pub enum WorkerProtocolVersion {
90    /// Compatibility with Servers that implement only worker protocol 1.19.
91    V119,
92    /// The default worker protocol.
93    #[default]
94    V120,
95}
96
97impl WorkerProtocolVersion {
98    fn as_str(self) -> &'static str {
99        match self {
100            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
101            Self::V120 => WORKER_PROTOCOL_VERSION,
102        }
103    }
104}
105const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
106/// First additive worker protocol that defines portable worker-affinity features.
107pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
108pub const CONTROL_PLANE_VERSION: &str = "2";
109pub const DEFAULT_CODEC: &str = "avro";
110pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
111/// Worker-registration capability for authored condition-wait occurrence identity.
112pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
113    "condition_wait_occurrence_identity";
114/// Worker-registration capability for portable memo upserts.
115pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
116/// Worker-registration capability for server-routed read-only queries.
117pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
118/// Worker-registration capability for canonical typed search attributes.
119pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
120/// Worker-registration capability for synchronous workflow updates.
121pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
122/// Worker-registration capability for durable named input streams.
123pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
124/// Worker-registration capability for persisted first-completion selection.
125pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
126pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
127pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
128pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
129pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
130pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
131/// First additive worker protocol that defines query-task transport.
132pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
133/// First additive worker protocol that defines typed search-attribute upserts.
134pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
135/// First additive worker protocol that defines portable memo upserts.
136pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
137/// First additive worker protocol that preserves declared search-attribute types.
138pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
139/// First additive worker protocol that defines external durable condition waits.
140pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
141/// First additive worker protocol that preserves authored condition-wait occurrences.
142pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
143/// First additive worker protocol that defines durable selection groups.
144pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
145
146pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
147    let Some((major, minor)) = version.split_once('.') else {
148        return false;
149    };
150    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
151}
152
153fn validate_user_signal_name(signal_name: &str) -> Result<()> {
154    if signal_name == MESSAGE_STREAM_SIGNAL {
155        return Err(Error::Codec(format!(
156            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
157        )));
158    }
159    Ok(())
160}
161
162const REQUEST_ID_CONFLICT_REASON: &str = "request_id_conflict";
163const MAX_REQUEST_ID_CHARACTERS: usize = 255;
164
165/// The caller command key is a case-sensitive body field of 1 to 255 Unicode characters.
166fn validate_request_id(request_id: &str) -> Result<()> {
167    if request_id.is_empty() || request_id.chars().count() > MAX_REQUEST_ID_CHARACTERS {
168        return Err(Error::Codec(format!(
169            "request_id must be 1 to {MAX_REQUEST_ID_CHARACTERS} Unicode characters"
170        )));
171    }
172    Ok(())
173}
174
175fn generated_request_id(command: &str) -> String {
176    format!("sdk-rust-{command}-{}", Uuid::new_v4().simple())
177}
178
179/// Guarantee the sent caller command key on a receipt from a Server that does not echo it.
180fn with_request_id(mut receipt: Value, request_id: &str) -> Value {
181    if receipt.is_null() {
182        return json!({ "request_id": request_id });
183    }
184    if let Some(receipt) = receipt.as_object_mut() {
185        receipt
186            .entry("request_id")
187            .or_insert_with(|| Value::String(request_id.to_string()));
188    }
189    receipt
190}
191
192const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
193const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
194    "Workflow task waiting for scheduled history.";
195const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
196const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
197const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
198const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
199const MAX_MEMO_ENTRIES: usize = 100;
200const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
201const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
202
203const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
204    "lease_expired",
205    "query_task_not_found",
206    "query_task_not_leased",
207    "query_task_timed_out",
208    "query_deadline_unavailable",
209    "lease_owner_mismatch",
210    "query_task_attempt_mismatch",
211];
212
213/// Manifest for the default service-worker profile.
214///
215/// Inline local execution is enabled separately by [`Worker::local_activities`].
216/// Local execution, sessions and caching require explicit Worker configuration.
217pub fn portable_worker_affinity_capability_manifest() -> Value {
218    json!({
219        "local_activities": {
220            "supported": false,
221            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
222            "reason": "rust_worker_does_not_execute_record_local_activity",
223        },
224        "worker_sessions": {
225            "supported": false,
226            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
227            "reason": "rust_worker_has_no_typed_session_lifecycle",
228        },
229        "sticky_execution": {
230            "supported": false,
231            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
232            "reason": "rust_worker_uses_complete_durable_history_replay",
233        },
234    })
235}
236
237/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
238pub const AVRO_VALUE_SCHEMA_JSON: &str =
239    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
240pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
241pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
242const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
243
244static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
245static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
246    OnceLock::new();
247
248#[derive(Clone, Copy)]
249enum RequestProtocol {
250    ControlPlane,
251    DefaultWorker,
252    Worker(&'static str),
253}
254
255pub type Result<T> = std::result::Result<T, Error>;
256
257pub use nexus::{
258    NexusOperationFailure, NexusOperationMode, NexusOperationResult, NexusServiceCall,
259    NexusServiceOptions, NexusWaitFor,
260};
261
262#[derive(Debug, Error)]
263#[non_exhaustive]
264pub enum Error {
265    #[error("transport error: {0}")]
266    Transport(#[from] reqwest::Error),
267    #[error(
268        "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"
269    )]
270    InvalidBaseUrl,
271    #[error("invalid additional root certificates: {0}")]
272    InvalidRootCertificates(String),
273    #[error(transparent)]
274    Testing(#[from] testing::TestingError),
275    #[error(transparent)]
276    Pagination(#[from] pagination::PaginationError),
277    #[error("json error: {0}")]
278    Json(#[from] serde_json::Error),
279    #[error("http {status}: {body}")]
280    Http {
281        status: reqwest::StatusCode,
282        body: String,
283    },
284    #[error("codec error: {0}")]
285    Codec(String),
286    #[error(transparent)]
287    QueryFailed(QueryFailure),
288    #[error(transparent)]
289    Protocol(ProtocolFailure),
290    #[error(transparent)]
291    NonDeterministicReplay(ReplayFailure),
292    #[error(transparent)]
293    ChildWorkflowFailed(ChildWorkflowFailure),
294    #[error(transparent)]
295    ActivityFailed(ActivityFailure),
296    #[error(transparent)]
297    ActivityError(#[from] ActivityError),
298    #[error(transparent)]
299    NexusOperationFailed(Box<NexusOperationFailure>),
300    #[error(transparent)]
301    ParallelFailed(ParallelFailure),
302    #[error(transparent)]
303    SagaCompensationFailed(SagaCompensationFailure),
304    #[error(transparent)]
305    InvalidParallelGroup(ParallelGroupError),
306    #[error(transparent)]
307    DurableOperationCancelled(DurableOperationCancelled),
308    #[error(transparent)]
309    WorkflowCancellationRequested(WorkflowCancellationRequested),
310    #[error(transparent)]
311    CooperativeCancellationRequested(CooperativeCancellationRequested),
312    #[error(transparent)]
313    CancellationScopeRequested(CancellationScopeRequested),
314    #[error(transparent)]
315    WorkflowCommandRejected(WorkflowCommandRejection),
316    #[error(transparent)]
317    WorkflowFailed(WorkflowTerminalOutcome),
318    #[error(transparent)]
319    WorkflowCancelled(WorkflowTerminalOutcome),
320    #[error(transparent)]
321    WorkflowTerminated(WorkflowTerminalOutcome),
322    #[error(transparent)]
323    WorkflowTimedOut(WorkflowTerminalOutcome),
324    #[error(transparent)]
325    ActivityTaskRejected(ActivityTaskRejection),
326    #[error("activity lease renewal unavailable: {0}")]
327    ActivityLeaseRenewalUnavailable(String),
328    #[error("workflow handler {0:?} is not registered")]
329    WorkflowNotRegistered(String),
330    #[error("activity handler {0:?} is not registered")]
331    ActivityNotRegistered(String),
332    #[error(
333        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
334    )]
335    HandlerType {
336        handler_kind: HandlerKind,
337        handler_name: String,
338        value_kind: HandlerValueKind,
339        rust_type: &'static str,
340        message: String,
341    },
342    #[error("workflow future yielded without emitting a durable command")]
343    WorkflowYieldedWithoutCommand,
344    #[error(
345        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
346    )]
347    MissingWorkflowCommandIdentity,
348    #[error("workflow state lock is poisoned")]
349    WorkflowStatePoisoned,
350    #[error("timer duration is too large for the worker protocol")]
351    TimerDurationOverflow,
352    #[error(transparent)]
353    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
354    #[error(transparent)]
355    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
356    #[error("operation timed out")]
357    Timeout,
358    #[error(
359        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
360    )]
361    MissingRoleCredentials {
362        role: &'static str,
363        opposite_role: &'static str,
364    },
365    #[error("worker loop error: {0}")]
366    WorkerLoop(String),
367    #[error(
368        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
369    )]
370    UnsupportedUpdateValidators { workflow_type: String },
371    #[error("{primary}; worker deregistration also failed: {deregistration}")]
372    WorkerShutdown {
373        primary: Box<Error>,
374        deregistration: Box<Error>,
375    },
376    #[error("invalid child workflow options: {0}")]
377    InvalidChildWorkflowOptions(String),
378    #[error("invalid workflow memo update: {0}")]
379    InvalidMemoUpdate(String),
380    #[error(
381        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
382    )]
383    WorkflowMemoUpdatesUnavailable,
384    #[error("cooperative cancellation is unavailable: {0}")]
385    CooperativeCancellationUnavailable(String),
386    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
387    CancellationScopeExecutionUnavailable,
388    #[error("invalid cooperative cancellation: {0}")]
389    InvalidCooperativeCancellation(String),
390    #[error("activity execution no longer owns its claim: {0}")]
391    ActivityExecutionAbandoned(String),
392    #[error(transparent)]
393    InvalidActivityOptions(ActivityOptionsError),
394    #[error(transparent)]
395    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
396    #[doc(hidden)]
397    #[error("workflow requested continue as new")]
398    ContinueAsNew(ContinueAsNewRequest),
399}
400
401impl Error {
402    /// The caller command key echoed by the Server in a refusal body.
403    ///
404    /// Signals and updates send their key as the `request_id` body field, and a
405    /// Server refusal such as `request_id_conflict` echoes it. Transport failures
406    /// and refusals without an echoed key return `None`: keep the key you passed
407    /// to a `*_with_request_id` method, or obtained from
408    /// [`Client::generate_signal_request_id`] or
409    /// [`Client::generate_update_request_id`], to retry the same logical command
410    /// after an uncertain outcome.
411    pub fn request_id(&self) -> Option<String> {
412        self.refusal_body()?
413            .get("request_id")
414            .and_then(Value::as_str)
415            .filter(|request_id| !request_id.is_empty())
416            .map(str::to_string)
417    }
418
419    /// Whether the Server refused a signal or update because its caller command
420    /// key is retained for a command with a different intent
421    /// (HTTP 409, `reason: "request_id_conflict"`).
422    pub fn is_request_id_conflict(&self) -> bool {
423        self.request_id_conflict().is_some()
424    }
425
426    /// The retained-command details of a `request_id_conflict` refusal.
427    pub fn request_id_conflict(&self) -> Option<RequestIdConflict> {
428        let status = match self {
429            Self::Http { status, .. } => status.as_u16(),
430            Self::WorkflowCommandRejected(rejection) => rejection.status,
431            _ => return None,
432        };
433        request_id_conflict(status, self.refusal_body()?)
434    }
435
436    fn refusal_body(&self) -> Option<Value> {
437        match self {
438            Self::Http { body, .. } => serde_json::from_str(body).ok(),
439            Self::WorkflowCommandRejected(rejection) => Some(rejection.body.clone()),
440            _ => None,
441        }
442    }
443}
444
445/// A refused signal or update whose caller command key is already retained for
446/// a command with a different intent.
447///
448/// Nothing was admitted or recorded, and the key stays bound to the retained
449/// command. Send a new key for a different command, or repeat the retained
450/// command's exact intent to receive its receipt. `conflict` lists the
451/// mismatched intent parts among `name`, `arguments` and `target`.
452#[derive(Clone, Debug, PartialEq)]
453#[non_exhaustive]
454pub struct RequestIdConflict {
455    pub status: u16,
456    pub request_id: String,
457    pub message: String,
458    pub retained_command_id: Option<String>,
459    pub retained_command_type: Option<String>,
460    pub retained_outcome: Option<String>,
461    pub conflict: Vec<String>,
462    pub body: Value,
463}
464
465fn request_id_conflict(status: u16, body: Value) -> Option<RequestIdConflict> {
466    if body.get("reason").and_then(Value::as_str) != Some(REQUEST_ID_CONFLICT_REASON) {
467        return None;
468    }
469    let string = |name: &str| body.get(name).and_then(Value::as_str).map(str::to_string);
470    Some(RequestIdConflict {
471        status,
472        request_id: string("request_id").unwrap_or_default(),
473        message: string("message")
474            .or_else(|| string("error"))
475            .unwrap_or_else(|| "request id is retained for a different command intent".to_string()),
476        retained_command_id: string("retained_command_id"),
477        retained_command_type: string("retained_command_type"),
478        retained_outcome: string("retained_outcome"),
479        conflict: body
480            .get("conflict")
481            .and_then(Value::as_array)
482            .map(|parts| {
483                parts
484                    .iter()
485                    .filter_map(Value::as_str)
486                    .map(str::to_string)
487                    .collect()
488            })
489            .unwrap_or_default(),
490        body,
491    })
492}
493
494/// Handler namespaces checked independently within a Worker.
495#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
496pub enum RegistrationKind {
497    Workflow,
498    Activity,
499    Query,
500    Update,
501}
502
503impl std::fmt::Display for RegistrationKind {
504    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
505        formatter.write_str(match self {
506            Self::Workflow => "workflow",
507            Self::Activity => "activity",
508            Self::Query => "query",
509            Self::Update => "update",
510        })
511    }
512}
513
514/// The authoring adapter and source location of a handler registration.
515#[derive(Clone, Debug, PartialEq, Eq)]
516pub struct HandlerRegistration {
517    pub method: &'static str,
518    pub handler_type: &'static str,
519    pub file: &'static str,
520    pub line: u32,
521    pub column: u32,
522}
523
524impl std::fmt::Display for HandlerRegistration {
525    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
526        write!(
527            formatter,
528            "{} at {}:{}:{} ({})",
529            self.method, self.file, self.line, self.column, self.handler_type
530        )
531    }
532}
533
534/// Ambiguous local configuration, rejected before contacting Server.
535#[derive(Clone, Debug, Error, PartialEq, Eq)]
536#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
537pub struct DuplicateRegistrationError {
538    pub handler_kind: RegistrationKind,
539    pub handler_name: String,
540    /// Query/update registrations are scoped to their owning workflow type.
541    pub workflow_type: Option<String>,
542    pub first_definition: HandlerRegistration,
543    pub second_definition: HandlerRegistration,
544}
545
546impl From<DuplicateRegistrationError> for Error {
547    fn from(error: DuplicateRegistrationError) -> Self {
548        Self::WorkerLoop(error.to_string())
549    }
550}
551
552/// Validation failure for a durable condition-wait definition.
553#[derive(Clone, Debug, Error, PartialEq, Eq)]
554pub enum ConditionWaitOptionsError {
555    #[error("condition_key must be non-empty")]
556    EmptyKey,
557    #[error("condition_definition_fingerprint must be non-empty")]
558    EmptyPredicateIdentity,
559    #[error("condition timeout is too large for the worker protocol")]
560    TimeoutOverflow,
561}
562
563/// Stable identity and optional durable timeout for a condition wait.
564///
565/// `predicate_identity` is recorded as the worker protocol's
566/// `condition_definition_fingerprint` and must change whenever predicate
567/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
568/// is written inline; it derives this identity from the predicate tokens.
569#[derive(Clone, Debug, PartialEq, Eq)]
570pub struct ConditionWaitOptions {
571    condition_key: String,
572    predicate_identity: String,
573    timeout: Option<Duration>,
574}
575
576impl ConditionWaitOptions {
577    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
578        Self {
579            condition_key: condition_key.into(),
580            predicate_identity: predicate_identity.into(),
581            timeout: None,
582        }
583    }
584
585    pub fn timeout(mut self, timeout: Duration) -> Self {
586        self.timeout = Some(timeout);
587        self
588    }
589
590    fn validate(
591        &self,
592    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
593        let condition_key = self.condition_key.trim();
594        if condition_key.is_empty() {
595            return Err(ConditionWaitOptionsError::EmptyKey);
596        }
597        let predicate_identity = self.predicate_identity.trim();
598        if predicate_identity.is_empty() {
599            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
600        }
601        let timeout_seconds = self
602            .timeout
603            .map(|timeout| {
604                timeout
605                    .as_secs()
606                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
607                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
608            })
609            .transpose()?;
610
611        Ok(ValidatedConditionWaitOptions {
612            condition_key: condition_key.to_string(),
613            predicate_identity: predicate_identity.to_string(),
614            timeout_seconds,
615        })
616    }
617}
618
619#[derive(Clone, Debug, PartialEq, Eq)]
620struct ValidatedConditionWaitOptions {
621    condition_key: String,
622    predicate_identity: String,
623    timeout_seconds: Option<u64>,
624}
625
626const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
627
628/// Unambiguous terminal result of a durable condition wait.
629#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
630#[serde(rename_all = "snake_case")]
631pub enum ConditionWaitResult {
632    Satisfied,
633    TimedOut,
634}
635
636impl ConditionWaitResult {
637    pub fn is_satisfied(self) -> bool {
638        self == Self::Satisfied
639    }
640
641    pub fn is_timed_out(self) -> bool {
642        self == Self::TimedOut
643    }
644}
645
646/// Build the stable condition definition identity used by [`wait_condition!`].
647#[doc(hidden)]
648pub fn __condition_definition_fingerprint(source: &str) -> String {
649    let mut digest = Sha256::new();
650    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
651    digest.update(source.as_bytes());
652    format!("sha256:{:x}", digest.finalize())
653}
654
655/// Create a durable condition wait whose predicate definition is fingerprinted
656/// from its inline Rust tokens.
657///
658/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
659/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
660#[macro_export]
661macro_rules! wait_condition {
662    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
663        $ctx.wait_condition(
664            $crate::ConditionWaitOptions::new(
665                $key,
666                $crate::__condition_definition_fingerprint(concat!(
667                    module_path!(),
668                    "\0",
669                    stringify!($predicate)
670                )),
671            )
672            .timeout($timeout),
673            $predicate,
674        )
675    }};
676    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
677        $ctx.wait_condition(
678            $crate::ConditionWaitOptions::new(
679                $key,
680                $crate::__condition_definition_fingerprint(concat!(
681                    module_path!(),
682                    "\0",
683                    stringify!($predicate)
684                )),
685            ),
686            $predicate,
687        )
688    }};
689}
690
691const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
692const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
693const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
694const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
695const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
696
697/// Validation failure for a typed workflow search-attribute update.
698#[derive(Clone, Debug, Error, PartialEq, Eq)]
699pub enum SearchAttributeUpdateError {
700    #[error("search-attribute update requires at least one attribute")]
701    Empty,
702    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
703    InvalidKey(String),
704    #[error("search-attribute update exceeds the limit of 100 attributes")]
705    TooManyAttributes,
706    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
707    ValueTooLong {
708        key: String,
709        kind: &'static str,
710        limit: usize,
711    },
712    #[error(
713        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
714    )]
715    EmptyString(String),
716    #[error("search attribute {0:?} has a non-finite float value")]
717    NonFiniteFloat(String),
718    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
719    InvalidDateTime(String),
720    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
721    PayloadTooLarge,
722}
723
724/// One public typed search-attribute value.
725#[derive(Clone, Debug, PartialEq)]
726pub enum SearchAttributeValue {
727    String(String),
728    Keyword(String),
729    KeywordList(Vec<String>),
730    Int(i64),
731    Float(f64),
732    Bool(bool),
733    DateTime(String),
734    Delete,
735}
736
737impl SearchAttributeValue {
738    fn type_name(&self) -> Option<&'static str> {
739        match self {
740            Self::String(_) => Some("string"),
741            Self::Keyword(_) => Some("keyword"),
742            Self::KeywordList(_) => Some("keyword_list"),
743            Self::Int(_) => Some("int"),
744            Self::Float(_) => Some("float"),
745            Self::Bool(_) => Some("bool"),
746            Self::DateTime(_) => Some("datetime"),
747            Self::Delete => None,
748        }
749    }
750
751    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
752        let normalize_string = |value: String, kind: &'static str, limit: usize| {
753            let value = value.trim().to_string();
754            if value.is_empty() {
755                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
756            }
757            if value.len() > limit {
758                return Err(SearchAttributeUpdateError::ValueTooLong {
759                    key: key.to_string(),
760                    kind,
761                    limit,
762                });
763            }
764            Ok(value)
765        };
766
767        match self {
768            Self::String(value) => Ok(Self::String(normalize_string(
769                value,
770                "string",
771                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
772            )?)),
773            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
774                value,
775                "keyword",
776                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
777            )?)),
778            Self::KeywordList(values) => {
779                let values = values
780                    .into_iter()
781                    .map(|value| {
782                        let value = value.trim().to_string();
783                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
784                            return Err(SearchAttributeUpdateError::ValueTooLong {
785                                key: key.to_string(),
786                                kind: "keyword-list entry",
787                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
788                            });
789                        }
790                        Ok(value)
791                    })
792                    .collect::<std::result::Result<Vec<_>, _>>()?;
793                Ok(Self::KeywordList(values))
794            }
795            Self::Float(value) if !value.is_finite() => {
796                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
797            }
798            Self::DateTime(value) => {
799                let value =
800                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
801                if DateTime::parse_from_rfc3339(&value).is_err() {
802                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
803                }
804                Ok(Self::DateTime(value))
805            }
806            value => Ok(value),
807        }
808    }
809
810    fn into_json(self) -> Value {
811        match self {
812            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
813                Value::String(value)
814            }
815            Self::KeywordList(values) => {
816                Value::Array(values.into_iter().map(Value::String).collect())
817            }
818            Self::Int(value) => json!(value),
819            Self::Float(value) => json!(value),
820            Self::Bool(value) => json!(value),
821            Self::Delete => Value::Null,
822        }
823    }
824}
825
826/// Validated typed workflow-side search-attribute mutation.
827#[derive(Clone, Debug, Default, PartialEq)]
828pub struct SearchAttributeUpdate {
829    attributes: BTreeMap<String, SearchAttributeValue>,
830}
831
832impl SearchAttributeUpdate {
833    pub fn new() -> Self {
834        Self::default()
835    }
836
837    pub fn set(
838        mut self,
839        key: impl Into<String>,
840        value: SearchAttributeValue,
841    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
842        let key = key.into();
843        validate_search_attribute_key(&key)?;
844        if !self.attributes.contains_key(&key)
845            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
846        {
847            return Err(SearchAttributeUpdateError::TooManyAttributes);
848        }
849        self.attributes.insert(key.clone(), value.normalized(&key)?);
850        self.validate_size()?;
851        Ok(self)
852    }
853
854    pub fn string(
855        self,
856        key: impl Into<String>,
857        value: impl Into<String>,
858    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
859        self.set(key, SearchAttributeValue::String(value.into()))
860    }
861
862    pub fn keyword(
863        self,
864        key: impl Into<String>,
865        value: impl Into<String>,
866    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
867        self.set(key, SearchAttributeValue::Keyword(value.into()))
868    }
869
870    pub fn keyword_list<I, V>(
871        self,
872        key: impl Into<String>,
873        values: I,
874    ) -> std::result::Result<Self, SearchAttributeUpdateError>
875    where
876        I: IntoIterator<Item = V>,
877        V: Into<String>,
878    {
879        self.set(
880            key,
881            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
882        )
883    }
884
885    pub fn int(
886        self,
887        key: impl Into<String>,
888        value: i64,
889    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
890        self.set(key, SearchAttributeValue::Int(value))
891    }
892
893    pub fn float(
894        self,
895        key: impl Into<String>,
896        value: f64,
897    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
898        self.set(key, SearchAttributeValue::Float(value))
899    }
900
901    pub fn bool(
902        self,
903        key: impl Into<String>,
904        value: bool,
905    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
906        self.set(key, SearchAttributeValue::Bool(value))
907    }
908
909    pub fn datetime(
910        self,
911        key: impl Into<String>,
912        value: impl Into<String>,
913    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
914        self.set(key, SearchAttributeValue::DateTime(value.into()))
915    }
916
917    pub fn delete(
918        self,
919        key: impl Into<String>,
920    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
921        self.set(key, SearchAttributeValue::Delete)
922    }
923
924    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
925        let (attributes, _) = self.clone().into_wire_parts();
926        if serde_json::to_vec(&attributes)
927            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
928            .unwrap_or(true)
929        {
930            return Err(SearchAttributeUpdateError::PayloadTooLarge);
931        }
932        Ok(())
933    }
934
935    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
936        let mut attributes = serde_json::Map::new();
937        let mut attribute_types = BTreeMap::new();
938        for (key, value) in self.attributes {
939            if let Some(type_name) = value.type_name() {
940                attribute_types.insert(key.clone(), type_name.to_string());
941            }
942            attributes.insert(key, value.into_json());
943        }
944        (Value::Object(attributes), attribute_types)
945    }
946
947    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
948        if self.attributes.is_empty() {
949            return Err(SearchAttributeUpdateError::Empty);
950        }
951        self.validate_size()
952    }
953}
954
955fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
956    let valid = !key.is_empty()
957        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
958        && key
959            .bytes()
960            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
961    if valid {
962        Ok(())
963    } else {
964        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
965    }
966}
967
968/// The registered handler family reported by [`Error::HandlerType`].
969#[derive(Clone, Copy, Debug, PartialEq, Eq)]
970pub enum HandlerKind {
971    Workflow,
972    Activity,
973}
974
975impl std::fmt::Display for HandlerKind {
976    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
977        formatter.write_str(match self {
978            Self::Workflow => "workflow",
979            Self::Activity => "activity",
980        })
981    }
982}
983
984/// Whether a typed handler failed to adapt its input or result.
985#[derive(Clone, Copy, Debug, PartialEq, Eq)]
986pub enum HandlerValueKind {
987    Input,
988    Result,
989}
990
991impl std::fmt::Display for HandlerValueKind {
992    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
993        formatter.write_str(match self {
994            Self::Input => "input",
995            Self::Result => "result",
996        })
997    }
998}
999
1000/// The lifecycle command sent to a workflow execution.
1001#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1002pub enum WorkflowCommandKind {
1003    Cancel,
1004    Terminate,
1005}
1006
1007impl WorkflowCommandKind {
1008    fn as_str(self) -> &'static str {
1009        match self {
1010            Self::Cancel => "cancel",
1011            Self::Terminate => "terminate",
1012        }
1013    }
1014}
1015
1016/// Optional structured fields for a cancellation or termination request.
1017#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
1018pub struct WorkflowCommandOptions {
1019    #[serde(skip_serializing_if = "Option::is_none")]
1020    pub reason: Option<String>,
1021    #[serde(skip_serializing_if = "Option::is_none")]
1022    pub request_id: Option<String>,
1023}
1024
1025/// Server-enforced timeout policy for a workflow start.
1026///
1027/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
1028/// only bounds how long the caller waits. A server deadline produces a terminal
1029/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
1030/// `run_timeout`.
1031#[derive(Clone, Debug, PartialEq, Eq)]
1032pub struct WorkflowStartOptions {
1033    pub execution_timeout_seconds: u64,
1034    pub run_timeout_seconds: u64,
1035}
1036
1037impl Default for WorkflowStartOptions {
1038    fn default() -> Self {
1039        Self {
1040            execution_timeout_seconds: 3600,
1041            run_timeout_seconds: 600,
1042        }
1043    }
1044}
1045
1046impl WorkflowStartOptions {
1047    pub fn new() -> Self {
1048        Self::default()
1049    }
1050
1051    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1052        self.execution_timeout_seconds = seconds;
1053        self
1054    }
1055
1056    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1057        self.run_timeout_seconds = seconds;
1058        self
1059    }
1060
1061    fn validate(&self) -> Result<()> {
1062        if self.execution_timeout_seconds == 0 {
1063            return Err(Error::Codec(
1064                "execution_timeout_seconds must be at least 1".to_string(),
1065            ));
1066        }
1067        if self.run_timeout_seconds == 0 {
1068            return Err(Error::Codec(
1069                "run_timeout_seconds must be at least 1".to_string(),
1070            ));
1071        }
1072        if self.run_timeout_seconds > self.execution_timeout_seconds {
1073            return Err(Error::Codec(
1074                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
1075            ));
1076        }
1077
1078        Ok(())
1079    }
1080}
1081
1082/// Optional routing overrides for a continue-as-new transition.
1083///
1084/// Omitted values retain the current workflow type and task queue. Server-owned
1085/// instance metadata is not accepted here and is carried by the server.
1086#[derive(Clone, Debug, Default, PartialEq, Eq)]
1087pub struct ContinueAsNewOptions {
1088    pub workflow_type: Option<String>,
1089    pub task_queue: Option<String>,
1090}
1091
1092impl ContinueAsNewOptions {
1093    pub fn new() -> Self {
1094        Self::default()
1095    }
1096
1097    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
1098        self.workflow_type = Some(workflow_type.into());
1099        self
1100    }
1101
1102    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1103        self.task_queue = Some(task_queue.into());
1104        self
1105    }
1106
1107    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
1108        for (field, value) in [
1109            ("workflow_type", self.workflow_type.as_deref()),
1110            ("task_queue", self.task_queue.as_deref()),
1111        ] {
1112            if value.is_some_and(|value| value.trim().is_empty()) {
1113                return Err(ContinueAsNewOptionsError {
1114                    field,
1115                    message: format!("{field} must not be empty"),
1116                });
1117            }
1118        }
1119        Ok(())
1120    }
1121}
1122
1123/// A stable validation error raised before a continue-as-new command is emitted.
1124#[derive(Clone, Debug, Error, PartialEq, Eq)]
1125#[error("invalid continue-as-new option {field}: {message}")]
1126pub struct ContinueAsNewOptionsError {
1127    pub field: &'static str,
1128    pub message: String,
1129}
1130
1131/// Public history-budget information attached to the current workflow task.
1132#[derive(Clone, Debug, Default, PartialEq, Eq)]
1133pub struct WorkflowHistoryBudget {
1134    pub event_count: u64,
1135    pub size_bytes: Option<u64>,
1136    pub continue_as_new_recommended: bool,
1137    pub pressure: Option<String>,
1138}
1139
1140#[doc(hidden)]
1141#[derive(Clone, Debug)]
1142pub struct ContinueAsNewRequest {
1143    arguments: AvroValue,
1144    options: ContinueAsNewOptions,
1145}
1146
1147impl WorkflowCommandOptions {
1148    pub fn new() -> Self {
1149        Self::default()
1150    }
1151
1152    pub fn reason(mut self, reason: impl Into<String>) -> Self {
1153        self.reason = Some(reason.into());
1154        self
1155    }
1156
1157    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
1158        self.request_id = Some(request_id.into());
1159        self
1160    }
1161}
1162
1163/// The accepted, machine-readable result of a lifecycle command.
1164#[derive(Clone, Debug, PartialEq)]
1165pub struct WorkflowCommandResult {
1166    pub command: WorkflowCommandKind,
1167    pub workflow_id: String,
1168    pub run_id: Option<String>,
1169    pub outcome: Option<String>,
1170    pub reason: Option<String>,
1171    pub command_status: Option<String>,
1172    pub raw: Value,
1173}
1174
1175/// A new run continuing a failed run from its recorded activity boundary.
1176#[derive(Clone, Debug, PartialEq)]
1177pub struct WorkflowRedriveResult {
1178    pub workflow_id: String,
1179    pub source_run_id: String,
1180    pub run_id: String,
1181    pub resume_step_sequence: u64,
1182    pub raw: Value,
1183}
1184
1185/// A stable rejection returned by instance- or selected-run lifecycle commands.
1186#[derive(Clone, Debug, Error)]
1187#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1188pub struct WorkflowCommandRejection {
1189    pub command: WorkflowCommandKind,
1190    pub status: u16,
1191    pub reason: String,
1192    pub message: String,
1193    pub workflow_id: String,
1194    pub run_id: Option<String>,
1195    pub target_scope: Option<String>,
1196    pub body: Value,
1197}
1198
1199/// Stable terminal categories returned by [`WorkflowHandle::result`].
1200#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1201pub enum WorkflowTerminalKind {
1202    Failed,
1203    Cancelled,
1204    Terminated,
1205    TimedOut,
1206}
1207
1208/// A typed terminal workflow outcome with durable identity and failure metadata.
1209///
1210/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1211/// of parsing its display representation. Fields remain `None` when an older
1212/// server did not publish that metadata.
1213#[derive(Clone, Debug, Error)]
1214#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1215pub struct WorkflowTerminalOutcome {
1216    pub kind: WorkflowTerminalKind,
1217    pub workflow_id: String,
1218    pub run_id: Option<String>,
1219    pub reason: String,
1220    pub failure_category: Option<String>,
1221    pub failure_id: Option<String>,
1222    pub exception_type: Option<String>,
1223    pub exception_class: Option<String>,
1224    pub non_retryable: Option<bool>,
1225    pub message: Option<String>,
1226    pub exception: Option<Value>,
1227    pub raw: Value,
1228}
1229
1230/// A worker-side activity settlement or heartbeat rejected by durable state.
1231#[derive(Clone, Debug, Error)]
1232#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1233pub struct ActivityTaskRejection {
1234    pub operation: String,
1235    pub status: u16,
1236    pub reason: String,
1237    pub task_id: String,
1238    pub activity_attempt_id: String,
1239    pub cancel_requested: bool,
1240    pub can_continue: Option<bool>,
1241    pub run_closed_reason: Option<String>,
1242    pub body: Value,
1243}
1244
1245/// Stable validation categories for [`ActivityOptions`].
1246#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1247pub enum ActivityOptionsErrorKind {
1248    EmptyTaskQueue,
1249    EmptyRetryPolicy,
1250    InvalidMaxAttempts,
1251    BackoffWithoutRetryBudget,
1252    TooManyBackoffIntervals,
1253    InvalidBackoffCoefficient,
1254    BackoffGenerationTooLarge,
1255    BackoffOverflow,
1256    EmptyNonRetryableErrorType,
1257    TimeoutNotPositive,
1258    MissingTotalTimeout,
1259    TimeoutOverflow,
1260    TimeoutOrder,
1261}
1262
1263/// A machine-readable activity-options validation failure.
1264#[derive(Clone, Debug, Error, PartialEq, Eq)]
1265#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1266pub struct ActivityOptionsError {
1267    pub kind: ActivityOptionsErrorKind,
1268    pub field: Option<&'static str>,
1269    pub message: String,
1270}
1271
1272impl ActivityOptionsError {
1273    fn new(
1274        kind: ActivityOptionsErrorKind,
1275        field: Option<&'static str>,
1276        message: impl Into<String>,
1277    ) -> Self {
1278        Self {
1279            kind,
1280            field,
1281            message: message.into(),
1282        }
1283    }
1284}
1285
1286/// Stable terminal categories returned when an awaited activity does not succeed.
1287#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1288pub enum ActivityFailureKind {
1289    Failed,
1290    Cancelled,
1291    TimedOut,
1292}
1293
1294/// A stable, machine-readable terminal activity failure.
1295///
1296/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1297/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1298#[derive(Clone, Debug, Error, PartialEq)]
1299#[error("activity failed ({reason}): {message}")]
1300pub struct ActivityFailure {
1301    pub kind: ActivityFailureKind,
1302    pub reason: String,
1303    pub message: String,
1304    pub activity_execution_id: Option<String>,
1305    pub activity_attempt_id: Option<String>,
1306    pub activity_type: Option<String>,
1307    pub activity_class: Option<String>,
1308    pub attempt_number: Option<u64>,
1309    pub failure_id: Option<String>,
1310    pub failure_category: Option<String>,
1311    pub timeout_kind: Option<String>,
1312    pub non_retryable: bool,
1313    pub exception_type: Option<String>,
1314    pub exception_class: Option<String>,
1315    pub code: Option<Value>,
1316    pub exception: Option<Value>,
1317}
1318
1319/// Stable terminal categories returned when an awaited child does not succeed.
1320#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1321pub enum ChildWorkflowFailureKind {
1322    Failed,
1323    Cancelled,
1324    Terminated,
1325}
1326
1327/// A stable, machine-readable child workflow failure delivered to its parent.
1328///
1329/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1330/// of parsing the display message. Child and parent identifiers retain the
1331/// relationship recorded in durable history across worker restarts.
1332#[derive(Clone, Debug, Error)]
1333#[error("child workflow failed ({reason}): {message}")]
1334pub struct ChildWorkflowFailure {
1335    pub kind: ChildWorkflowFailureKind,
1336    pub reason: String,
1337    pub message: String,
1338    pub parent_workflow_id: Option<String>,
1339    pub parent_workflow_run_id: Option<String>,
1340    pub child_workflow_id: Option<String>,
1341    pub child_workflow_run_id: Option<String>,
1342    pub child_workflow_type: Option<String>,
1343    pub failure_id: Option<String>,
1344    pub failure_category: Option<String>,
1345    pub exception_type: Option<String>,
1346    pub exception_class: Option<String>,
1347    pub non_retryable: bool,
1348    pub code: Option<Value>,
1349    pub exception: Option<Value>,
1350}
1351
1352/// The identity of one durable workflow execution.
1353#[derive(Clone, Debug, PartialEq, Eq)]
1354pub struct WorkflowIdentity {
1355    pub workflow_id: Option<String>,
1356    pub run_id: Option<String>,
1357}
1358
1359/// A successful child result together with its durable parent-child identity.
1360#[derive(Clone, Debug, PartialEq)]
1361pub struct ChildWorkflowResult {
1362    pub parent: WorkflowIdentity,
1363    pub child: WorkflowIdentity,
1364    pub child_workflow_type: Option<String>,
1365    pub result: Value,
1366}
1367
1368/// Lossless successful child result for fixed Avro Value workflows.
1369#[derive(Clone, Debug, PartialEq)]
1370pub struct ChildWorkflowAvroResult {
1371    pub parent: WorkflowIdentity,
1372    pub child: WorkflowIdentity,
1373    pub child_workflow_type: Option<String>,
1374    pub result: AvroValue,
1375}
1376
1377/// Stable user-facing identity for one member of a durable selection group.
1378#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1379#[serde(untagged)]
1380pub enum SelectionKey {
1381    Index(usize),
1382    Name(String),
1383}
1384
1385impl From<usize> for SelectionKey {
1386    fn from(value: usize) -> Self {
1387        Self::Index(value)
1388    }
1389}
1390
1391impl From<String> for SelectionKey {
1392    fn from(value: String) -> Self {
1393        Self::Name(value)
1394    }
1395}
1396
1397impl From<&str> for SelectionKey {
1398    fn from(value: &str) -> Self {
1399        Self::Name(value.to_string())
1400    }
1401}
1402
1403/// Typed result of explicitly awaiting a cancelled non-winning operation.
1404#[derive(Clone, Debug, Error, PartialEq, Eq)]
1405#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1406pub struct DurableOperationCancelled {
1407    pub selection_group_id: String,
1408    pub member_key: SelectionKey,
1409    pub member_index: usize,
1410    pub operation_kind: String,
1411    pub operation_identity: String,
1412}
1413
1414/// Stable identity for one enclosing deterministic parallel group.
1415///
1416/// The same fields are attached to every ordinary activity, timer, or child
1417/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1418/// no Rust-specific wire command is introduced.
1419#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1420pub struct ParallelGroupMetadata {
1421    pub parallel_group_id: String,
1422    pub parallel_group_kind: String,
1423    pub parallel_group_base_sequence: u64,
1424    pub parallel_group_size: usize,
1425    pub parallel_group_index: usize,
1426    #[serde(default, skip_serializing_if = "Option::is_none")]
1427    pub parallel_group_mode: Option<String>,
1428    #[serde(default, skip_serializing_if = "Option::is_none")]
1429    pub selection_member_key: Option<SelectionKey>,
1430    #[serde(default, skip_serializing_if = "Option::is_none")]
1431    pub selection_member_index: Option<usize>,
1432    #[serde(default, skip_serializing_if = "Option::is_none")]
1433    pub selection_member_base_sequence: Option<u64>,
1434    #[serde(default, skip_serializing_if = "Option::is_none")]
1435    pub selection_member_size: Option<usize>,
1436    #[serde(default, skip_serializing_if = "Option::is_none")]
1437    pub selection_member_kind: Option<String>,
1438}
1439
1440/// One input-ordered result returned by [`WorkflowContext::parallel`].
1441#[derive(Clone, Debug, PartialEq)]
1442pub enum ParallelResult {
1443    Activity(Value),
1444    ChildWorkflow(ChildWorkflowResult),
1445    Timer,
1446    Signal(Vec<Value>),
1447    Condition(ConditionWaitResult),
1448    Group(Vec<ParallelResult>),
1449}
1450
1451/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1452#[derive(Clone, Debug, PartialEq)]
1453pub enum ParallelAvroResult {
1454    Activity(AvroValue),
1455    ChildWorkflow(ChildWorkflowAvroResult),
1456    Timer,
1457    Signal(Vec<AvroValue>),
1458    Condition(ConditionWaitResult),
1459    Group(Vec<ParallelAvroResult>),
1460}
1461
1462impl ParallelAvroResult {
1463    fn into_json_result(self) -> Result<ParallelResult> {
1464        match self {
1465            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1466            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1467                parent: result.parent,
1468                child: result.child,
1469                child_workflow_type: result.child_workflow_type,
1470                result: result.result.into_json()?,
1471            })),
1472            Self::Timer => Ok(ParallelResult::Timer),
1473            Self::Signal(values) => Ok(ParallelResult::Signal(
1474                values
1475                    .into_iter()
1476                    .map(AvroValue::into_json)
1477                    .collect::<Result<Vec<_>>>()?,
1478            )),
1479            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1480            Self::Group(results) => Ok(ParallelResult::Group(
1481                results
1482                    .into_iter()
1483                    .map(Self::into_json_result)
1484                    .collect::<Result<Vec<_>>>()?,
1485            )),
1486        }
1487    }
1488}
1489
1490/// One successful leaf retained when another parallel member failed.
1491#[derive(Clone, Debug, PartialEq)]
1492pub struct ParallelCompletion {
1493    pub member_path: Vec<usize>,
1494    pub result: ParallelResult,
1495}
1496
1497/// A deterministic join failed after some siblings had already completed.
1498///
1499/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1500/// error. `completed` is declaration ordered and contains only durable
1501/// successes observed in the same replay. Late sibling completions can add
1502/// entries on a later replay without changing `member_path` or the selected
1503/// positional failure.
1504#[derive(Debug, Error)]
1505#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1506pub struct ParallelFailure {
1507    pub group_id: String,
1508    pub member_path: Vec<usize>,
1509    pub group_path: Vec<ParallelGroupMetadata>,
1510    pub completed: Vec<ParallelCompletion>,
1511    #[source]
1512    pub cause: Box<Error>,
1513}
1514
1515/// Stable validation error returned before an invalid group emits commands.
1516#[derive(Clone, Debug, Error, PartialEq, Eq)]
1517#[error("invalid deterministic parallel group ({reason}): {message}")]
1518pub struct ParallelGroupError {
1519    pub reason: &'static str,
1520    pub member_path: Vec<usize>,
1521    pub message: String,
1522}
1523
1524/// Cooperative workflow cancellation observed at an author-controlled point.
1525#[derive(Clone, Debug, Error, PartialEq, Eq)]
1526#[error("workflow cancellation was requested")]
1527pub struct WorkflowCancellationRequested;
1528
1529/// A forward saga failure followed by a terminal compensation failure.
1530#[derive(Debug, Error)]
1531#[error(
1532    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1533)]
1534pub struct SagaCompensationFailure {
1535    pub initiating_failure: Box<Error>,
1536    pub compensation_failure: Box<Error>,
1537    pub compensation_activity_type: String,
1538    pub compensation_registration_order: usize,
1539}
1540
1541/// Server behavior when a parent closes while its child is still open.
1542#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1543pub enum ParentClosePolicy {
1544    #[default]
1545    Abandon,
1546    /// Legacy terminal cancellation without cooperative cleanup.
1547    RequestCancel,
1548    /// Request cooperative cleanup with the original lineage and deadline.
1549    RequestCancellation,
1550    Terminate,
1551}
1552
1553impl ParentClosePolicy {
1554    fn as_str(self) -> &'static str {
1555        match self {
1556            Self::Abandon => "abandon",
1557            Self::RequestCancel => "request_cancel",
1558            Self::RequestCancellation => "request_cancellation",
1559            Self::Terminate => "terminate",
1560        }
1561    }
1562}
1563
1564/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1565#[non_exhaustive]
1566#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1567pub enum CancellationPolicy {
1568    /// Request cancellation and continue without waiting. Historical Activity default.
1569    TryCancel,
1570    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1571    WaitCancellationCompleted,
1572    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1573    #[default]
1574    Abandon,
1575}
1576
1577impl CancellationPolicy {
1578    fn as_str(self) -> &'static str {
1579        match self {
1580            Self::TryCancel => "try_cancel",
1581            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1582            Self::Abandon => "abandon",
1583        }
1584    }
1585}
1586
1587/// Durable retry policy for one child workflow invocation.
1588#[derive(Clone, Debug, Default, PartialEq, Eq)]
1589pub struct ChildWorkflowRetryPolicy {
1590    pub max_attempts: Option<u32>,
1591    pub backoff_seconds: Vec<u64>,
1592    pub non_retryable_error_types: Vec<String>,
1593}
1594
1595/// Options recorded with a child-workflow command.
1596///
1597/// The task queue is mandatory so routing is explicit and replay-stable.
1598#[derive(Clone, Debug, PartialEq, Eq)]
1599pub struct ChildWorkflowOptions {
1600    pub task_queue: String,
1601    pub parent_close_policy: ParentClosePolicy,
1602    pub cancellation_policy: CancellationPolicy,
1603    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1604    pub execution_timeout_seconds: Option<u64>,
1605    pub run_timeout_seconds: Option<u64>,
1606}
1607
1608impl ChildWorkflowOptions {
1609    pub fn new(task_queue: impl Into<String>) -> Self {
1610        Self {
1611            task_queue: task_queue.into(),
1612            parent_close_policy: ParentClosePolicy::Abandon,
1613            cancellation_policy: CancellationPolicy::Abandon,
1614            retry_policy: None,
1615            execution_timeout_seconds: None,
1616            run_timeout_seconds: None,
1617        }
1618    }
1619
1620    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1621        self.parent_close_policy = policy;
1622        self
1623    }
1624
1625    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1626        self.cancellation_policy = policy;
1627        self
1628    }
1629
1630    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1631        self.retry_policy = Some(policy);
1632        self
1633    }
1634
1635    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1636        self.execution_timeout_seconds = Some(seconds);
1637        self
1638    }
1639
1640    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1641        self.run_timeout_seconds = Some(seconds);
1642        self
1643    }
1644}
1645
1646/// Backoff intervals for one durable activity retry policy.
1647#[derive(Clone, Debug, PartialEq, Eq)]
1648pub enum ActivityBackoff {
1649    /// Use these intervals between attempts. The server repeats the final
1650    /// interval if the retry budget contains more attempts than entries.
1651    /// All entries are retained, including those beyond the retry budget.
1652    Explicit(Vec<Duration>),
1653    /// Generate one interval for every retry using integer exponential growth.
1654    Exponential {
1655        initial_interval: Duration,
1656        coefficient: u32,
1657        maximum_interval: Option<Duration>,
1658    },
1659}
1660
1661/// Durable server-side retry policy for one activity execution.
1662#[derive(Clone, Debug, Default, PartialEq, Eq)]
1663pub struct ActivityRetryPolicy {
1664    pub max_attempts: Option<u32>,
1665    pub backoff: Option<ActivityBackoff>,
1666    pub non_retryable_error_types: Vec<String>,
1667}
1668
1669impl ActivityRetryPolicy {
1670    /// Start a policy with a finite attempt budget, including the first attempt.
1671    pub fn new(max_attempts: u32) -> Self {
1672        Self {
1673            max_attempts: Some(max_attempts),
1674            ..Self::default()
1675        }
1676    }
1677
1678    /// Preserve the complete explicit list independently of the attempt budget.
1679    /// Unused entries remain part of the policy compared during replay.
1680    /// Set explicit durable retry intervals. Each positive fractional second
1681    /// is rounded up when encoded: `Duration::from_millis(100)` becomes one
1682    /// second. Zero stays zero. Queue latency can delay the next attempt further.
1683    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1684        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1685        self
1686    }
1687
1688    /// Generate durable retry intervals from `initial_interval` and `coefficient`.
1689    /// Each interval is capped by `maximum_interval`, when present, then rounded
1690    /// up to whole seconds. A 100 ms interval or cap therefore encodes one second.
1691    /// Zero stays zero. This policy is separate from HTTP transport retries.
1692    pub fn exponential_backoff(
1693        mut self,
1694        initial_interval: Duration,
1695        coefficient: u32,
1696        maximum_interval: Option<Duration>,
1697    ) -> Self {
1698        self.backoff = Some(ActivityBackoff::Exponential {
1699            initial_interval,
1700            coefficient,
1701            maximum_interval,
1702        });
1703        self
1704    }
1705
1706    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1707        self.non_retryable_error_types.push(error_type.into());
1708        self
1709    }
1710
1711    pub fn non_retryable_error_types(
1712        mut self,
1713        error_types: impl IntoIterator<Item = impl Into<String>>,
1714    ) -> Self {
1715        self.non_retryable_error_types
1716            .extend(error_types.into_iter().map(Into::into));
1717        self
1718    }
1719}
1720
1721/// Options recorded atomically on one deterministic `schedule_activity` command.
1722///
1723/// Durations are rounded up to whole seconds when encoded, so the server never
1724/// receives a shorter timeout or backoff than the caller requested.
1725#[derive(Clone, Debug, Default, PartialEq, Eq)]
1726pub struct ActivityOptions {
1727    pub task_queue: Option<String>,
1728    pub retry_policy: Option<ActivityRetryPolicy>,
1729    pub start_to_close_timeout: Option<Duration>,
1730    pub schedule_to_start_timeout: Option<Duration>,
1731    pub schedule_to_close_timeout: Option<Duration>,
1732    pub heartbeat_timeout: Option<Duration>,
1733    pub cancellation_policy: Option<CancellationPolicy>,
1734}
1735
1736impl ActivityOptions {
1737    pub fn new() -> Self {
1738        Self::default()
1739    }
1740
1741    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1742        self.task_queue = Some(task_queue.into());
1743        self
1744    }
1745
1746    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1747        self.retry_policy = Some(policy);
1748        self
1749    }
1750
1751    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1752        self.start_to_close_timeout = Some(timeout);
1753        self
1754    }
1755
1756    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1757        self.schedule_to_start_timeout = Some(timeout);
1758        self
1759    }
1760
1761    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1762        self.schedule_to_close_timeout = Some(timeout);
1763        self
1764    }
1765
1766    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1767        self.heartbeat_timeout = Some(timeout);
1768        self
1769    }
1770
1771    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1772        self.cancellation_policy = Some(policy);
1773        self
1774    }
1775
1776    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1777        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1778            && self.schedule_to_close_timeout.is_none()
1779        {
1780            return Err(ActivityOptionsError::new(
1781                ActivityOptionsErrorKind::MissingTotalTimeout,
1782                Some("schedule_to_close_timeout"),
1783                "remote Activity Abandon requires a finite positive total timeout",
1784            ));
1785        }
1786        if self
1787            .task_queue
1788            .as_deref()
1789            .is_some_and(|queue| queue.trim().is_empty())
1790        {
1791            return Err(ActivityOptionsError::new(
1792                ActivityOptionsErrorKind::EmptyTaskQueue,
1793                Some("task_queue"),
1794                "task_queue must not be empty",
1795            ));
1796        }
1797
1798        for (field, value) in [
1799            ("start_to_close_timeout", self.start_to_close_timeout),
1800            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1801            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1802            ("heartbeat_timeout", self.heartbeat_timeout),
1803        ] {
1804            if value.is_some_and(|value| value.is_zero()) {
1805                return Err(ActivityOptionsError::new(
1806                    ActivityOptionsErrorKind::TimeoutNotPositive,
1807                    Some(field),
1808                    format!("{field} must be positive"),
1809                ));
1810            }
1811        }
1812
1813        validate_timeout_order(
1814            "heartbeat_timeout",
1815            self.heartbeat_timeout,
1816            "start_to_close_timeout",
1817            self.start_to_close_timeout,
1818        )?;
1819        validate_timeout_order(
1820            "start_to_close_timeout",
1821            self.start_to_close_timeout,
1822            "schedule_to_close_timeout",
1823            self.schedule_to_close_timeout,
1824        )?;
1825        validate_timeout_order(
1826            "schedule_to_start_timeout",
1827            self.schedule_to_start_timeout,
1828            "schedule_to_close_timeout",
1829            self.schedule_to_close_timeout,
1830        )?;
1831
1832        Ok(ValidatedActivityOptions {
1833            task_queue: self.task_queue.clone(),
1834            retry_policy: self
1835                .retry_policy
1836                .as_ref()
1837                .map(validate_activity_retry_policy)
1838                .transpose()?,
1839            start_to_close_timeout: timeout_seconds(
1840                "start_to_close_timeout",
1841                self.start_to_close_timeout,
1842            )?,
1843            schedule_to_start_timeout: timeout_seconds(
1844                "schedule_to_start_timeout",
1845                self.schedule_to_start_timeout,
1846            )?,
1847            schedule_to_close_timeout: timeout_seconds(
1848                "schedule_to_close_timeout",
1849                self.schedule_to_close_timeout,
1850            )?,
1851            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1852            cancellation_policy: self.cancellation_policy,
1853        })
1854    }
1855}
1856
1857/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1858///
1859/// Constructors capture arguments but perform no I/O. The join validates the
1860/// complete tree, attaches the existing parallel-group metadata to every
1861/// ordinary command, schedules all leaves, and then suspends.
1862pub enum ParallelOperation {
1863    Activity {
1864        activity_type: String,
1865        options: ActivityOptions,
1866        arguments: Result<AvroValue>,
1867    },
1868    ChildWorkflow {
1869        workflow_type: String,
1870        options: ChildWorkflowOptions,
1871        arguments: Result<AvroValue>,
1872    },
1873    Timer(Duration),
1874    Signal(String),
1875    Condition {
1876        options: ConditionWaitOptions,
1877        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1878    },
1879    Group(Vec<ParallelOperation>),
1880}
1881
1882impl ParallelOperation {
1883    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1884        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1885    }
1886
1887    pub fn activity_with_options<T: Serialize>(
1888        activity_type: impl Into<String>,
1889        options: ActivityOptions,
1890        args: T,
1891    ) -> Self {
1892        Self::Activity {
1893            activity_type: activity_type.into(),
1894            options,
1895            arguments: AvroValue::from_serialize(&args),
1896        }
1897    }
1898
1899    pub fn child_workflow<T: Serialize>(
1900        workflow_type: impl Into<String>,
1901        options: ChildWorkflowOptions,
1902        args: T,
1903    ) -> Self {
1904        Self::ChildWorkflow {
1905            workflow_type: workflow_type.into(),
1906            options,
1907            arguments: AvroValue::from_serialize(&args),
1908        }
1909    }
1910
1911    pub fn timer(duration: Duration) -> Self {
1912        Self::Timer(duration)
1913    }
1914
1915    pub fn signal(signal_name: impl Into<String>) -> Self {
1916        Self::Signal(signal_name.into())
1917    }
1918
1919    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1920    where
1921        F: Fn() -> Result<bool> + Send + 'static,
1922    {
1923        Self::Condition {
1924            options,
1925            predicate: Box::new(predicate),
1926        }
1927    }
1928
1929    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1930        Self::Group(operations)
1931    }
1932}
1933
1934#[derive(Clone, Debug)]
1935struct ValidatedActivityOptions {
1936    task_queue: Option<String>,
1937    retry_policy: Option<Value>,
1938    start_to_close_timeout: Option<u64>,
1939    schedule_to_start_timeout: Option<u64>,
1940    schedule_to_close_timeout: Option<u64>,
1941    heartbeat_timeout: Option<u64>,
1942    cancellation_policy: Option<CancellationPolicy>,
1943}
1944
1945fn validate_timeout_order(
1946    smaller_name: &'static str,
1947    smaller: Option<Duration>,
1948    larger_name: &'static str,
1949    larger: Option<Duration>,
1950) -> std::result::Result<(), ActivityOptionsError> {
1951    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1952        return Err(ActivityOptionsError::new(
1953            ActivityOptionsErrorKind::TimeoutOrder,
1954            Some(smaller_name),
1955            format!("{smaller_name} must be <= {larger_name}"),
1956        ));
1957    }
1958    Ok(())
1959}
1960
1961fn timeout_seconds(
1962    field: &'static str,
1963    value: Option<Duration>,
1964) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1965    value
1966        .map(|value| {
1967            activity_protocol_seconds(value).ok_or_else(|| {
1968                ActivityOptionsError::new(
1969                    ActivityOptionsErrorKind::TimeoutOverflow,
1970                    Some(field),
1971                    format!("{field} is too large for the worker protocol"),
1972                )
1973            })
1974        })
1975        .transpose()
1976}
1977
1978fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1979    value
1980        .as_secs()
1981        .checked_add(u64::from(value.subsec_nanos() > 0))
1982}
1983
1984fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1985    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1986}
1987
1988fn validate_activity_retry_policy(
1989    policy: &ActivityRetryPolicy,
1990) -> std::result::Result<Value, ActivityOptionsError> {
1991    if policy.max_attempts.is_none()
1992        && policy.backoff.is_none()
1993        && policy.non_retryable_error_types.is_empty()
1994    {
1995        return Err(ActivityOptionsError::new(
1996            ActivityOptionsErrorKind::EmptyRetryPolicy,
1997            Some("retry_policy"),
1998            "retry_policy must configure at least one field",
1999        ));
2000    }
2001    if policy.max_attempts == Some(0) {
2002        return Err(ActivityOptionsError::new(
2003            ActivityOptionsErrorKind::InvalidMaxAttempts,
2004            Some("retry_policy.max_attempts"),
2005            "max_attempts must be >= 1",
2006        ));
2007    }
2008    if policy
2009        .non_retryable_error_types
2010        .iter()
2011        .any(|error_type| error_type.trim().is_empty())
2012    {
2013        return Err(ActivityOptionsError::new(
2014            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
2015            Some("retry_policy.non_retryable_error_types"),
2016            "non_retryable_error_types must not contain empty values",
2017        ));
2018    }
2019
2020    let backoff_seconds = match &policy.backoff {
2021        None => None,
2022        Some(backoff) => {
2023            let max_attempts = policy.max_attempts.ok_or_else(|| {
2024                ActivityOptionsError::new(
2025                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
2026                    Some("retry_policy.backoff"),
2027                    "backoff requires max_attempts",
2028                )
2029            })?;
2030            let retry_count = max_attempts.saturating_sub(1) as usize;
2031            let intervals = match backoff {
2032                ActivityBackoff::Explicit(intervals) => intervals.clone(),
2033                ActivityBackoff::Exponential {
2034                    initial_interval,
2035                    coefficient,
2036                    maximum_interval,
2037                } => {
2038                    if *coefficient < 1 {
2039                        return Err(ActivityOptionsError::new(
2040                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
2041                            Some("retry_policy.backoff.coefficient"),
2042                            "backoff coefficient must be >= 1",
2043                        ));
2044                    }
2045                    if retry_count > 10_000 {
2046                        return Err(ActivityOptionsError::new(
2047                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
2048                            Some("retry_policy.max_attempts"),
2049                            "generated backoff supports at most 10000 retry intervals",
2050                        ));
2051                    }
2052                    let mut current = *initial_interval;
2053                    let mut intervals = Vec::with_capacity(retry_count);
2054                    for _ in 0..retry_count {
2055                        let interval = maximum_interval
2056                            .map(|maximum| current.min(maximum))
2057                            .unwrap_or(current);
2058                        intervals.push(interval);
2059                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
2060                            break;
2061                        }
2062                        current = current.checked_mul(*coefficient).ok_or_else(|| {
2063                            ActivityOptionsError::new(
2064                                ActivityOptionsErrorKind::BackoffOverflow,
2065                                Some("retry_policy.backoff"),
2066                                "generated backoff interval overflowed",
2067                            )
2068                        })?;
2069                    }
2070                    intervals
2071                }
2072            };
2073            Some(
2074                intervals
2075                    .into_iter()
2076                    .map(|interval| {
2077                        activity_protocol_seconds(interval).ok_or_else(|| {
2078                            ActivityOptionsError::new(
2079                                ActivityOptionsErrorKind::BackoffOverflow,
2080                                Some("retry_policy.backoff"),
2081                                "backoff interval is too large for the worker protocol",
2082                            )
2083                        })
2084                    })
2085                    .collect::<std::result::Result<Vec<_>, _>>()?,
2086            )
2087        }
2088    };
2089
2090    let mut encoded = serde_json::Map::new();
2091    if let Some(max_attempts) = policy.max_attempts {
2092        encoded.insert("max_attempts".to_string(), json!(max_attempts));
2093    }
2094    if let Some(backoff_seconds) = backoff_seconds {
2095        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
2096    }
2097    if !policy.non_retryable_error_types.is_empty() {
2098        let mut canonical_error_types = Vec::new();
2099        for error_type in policy
2100            .non_retryable_error_types
2101            .iter()
2102            .map(|error_type| error_type.trim())
2103        {
2104            if !canonical_error_types.contains(&error_type) {
2105                canonical_error_types.push(error_type);
2106            }
2107        }
2108        encoded.insert(
2109            "non_retryable_error_types".to_string(),
2110            json!(canonical_error_types),
2111        );
2112    }
2113    Ok(Value::Object(encoded))
2114}
2115
2116/// A stable, machine-readable failure raised when workflow code no longer
2117/// reconstructs the durable command stream recorded in history.
2118#[derive(Clone, Debug, Error)]
2119#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
2120pub struct ReplayFailure {
2121    pub reason: String,
2122    pub sequence: Option<u64>,
2123    pub expected: Option<String>,
2124    pub actual: Option<String>,
2125    pub message: String,
2126}
2127
2128impl ReplayFailure {
2129    fn new(
2130        reason: impl Into<String>,
2131        sequence: Option<u64>,
2132        expected: Option<String>,
2133        actual: Option<String>,
2134        message: impl Into<String>,
2135    ) -> Self {
2136        Self {
2137            reason: reason.into(),
2138            sequence,
2139            expected,
2140            actual,
2141            message: message.into(),
2142        }
2143    }
2144}
2145
2146/// A stable, machine-readable workflow query or query-task settlement failure.
2147#[derive(Clone, Debug, Error)]
2148#[error("query failed ({reason}, HTTP {status}): {message}")]
2149pub struct QueryFailure {
2150    pub status: u16,
2151    pub reason: String,
2152    pub message: String,
2153    pub body: Value,
2154}
2155
2156/// A stable failure returned when a server rejects an SDK protocol version.
2157#[derive(Clone, Debug, Error)]
2158#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
2159pub struct ProtocolFailure {
2160    pub status: u16,
2161    pub reason: String,
2162    pub message: String,
2163    pub supported_version: Option<String>,
2164    pub requested_version: Option<String>,
2165    pub body: Value,
2166}
2167
2168#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2169pub struct PayloadEnvelope {
2170    pub codec: String,
2171    pub blob: String,
2172}
2173
2174impl PayloadEnvelope {
2175    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2176        encode_payload(value, DEFAULT_CODEC)
2177    }
2178
2179    /// Encode an explicit typed value, including the bytes branch that JSON
2180    /// serialization cannot represent.
2181    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2182        encode_avro_value(value)
2183    }
2184}
2185
2186/// Native adapter for the fixed language-neutral Avro Value schema.
2187#[derive(Clone, Debug)]
2188pub enum AvroValue {
2189    Null,
2190    Boolean(bool),
2191    Long(i64),
2192    Double(f64),
2193    Bytes(Vec<u8>),
2194    String(String),
2195    Array(Vec<AvroValue>),
2196    Map(BTreeMap<String, AvroValue>),
2197}
2198
2199impl PartialEq for AvroValue {
2200    fn eq(&self, other: &Self) -> bool {
2201        match (self, other) {
2202            (Self::Null, Self::Null) => true,
2203            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2204            (Self::Long(left), Self::Long(right)) => left == right,
2205            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2206            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2207            (Self::String(left), Self::String(right)) => left == right,
2208            (Self::Array(left), Self::Array(right)) => left == right,
2209            (Self::Map(left), Self::Map(right)) => left == right,
2210            _ => false,
2211        }
2212    }
2213}
2214
2215impl AvroValue {
2216    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2217        Self::from_serde_value(
2218            serde_value::to_value(value).map_err(|error| {
2219                Error::Codec(format!("could not adapt value for Avro: {error}"))
2220            })?,
2221        )
2222    }
2223
2224    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2225        use serde_value::Value as SerdeValue;
2226
2227        match value {
2228            SerdeValue::Unit => Ok(Self::Null),
2229            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2230            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2231            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2232            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2233            SerdeValue::I64(value) => Ok(Self::Long(value)),
2234            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2235            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2236            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2237            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2238                Error::Codec(
2239                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2240                        .to_string(),
2241                )
2242            }),
2243            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2244            SerdeValue::F64(value) => Self::finite_double(value),
2245            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2246            SerdeValue::String(value) => Ok(Self::String(value)),
2247            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2248            SerdeValue::Option(None) => Ok(Self::Null),
2249            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2250                Self::from_serde_value(*value)
2251            }
2252            SerdeValue::Seq(values) => values
2253                .into_iter()
2254                .map(Self::from_serde_value)
2255                .collect::<Result<Vec<_>>>()
2256                .map(Self::Array),
2257            SerdeValue::Map(values) => values
2258                .into_iter()
2259                .map(|(key, value)| {
2260                    let SerdeValue::String(key) = key else {
2261                        return Err(Error::Codec(
2262                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2263                        ));
2264                    };
2265
2266                    Ok((key, Self::from_serde_value(value)?))
2267                })
2268                .collect::<Result<BTreeMap<_, _>>>()
2269                .map(Self::Map),
2270        }
2271    }
2272
2273    fn finite_double(value: f64) -> Result<Self> {
2274        if !value.is_finite() {
2275            return Err(Error::Codec(
2276                "non_finite_float: Avro Value doubles must be finite".to_string(),
2277            ));
2278        }
2279
2280        Ok(Self::Double(value))
2281    }
2282
2283    fn into_json(self) -> Result<Value> {
2284        match self {
2285            Self::Null => Ok(Value::Null),
2286            Self::Boolean(value) => Ok(Value::Bool(value)),
2287            Self::Long(value) => Ok(Value::Number(value.into())),
2288            Self::Double(value) => serde_json::Number::from_f64(value)
2289                .map(Value::Number)
2290                .ok_or_else(|| {
2291                    Error::Codec(
2292                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2293                    )
2294                }),
2295            Self::Bytes(value) => Ok(json!({
2296                "$type": "bytes",
2297                "base64": BASE64.encode(value),
2298            })),
2299            Self::String(value) => Ok(Value::String(value)),
2300            Self::Array(values) => values
2301                .into_iter()
2302                .map(Self::into_json)
2303                .collect::<Result<Vec<_>>>()
2304                .map(Value::Array),
2305            Self::Map(values) => values
2306                .into_iter()
2307                .map(|(key, value)| Ok((key, value.into_json()?)))
2308                .collect::<Result<serde_json::Map<_, _>>>()
2309                .map(Value::Object),
2310        }
2311    }
2312
2313    fn into_serde_value(self) -> serde_value::Value {
2314        use serde_value::Value as SerdeValue;
2315
2316        match self {
2317            Self::Null => SerdeValue::Unit,
2318            Self::Boolean(value) => SerdeValue::Bool(value),
2319            Self::Long(value) => SerdeValue::I64(value),
2320            Self::Double(value) => SerdeValue::F64(value),
2321            Self::Bytes(value) => SerdeValue::Bytes(value),
2322            Self::String(value) => SerdeValue::String(value),
2323            Self::Array(values) => {
2324                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2325            }
2326            Self::Map(values) => SerdeValue::Map(
2327                values
2328                    .into_iter()
2329                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2330                    .collect(),
2331            ),
2332        }
2333    }
2334
2335    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2336        self.into_serde_value().deserialize_into().map_err(|error| {
2337            Error::Codec(format!(
2338                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2339            ))
2340        })
2341    }
2342}
2343
2344impl Serialize for AvroValue {
2345    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2346    where
2347        S: Serializer,
2348    {
2349        match self {
2350            Self::Null => serializer.serialize_unit(),
2351            Self::Boolean(value) => serializer.serialize_bool(*value),
2352            Self::Long(value) => serializer.serialize_i64(*value),
2353            Self::Double(value) => serializer.serialize_f64(*value),
2354            Self::Bytes(value) => serializer.serialize_bytes(value),
2355            Self::String(value) => serializer.serialize_str(value),
2356            Self::Array(values) => {
2357                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2358                for value in values {
2359                    sequence.serialize_element(value)?;
2360                }
2361                sequence.end()
2362            }
2363            Self::Map(values) => {
2364                let mut map = serializer.serialize_map(Some(values.len()))?;
2365                for (key, value) in values {
2366                    map.serialize_entry(key, value)?;
2367                }
2368                map.end()
2369            }
2370        }
2371    }
2372}
2373
2374pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2375    let datum = avro_value_to_datum(value)?;
2376    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2377        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2378    let mut bytes = Vec::with_capacity(datum.len() + 10);
2379    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2380    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2381    bytes.extend_from_slice(&datum);
2382    Ok(PayloadEnvelope {
2383        codec: DEFAULT_CODEC.to_string(),
2384        blob: BASE64.encode(bytes),
2385    })
2386}
2387
2388pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2389    if envelope.codec != DEFAULT_CODEC {
2390        return Err(unsupported_payload_codec(&envelope.codec));
2391    }
2392    decode_avro_value_blob(&envelope.blob)
2393}
2394
2395pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2396    let blob = match codec {
2397        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2398        other => return Err(unsupported_payload_codec(other)),
2399    };
2400
2401    Ok(PayloadEnvelope {
2402        codec: codec.to_string(),
2403        blob,
2404    })
2405}
2406
2407pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2408    match envelope.codec.as_str() {
2409        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2410        other => Err(unsupported_payload_codec(other)),
2411    }
2412}
2413
2414fn handler_type_error<T>(
2415    handler_kind: HandlerKind,
2416    handler_name: &str,
2417    value_kind: HandlerValueKind,
2418    message: impl Into<String>,
2419) -> Error {
2420    Error::HandlerType {
2421        handler_kind,
2422        handler_name: handler_name.to_string(),
2423        value_kind,
2424        rust_type: type_name::<T>(),
2425        message: message.into(),
2426    }
2427}
2428
2429fn decode_handler_input<T: DeserializeOwned>(
2430    arguments: AvroValue,
2431    handler_kind: HandlerKind,
2432    handler_name: &str,
2433) -> Result<T> {
2434    let argument = match arguments {
2435        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2436            arguments.pop().expect("one typed handler argument")
2437        }
2438        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2439        AvroValue::Array(arguments) => {
2440            return Err(handler_type_error::<T>(
2441                handler_kind,
2442                handler_name,
2443                HandlerValueKind::Input,
2444                format!(
2445                    "typed handlers accept one request value, but the task carried {} arguments",
2446                    arguments.len()
2447                ),
2448            ));
2449        }
2450        argument => argument,
2451    };
2452
2453    argument.deserialize().map_err(|error| {
2454        handler_type_error::<T>(
2455            handler_kind,
2456            handler_name,
2457            HandlerValueKind::Input,
2458            error.to_string(),
2459        )
2460    })
2461}
2462
2463fn decode_workflow_entry<T: DeserializeOwned>(
2464    arguments: AvroValue,
2465    workflow_type: &str,
2466) -> Result<T> {
2467    decode_handler_input(arguments, HandlerKind::Workflow, workflow_type).map_err(|_| {
2468        // Serde errors may contain recorded values. The entry refusal exposes
2469        // only the registered workflow and expected Rust type.
2470        handler_type_error::<T>(
2471            HandlerKind::Workflow,
2472            workflow_type,
2473            HandlerValueKind::Input,
2474            "workflow_entry_arguments_mismatch: restore compatible entry code before retrying the original task",
2475        )
2476    })
2477}
2478
2479fn encode_handler_result<T: Serialize>(
2480    result: &T,
2481    handler_kind: HandlerKind,
2482    handler_name: &str,
2483) -> Result<AvroValue> {
2484    AvroValue::from_serialize(result).map_err(|error| {
2485        handler_type_error::<T>(
2486            handler_kind,
2487            handler_name,
2488            HandlerValueKind::Result,
2489            error.to_string(),
2490        )
2491    })
2492}
2493
2494fn decode_handler_result<T: DeserializeOwned>(
2495    result: AvroValue,
2496    handler_kind: HandlerKind,
2497    handler_name: &str,
2498) -> Result<T> {
2499    result.deserialize().map_err(|error| {
2500        handler_type_error::<T>(
2501            handler_kind,
2502            handler_name,
2503            HandlerValueKind::Result,
2504            error.to_string(),
2505        )
2506    })
2507}
2508
2509#[cfg(test)]
2510fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2511    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2512}
2513
2514fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2515    validate_payload_codec(fallback_codec)?;
2516
2517    if value.is_null() {
2518        return Ok(Value::Null);
2519    }
2520
2521    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2522        return decode_blob(blob, codec);
2523    }
2524
2525    if let Some(blob) = value.as_str() {
2526        return decode_blob(blob, fallback_codec);
2527    }
2528
2529    Err(untagged_payload_value())
2530}
2531
2532fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2533    let envelope = match codec {
2534        DEFAULT_CODEC => encode_avro_value(value)?,
2535        other => return Err(unsupported_payload_codec(other)),
2536    };
2537    Ok(serde_json::to_value(envelope)?)
2538}
2539
2540fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2541    validate_payload_codec(fallback_codec)?;
2542
2543    if value.is_null() {
2544        return Ok(AvroValue::Null);
2545    }
2546
2547    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2548        validate_payload_codec(codec)?;
2549        return decode_avro_value_blob(blob);
2550    }
2551
2552    if let Some(blob) = value.as_str() {
2553        return match fallback_codec {
2554            DEFAULT_CODEC => decode_avro_value_blob(blob),
2555            other => Err(unsupported_payload_codec(other)),
2556        };
2557    }
2558
2559    Err(untagged_payload_value())
2560}
2561
2562fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2563    match value {
2564        AvroValue::Null => AvroValue::Array(Vec::new()),
2565        AvroValue::Array(_) => value,
2566        other => AvroValue::Array(vec![other]),
2567    }
2568}
2569
2570fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2571    match codec {
2572        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2573        other => Err(unsupported_payload_codec(other)),
2574    }
2575}
2576
2577fn validate_payload_codec(codec: &str) -> Result<()> {
2578    match codec {
2579        DEFAULT_CODEC => Ok(()),
2580        MISSING_TASK_PAYLOAD_CODEC => {
2581            Err(invalid_task_payload_codec("task payload_codec is missing"))
2582        }
2583        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2584        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2585            "task payload_codec must be a string",
2586        )),
2587        other => Err(unsupported_payload_codec(other)),
2588    }
2589}
2590
2591fn invalid_task_payload_codec(reason: &str) -> Error {
2592    Error::Codec(format!(
2593        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2594    ))
2595}
2596
2597fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2598    let Some(object) = value.as_object() else {
2599        return Ok(None);
2600    };
2601    if !object.contains_key("codec") && !object.contains_key("blob") {
2602        return Ok(None);
2603    }
2604
2605    let codec = object
2606        .get("codec")
2607        .and_then(Value::as_str)
2608        .ok_or_else(invalid_payload_envelope)?;
2609    validate_payload_codec(codec)?;
2610    let blob = object
2611        .get("blob")
2612        .and_then(Value::as_str)
2613        .ok_or_else(invalid_payload_envelope)?;
2614    Ok(Some((codec, blob)))
2615}
2616
2617fn invalid_payload_envelope() -> Error {
2618    Error::Codec(
2619        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2620            .to_string(),
2621    )
2622}
2623
2624fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2625    for command in commands {
2626        let Some(command) = command.as_object() else {
2627            continue;
2628        };
2629        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2630            continue;
2631        };
2632        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2633            continue;
2634        };
2635
2636        if let Some(codec) = command.get("payload_codec") {
2637            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2638            validate_payload_codec(codec)?;
2639        }
2640
2641        let payload = command
2642            .get(payload_field)
2643            .ok_or_else(invalid_payload_envelope)?;
2644        if runtime_payloads::Reference::parse(payload)?.is_none() {
2645            validate_outbound_payload_envelope(payload)?;
2646        }
2647    }
2648    Ok(())
2649}
2650
2651fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2652    if commands.iter().any(|command| {
2653        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2654            && command
2655                .get("condition_wait_occurrence_id")
2656                .and_then(Value::as_str)
2657                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2658    }) {
2659        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2660    } else if commands.iter().any(|command| {
2661        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2662            && command.get("attribute_types").is_some()
2663    }) {
2664        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2665    } else if commands
2666        .iter()
2667        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2668    {
2669        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2670    } else if commands
2671        .iter()
2672        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2673    {
2674        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2675    } else if commands.iter().any(|command| {
2676        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2677    }) {
2678        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2679    } else {
2680        MINIMUM_WORKER_PROTOCOL_VERSION
2681    }
2682}
2683
2684fn workflow_completion_protocol_version_with_message_streams(
2685    commands: &[Value],
2686    has_message_stream_metadata: bool,
2687) -> &'static str {
2688    let command_protocol = workflow_completion_protocol_version(commands);
2689    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2690        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2691    } else {
2692        command_protocol
2693    }
2694}
2695
2696fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2697    match command_type {
2698        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2699        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2700        "start_service_operation" => Some("request_payload"),
2701        "upsert_memo" => Some("entries"),
2702        _ => None,
2703    }
2704}
2705
2706fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2707    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2708        return Err(untagged_payload_value());
2709    };
2710    validate_payload_codec(codec)?;
2711    decode_avro_value_blob(blob)?;
2712    Ok(())
2713}
2714
2715fn unsupported_payload_codec(codec: &str) -> Error {
2716    Error::Codec(format!(
2717        "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"
2718    ))
2719}
2720
2721fn untagged_payload_value() -> Error {
2722    Error::Codec(
2723        "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"
2724            .to_string(),
2725    )
2726}
2727
2728fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2729    let bytes = BASE64.decode(blob).map_err(|err| {
2730        Error::Codec(format!(
2731            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2732        ))
2733    })?;
2734
2735    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2736        return Err(unsupported_payload_codec("json"));
2737    }
2738
2739    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2740        return Err(Error::Codec(
2741            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2742        ));
2743    }
2744
2745    let fingerprint: [u8; 8] = bytes[2..10]
2746        .try_into()
2747        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2748    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2749        return Err(Error::Codec(format!(
2750            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2751            fingerprint
2752                .iter()
2753                .map(|byte| format!("{byte:02x}"))
2754                .collect::<String>()
2755        )));
2756    }
2757
2758    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2759    // The current fingerprint selects the current immutable schema, so reader
2760    // resolution would only re-walk the same recursive union. Future retained
2761    // writer fingerprints supply a distinct reader schema in this branch.
2762    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2763    if datum_reader.truncated {
2764        return Err(Error::Codec(
2765            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2766        ));
2767    }
2768    let datum = datum.map_err(|err| {
2769        Error::Codec(format!(
2770            "invalid_payload_framing: malformed Avro Value datum: {err}"
2771        ))
2772    })?;
2773    if datum_reader.remaining() != 0 {
2774        return Err(Error::Codec(format!(
2775            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2776            datum_reader.remaining()
2777        )));
2778    }
2779    avro_value_from_datum(datum)
2780}
2781
2782struct StrictAvroDatumReader<'a> {
2783    bytes: &'a [u8],
2784    offset: usize,
2785    truncated: bool,
2786}
2787
2788impl<'a> StrictAvroDatumReader<'a> {
2789    fn new(bytes: &'a [u8]) -> Self {
2790        Self {
2791            bytes,
2792            offset: 0,
2793            truncated: false,
2794        }
2795    }
2796
2797    fn remaining(&self) -> usize {
2798        self.bytes.len() - self.offset
2799    }
2800}
2801
2802impl Read for StrictAvroDatumReader<'_> {
2803    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2804        let count = buffer.len().min(self.remaining());
2805        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2806        self.offset += count;
2807        if count < buffer.len() {
2808            self.truncated = true;
2809        }
2810
2811        Ok(count)
2812    }
2813}
2814
2815fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2816    let branch = match value {
2817        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2818        AvroValue::Boolean(value) => AvroDatum::Union(
2819            1,
2820            Box::new(AvroDatum::Record(vec![(
2821                "boolean".to_string(),
2822                AvroDatum::Boolean(*value),
2823            )])),
2824        ),
2825        AvroValue::Long(value) => AvroDatum::Union(
2826            2,
2827            Box::new(AvroDatum::Record(vec![(
2828                "long".to_string(),
2829                AvroDatum::Long(*value),
2830            )])),
2831        ),
2832        AvroValue::Double(value) => {
2833            if !value.is_finite() {
2834                return Err(Error::Codec(
2835                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2836                ));
2837            }
2838            AvroDatum::Union(
2839                3,
2840                Box::new(AvroDatum::Record(vec![(
2841                    "double".to_string(),
2842                    AvroDatum::Double(*value),
2843                )])),
2844            )
2845        }
2846        AvroValue::Bytes(value) => AvroDatum::Union(
2847            4,
2848            Box::new(AvroDatum::Record(vec![(
2849                "bytes".to_string(),
2850                AvroDatum::Bytes(value.clone()),
2851            )])),
2852        ),
2853        AvroValue::String(value) => AvroDatum::Union(
2854            5,
2855            Box::new(AvroDatum::Record(vec![(
2856                "string".to_string(),
2857                AvroDatum::String(value.clone()),
2858            )])),
2859        ),
2860        AvroValue::Array(values) => AvroDatum::Union(
2861            6,
2862            Box::new(AvroDatum::Record(vec![(
2863                "items".to_string(),
2864                AvroDatum::Array(
2865                    values
2866                        .iter()
2867                        .map(avro_value_to_datum)
2868                        .collect::<Result<Vec<_>>>()?,
2869                ),
2870            )])),
2871        ),
2872        AvroValue::Map(values) => AvroDatum::Union(
2873            7,
2874            Box::new(AvroDatum::Record(vec![(
2875                "entries".to_string(),
2876                AvroDatum::Array(
2877                    values
2878                        .iter()
2879                        .map(|(key, value)| {
2880                            Ok(AvroDatum::Record(vec![
2881                                ("key".to_string(), AvroDatum::String(key.clone())),
2882                                ("value".to_string(), avro_value_to_datum(value)?),
2883                            ]))
2884                        })
2885                        .collect::<Result<Vec<_>>>()?,
2886                ),
2887            )])),
2888        ),
2889    };
2890    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2891}
2892
2893fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2894    let AvroDatum::Record(mut outer) = datum else {
2895        return Err(Error::Codec(
2896            "invalid_payload_framing: datum is not a Value record".to_string(),
2897        ));
2898    };
2899    let (_, branch) = outer
2900        .pop()
2901        .filter(|(name, _)| name == "value")
2902        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2903    let AvroDatum::Union(_, branch) = branch else {
2904        return Err(Error::Codec(
2905            "invalid_payload_framing: invalid Value union".to_string(),
2906        ));
2907    };
2908    match *branch {
2909        AvroDatum::Null => Ok(AvroValue::Null),
2910        AvroDatum::Record(mut fields) => {
2911            let (name, value) = fields.pop().ok_or_else(|| {
2912                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2913            })?;
2914            match (name.as_str(), value) {
2915                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2916                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2917                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2918                    Ok(AvroValue::Double(value))
2919                }
2920                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2921                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2922                ("items", AvroDatum::Array(values)) => values
2923                    .into_iter()
2924                    .map(avro_value_from_datum)
2925                    .collect::<Result<Vec<_>>>()
2926                    .map(AvroValue::Array),
2927                ("entries", AvroDatum::Map(values)) => values
2928                    .into_iter()
2929                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2930                    .collect::<Result<BTreeMap<_, _>>>()
2931                    .map(AvroValue::Map),
2932                _ => Err(Error::Codec(
2933                    "invalid_payload_framing: unknown Value branch".to_string(),
2934                )),
2935            }
2936        }
2937        _ => Err(Error::Codec(
2938            "invalid_payload_framing: invalid Value branch".to_string(),
2939        )),
2940    }
2941}
2942
2943fn avro_value_schema() -> Result<&'static Schema> {
2944    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2945        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2946            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2947    }) {
2948        Ok(schema) => Ok(schema),
2949        Err(message) => Err(Error::Codec(message.clone())),
2950    }
2951}
2952
2953fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2954    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2955        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2956        // have the same block representation when each ordered array record
2957        // contains the map key followed by its value, so this encoding-only
2958        // adaptation lets the official encoder retain BTreeMap wire order.
2959        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2960            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2961        let entries_schema = schema
2962            .pointer_mut("/fields/0/type/7/fields/0/type")
2963            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2964        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2965            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2966        }
2967        *entries_schema = json!({
2968            "type": "array",
2969            "items": {
2970                "type": "record",
2971                "name": "MapEntry",
2972                "fields": [
2973                    {"name": "key", "type": "string"},
2974                    {"name": "value", "type": "Value"}
2975                ]
2976            }
2977        });
2978        Schema::parse_str(&schema.to_string())
2979            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2980    }) {
2981        Ok(schema) => Ok(schema),
2982        Err(message) => Err(Error::Codec(message.clone())),
2983    }
2984}
2985
2986#[derive(Clone, Debug)]
2987pub struct Client {
2988    metrics: metrics::Metrics,
2989    http: reqwest::Client,
2990    hydration_timeout: Duration,
2991    base_url: String,
2992    token: Option<String>,
2993    control_token: Option<String>,
2994    worker_token: Option<String>,
2995    namespace: String,
2996    max_external_payload_bytes: usize,
2997    worker_storage_admission: Option<WorkerStorageAdmission>,
2998    worker_task_slot: Option<Arc<worker_capacity::TaskSlotMarker>>,
2999    cooperative_worker_protocol: bool,
3000    worker_protocol_version: WorkerProtocolVersion,
3001    local_activities_enabled: bool,
3002    worker_sessions_enabled: bool,
3003    max_concurrent_worker_sessions: usize,
3004    worker_build_id: Option<String>,
3005    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
3006    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
3007    activity_lease_renewal_supported: Arc<AtomicBool>,
3008    activity_lease_authority: Option<Arc<activity_lease::authority::Authority>>,
3009    #[cfg(feature = "telemetry")]
3010    execution_telemetry: Option<telemetry::ExecutionTelemetry>,
3011    #[cfg(feature = "telemetry")]
3012    observability_context_supported: Arc<AtomicBool>,
3013}
3014
3015impl Client {
3016    /// Configure optional propagation. Actual cluster discovery must advertise
3017    /// the exact supported capability before any command carries context.
3018    #[cfg(feature = "telemetry")]
3019    pub fn with_telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
3020        self.execution_telemetry = Some(telemetry);
3021        self
3022    }
3023
3024    #[cfg(feature = "telemetry")]
3025    fn with_observability_context(&self, mut body: Value) -> Value {
3026        if self.observability_context_supported.load(Ordering::SeqCst) {
3027            if let Some(context) = self
3028                .execution_telemetry
3029                .as_ref()
3030                .and_then(|telemetry| telemetry.capture())
3031            {
3032                body["observability_context"] = context;
3033            }
3034        }
3035        body
3036    }
3037
3038    #[cfg(not(feature = "telemetry"))]
3039    fn with_observability_context(&self, body: Value) -> Value {
3040        body
3041    }
3042
3043    pub fn new(base_url: impl Into<String>) -> Result<Self> {
3044        Self::builder(base_url).build()
3045    }
3046
3047    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
3048        ClientBuilder {
3049            base_url: base_url.into(),
3050            token: None,
3051            control_token: None,
3052            worker_token: None,
3053            namespace: "default".to_string(),
3054            timeout: Duration::from_secs(60),
3055            max_external_payload_bytes: 64 * 1024 * 1024,
3056            worker_protocol_version: WorkerProtocolVersion::default(),
3057            additional_root_certificates: Vec::new(),
3058            metrics: metrics::Metrics::default(),
3059        }
3060    }
3061
3062    pub async fn health(&self) -> Result<Value> {
3063        self.request_json(
3064            reqwest::Method::GET,
3065            "/health",
3066            RequestProtocol::ControlPlane,
3067            Option::<&Value>::None,
3068        )
3069        .await
3070    }
3071
3072    pub async fn cluster_info(&self) -> Result<Value> {
3073        let discovery: Value = self
3074            .request_json(
3075                reqwest::Method::GET,
3076                "/cluster/info",
3077                RequestProtocol::ControlPlane,
3078                Option::<&Value>::None,
3079            )
3080            .await?;
3081        self.observe_activity_lease_capabilities(
3082            &discovery["worker_protocol"]["server_capabilities"],
3083        );
3084        Ok(discovery)
3085    }
3086
3087    pub async fn start_workflow<T: Serialize>(
3088        &self,
3089        workflow_type: &str,
3090        task_queue: &str,
3091        workflow_id: &str,
3092        input: T,
3093    ) -> Result<WorkflowHandle> {
3094        self.start_workflow_with_options(
3095            workflow_type,
3096            task_queue,
3097            workflow_id,
3098            WorkflowStartOptions::default(),
3099            input,
3100        )
3101        .await
3102    }
3103
3104    /// Start a workflow with explicit server-enforced execution and run
3105    /// deadlines.
3106    pub async fn start_workflow_with_options<T: Serialize>(
3107        &self,
3108        workflow_type: &str,
3109        task_queue: &str,
3110        workflow_id: &str,
3111        options: WorkflowStartOptions,
3112        input: T,
3113    ) -> Result<WorkflowHandle> {
3114        options.validate()?;
3115        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3116        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3117        let body = self.with_observability_context(json!({
3118            "workflow_id": workflow_id,
3119            "workflow_type": workflow_type,
3120            "task_queue": task_queue,
3121            "input": input_envelope,
3122            "execution_timeout_seconds": options.execution_timeout_seconds,
3123            "run_timeout_seconds": options.run_timeout_seconds
3124        }));
3125
3126        let data: Value = self
3127            .request_json(
3128                reqwest::Method::POST,
3129                "/workflows",
3130                RequestProtocol::ControlPlane,
3131                Some(&body),
3132            )
3133            .await?;
3134
3135        Ok(WorkflowHandle {
3136            client: self.clone(),
3137            workflow_id: data
3138                .get("workflow_id")
3139                .and_then(Value::as_str)
3140                .unwrap_or(workflow_id)
3141                .to_string(),
3142            run_id: data
3143                .get("run_id")
3144                .and_then(Value::as_str)
3145                .map(str::to_string),
3146            workflow_type: data
3147                .get("workflow_type")
3148                .and_then(Value::as_str)
3149                .unwrap_or(workflow_type)
3150                .to_string(),
3151        })
3152    }
3153
3154    /// Send a signal with an SDK-generated caller command key.
3155    ///
3156    /// The key is sent as the `request_id` body field and is present in the
3157    /// returned receipt's `request_id`. A Server that already retains the key
3158    /// for the same signal intent returns the original receipt with
3159    /// `retained: true`; a different intent is refused with
3160    /// [`Error::is_request_id_conflict`]. Choose the key yourself with
3161    /// [`Client::signal_workflow_with_request_id`] when the application must be
3162    /// able to retry the same logical signal after a transport failure.
3163    pub async fn signal_workflow<T: Serialize>(
3164        &self,
3165        workflow_id: &str,
3166        signal_name: &str,
3167        input: T,
3168    ) -> Result<Value> {
3169        let request_id = Self::generate_signal_request_id();
3170        self.signal_workflow_target(workflow_id, None, signal_name, input, &request_id)
3171            .await
3172    }
3173
3174    /// Send a signal with an explicit caller command key (1 to 255 Unicode characters).
3175    ///
3176    /// Resend the identical signal with the same key after an uncertain
3177    /// outcome: the Server returns the retained receipt instead of admitting a
3178    /// second signal, for as long as the retained run's details are kept.
3179    pub async fn signal_workflow_with_request_id<T: Serialize>(
3180        &self,
3181        workflow_id: &str,
3182        signal_name: &str,
3183        input: T,
3184        request_id: &str,
3185    ) -> Result<Value> {
3186        self.signal_workflow_target(workflow_id, None, signal_name, input, request_id)
3187            .await
3188    }
3189
3190    /// A fresh caller command key for one logical signal (`sdk-rust-signal-<uuid>`).
3191    ///
3192    /// Methods without an explicit key generate one of these per call. Obtain it
3193    /// up front and pass it to [`Client::signal_workflow_with_request_id`] so a
3194    /// transport failure does not lose the key needed for a safe retry.
3195    pub fn generate_signal_request_id() -> String {
3196        generated_request_id("signal")
3197    }
3198
3199    /// A fresh caller command key for one logical update (`sdk-rust-update-<uuid>`).
3200    ///
3201    /// [`Client::update_workflow`] generates one of these when `request_id` is
3202    /// `None`. Obtain it up front and pass it explicitly so a transport failure
3203    /// does not lose the key needed for a safe retry.
3204    pub fn generate_update_request_id() -> String {
3205        generated_request_id("update")
3206    }
3207
3208    /// Append one idempotently identified item to an instance-scoped input stream.
3209    pub async fn append_message_stream<T: Serialize>(
3210        &self,
3211        workflow_id: &str,
3212        stream_name: &str,
3213        message_id: &str,
3214        input: T,
3215    ) -> Result<Value> {
3216        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3217        let body = json!({
3218            "message_id": message_id,
3219            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
3220        });
3221        self.request_json(
3222            reqwest::Method::POST,
3223            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
3224            RequestProtocol::ControlPlane,
3225            Some(&body),
3226        )
3227        .await
3228    }
3229
3230    /// Signal only if `run_id` is still the current run for this instance,
3231    /// with an SDK-generated caller command key.
3232    pub async fn signal_workflow_run<T: Serialize>(
3233        &self,
3234        workflow_id: &str,
3235        run_id: &str,
3236        signal_name: &str,
3237        input: T,
3238    ) -> Result<Value> {
3239        let request_id = Self::generate_signal_request_id();
3240        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, &request_id)
3241            .await
3242    }
3243
3244    /// Signal only if `run_id` is still the current run for this instance,
3245    /// with an explicit caller command key (1 to 255 Unicode characters).
3246    ///
3247    /// The selected run is part of the signal's intent: retrying with the same
3248    /// key and a different run target is a `request_id_conflict` refusal.
3249    pub async fn signal_workflow_run_with_request_id<T: Serialize>(
3250        &self,
3251        workflow_id: &str,
3252        run_id: &str,
3253        signal_name: &str,
3254        input: T,
3255        request_id: &str,
3256    ) -> Result<Value> {
3257        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, request_id)
3258            .await
3259    }
3260
3261    async fn signal_workflow_target<T: Serialize>(
3262        &self,
3263        workflow_id: &str,
3264        run_id: Option<&str>,
3265        signal_name: &str,
3266        input: T,
3267        request_id: &str,
3268    ) -> Result<Value> {
3269        validate_user_signal_name(signal_name)?;
3270        validate_request_id(request_id)?;
3271        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3272        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3273        let body = self.with_observability_context(json!({
3274            "input": input_envelope,
3275            "request_id": request_id,
3276        }));
3277        let path = match run_id {
3278            Some(run_id) => {
3279                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
3280            }
3281            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
3282        };
3283        let receipt = self
3284            .request_json(
3285                reqwest::Method::POST,
3286                &path,
3287                RequestProtocol::ControlPlane,
3288                Some(&body),
3289            )
3290            .await?;
3291        Ok(with_request_id(receipt, request_id))
3292    }
3293
3294    /// Close the current run as cancelled immediately.
3295    ///
3296    /// Server revokes open tasks and timers without resuming workflow code for
3297    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3298    /// request on a supporting runtime and opted-in worker.
3299    pub async fn cancel_workflow(
3300        &self,
3301        workflow_id: &str,
3302        options: WorkflowCommandOptions,
3303    ) -> Result<WorkflowCommandResult> {
3304        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3305            .await
3306    }
3307
3308    /// Close the selected run as cancelled, only if `run_id` is still current.
3309    pub async fn cancel_workflow_run(
3310        &self,
3311        workflow_id: &str,
3312        run_id: &str,
3313        options: WorkflowCommandOptions,
3314    ) -> Result<WorkflowCommandResult> {
3315        self.workflow_command(
3316            workflow_id,
3317            Some(run_id),
3318            WorkflowCommandKind::Cancel,
3319            options,
3320        )
3321        .await
3322    }
3323
3324    /// Forcefully terminate the current run for an instance.
3325    pub async fn terminate_workflow(
3326        &self,
3327        workflow_id: &str,
3328        options: WorkflowCommandOptions,
3329    ) -> Result<WorkflowCommandResult> {
3330        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3331            .await
3332    }
3333
3334    /// Forcefully terminate only if `run_id` is still current.
3335    pub async fn terminate_workflow_run(
3336        &self,
3337        workflow_id: &str,
3338        run_id: &str,
3339        options: WorkflowCommandOptions,
3340    ) -> Result<WorkflowCommandResult> {
3341        self.workflow_command(
3342            workflow_id,
3343            Some(run_id),
3344            WorkflowCommandKind::Terminate,
3345            options,
3346        )
3347        .await
3348    }
3349
3350    /// Continue a failed run from its recorded activity failure boundary.
3351    pub async fn redrive_workflow_run(
3352        &self,
3353        workflow_id: &str,
3354        failed_run_id: &str,
3355        request_id: Option<&str>,
3356    ) -> Result<WorkflowRedriveResult> {
3357        let body = request_id
3358            .map(|id| json!({"request_id": id}))
3359            .unwrap_or_else(|| json!({}));
3360        let data: Value = self
3361            .request_json(
3362                reqwest::Method::POST,
3363                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
3364                RequestProtocol::ControlPlane,
3365                Some(&body),
3366            )
3367            .await?;
3368        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3369            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3370        {
3371            return Err(Error::Codec(
3372                "redrive response was not accepted".to_string(),
3373            ));
3374        }
3375        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3376            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3377        {
3378            return Err(Error::Codec(
3379                "redrive response does not match the requested source run".to_string(),
3380            ));
3381        }
3382        let run_id = data
3383            .get("run_id")
3384            .and_then(Value::as_str)
3385            .filter(|id| !id.is_empty() && *id != failed_run_id)
3386            .ok_or_else(|| {
3387                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3388            })?;
3389        let resume_step_sequence = data
3390            .get("resume_step_sequence")
3391            .and_then(Value::as_u64)
3392            .filter(|sequence| *sequence > 0)
3393            .ok_or_else(|| {
3394                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3395            })?;
3396        Ok(WorkflowRedriveResult {
3397            workflow_id: workflow_id.to_string(),
3398            source_run_id: failed_run_id.to_string(),
3399            run_id: run_id.to_string(),
3400            resume_step_sequence,
3401            raw: data,
3402        })
3403    }
3404
3405    async fn workflow_command(
3406        &self,
3407        workflow_id: &str,
3408        run_id: Option<&str>,
3409        command: WorkflowCommandKind,
3410        options: WorkflowCommandOptions,
3411    ) -> Result<WorkflowCommandResult> {
3412        #[cfg(feature = "telemetry")]
3413        let body = if command == WorkflowCommandKind::Cancel {
3414            self.with_observability_context(serde_json::to_value(&options)?)
3415        } else {
3416            serde_json::to_value(&options)?
3417        };
3418        #[cfg(not(feature = "telemetry"))]
3419        let body = &options;
3420        let path = match run_id {
3421            Some(run_id) => format!(
3422                "/workflows/{workflow_id}/runs/{run_id}/{}",
3423                command.as_str()
3424            ),
3425            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3426        };
3427        let data = match self
3428            .request_json(
3429                reqwest::Method::POST,
3430                &path,
3431                RequestProtocol::ControlPlane,
3432                Some(&body),
3433            )
3434            .await
3435        {
3436            Ok(data) => data,
3437            Err(Error::Http { status, body }) => {
3438                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3439                    command,
3440                    status,
3441                    body,
3442                    workflow_id,
3443                    run_id,
3444                )));
3445            }
3446            Err(error) => return Err(error),
3447        };
3448
3449        Ok(workflow_command_result(command, data, workflow_id, run_id))
3450    }
3451
3452    /// Execute a named, read-only query against a running or completed workflow.
3453    ///
3454    /// Arguments and results use the platform payload envelope. Server and
3455    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3456    /// reason, HTTP status, and original response body.
3457    pub async fn query_workflow<T: Serialize>(
3458        &self,
3459        workflow_id: &str,
3460        query_name: &str,
3461        input: T,
3462    ) -> Result<Value> {
3463        self.query_workflow_target(workflow_id, None, query_name, input)
3464            .await
3465    }
3466
3467    /// Query only if `run_id` is still current, preventing accidental retargeting.
3468    pub async fn query_workflow_run<T: Serialize>(
3469        &self,
3470        workflow_id: &str,
3471        run_id: &str,
3472        query_name: &str,
3473        input: T,
3474    ) -> Result<Value> {
3475        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3476            .await
3477    }
3478
3479    /// Query a workflow and return the lossless fixed Avro Value result.
3480    pub async fn query_workflow_avro_value<T: Serialize>(
3481        &self,
3482        workflow_id: &str,
3483        query_name: &str,
3484        input: T,
3485    ) -> Result<AvroValue> {
3486        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3487            .await
3488    }
3489
3490    /// Query a selected run and return the lossless fixed Avro Value result.
3491    pub async fn query_workflow_run_avro_value<T: Serialize>(
3492        &self,
3493        workflow_id: &str,
3494        run_id: &str,
3495        query_name: &str,
3496        input: T,
3497    ) -> Result<AvroValue> {
3498        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3499            .await
3500    }
3501
3502    async fn query_workflow_avro_value_target<T: Serialize>(
3503        &self,
3504        workflow_id: &str,
3505        run_id: Option<&str>,
3506        query_name: &str,
3507        input: T,
3508    ) -> Result<AvroValue> {
3509        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3510        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3511        let path = match run_id {
3512            Some(run_id) => {
3513                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3514            }
3515            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3516        };
3517        let response: Value = match self
3518            .request_json(
3519                reqwest::Method::POST,
3520                &path,
3521                RequestProtocol::ControlPlane,
3522                Some(&body),
3523            )
3524            .await
3525        {
3526            Ok(response) => response,
3527            Err(Error::Http { status, body }) => {
3528                return Err(Error::QueryFailed(query_failure(status, body)));
3529            }
3530            Err(error) => return Err(error),
3531        };
3532
3533        let envelope = response
3534            .get("result_envelope")
3535            .filter(|envelope| !envelope.is_null())
3536            .ok_or_else(|| {
3537                Error::Codec(
3538                    "missing_payload_envelope: typed query result requires result_envelope"
3539                        .to_string(),
3540                )
3541            })?;
3542        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3543    }
3544
3545    async fn query_workflow_target<T: Serialize>(
3546        &self,
3547        workflow_id: &str,
3548        run_id: Option<&str>,
3549        query_name: &str,
3550        input: T,
3551    ) -> Result<Value> {
3552        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3553        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3554        let body = json!({
3555            "input": input_envelope
3556        });
3557        let path = match run_id {
3558            Some(run_id) => {
3559                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3560            }
3561            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3562        };
3563        let response: Value = match self
3564            .request_json(
3565                reqwest::Method::POST,
3566                &path,
3567                RequestProtocol::ControlPlane,
3568                Some(&body),
3569            )
3570            .await
3571        {
3572            Ok(response) => response,
3573            Err(Error::Http { status, body }) => {
3574                return Err(Error::QueryFailed(query_failure(status, body)));
3575            }
3576            Err(error) => return Err(error),
3577        };
3578
3579        if let Some(envelope) = response
3580            .get("result_envelope")
3581            .filter(|envelope| !envelope.is_null())
3582        {
3583            return decode_wire_value(envelope, DEFAULT_CODEC);
3584        }
3585
3586        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3587    }
3588
3589    /// Send a synchronous update using fixed Avro Value arguments.
3590    ///
3591    /// `request_id` is the caller command key (1 to 255 Unicode characters), sent as the
3592    /// `request_id` body field; `None` generates one with
3593    /// [`Client::generate_update_request_id`]. A Server that already retains the
3594    /// key for the same update intent returns the original update's receipt and
3595    /// result instead of admitting a second update; a different intent is
3596    /// refused with [`Error::is_request_id_conflict`].
3597    pub async fn update_workflow<T: Serialize>(
3598        &self,
3599        workflow_id: &str,
3600        update_name: &str,
3601        input: T,
3602        request_id: Option<&str>,
3603    ) -> Result<Value> {
3604        let response = self
3605            .update_workflow_response(workflow_id, update_name, input, request_id)
3606            .await?;
3607        if let Some(envelope) = response
3608            .get("result_envelope")
3609            .filter(|envelope| !envelope.is_null())
3610        {
3611            return decode_wire_value(envelope, DEFAULT_CODEC);
3612        }
3613        Ok(response.get("result").cloned().unwrap_or(response))
3614    }
3615
3616    /// Send a synchronous update and retain a bytes-capable Avro result.
3617    pub async fn update_workflow_avro_value<T: Serialize>(
3618        &self,
3619        workflow_id: &str,
3620        update_name: &str,
3621        input: T,
3622        request_id: Option<&str>,
3623    ) -> Result<AvroValue> {
3624        let response = self
3625            .update_workflow_response(workflow_id, update_name, input, request_id)
3626            .await?;
3627        let envelope = response
3628            .get("result_envelope")
3629            .filter(|envelope| !envelope.is_null())
3630            .ok_or_else(|| {
3631                Error::Codec(
3632                    "missing_payload_envelope: typed update result requires result_envelope"
3633                        .to_string(),
3634                )
3635            })?;
3636        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3637    }
3638
3639    async fn update_workflow_response<T: Serialize>(
3640        &self,
3641        workflow_id: &str,
3642        update_name: &str,
3643        input: T,
3644        request_id: Option<&str>,
3645    ) -> Result<Value> {
3646        let request_id = match request_id {
3647            Some(request_id) => {
3648                validate_request_id(request_id)?;
3649                request_id.to_string()
3650            }
3651            None => Self::generate_update_request_id(),
3652        };
3653        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3654        let body = self.with_observability_context(json!({
3655            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3656            "wait_for": "completed",
3657            "request_id": request_id,
3658        }));
3659        let receipt = self
3660            .request_json(
3661                reqwest::Method::POST,
3662                &format!("/workflows/{workflow_id}/update/{update_name}"),
3663                RequestProtocol::ControlPlane,
3664                Some(&body),
3665            )
3666            .await?;
3667        Ok(with_request_id(receipt, &request_id))
3668    }
3669
3670    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3671        let path = format!("/workflows/{workflow_id}");
3672        let mut data: WorkflowDescription = self
3673            .request_json(
3674                reqwest::Method::GET,
3675                &path,
3676                RequestProtocol::ControlPlane,
3677                Option::<&Value>::None,
3678            )
3679            .await?;
3680        data.decode_payloads()?;
3681        Ok(data)
3682    }
3683
3684    /// Describe one selected run, including historical terminal runs.
3685    pub async fn describe_workflow_run(
3686        &self,
3687        workflow_id: &str,
3688        run_id: &str,
3689    ) -> Result<WorkflowDescription> {
3690        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3691        let mut data: WorkflowDescription = self
3692            .request_json(
3693                reqwest::Method::GET,
3694                &path,
3695                RequestProtocol::ControlPlane,
3696                Option::<&Value>::None,
3697            )
3698            .await?;
3699        data.decode_payloads()?;
3700        Ok(data)
3701    }
3702
3703    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3704        let mut path = format!(
3705            "/workflows/{}/runs/{}/streams",
3706            percent_encode_path_segment(workflow_id),
3707            percent_encode_path_segment(run_id),
3708        );
3709        if let Some(stream_name) = stream_name {
3710            path.push('/');
3711            path.push_str(&percent_encode_path_segment(stream_name));
3712        }
3713        path
3714    }
3715
3716    /// List the run-scoped output streams already opened by a workflow.
3717    pub async fn list_workflow_streams(
3718        &self,
3719        workflow_id: &str,
3720        run_id: &str,
3721    ) -> Result<Vec<WorkflowStreamDescription>> {
3722        let response: WorkflowStreamListResponse = self
3723            .request_json(
3724                reqwest::Method::GET,
3725                &Self::workflow_stream_path(workflow_id, run_id, None),
3726                RequestProtocol::ControlPlane,
3727                Option::<&Value>::None,
3728            )
3729            .await?;
3730        Ok(response.streams)
3731    }
3732
3733    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3734    pub async fn describe_workflow_stream(
3735        &self,
3736        workflow_id: &str,
3737        run_id: &str,
3738        stream_name: &str,
3739    ) -> Result<WorkflowStreamDescription> {
3740        let response: WorkflowStreamDescriptionResponse = self
3741            .request_json(
3742                reqwest::Method::GET,
3743                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3744                RequestProtocol::ControlPlane,
3745                Option::<&Value>::None,
3746            )
3747            .await?;
3748        Ok(response.stream)
3749    }
3750
3751    /// Read one bounded page beginning at a zero-based offset.
3752    ///
3753    /// Delivery is at least once: persist `next_offset` only after processing
3754    /// the page. The future is cancellation-safe; dropping it cancels the
3755    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3756    /// service contract.
3757    pub async fn subscribe_workflow_stream(
3758        &self,
3759        workflow_id: &str,
3760        run_id: &str,
3761        stream_name: &str,
3762        from_offset: u64,
3763        max_items: usize,
3764        wait: Duration,
3765    ) -> Result<WorkflowStreamPage> {
3766        let max_items = max_items.clamp(1, 500);
3767        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3768        let path = format!(
3769            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3770            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3771        );
3772        let response: WorkflowStreamPageResponse = self
3773            .request_json_with_timeout(
3774                reqwest::Method::GET,
3775                &path,
3776                RequestProtocol::ControlPlane,
3777                Option::<&Value>::None,
3778                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3779            )
3780            .await?;
3781
3782        let items = response
3783            .items
3784            .into_iter()
3785            .map(|raw| {
3786                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3787                let envelope = raw.get("payload").cloned();
3788                let payload = envelope
3789                    .as_ref()
3790                    .filter(|value| value.get("blob").is_some())
3791                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3792                    .transpose()?
3793                    .map(AvroValue::into_json)
3794                    .transpose()?;
3795                Ok(WorkflowStreamItem {
3796                    offset,
3797                    payload,
3798                    payload_envelope: envelope,
3799                    payload_reference: raw
3800                        .get("payload_reference")
3801                        .and_then(Value::as_str)
3802                        .map(str::to_string),
3803                    payload_codec: raw
3804                        .get("payload_codec")
3805                        .and_then(Value::as_str)
3806                        .map(str::to_string),
3807                    idempotency_key: raw
3808                        .get("idempotency_key")
3809                        .and_then(Value::as_str)
3810                        .map(str::to_string),
3811                    item_type: raw
3812                        .get("item_type")
3813                        .and_then(Value::as_str)
3814                        .map(str::to_string),
3815                    content_type: raw
3816                        .get("content_type")
3817                        .and_then(Value::as_str)
3818                        .map(str::to_string),
3819                    origin: raw
3820                        .get("origin")
3821                        .and_then(Value::as_str)
3822                        .map(str::to_string),
3823                    origin_reference: raw
3824                        .get("origin_reference")
3825                        .and_then(Value::as_str)
3826                        .map(str::to_string),
3827                    emitted_at: raw
3828                        .get("emitted_at")
3829                        .and_then(Value::as_str)
3830                        .map(str::to_string),
3831                    raw,
3832                })
3833            })
3834            .collect::<Result<Vec<_>>>()?;
3835        Ok(WorkflowStreamPage {
3836            stream: response.stream,
3837            items,
3838            next_offset: response.next_offset,
3839            terminal: response.terminal,
3840        })
3841    }
3842
3843    /// Append inline Avro envelopes or opaque external payload references.
3844    pub async fn append_workflow_stream(
3845        &self,
3846        workflow_id: &str,
3847        run_id: &str,
3848        stream_name: &str,
3849        items: &[WorkflowStreamAppendItem],
3850        max_pending_items: Option<u64>,
3851    ) -> Result<WorkflowStreamAppendResult> {
3852        if items.is_empty() {
3853            return Err(Error::Codec(
3854                "workflow_stream_items_empty: append requires at least one item".to_string(),
3855            ));
3856        }
3857        let mut body = json!({
3858            "items": items
3859                .iter()
3860                .map(|item| item.wire_value(None))
3861                .collect::<Vec<_>>(),
3862        });
3863        if let Some(max_pending_items) = max_pending_items {
3864            if max_pending_items == 0 {
3865                return Err(Error::Codec(
3866                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3867                        .to_string(),
3868                ));
3869            }
3870            body["max_pending_items"] = json!(max_pending_items);
3871        }
3872        let response: WorkflowStreamAppendResponse = self
3873            .request_json(
3874                reqwest::Method::POST,
3875                &format!(
3876                    "{}/items",
3877                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3878                ),
3879                RequestProtocol::ControlPlane,
3880                Some(&body),
3881            )
3882            .await?;
3883        Ok(WorkflowStreamAppendResult {
3884            stream: response.stream,
3885            accepted_offsets: response.accepted_offsets,
3886            accepted: response.accepted,
3887            deduped: response.deduped,
3888        })
3889    }
3890
3891    /// Close a stream, or mark it errored when `error_reason` is supplied.
3892    pub async fn close_workflow_stream(
3893        &self,
3894        workflow_id: &str,
3895        run_id: &str,
3896        stream_name: &str,
3897        error_reason: Option<&str>,
3898        retention_seconds: Option<u64>,
3899    ) -> Result<WorkflowStreamDescription> {
3900        let mut body = json!({});
3901        if let Some(error_reason) = error_reason {
3902            body["error_reason"] = json!(error_reason);
3903        }
3904        if let Some(retention_seconds) = retention_seconds {
3905            if retention_seconds == 0 {
3906                return Err(Error::Codec(
3907                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3908                        .to_string(),
3909                ));
3910            }
3911            body["retention_seconds"] = json!(retention_seconds);
3912        }
3913        let response: WorkflowStreamDescriptionResponse = self
3914            .request_json(
3915                reqwest::Method::POST,
3916                &format!(
3917                    "{}/close",
3918                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3919                ),
3920                RequestProtocol::ControlPlane,
3921                Some(&body),
3922            )
3923            .await?;
3924        Ok(response.stream)
3925    }
3926
3927    pub async fn register_worker(
3928        &self,
3929        worker_id: &str,
3930        task_queue: &str,
3931        supported_workflow_types: Vec<String>,
3932        supported_activity_types: Vec<String>,
3933        max_concurrent_workflow_tasks: usize,
3934        max_concurrent_activity_tasks: usize,
3935    ) -> Result<RegisterWorkerResponse> {
3936        self.register_worker_with_capabilities(
3937            worker_id,
3938            task_queue,
3939            supported_workflow_types,
3940            supported_activity_types,
3941            max_concurrent_workflow_tasks,
3942            max_concurrent_activity_tasks,
3943            Vec::new(),
3944        )
3945        .await
3946    }
3947
3948    /// Register a worker and explicitly advertise additive worker capabilities.
3949    pub async fn register_worker_with_capabilities(
3950        &self,
3951        worker_id: &str,
3952        task_queue: &str,
3953        supported_workflow_types: Vec<String>,
3954        supported_activity_types: Vec<String>,
3955        max_concurrent_workflow_tasks: usize,
3956        max_concurrent_activity_tasks: usize,
3957        capabilities: Vec<String>,
3958    ) -> Result<RegisterWorkerResponse> {
3959        self.register_worker_with_command_contracts(
3960            worker_id,
3961            task_queue,
3962            supported_workflow_types,
3963            supported_activity_types,
3964            max_concurrent_workflow_tasks,
3965            max_concurrent_activity_tasks,
3966            capabilities,
3967            Value::Object(serde_json::Map::new()),
3968        )
3969        .await
3970    }
3971
3972    /// Register a worker and advertise its named query and update handlers.
3973    ///
3974    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3975    /// so a workflow contract with a non-empty or malformed
3976    /// `update_validators` declaration returns
3977    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3978    #[allow(clippy::too_many_arguments)]
3979    pub async fn register_worker_with_command_contracts(
3980        &self,
3981        worker_id: &str,
3982        task_queue: &str,
3983        supported_workflow_types: Vec<String>,
3984        supported_activity_types: Vec<String>,
3985        max_concurrent_workflow_tasks: usize,
3986        max_concurrent_activity_tasks: usize,
3987        capabilities: Vec<String>,
3988        workflow_command_contracts: Value,
3989    ) -> Result<RegisterWorkerResponse> {
3990        self.register_worker_with_definition_fingerprints(
3991            worker_id,
3992            task_queue,
3993            supported_workflow_types,
3994            supported_activity_types,
3995            max_concurrent_workflow_tasks,
3996            max_concurrent_activity_tasks,
3997            capabilities,
3998            workflow_command_contracts,
3999            None,
4000        )
4001        .await
4002    }
4003
4004    #[allow(clippy::too_many_arguments)]
4005    async fn register_worker_with_definition_fingerprints(
4006        &self,
4007        worker_id: &str,
4008        task_queue: &str,
4009        supported_workflow_types: Vec<String>,
4010        supported_activity_types: Vec<String>,
4011        max_concurrent_workflow_tasks: usize,
4012        max_concurrent_activity_tasks: usize,
4013        capabilities: Vec<String>,
4014        workflow_command_contracts: Value,
4015        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
4016    ) -> Result<RegisterWorkerResponse> {
4017        if let Some(contracts) = workflow_command_contracts.as_object() {
4018            for (workflow_type, contract) in contracts {
4019                let Some(update_validators) = contract.get("update_validators") else {
4020                    continue;
4021                };
4022                if !update_validators
4023                    .as_array()
4024                    .is_some_and(|validators| validators.is_empty())
4025                {
4026                    return Err(Error::UnsupportedUpdateValidators {
4027                        workflow_type: workflow_type.clone(),
4028                    });
4029                }
4030            }
4031        }
4032
4033        let mut body = json!({
4034            "worker_id": worker_id,
4035            "task_queue": task_queue,
4036            "runtime": "rust",
4037            "sdk_version": SDK_VERSION,
4038            "supported_workflow_types": supported_workflow_types,
4039            "supported_activity_types": supported_activity_types,
4040            "capabilities": capabilities,
4041            "capability_manifest": portable_worker_affinity_capability_manifest(),
4042            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
4043            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
4044        });
4045        if capabilities
4046            .iter()
4047            .any(|capability| capability == "nexus_cooperative_cancellation")
4048        {
4049            body["capability_manifest"]["nexus_cooperative_cancellation"] = json!({
4050                "supported":true, "minimum_protocol_version":"1.20",
4051                "implementation":"owned_workflow_run_canonical_delivery", "binding_kinds":["workflow_run"],
4052            });
4053        }
4054        if let Some(build_id) = &self.worker_build_id {
4055            if build_id.is_empty() || build_id.len() > 255 {
4056                return Err(Error::WorkerLoop(
4057                    "worker build ID must contain 1 to 255 bytes".into(),
4058                ));
4059            }
4060            body["build_id"] = json!(build_id);
4061        }
4062        if self.sticky_cache.is_some() {
4063            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
4064                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
4065                "implementation":"bounded_durable_history_cache"});
4066        }
4067        if self.local_activities_enabled {
4068            body["capability_manifest"]["local_activities"] = json!({"supported":true,
4069                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4070        }
4071        if self.worker_sessions_enabled {
4072            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
4073                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4074            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
4075        }
4076        if workflow_command_contracts
4077            .as_object()
4078            .is_some_and(|contracts| !contracts.is_empty())
4079        {
4080            body["workflow_command_contracts"] = workflow_command_contracts;
4081        }
4082        if let Some(fingerprints) = workflow_definition_fingerprints {
4083            body["workflow_definition_fingerprints"] = json!(fingerprints);
4084        }
4085
4086        let response: Value = self
4087            .request_json(
4088                reqwest::Method::POST,
4089                "/worker/register",
4090                RequestProtocol::DefaultWorker,
4091                Some(&body),
4092            )
4093            .await?;
4094        if response["registered"] == true && response["worker_id"].as_str() == Some(worker_id) {
4095            self.observe_activity_lease_capabilities(&response["server_capabilities"]);
4096        }
4097        if self.sticky_cache.is_some() {
4098            self.confirm_sticky_registration(&response, worker_id, task_queue)
4099                .await?;
4100        }
4101        if self.local_activities_enabled || self.worker_sessions_enabled {
4102            let compatible = response["registered"].as_bool() == Some(true)
4103                && response["worker_id"].as_str() == Some(worker_id)
4104                && response["namespace"].as_str() == Some(self.namespace.as_str())
4105                && response["task_queue"].as_str() == Some(task_queue)
4106                && response["protocol_version"]
4107                    .as_str()
4108                    .and_then(|version| version.strip_prefix("1."))
4109                    .and_then(|minor| minor.parse::<u64>().ok())
4110                    .is_some_and(|minor| minor >= 18)
4111                && (!self.local_activities_enabled
4112                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
4113                        == Some(true))
4114                && (!self.worker_sessions_enabled
4115                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
4116                        == Some(true)
4117                        && response["capabilities"].as_array().is_some_and(|accepted| {
4118                            capabilities.iter().all(|capability| {
4119                                accepted
4120                                    .iter()
4121                                    .any(|value| value.as_str() == Some(capability.as_str()))
4122                            })
4123                        })));
4124            if !compatible {
4125                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
4126                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
4127                } else {
4128                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
4129                });
4130                if response["registered"] == true
4131                    && response["worker_id"].as_str() == Some(worker_id)
4132                {
4133                    if let Err(deregistration) =
4134                        self.deregister_worker_registration(worker_id).await
4135                    {
4136                        return Err(Error::WorkerShutdown {
4137                            primary: Box::new(error),
4138                            deregistration: Box::new(deregistration),
4139                        });
4140                    }
4141                }
4142                return Err(error);
4143            }
4144        }
4145        if self.cooperative_worker_protocol {
4146            let compatible = response["registered"].as_bool() == Some(true)
4147                && response["worker_id"].as_str() == Some(worker_id)
4148                && response["namespace"].as_str() == Some(self.namespace.as_str())
4149                && response["task_queue"].as_str() == Some(task_queue)
4150                && response["protocol_version"]
4151                    .as_str()
4152                    .is_some_and(cooperative_cancellation::supports_protocol)
4153                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
4154                    == Some(true)
4155                && (!capabilities
4156                    .iter()
4157                    .any(|capability| capability == "nexus_cooperative_cancellation")
4158                    || nexus::installed_cooperation(&response["server_capabilities"]))
4159                && response["capabilities"].as_array().is_some_and(|accepted| {
4160                    capabilities.iter().all(|capability| {
4161                        accepted
4162                            .iter()
4163                            .any(|value| value.as_str() == Some(capability.as_str()))
4164                    })
4165                });
4166            if !compatible {
4167                let error = Error::CooperativeCancellationUnavailable(
4168                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
4169                );
4170                if response["registered"].as_bool() == Some(true)
4171                    && response["worker_id"].as_str() == Some(worker_id)
4172                {
4173                    if let Err(deregistration) =
4174                        self.deregister_worker_registration(worker_id).await
4175                    {
4176                        return Err(Error::WorkerShutdown {
4177                            primary: Box::new(error),
4178                            deregistration: Box::new(deregistration),
4179                        });
4180                    }
4181                }
4182                return Err(error);
4183            }
4184        }
4185        Ok(serde_json::from_value(response)?)
4186    }
4187
4188    /// Gracefully remove one worker's registration through the worker plane.
4189    ///
4190    /// This operation is separate from operator-facing worker management. It
4191    /// uses worker-protocol authentication and returns the server's lease
4192    /// recovery result.
4193    pub async fn deregister_worker_registration(
4194        &self,
4195        worker_id: &str,
4196    ) -> Result<WorkerDeregistrationEnvelope> {
4197        let path = format!(
4198            "/worker/registrations/{}",
4199            percent_encode_path_segment(worker_id)
4200        );
4201        self.request_json(
4202            reqwest::Method::DELETE,
4203            &path,
4204            RequestProtocol::DefaultWorker,
4205            Option::<&Value>::None,
4206        )
4207        .await
4208    }
4209
4210    /// Long-poll for an ephemeral, read-only workflow query task.
4211    pub async fn poll_query_task(
4212        &self,
4213        worker_id: &str,
4214        task_queue: &str,
4215        timeout: Duration,
4216    ) -> Result<Option<QueryTask>> {
4217        Ok(self
4218            .poll_query_task_response(worker_id, task_queue, timeout)
4219            .await?
4220            .task)
4221    }
4222
4223    /// Poll a query task while preserving server stop and drain metadata.
4224    pub async fn poll_query_task_response(
4225        &self,
4226        worker_id: &str,
4227        task_queue: &str,
4228        timeout: Duration,
4229    ) -> Result<PollQueryTaskResponse> {
4230        let poll_request_id = unique_request_id("rust-query-poll");
4231        self.poll_query_task_response_with_request_id(
4232            worker_id,
4233            task_queue,
4234            timeout,
4235            &poll_request_id,
4236            1,
4237        )
4238        .await
4239    }
4240
4241    async fn poll_query_task_response_with_request_id(
4242        &self,
4243        worker_id: &str,
4244        task_queue: &str,
4245        timeout: Duration,
4246        poll_request_id: &str,
4247        transport_retries: usize,
4248    ) -> Result<PollQueryTaskResponse> {
4249        let timeout_seconds = long_poll_timeout_seconds(timeout);
4250        let body = json!({
4251            "worker_id": worker_id,
4252            "task_queue": task_queue,
4253            "poll_request_id": poll_request_id,
4254            "timeout_seconds": timeout_seconds,
4255        });
4256        self.poll_request_json(
4257            "/worker/query-tasks/poll",
4258            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4259            &body,
4260            timeout + Duration::from_secs(5),
4261            transport_retries,
4262        )
4263        .await
4264    }
4265
4266    /// Complete a query task without appending workflow history.
4267    pub async fn complete_query_task<T: Serialize>(
4268        &self,
4269        query_task_id: &str,
4270        lease_owner: &str,
4271        query_task_attempt: u64,
4272        result: T,
4273        codec: &str,
4274    ) -> Result<Value> {
4275        let typed_result = AvroValue::from_serialize(&result)?;
4276        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
4277        self.complete_query_task_with_envelope(
4278            query_task_id,
4279            lease_owner,
4280            query_task_attempt,
4281            typed_result.into_json()?,
4282            result_envelope,
4283        )
4284        .await
4285    }
4286
4287    async fn complete_query_task_with_envelope(
4288        &self,
4289        query_task_id: &str,
4290        lease_owner: &str,
4291        query_task_attempt: u64,
4292        result: Value,
4293        result_envelope: Value,
4294    ) -> Result<Value> {
4295        let body = json!({
4296            "lease_owner": lease_owner,
4297            "query_task_attempt": query_task_attempt,
4298            "result": result,
4299            "result_envelope": result_envelope,
4300        });
4301        let path = format!("/worker/query-tasks/{query_task_id}/complete");
4302        let response = self
4303            .request_json(
4304                reqwest::Method::POST,
4305                &path,
4306                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4307                Some(&body),
4308            )
4309            .await;
4310        query_task_response(response)
4311    }
4312
4313    /// Report a stable machine-readable query-task failure.
4314    pub async fn fail_query_task(
4315        &self,
4316        query_task_id: &str,
4317        lease_owner: &str,
4318        query_task_attempt: u64,
4319        message: impl Into<String>,
4320        reason: impl Into<String>,
4321        failure_type: impl Into<String>,
4322    ) -> Result<Value> {
4323        let body = json!({
4324            "lease_owner": lease_owner,
4325            "query_task_attempt": query_task_attempt,
4326            "failure": {
4327                "message": message.into(),
4328                "reason": reason.into(),
4329                "type": failure_type.into(),
4330            }
4331        });
4332        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4333        let response = self
4334            .request_json(
4335                reqwest::Method::POST,
4336                &path,
4337                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4338                Some(&body),
4339            )
4340            .await;
4341        query_task_response(response)
4342    }
4343
4344    pub async fn heartbeat_worker(
4345        &self,
4346        worker_id: &str,
4347        workflow_available: usize,
4348        activity_available: usize,
4349    ) -> Result<Value> {
4350        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4351            .await
4352    }
4353
4354    async fn heartbeat_worker_with_sessions(
4355        &self,
4356        worker_id: &str,
4357        workflow_available: usize,
4358        activity_available: usize,
4359        session_available: Option<usize>,
4360    ) -> Result<Value> {
4361        let mut body = json!({
4362            "worker_id": worker_id,
4363            "task_slots": {
4364                "workflow_available": workflow_available,
4365                "activity_available": activity_available
4366            },
4367            "process_metrics": {
4368                "process_id": std::process::id(),
4369                "process_uptime_seconds": 0
4370            }
4371        });
4372
4373        if let Some(available) = session_available {
4374            body["task_slots"]["session_available"] = json!(available);
4375        }
4376
4377        self.request_json(
4378            reqwest::Method::POST,
4379            "/worker/heartbeat",
4380            RequestProtocol::DefaultWorker,
4381            Some(&body),
4382        )
4383        .await
4384    }
4385
4386    pub async fn poll_workflow_task(
4387        &self,
4388        worker_id: &str,
4389        task_queue: &str,
4390        timeout: Duration,
4391    ) -> Result<Option<WorkflowTask>> {
4392        Ok(self
4393            .poll_workflow_task_response(worker_id, task_queue, timeout)
4394            .await?
4395            .task)
4396    }
4397
4398    pub async fn poll_workflow_task_response(
4399        &self,
4400        worker_id: &str,
4401        task_queue: &str,
4402        timeout: Duration,
4403    ) -> Result<PollWorkflowTaskResponse> {
4404        let poll_request_id = unique_request_id("rust-workflow-poll");
4405        self.poll_workflow_task_response_with_request_id(
4406            worker_id,
4407            task_queue,
4408            timeout,
4409            &poll_request_id,
4410            1,
4411        )
4412        .await
4413    }
4414
4415    async fn poll_workflow_task_response_with_request_id(
4416        &self,
4417        worker_id: &str,
4418        task_queue: &str,
4419        timeout: Duration,
4420        poll_request_id: &str,
4421        transport_retries: usize,
4422    ) -> Result<PollWorkflowTaskResponse> {
4423        let body = json!({
4424            "worker_id": worker_id,
4425            "task_queue": task_queue,
4426            "poll_request_id": poll_request_id,
4427            "timeout_seconds": long_poll_timeout_seconds(timeout),
4428            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4429        });
4430        let mut wire: Value = self
4431            .poll_request_json_unresolved(
4432                "/worker/workflow-tasks/poll",
4433                RequestProtocol::DefaultWorker,
4434                &body,
4435                timeout + Duration::from_secs(5),
4436                transport_retries,
4437            )
4438            .await?;
4439        let claim =
4440            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4441        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4442            self.resolve_runtime_payloads(
4443                &mut wire,
4444                "/worker/workflow-tasks/poll",
4445                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4446            )
4447            .await?;
4448            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4449            if let Some(task) = data.task.as_mut() {
4450                self.fetch_remaining_workflow_history(worker_id, task)
4451                    .await?;
4452            }
4453            Ok(data)
4454        })
4455        .await?;
4456        Ok(data)
4457    }
4458
4459    async fn fetch_remaining_workflow_history(
4460        &self,
4461        worker_id: &str,
4462        task: &mut WorkflowTask,
4463    ) -> Result<()> {
4464        let mut next_token = task.next_history_page_token.clone();
4465        let mut seen = BTreeSet::new();
4466
4467        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4468            if seen.len() >= 128 || !seen.insert(token.clone()) {
4469                return Err(Error::Codec(
4470                    "workflow history pagination exceeded its page bound or repeated a token"
4471                        .into(),
4472                ));
4473            }
4474            let lease_owner = task
4475                .lease_owner
4476                .clone()
4477                .unwrap_or_else(|| worker_id.to_string());
4478            let page = self
4479                .workflow_task_history_page(
4480                    &task.task_id,
4481                    &lease_owner,
4482                    task.workflow_task_attempt,
4483                    &token,
4484                )
4485                .await?;
4486
4487            task.append_history_page(page);
4488
4489            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4490                return Err(Error::Codec(
4491                    "workflow history pagination returned the same page token".to_string(),
4492                ));
4493            }
4494
4495            next_token = task.next_history_page_token.clone();
4496        }
4497
4498        Ok(())
4499    }
4500
4501    async fn workflow_task_history_page(
4502        &self,
4503        task_id: &str,
4504        lease_owner: &str,
4505        workflow_task_attempt: u64,
4506        next_history_page_token: &str,
4507    ) -> Result<WorkflowTaskHistoryPage> {
4508        let body = json!({
4509            "lease_owner": lease_owner,
4510            "workflow_task_attempt": workflow_task_attempt,
4511            "next_history_page_token": next_history_page_token
4512        });
4513        let path = format!("/worker/workflow-tasks/{task_id}/history");
4514
4515        self.request_json(
4516            reqwest::Method::POST,
4517            &path,
4518            RequestProtocol::DefaultWorker,
4519            Some(&body),
4520        )
4521        .await
4522    }
4523
4524    pub async fn complete_workflow_task(
4525        &self,
4526        task_id: &str,
4527        lease_owner: &str,
4528        workflow_task_attempt: u64,
4529        commands: Vec<Value>,
4530    ) -> Result<Value> {
4531        self.complete_workflow_task_with_message_streams(
4532            task_id,
4533            lease_owner,
4534            workflow_task_attempt,
4535            commands,
4536            Vec::new(),
4537            Vec::new(),
4538            None,
4539        )
4540        .await
4541    }
4542
4543    #[allow(clippy::too_many_arguments)]
4544    async fn complete_workflow_task_with_message_streams(
4545        &self,
4546        task_id: &str,
4547        lease_owner: &str,
4548        workflow_task_attempt: u64,
4549        commands: Vec<Value>,
4550        message_stream_cursors: Vec<Value>,
4551        message_stream_waits: Vec<Value>,
4552        sticky_cache: Option<Value>,
4553    ) -> Result<Value> {
4554        validate_workflow_task_commands(&commands)?;
4555        let has_message_stream_metadata =
4556            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4557        if has_message_stream_metadata
4558            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4559        {
4560            return Err(Error::Codec(
4561                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4562                    .to_string(),
4563            ));
4564        }
4565        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4566            &commands,
4567            has_message_stream_metadata,
4568        );
4569        let protocol_version = if sticky_cache.is_some()
4570            && protocol_version
4571                .strip_prefix("1.")
4572                .and_then(|minor| minor.parse::<u64>().ok())
4573                .is_some_and(|minor| minor < 18)
4574        {
4575            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4576        } else {
4577            protocol_version
4578        };
4579        let mut body = json!({
4580            "lease_owner": lease_owner,
4581            "workflow_task_attempt": workflow_task_attempt,
4582            "commands": commands
4583        });
4584        #[cfg(feature = "telemetry")]
4585        if self.observability_context_supported.load(Ordering::SeqCst)
4586            && opentelemetry::Context::current()
4587                .get::<telemetry::ExecutionFields>()
4588                .is_some()
4589        {
4590            if let Some(commands) = body["commands"].as_array_mut() {
4591                for command in commands {
4592                    if command.get("observability_context").is_none()
4593                        && matches!(
4594                            command["type"].as_str(),
4595                            Some("start_child_workflow" | "continue_as_new")
4596                        )
4597                    {
4598                        *command = self.with_observability_context(command.take());
4599                    }
4600                }
4601            }
4602        }
4603        if !message_stream_cursors.is_empty() {
4604            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4605        }
4606        if !message_stream_waits.is_empty() {
4607            body["message_stream_waits"] = Value::Array(message_stream_waits);
4608        }
4609        if let Some(claim) = sticky_cache {
4610            body["sticky_cache"] = claim;
4611        }
4612        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4613        self.request_json(
4614            reqwest::Method::POST,
4615            &path,
4616            RequestProtocol::Worker(protocol_version),
4617            Some(&body),
4618        )
4619        .await
4620    }
4621
4622    pub async fn fail_workflow_task(
4623        &self,
4624        task_id: &str,
4625        lease_owner: &str,
4626        workflow_task_attempt: u64,
4627        message: impl Into<String>,
4628    ) -> Result<Value> {
4629        self.fail_workflow_task_with_type(
4630            task_id,
4631            lease_owner,
4632            workflow_task_attempt,
4633            message,
4634            "RustWorkflowTaskFailure",
4635        )
4636        .await
4637    }
4638
4639    async fn fail_workflow_task_with_type(
4640        &self,
4641        task_id: &str,
4642        lease_owner: &str,
4643        workflow_task_attempt: u64,
4644        message: impl Into<String>,
4645        failure_type: &str,
4646    ) -> Result<Value> {
4647        self.fail_workflow_task_with_failure(
4648            task_id,
4649            lease_owner,
4650            workflow_task_attempt,
4651            json!({"message": message.into(), "type": failure_type}),
4652        )
4653        .await
4654    }
4655
4656    async fn fail_workflow_task_with_failure(
4657        &self,
4658        task_id: &str,
4659        lease_owner: &str,
4660        workflow_task_attempt: u64,
4661        failure: Value,
4662    ) -> Result<Value> {
4663        let body = json!({
4664            "lease_owner": lease_owner,
4665            "workflow_task_attempt": workflow_task_attempt,
4666            "failure": failure,
4667        });
4668        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4669        self.request_json(
4670            reqwest::Method::POST,
4671            &path,
4672            RequestProtocol::DefaultWorker,
4673            Some(&body),
4674        )
4675        .await
4676    }
4677
4678    pub async fn poll_activity_task(
4679        &self,
4680        worker_id: &str,
4681        task_queue: &str,
4682        timeout: Duration,
4683    ) -> Result<Option<ActivityTask>> {
4684        Ok(self
4685            .poll_activity_task_response(worker_id, task_queue, timeout)
4686            .await?
4687            .task)
4688    }
4689
4690    /// Poll an activity task while preserving server stop and drain metadata.
4691    pub async fn poll_activity_task_response(
4692        &self,
4693        worker_id: &str,
4694        task_queue: &str,
4695        timeout: Duration,
4696    ) -> Result<PollActivityTaskResponse> {
4697        let poll_request_id = unique_request_id("rust-activity-poll");
4698        self.poll_activity_task_response_with_request_id(
4699            worker_id,
4700            task_queue,
4701            timeout,
4702            &poll_request_id,
4703            1,
4704        )
4705        .await
4706        .map(worker_session::SessionPollResponse::ordinary)
4707    }
4708
4709    async fn poll_activity_task_response_with_request_id(
4710        &self,
4711        worker_id: &str,
4712        task_queue: &str,
4713        timeout: Duration,
4714        poll_request_id: &str,
4715        transport_retries: usize,
4716    ) -> Result<worker_session::SessionPollResponse> {
4717        let body = json!({
4718            "worker_id": worker_id,
4719            "task_queue": task_queue,
4720            "poll_request_id": poll_request_id,
4721            "timeout_seconds": long_poll_timeout_seconds(timeout),
4722        });
4723        let mut wire: Value = self
4724            .poll_request_json_unresolved(
4725                "/worker/activity-tasks/poll",
4726                RequestProtocol::DefaultWorker,
4727                &body,
4728                timeout + Duration::from_secs(5),
4729                transport_retries,
4730            )
4731            .await?;
4732        let lease =
4733            activity_lease::authority::Lease::confirm(self, &wire, worker_id, task_queue).await?;
4734        let observed = self.with_activity_lease_authority(
4735            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
4736        );
4737        let claim = if lease.is_none() {
4738            activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?
4739        } else {
4740            None
4741        };
4742        let loading = async {
4743            observed
4744                .resolve_runtime_payloads(
4745                    &mut wire,
4746                    "/worker/activity-tasks/poll",
4747                    RequestProtocol::DefaultWorker,
4748                )
4749                .await?;
4750            if let Some(lease) = &lease {
4751                lease
4752                    .authority
4753                    .refresh_delivery_session(&mut wire["task"])?;
4754            }
4755            Ok(serde_json::from_value(wire)?)
4756        };
4757        let mut data: worker_session::SessionPollResponse = match lease.as_ref() {
4758            Some(lease) => lease.authority.protect(loading).await?,
4759            None => {
4760                activity_hydration::HydrationClaim::protect(claim.as_ref(), self, loading).await?
4761            }
4762        };
4763        if let Some(task) = data.task.as_mut() {
4764            task.hydration_claim = claim;
4765            task.activity_lease = lease;
4766        }
4767        Ok(data)
4768    }
4769
4770    pub async fn complete_activity_task<T: Serialize>(
4771        &self,
4772        task_id: &str,
4773        activity_attempt_id: &str,
4774        lease_owner: &str,
4775        result: T,
4776        codec: &str,
4777    ) -> Result<Value> {
4778        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4779        let body = json!({
4780            "activity_attempt_id": activity_attempt_id,
4781            "lease_owner": lease_owner,
4782            "result": result
4783        });
4784        let path = format!("/worker/activity-tasks/{task_id}/complete");
4785        activity_task_response(
4786            self.request_json(
4787                reqwest::Method::POST,
4788                &path,
4789                RequestProtocol::DefaultWorker,
4790                Some(&body),
4791            )
4792            .await,
4793            "complete",
4794            task_id,
4795            activity_attempt_id,
4796        )
4797    }
4798
4799    pub async fn fail_activity_task(
4800        &self,
4801        task_id: &str,
4802        activity_attempt_id: &str,
4803        lease_owner: &str,
4804        message: impl Into<String>,
4805        non_retryable: bool,
4806    ) -> Result<Value> {
4807        self.fail_activity_task_with_error(
4808            task_id,
4809            activity_attempt_id,
4810            lease_owner,
4811            &ActivityError::new("RustActivityFailure", message).non_retryable(non_retryable),
4812        )
4813        .await
4814    }
4815
4816    /// Report an activity's application-defined failure type and retry marker.
4817    pub async fn fail_activity_task_with_error(
4818        &self,
4819        task_id: &str,
4820        activity_attempt_id: &str,
4821        lease_owner: &str,
4822        error: &ActivityError,
4823    ) -> Result<Value> {
4824        let error = error.validated();
4825        let body = json!({
4826            "activity_attempt_id": activity_attempt_id,
4827            "lease_owner": lease_owner,
4828            "failure": {
4829                "message": error.message,
4830                "type": error.exception_type,
4831                "non_retryable": error.non_retryable
4832            }
4833        });
4834        let path = format!("/worker/activity-tasks/{task_id}/fail");
4835        activity_task_response(
4836            self.request_json(
4837                reqwest::Method::POST,
4838                &path,
4839                RequestProtocol::DefaultWorker,
4840                Some(&body),
4841            )
4842            .await,
4843            "fail",
4844            task_id,
4845            activity_attempt_id,
4846        )
4847    }
4848
4849    /// Record a flat map of scalar/null activity progress metadata.
4850    ///
4851    /// Heartbeat details use the Server's bounded JSON progress contract.
4852    /// They are not workflow payload envelopes.
4853    pub async fn heartbeat_activity_task<T: Serialize>(
4854        &self,
4855        task_id: &str,
4856        activity_attempt_id: &str,
4857        lease_owner: &str,
4858        details: T,
4859    ) -> Result<ActivityHeartbeatResponse> {
4860        serde_json::from_value(
4861            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4862                .await?,
4863        )
4864        .map_err(Error::from)
4865    }
4866
4867    async fn heartbeat_activity_task_value<T: Serialize>(
4868        &self,
4869        task_id: &str,
4870        activity_attempt_id: &str,
4871        lease_owner: &str,
4872        details: T,
4873    ) -> Result<Value> {
4874        let details = AvroValue::from_serialize(&details)?.into_json()?;
4875        let body = json!({
4876            "activity_attempt_id": activity_attempt_id,
4877            "lease_owner": lease_owner,
4878            "details": details
4879        });
4880        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4881        let started = tokio::time::Instant::now();
4882        let response = activity_task_response(
4883            self.request_json(
4884                reqwest::Method::POST,
4885                &path,
4886                RequestProtocol::DefaultWorker,
4887                Some(&body),
4888            )
4889            .await,
4890            "heartbeat",
4891            task_id,
4892            activity_attempt_id,
4893        )?;
4894        if let Some(authority) = &self.activity_lease_authority {
4895            authority.progress(&response, started)?;
4896        }
4897        Ok(response)
4898    }
4899
4900    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4901        &self,
4902        method: reqwest::Method,
4903        path: &str,
4904        protocol: RequestProtocol,
4905        body: Option<&B>,
4906    ) -> Result<T> {
4907        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4908            .await
4909    }
4910
4911    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4912        &self,
4913        method: reqwest::Method,
4914        path: &str,
4915        protocol: RequestProtocol,
4916        body: Option<&B>,
4917        timeout: Duration,
4918    ) -> Result<T> {
4919        self.metrics_request(method, path, protocol, body, timeout, true)
4920            .await
4921    }
4922
4923    fn worker_request_protocol(&self, protocol: RequestProtocol) -> Result<RequestProtocol> {
4924        Ok(match protocol {
4925            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4926                let selected = self.worker_protocol_version.as_str();
4927                if self.cooperative_worker_protocol
4928                    && !cooperative_cancellation::supports_protocol(selected)
4929                {
4930                    return Err(Error::CooperativeCancellationUnavailable(
4931                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
4932                    ));
4933                }
4934                if let RequestProtocol::Worker(minimum) = protocol {
4935                    let supported = minimum
4936                        .strip_prefix("1.")
4937                        .and_then(|minor| minor.parse::<u64>().ok())
4938                        .zip(
4939                            selected
4940                                .strip_prefix("1.")
4941                                .and_then(|minor| minor.parse::<u64>().ok()),
4942                        )
4943                        .is_some_and(|(minimum, selected)| selected >= minimum);
4944                    if !supported {
4945                        return Err(Error::WorkerLoop(format!(
4946                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
4947                        )));
4948                    }
4949                }
4950                RequestProtocol::Worker(selected)
4951            }
4952            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4953        })
4954    }
4955
4956    fn check_activity_lease_request(&self, path: &str, body: Option<&Value>) -> Result<()> {
4957        match &self.activity_lease_authority {
4958            Some(authority) => authority.check(path, body),
4959            None => Ok(()),
4960        }
4961    }
4962
4963    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4964        &self,
4965        method: reqwest::Method,
4966        path: &str,
4967        protocol: RequestProtocol,
4968        body: Option<&B>,
4969        timeout: Duration,
4970    ) -> Result<T> {
4971        self.metrics_request(method, path, protocol, body, timeout, false)
4972            .await
4973    }
4974
4975    async fn send_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4976        &self,
4977        method: reqwest::Method,
4978        path: &str,
4979        protocol: RequestProtocol,
4980        body: Option<&B>,
4981        timeout: Duration,
4982        observation: &metrics::ClientObservation,
4983    ) -> Result<T> {
4984        #[cfg(feature = "telemetry")]
4985        self.begin_observability_discovery(&method, path);
4986        let protocol = self.worker_request_protocol(protocol)?;
4987        let auth_token = self.auth_token(protocol)?;
4988        let mut request = self
4989            .http
4990            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4991            .timeout(timeout)
4992            .header(reqwest::header::ACCEPT, "application/json")
4993            .header(reqwest::header::CONTENT_TYPE, "application/json")
4994            .header("X-Namespace", &self.namespace);
4995
4996        match protocol {
4997            RequestProtocol::DefaultWorker => {
4998                request = request.header(
4999                    "X-Durable-Workflow-Protocol-Version",
5000                    self.worker_protocol_version.as_str(),
5001                );
5002            }
5003            RequestProtocol::Worker(version) => {
5004                request = request.header("X-Durable-Workflow-Protocol-Version", version);
5005            }
5006            RequestProtocol::ControlPlane => {
5007                request = request.header(
5008                    "X-Durable-Workflow-Control-Plane-Version",
5009                    CONTROL_PLANE_VERSION,
5010                );
5011            }
5012        }
5013
5014        if let Some(token) = auth_token {
5015            request = request.bearer_auth(token);
5016        }
5017
5018        if let Some(body) = body {
5019            let mut body = serde_json::to_value(body)?;
5020            if matches!(
5021                method,
5022                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
5023            ) {
5024                self.check_activity_lease_request(path, Some(&body))?;
5025                self.externalize_runtime_payloads(&mut body, path, protocol)
5026                    .await?;
5027                self.check_activity_lease_request(path, Some(&body))?;
5028            }
5029            request = request.json(&body);
5030        }
5031
5032        let request = request.build()?;
5033        let request_body = request
5034            .body()
5035            .and_then(reqwest::Body::as_bytes)
5036            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
5037        let poll_request_id = path.ends_with("/poll").then(|| {
5038            request_body
5039                .as_ref()
5040                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
5041                .unwrap_or_default()
5042        });
5043        let mut storage_retries = 0_usize;
5044        let mut deferred_workflow_completion = false;
5045
5046        loop {
5047            // Keep the serialized body and lease/poll identity across admission pauses.
5048            self.check_activity_lease_request(path, request_body.as_ref())?;
5049            let receive = async {
5050                let response = self
5051                    .http
5052                    .execute(request.try_clone().ok_or_else(|| {
5053                        Error::WorkerLoop("worker request body cannot be retried".to_string())
5054                    })?)
5055                    .await?;
5056                let status = response.status();
5057                observation.status(status);
5058                Ok::<_, Error>((status, response.bytes().await?))
5059            };
5060            let retry_deadline = self
5061                .worker_storage_admission
5062                .as_ref()
5063                .and_then(|admission| admission.workflow_completion_retry_deadline);
5064            if deferred_workflow_completion
5065                && retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
5066            {
5067                return Err(Error::Timeout);
5068            }
5069            let received = async {
5070                match retry_deadline.filter(|_| deferred_workflow_completion) {
5071                    Some(deadline) => tokio::time::timeout_at(deadline, receive)
5072                        .await
5073                        .map_err(|_| Error::Timeout)?,
5074                    None => receive.await,
5075                }
5076            };
5077            let (status, bytes) = match self
5078                .activity_lease_authority
5079                .as_ref()
5080                .filter(|authority| authority.governs(path))
5081            {
5082                Some(authority) => authority.protect(received).await?,
5083                None => received.await?,
5084            };
5085
5086            if !status.is_success() {
5087                let body = String::from_utf8_lossy(&bytes).to_string();
5088                if let Some(protocol) = protocol_failure(status, &body) {
5089                    return Err(Error::Protocol(protocol));
5090                }
5091                let error = Error::Http { status, body };
5092                deferred_workflow_completion |= worker_deferred_workflow_completion_retry_after(
5093                    &error,
5094                    path,
5095                    request_body.as_ref(),
5096                )
5097                .is_some();
5098                if self
5099                    .wait_for_storage_admission(
5100                        &error,
5101                        protocol,
5102                        Some(path),
5103                        poll_request_id.as_deref(),
5104                        request_body.as_ref(),
5105                        &mut storage_retries,
5106                    )
5107                    .await
5108                {
5109                    continue;
5110                }
5111                return Err(error);
5112            }
5113
5114            if bytes.is_empty() {
5115                return Ok(serde_json::from_value(Value::Null)?);
5116            }
5117
5118            #[cfg(feature = "telemetry")]
5119            return self.decode_observability_response(
5120                &method,
5121                path,
5122                request_body.as_ref(),
5123                &bytes,
5124            );
5125
5126            #[cfg(not(feature = "telemetry"))]
5127            return Ok(serde_json::from_slice(&bytes)?);
5128        }
5129    }
5130
5131    #[cfg(feature = "telemetry")]
5132    fn begin_observability_discovery(&self, method: &reqwest::Method, path: &str) {
5133        if *method == reqwest::Method::GET && path == "/cluster/info" {
5134            self.observability_context_supported
5135                .store(false, Ordering::SeqCst);
5136        }
5137    }
5138
5139    #[cfg(feature = "telemetry")]
5140    fn decode_observability_response<T: DeserializeOwned>(
5141        &self,
5142        method: &reqwest::Method,
5143        path: &str,
5144        request_body: Option<&Value>,
5145        bytes: &[u8],
5146    ) -> Result<T> {
5147        if *method == reqwest::Method::POST
5148            && self.execution_telemetry.is_some()
5149            && matches!(
5150                path,
5151                "/worker/workflow-tasks/poll"
5152                    | "/worker/activity-tasks/poll"
5153                    | "/worker/query-tasks/poll"
5154            )
5155        {
5156            let mut wire: Value = serde_json::from_slice(bytes)?;
5157            telemetry::carrier::retain_poll_observations(
5158                &mut wire,
5159                request_body.unwrap_or(&Value::Null),
5160                path,
5161                &self.namespace,
5162            );
5163            return Ok(serde_json::from_value(wire)?);
5164        }
5165        if *method == reqwest::Method::GET && path == "/cluster/info" {
5166            let info: Value = serde_json::from_slice(bytes)?;
5167            self.observability_context_supported
5168                .store(telemetry::carrier::supported(&info), Ordering::SeqCst);
5169            return Ok(serde_json::from_value(info)?);
5170        }
5171        Ok(serde_json::from_slice(bytes)?)
5172    }
5173
5174    async fn wait_for_storage_admission(
5175        &self,
5176        error: &Error,
5177        protocol: RequestProtocol,
5178        path: Option<&str>,
5179        poll_request_id: Option<&str>,
5180        request_body: Option<&Value>,
5181        retries: &mut usize,
5182    ) -> bool {
5183        let Some(admission) = self
5184            .worker_storage_admission
5185            .as_ref()
5186            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
5187        else {
5188            return false;
5189        };
5190        let completion_deferred = path.and_then(|path| {
5191            worker_deferred_workflow_completion_retry_after(error, path, request_body)
5192        });
5193        let Some(advertised_delay) = completion_deferred
5194            .or_else(|| worker_storage_admission_retry_after(error, poll_request_id))
5195            .or_else(|| {
5196                path.and_then(|path| {
5197                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
5198                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
5199                })
5200            })
5201        else {
5202            return false;
5203        };
5204        *retries = retries.saturating_add(1);
5205        let delay = worker_retry_delay(admission.policy, *retries)
5206            .max(advertised_delay)
5207            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
5208        let delay = if completion_deferred.is_some() {
5209            delay.max(advertised_delay)
5210        } else {
5211            delay
5212        };
5213        let wait_deadline = tokio::time::Instant::now() + delay;
5214        loop {
5215            if admission.stop.load(Ordering::SeqCst) {
5216                return false;
5217            }
5218            let now = tokio::time::Instant::now();
5219            if admission
5220                .workflow_completion_retry_deadline
5221                .is_some_and(|deadline| now >= deadline)
5222            {
5223                return false;
5224            }
5225            let remaining = wait_deadline.saturating_duration_since(now);
5226            if remaining.is_zero() {
5227                return true;
5228            }
5229            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
5230        }
5231    }
5232
5233    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
5234        &self,
5235        path: &str,
5236        protocol: RequestProtocol,
5237        body: &B,
5238        timeout: Duration,
5239        max_retries: usize,
5240    ) -> Result<T> {
5241        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
5242            .await
5243    }
5244
5245    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
5246        &self,
5247        path: &str,
5248        protocol: RequestProtocol,
5249        body: &B,
5250        timeout: Duration,
5251        max_retries: usize,
5252    ) -> Result<T> {
5253        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
5254            .await
5255    }
5256
5257    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
5258        &self,
5259        path: &str,
5260        protocol: RequestProtocol,
5261        body: &B,
5262        timeout: Duration,
5263        max_retries: usize,
5264        resolve: bool,
5265    ) -> Result<T> {
5266        self.metrics_poll_request(path, protocol, body, timeout, max_retries, resolve)
5267            .await
5268    }
5269
5270    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
5271        match protocol {
5272            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
5273                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
5274                    return Ok(Some(token));
5275                }
5276                if self.control_token.is_some() {
5277                    return Err(Error::MissingRoleCredentials {
5278                        role: "worker",
5279                        opposite_role: "control",
5280                    });
5281                }
5282                Ok(None)
5283            }
5284            RequestProtocol::ControlPlane => {
5285                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
5286                    return Ok(Some(token));
5287                }
5288                if self.worker_token.is_some() {
5289                    return Err(Error::MissingRoleCredentials {
5290                        role: "control",
5291                        opposite_role: "worker",
5292                    });
5293                }
5294                Ok(None)
5295            }
5296        }
5297    }
5298}
5299
5300fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
5301    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
5302    let reason = body
5303        .get("reason")
5304        .and_then(Value::as_str)
5305        .unwrap_or("query_rejected")
5306        .to_string();
5307    let message = body
5308        .get("message")
5309        .or_else(|| body.get("error"))
5310        .and_then(Value::as_str)
5311        .unwrap_or("workflow query was rejected")
5312        .to_string();
5313
5314    QueryFailure {
5315        status: status.as_u16(),
5316        reason,
5317        message,
5318        body,
5319    }
5320}
5321
5322fn workflow_command_result(
5323    command: WorkflowCommandKind,
5324    data: Value,
5325    workflow_id: &str,
5326    run_id: Option<&str>,
5327) -> WorkflowCommandResult {
5328    WorkflowCommandResult {
5329        command,
5330        workflow_id: data
5331            .get("workflow_id")
5332            .and_then(Value::as_str)
5333            .unwrap_or(workflow_id)
5334            .to_string(),
5335        run_id: data
5336            .get("run_id")
5337            .and_then(Value::as_str)
5338            .or(run_id)
5339            .map(str::to_string),
5340        outcome: data
5341            .get("outcome")
5342            .and_then(Value::as_str)
5343            .map(str::to_string),
5344        reason: data
5345            .get("reason")
5346            .and_then(Value::as_str)
5347            .map(str::to_string),
5348        command_status: data
5349            .get("command_status")
5350            .and_then(Value::as_str)
5351            .map(str::to_string),
5352        raw: data,
5353    }
5354}
5355
5356fn workflow_command_rejection(
5357    command: WorkflowCommandKind,
5358    status: reqwest::StatusCode,
5359    raw_body: String,
5360    workflow_id: &str,
5361    run_id: Option<&str>,
5362) -> WorkflowCommandRejection {
5363    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
5364    WorkflowCommandRejection {
5365        command,
5366        status: status.as_u16(),
5367        reason: body
5368            .get("reason")
5369            .and_then(Value::as_str)
5370            .unwrap_or("workflow_command_rejected")
5371            .to_string(),
5372        message: body
5373            .get("message")
5374            .or_else(|| body.get("error"))
5375            .and_then(Value::as_str)
5376            .unwrap_or("workflow lifecycle command was rejected")
5377            .to_string(),
5378        workflow_id: body
5379            .get("workflow_id")
5380            .and_then(Value::as_str)
5381            .unwrap_or(workflow_id)
5382            .to_string(),
5383        run_id: body
5384            .get("run_id")
5385            .and_then(Value::as_str)
5386            .or(run_id)
5387            .map(str::to_string),
5388        target_scope: body
5389            .get("target_scope")
5390            .and_then(Value::as_str)
5391            .map(str::to_string),
5392        body,
5393    }
5394}
5395
5396fn query_task_response(response: Result<Value>) -> Result<Value> {
5397    match response {
5398        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
5399        response => response,
5400    }
5401}
5402
5403fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
5404    match response {
5405        Err(Error::Http { status, body })
5406            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
5407        {
5408            Ok(serde_json::from_str(&body)?)
5409        }
5410        response => response,
5411    }
5412}
5413
5414fn worker_poll_body_is_stop(body: &str) -> bool {
5415    serde_json::from_str::<Value>(body)
5416        .ok()
5417        .is_some_and(|body| {
5418            worker_poll_is_stop(
5419                body.get("poll_status").and_then(Value::as_str),
5420                body.get("reason").and_then(Value::as_str),
5421            )
5422        })
5423}
5424
5425fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
5426    matches!(poll_status, Some("draining" | "stopped"))
5427        || matches!(reason, Some("worker_draining" | "worker_stopped"))
5428}
5429
5430fn query_task_rejection_is_final(error: &Error) -> bool {
5431    matches!(
5432        error,
5433        Error::QueryFailed(failure)
5434            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
5435    )
5436}
5437
5438fn activity_task_response<T>(
5439    response: Result<T>,
5440    operation: &str,
5441    task_id: &str,
5442    activity_attempt_id: &str,
5443) -> Result<T> {
5444    match response {
5445        Err(Error::Http { status, body }) => {
5446            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
5447            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
5448                operation: operation.to_string(),
5449                status: status.as_u16(),
5450                reason: body
5451                    .get("reason")
5452                    .and_then(Value::as_str)
5453                    .unwrap_or("activity_task_rejected")
5454                    .to_string(),
5455                task_id: body
5456                    .get("task_id")
5457                    .and_then(Value::as_str)
5458                    .unwrap_or(task_id)
5459                    .to_string(),
5460                activity_attempt_id: body
5461                    .get("activity_attempt_id")
5462                    .and_then(Value::as_str)
5463                    .unwrap_or(activity_attempt_id)
5464                    .to_string(),
5465                cancel_requested: body
5466                    .get("cancel_requested")
5467                    .and_then(Value::as_bool)
5468                    .unwrap_or(false),
5469                can_continue: body.get("can_continue").and_then(Value::as_bool),
5470                run_closed_reason: body
5471                    .get("run_closed_reason")
5472                    .and_then(Value::as_str)
5473                    .map(str::to_string),
5474                body,
5475            }))
5476        }
5477        response => response,
5478    }
5479}
5480
5481fn activity_task_rejection_is_final(error: &Error) -> bool {
5482    matches!(
5483        error,
5484        Error::ActivityTaskRejected(rejection)
5485            if matches!(
5486                rejection.reason.as_str(),
5487                "run_cancelled"
5488                    | "run_terminated"
5489                    | "attempt_closed"
5490                    | "stale_attempt"
5491                    | "activity_cancelled"
5492                    | "task_cancelled"
5493                    | "run_closed"
5494                    | "activity_not_running"
5495                    | "attempt_not_found"
5496            )
5497    )
5498}
5499
5500fn workflow_task_completion_is_terminal_timeout(
5501    error: &Error,
5502    task_id: &str,
5503    workflow_task_attempt: u64,
5504    run_id: Option<&str>,
5505) -> bool {
5506    let Error::Http { status, body } = error else {
5507        return false;
5508    };
5509    if *status != reqwest::StatusCode::CONFLICT {
5510        return false;
5511    }
5512
5513    let Some(run_id) = run_id else {
5514        return false;
5515    };
5516    let Ok(body) = serde_json::from_str::<Value>(body) else {
5517        return false;
5518    };
5519
5520    body.get("recorded").and_then(Value::as_bool) == Some(false)
5521        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
5522        && body.get("run_status").and_then(Value::as_str) == Some("failed")
5523        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5524        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5525        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5526}
5527
5528fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5529    let body: Value = serde_json::from_str(raw_body).ok()?;
5530    let reason = body.get("reason")?.as_str()?;
5531    if !matches!(
5532        reason,
5533        "missing_protocol_version"
5534            | "unsupported_protocol_version"
5535            | "missing_control_plane_version"
5536            | "unsupported_control_plane_version"
5537    ) {
5538        return None;
5539    }
5540
5541    Some(ProtocolFailure {
5542        status: status.as_u16(),
5543        reason: reason.to_string(),
5544        message: body
5545            .get("message")
5546            .or_else(|| body.get("error"))
5547            .and_then(Value::as_str)
5548            .unwrap_or("protocol version rejected")
5549            .to_string(),
5550        supported_version: body
5551            .get("supported_version")
5552            .and_then(Value::as_str)
5553            .map(str::to_string),
5554        requested_version: body
5555            .get("requested_version")
5556            .and_then(Value::as_str)
5557            .map(str::to_string),
5558        body,
5559    })
5560}
5561
5562fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5563    timeout
5564        .as_secs()
5565        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5566        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5567}
5568
5569fn worker_operation_is_retryable(error: &Error) -> bool {
5570    if worker_poll_capacity_retry_after(error).is_some()
5571        || worker_storage_admission_body(error).is_some()
5572        || worker_backend_unavailable_body(error).is_some()
5573        || worker_operation_is_explicitly_non_retryable(error)
5574    {
5575        return false;
5576    }
5577
5578    match error {
5579        Error::Transport(error) => {
5580            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5581        }
5582        Error::Http { status, .. } => {
5583            matches!(
5584                *status,
5585                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5586            ) || status.is_server_error()
5587        }
5588        _ => false,
5589    }
5590}
5591
5592fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5593    let body: Value = match error {
5594        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5595        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5596        _ => return None,
5597    };
5598    matches!(
5599        body.get("reason").and_then(Value::as_str),
5600        Some("storage_pressure" | "storage_admission_unavailable")
5601    )
5602    .then_some(body)
5603}
5604
5605fn worker_storage_admission_retry_after(
5606    error: &Error,
5607    poll_request_id: Option<&str>,
5608) -> Option<Duration> {
5609    let Error::Http { status, .. } = error else {
5610        return None;
5611    };
5612    let body = worker_storage_admission_body(error)?;
5613    let delay = body.get("retry_after_seconds")?.as_u64()?;
5614    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5615        || delay == 0
5616        || body.get("retryable") != Some(&Value::Bool(true))
5617        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5618        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5619        || body
5620            .get("request_admitted")
5621            .is_some_and(|admitted| admitted != &Value::Bool(false))
5622    {
5623        return None;
5624    }
5625    match poll_request_id {
5626        Some(id) => {
5627            if id.is_empty()
5628                || body.get("task") != Some(&Value::Null)
5629                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5630                || body.get("poll_status") != body.get("reason")
5631                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5632                || body.get("claim_admitted") != Some(&Value::Bool(false))
5633            {
5634                return None;
5635            }
5636        }
5637        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5638        None => {}
5639    }
5640    Some(Duration::from_secs(delay))
5641}
5642
5643fn worker_backend_unavailable_retry_after(
5644    error: &Error,
5645    path: &str,
5646    poll_request_id: Option<&str>,
5647) -> Option<Duration> {
5648    let operation = match path {
5649        "/worker/register" => "register_worker",
5650        "/worker/heartbeat" => "heartbeat_worker",
5651        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5652        "/worker/activity-tasks/poll" => "poll_activity_task",
5653        "/worker/query-tasks/poll" => "poll_query_task",
5654        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
5655        _ => return None,
5656    };
5657    let body = worker_backend_unavailable_body(error)?;
5658    let delay = body.get("retry_after_seconds")?.as_u64()?;
5659    if delay == 0
5660        || body.get("operation")?.as_str()? != operation
5661        || body.get("outcome")?.as_str()? != "unknown"
5662        || body.get("retryable") != Some(&Value::Bool(true))
5663        || body.get("worker_id")?.as_str()?.is_empty()
5664    {
5665        return None;
5666    }
5667    if let Some(id) = poll_request_id {
5668        if id.is_empty()
5669            || body.get("task") != Some(&Value::Null)
5670            || body.get("poll_status")?.as_str()? != "backend_unavailable"
5671            || body.get("poll_request_id")?.as_str()? != id
5672            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5673        {
5674            return None;
5675        }
5676    } else if path.ends_with("/poll") {
5677        return None;
5678    }
5679    Some(Duration::from_secs(delay))
5680}
5681
5682fn worker_fenced_completion_retry_after(
5683    error: &Error,
5684    path: &str,
5685    request_body: Option<&Value>,
5686) -> Option<Duration> {
5687    let (operation, task_id, attempt_field) = if let Some(task_id) = path
5688        .strip_prefix("/worker/workflow-tasks/")
5689        .and_then(|tail| tail.strip_suffix("/complete"))
5690    {
5691        ("complete_workflow_task", task_id, "workflow_task_attempt")
5692    } else if let Some(task_id) = path
5693        .strip_prefix("/worker/activity-tasks/")
5694        .and_then(|tail| tail.strip_suffix("/complete"))
5695    {
5696        ("complete_activity_task", task_id, "activity_attempt_id")
5697    } else {
5698        return None;
5699    };
5700    if task_id.is_empty() || task_id.contains('/') {
5701        return None;
5702    }
5703
5704    let request = request_body?.as_object()?;
5705    let lease_owner = request.get("lease_owner")?.as_str()?;
5706    if lease_owner.is_empty() {
5707        return None;
5708    }
5709    let attempt = request.get(attempt_field)?;
5710    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5711        || (attempt_field == "activity_attempt_id"
5712            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5713    {
5714        return None;
5715    }
5716
5717    let body = worker_backend_unavailable_body(error)?;
5718    let delay = body.get("retry_after_seconds")?.as_u64()?;
5719    if delay == 0
5720        || body.get("operation")?.as_str()? != operation
5721        || body.get("outcome")?.as_str()? != "unknown"
5722        || body.get("retryable") != Some(&Value::Bool(true))
5723        || body.get("worker_id")?.as_str()? != lease_owner
5724        || body.get("task_queue") != Some(&Value::Null)
5725        || body.get("task_id")?.as_str()? != task_id
5726        || body.get("lease_owner")?.as_str()? != lease_owner
5727        || body.get(attempt_field) != Some(attempt)
5728    {
5729        return None;
5730    }
5731
5732    Some(Duration::from_secs(delay))
5733}
5734
5735fn worker_deferred_workflow_completion_retry_after(
5736    error: &Error,
5737    path: &str,
5738    request_body: Option<&Value>,
5739) -> Option<Duration> {
5740    let task_id = path
5741        .strip_prefix("/worker/workflow-tasks/")?
5742        .strip_suffix("/complete")?;
5743    if task_id.is_empty() || task_id.contains('/') {
5744        return None;
5745    }
5746    let request = request_body?.as_object()?;
5747    let owner = request.get("lease_owner")?.as_str()?;
5748    let attempt = request.get("workflow_task_attempt")?;
5749    if owner.trim().is_empty() || attempt.as_u64().filter(|attempt| *attempt > 0).is_none() {
5750        return None;
5751    }
5752    let Error::Http { status, body } = error else {
5753        return None;
5754    };
5755    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5756        return None;
5757    }
5758    let body: Value = serde_json::from_str(body).ok()?;
5759    let delay = body.get("retry_after_seconds")?.as_u64()?;
5760    if !(1..=5).contains(&delay)
5761        || body.get("reason")?.as_str()? != "backend_lock_pressure"
5762        || body.get("operation")?.as_str()? != "complete_workflow_task"
5763        || body.get("outcome")?.as_str()? != "deferred"
5764        || body.get("recorded") != Some(&Value::Bool(false))
5765        || body.get("retryable") != Some(&Value::Bool(true))
5766        || body.get("task_id")?.as_str()? != task_id
5767        || body.get("lease_owner")?.as_str()? != owner
5768        || body.get("workflow_task_attempt") != Some(attempt)
5769        || body.get("backend")?.get("lock_pressure") != Some(&Value::Bool(true))
5770    {
5771        return None;
5772    }
5773    Some(Duration::from_secs(delay))
5774}
5775
5776fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5777    let Error::Http { status, body } = error else {
5778        return None;
5779    };
5780    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5781        return None;
5782    }
5783    let body: Value = serde_json::from_str(body).ok()?;
5784    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5785}
5786
5787fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5788    let Error::Http { body, .. } = error else {
5789        return false;
5790    };
5791
5792    serde_json::from_str::<Value>(body)
5793        .ok()
5794        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5795        == Some(false)
5796}
5797
5798fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5799    let Error::Http { status, body } = error else {
5800        return None;
5801    };
5802    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5803        return None;
5804    }
5805
5806    let body = serde_json::from_str::<Value>(body).ok()?;
5807    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5808        == Some("long_poll_capacity_exhausted")
5809        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5810    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5811        return None;
5812    }
5813
5814    Some(Duration::from_secs(
5815        body.get("retry_after_seconds")
5816            .and_then(Value::as_u64)
5817            .unwrap_or_default(),
5818    ))
5819}
5820
5821fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5822    let exponent = retry.saturating_sub(1).min(31) as u32;
5823    policy
5824        .initial_backoff
5825        .saturating_mul(1_u32 << exponent)
5826        .min(policy.max_backoff)
5827}
5828
5829#[derive(Debug)]
5830pub struct ClientBuilder {
5831    metrics: metrics::Metrics,
5832    base_url: String,
5833    token: Option<String>,
5834    control_token: Option<String>,
5835    worker_token: Option<String>,
5836    namespace: String,
5837    timeout: Duration,
5838    max_external_payload_bytes: usize,
5839    worker_protocol_version: WorkerProtocolVersion,
5840    additional_root_certificates: Vec<reqwest::Certificate>,
5841}
5842
5843impl ClientBuilder {
5844    /// Configure stable request metrics. Newly constructed workers inherit this recorder.
5845    pub fn metrics_recorder(mut self, recorder: Arc<dyn metrics::MetricsRecorder>) -> Self {
5846        self.metrics = metrics::Metrics::new(recorder);
5847        self
5848    }
5849    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
5850    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
5851        self.worker_protocol_version = version;
5852        self
5853    }
5854
5855    pub fn token(mut self, token: Option<String>) -> Self {
5856        self.token = token;
5857        self
5858    }
5859
5860    pub fn control_token(mut self, token: Option<String>) -> Self {
5861        self.control_token = token;
5862        self
5863    }
5864
5865    pub fn worker_token(mut self, token: Option<String>) -> Self {
5866        self.worker_token = token;
5867        self
5868    }
5869
5870    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5871        self.namespace = namespace.into();
5872        self
5873    }
5874
5875    pub fn timeout(mut self, timeout: Duration) -> Self {
5876        self.timeout = timeout;
5877        self
5878    }
5879
5880    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5881    /// References are fetched only from this client's authenticated runtime.
5882    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5883        self.max_external_payload_bytes = bytes;
5884        self
5885    }
5886
5887    pub fn build(self) -> Result<Client> {
5888        let base_url = self.base_url.trim_end_matches('/').to_string();
5889        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5890            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5891            .unwrap_or_else(|_| base_url.ends_with("/api"));
5892
5893        if has_sdk_api_suffix {
5894            return Err(Error::InvalidBaseUrl);
5895        }
5896
5897        let mut http = reqwest::Client::builder()
5898            .timeout(self.timeout)
5899            .redirect(reqwest::redirect::Policy::none());
5900        for certificate in self.additional_root_certificates {
5901            http = http.add_root_certificate(certificate);
5902        }
5903        Ok(Client {
5904            metrics: self.metrics,
5905            http: http.build()?,
5906            hydration_timeout: self.timeout,
5907            base_url,
5908            token: self.token,
5909            control_token: self.control_token,
5910            worker_token: self.worker_token,
5911            namespace: self.namespace,
5912            max_external_payload_bytes: self.max_external_payload_bytes,
5913            worker_storage_admission: None,
5914            worker_task_slot: None,
5915            cooperative_worker_protocol: false,
5916            worker_protocol_version: self.worker_protocol_version,
5917            local_activities_enabled: false,
5918            worker_sessions_enabled: false,
5919            max_concurrent_worker_sessions: 10,
5920            worker_build_id: None,
5921            sticky_cache: None,
5922            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5923            activity_lease_renewal_supported: Arc::new(AtomicBool::new(false)),
5924            activity_lease_authority: None,
5925            #[cfg(feature = "telemetry")]
5926            execution_telemetry: None,
5927            #[cfg(feature = "telemetry")]
5928            observability_context_supported: Arc::new(AtomicBool::new(false)),
5929        })
5930    }
5931}
5932
5933#[derive(Clone, Debug)]
5934pub struct WorkflowHandle {
5935    client: Client,
5936    pub workflow_id: String,
5937    pub run_id: Option<String>,
5938    pub workflow_type: String,
5939}
5940
5941impl WorkflowHandle {
5942    /// Describe whichever run is current for this stable workflow instance.
5943    pub async fn describe(&self) -> Result<WorkflowDescription> {
5944        self.client.describe_workflow(&self.workflow_id).await
5945    }
5946
5947    /// Describe the run identity originally selected by this handle.
5948    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5949        let run_id = self.run_id.as_deref().ok_or_else(|| {
5950            Error::Codec("run_id is required for selected-run description".to_string())
5951        })?;
5952        self.client
5953            .describe_workflow_run(&self.workflow_id, run_id)
5954            .await
5955    }
5956
5957    /// Signal this workflow with an SDK-generated caller command key.
5958    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5959        self.client
5960            .signal_workflow(&self.workflow_id, signal_name, input)
5961            .await
5962    }
5963
5964    /// Signal this workflow with an explicit caller command key (1 to 255 Unicode characters).
5965    pub async fn signal_with_request_id<T: Serialize>(
5966        &self,
5967        signal_name: &str,
5968        input: T,
5969        request_id: &str,
5970    ) -> Result<Value> {
5971        self.client
5972            .signal_workflow_with_request_id(&self.workflow_id, signal_name, input, request_id)
5973            .await
5974    }
5975
5976    pub async fn append_message<T: Serialize>(
5977        &self,
5978        stream_name: &str,
5979        message_id: &str,
5980        input: T,
5981    ) -> Result<Value> {
5982        self.client
5983            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5984            .await
5985    }
5986
5987    /// Signal only if this handle's selected run is still current, with an
5988    /// SDK-generated caller command key.
5989    pub async fn signal_selected_run<T: Serialize>(
5990        &self,
5991        signal_name: &str,
5992        input: T,
5993    ) -> Result<Value> {
5994        let run_id = self.run_id.as_deref().ok_or_else(|| {
5995            Error::Codec("run_id is required for selected-run signaling".to_string())
5996        })?;
5997        self.client
5998            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
5999            .await
6000    }
6001
6002    /// Signal only if this handle's selected run is still current, with an
6003    /// explicit caller command key (1 to 255 Unicode characters).
6004    pub async fn signal_selected_run_with_request_id<T: Serialize>(
6005        &self,
6006        signal_name: &str,
6007        input: T,
6008        request_id: &str,
6009    ) -> Result<Value> {
6010        let run_id = self.run_id.as_deref().ok_or_else(|| {
6011            Error::Codec("run_id is required for selected-run signaling".to_string())
6012        })?;
6013        self.client
6014            .signal_workflow_run_with_request_id(
6015                &self.workflow_id,
6016                run_id,
6017                signal_name,
6018                input,
6019                request_id,
6020            )
6021            .await
6022    }
6023
6024    /// Close whichever run is current as cancelled, without workflow cleanup.
6025    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
6026        self.client
6027            .cancel_workflow(&self.workflow_id, options)
6028            .await
6029    }
6030
6031    /// Request cancellation only if this handle's selected run is still current.
6032    pub async fn cancel_selected_run(
6033        &self,
6034        options: WorkflowCommandOptions,
6035    ) -> Result<WorkflowCommandResult> {
6036        let run_id = self.run_id.as_deref().ok_or_else(|| {
6037            Error::Codec("run_id is required for selected-run cancellation".to_string())
6038        })?;
6039        self.client
6040            .cancel_workflow_run(&self.workflow_id, run_id, options)
6041            .await
6042    }
6043
6044    /// Forcefully terminate whichever run is current.
6045    pub async fn terminate(
6046        &self,
6047        options: WorkflowCommandOptions,
6048    ) -> Result<WorkflowCommandResult> {
6049        self.client
6050            .terminate_workflow(&self.workflow_id, options)
6051            .await
6052    }
6053
6054    /// Terminate only if this handle's selected run is still current.
6055    pub async fn terminate_selected_run(
6056        &self,
6057        options: WorkflowCommandOptions,
6058    ) -> Result<WorkflowCommandResult> {
6059        let run_id = self.run_id.as_deref().ok_or_else(|| {
6060            Error::Codec("run_id is required for selected-run termination".to_string())
6061        })?;
6062        self.client
6063            .terminate_workflow_run(&self.workflow_id, run_id, options)
6064            .await
6065    }
6066
6067    /// Continue this handle's failed run without repeating completed activities.
6068    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
6069        let run_id = self
6070            .run_id
6071            .as_deref()
6072            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
6073        self.client
6074            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
6075            .await
6076    }
6077
6078    /// Execute a named, read-only query against this workflow.
6079    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
6080        self.client
6081            .query_workflow(&self.workflow_id, query_name, input)
6082            .await
6083    }
6084
6085    pub async fn query_avro_value<T: Serialize>(
6086        &self,
6087        query_name: &str,
6088        input: T,
6089    ) -> Result<AvroValue> {
6090        self.client
6091            .query_workflow_avro_value(&self.workflow_id, query_name, input)
6092            .await
6093    }
6094
6095    pub async fn update<T: Serialize>(
6096        &self,
6097        update_name: &str,
6098        input: T,
6099        request_id: Option<&str>,
6100    ) -> Result<Value> {
6101        self.client
6102            .update_workflow(&self.workflow_id, update_name, input, request_id)
6103            .await
6104    }
6105
6106    pub async fn update_avro_value<T: Serialize>(
6107        &self,
6108        update_name: &str,
6109        input: T,
6110        request_id: Option<&str>,
6111    ) -> Result<AvroValue> {
6112        self.client
6113            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
6114            .await
6115    }
6116
6117    /// Query only if this handle's selected run is still current.
6118    pub async fn query_selected_run<T: Serialize>(
6119        &self,
6120        query_name: &str,
6121        input: T,
6122    ) -> Result<Value> {
6123        let run_id = self
6124            .run_id
6125            .as_deref()
6126            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
6127        self.client
6128            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
6129            .await
6130    }
6131
6132    /// Await the final terminal outcome of the current continue-as-new chain.
6133    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
6134        self.result_target(options, None).await
6135    }
6136
6137    /// Await the final result without projecting Avro bytes through JSON.
6138    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
6139        self.result_avro_value_target(options, None).await
6140    }
6141
6142    /// Await the final result and decode it into a Serde application type.
6143    pub async fn result_typed<T: DeserializeOwned>(
6144        &self,
6145        options: WorkflowResultOptions,
6146    ) -> Result<T> {
6147        let result = self.result_avro_value(options).await?;
6148        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
6149    }
6150
6151    /// Await only the run identity originally selected by this handle.
6152    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
6153        let run_id = self.run_id.as_deref().ok_or_else(|| {
6154            Error::Codec("run_id is required for selected-run result".to_string())
6155        })?;
6156        self.result_target(options, Some(run_id)).await
6157    }
6158
6159    /// Await the selected run's result on the lossless Avro Value surface.
6160    pub async fn result_selected_run_avro_value(
6161        &self,
6162        options: WorkflowResultOptions,
6163    ) -> Result<AvroValue> {
6164        let run_id = self.run_id.as_deref().ok_or_else(|| {
6165            Error::Codec("run_id is required for selected-run result".to_string())
6166        })?;
6167        self.result_avro_value_target(options, Some(run_id)).await
6168    }
6169
6170    /// Await the selected run and decode its result into a Serde type.
6171    pub async fn result_selected_run_typed<T: DeserializeOwned>(
6172        &self,
6173        options: WorkflowResultOptions,
6174    ) -> Result<T> {
6175        let result = self.result_selected_run_avro_value(options).await?;
6176        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
6177    }
6178
6179    async fn result_avro_value_target(
6180        &self,
6181        options: WorkflowResultOptions,
6182        selected_run_id: Option<&str>,
6183    ) -> Result<AvroValue> {
6184        let started = Instant::now();
6185
6186        loop {
6187            let description = match selected_run_id {
6188                Some(run_id) => {
6189                    self.client
6190                        .describe_workflow_run(&self.workflow_id, run_id)
6191                        .await?
6192                }
6193                None => self.describe().await?,
6194            };
6195            if description.is_completed() {
6196                return description.output_avro_value.ok_or_else(|| {
6197                    Error::Codec(
6198                        "missing_payload_envelope: typed workflow result requires output_envelope"
6199                            .to_string(),
6200                    )
6201                });
6202            }
6203            if description.is_terminal() {
6204                let outcome =
6205                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
6206                return Err(match outcome.kind {
6207                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
6208                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
6209                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
6210                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
6211                });
6212            }
6213            if started.elapsed() >= options.timeout {
6214                return Err(Error::Timeout);
6215            }
6216            tokio::time::sleep(options.poll_interval).await;
6217        }
6218    }
6219
6220    async fn result_target(
6221        &self,
6222        options: WorkflowResultOptions,
6223        selected_run_id: Option<&str>,
6224    ) -> Result<Value> {
6225        let started = Instant::now();
6226
6227        loop {
6228            let description = match selected_run_id {
6229                Some(run_id) => {
6230                    self.client
6231                        .describe_workflow_run(&self.workflow_id, run_id)
6232                        .await?
6233                }
6234                None => self.describe().await?,
6235            };
6236            if description.is_completed() {
6237                return Ok(description.output.unwrap_or(Value::Null));
6238            }
6239
6240            if description.is_terminal() {
6241                let outcome =
6242                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
6243                return Err(match outcome.kind {
6244                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
6245                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
6246                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
6247                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
6248                });
6249            }
6250
6251            if started.elapsed() >= options.timeout {
6252                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
6253                    kind: WorkflowTerminalKind::TimedOut,
6254                    workflow_id: description
6255                        .workflow_id
6256                        .clone()
6257                        .unwrap_or_else(|| self.workflow_id.clone()),
6258                    run_id: description
6259                        .run_id
6260                        .clone()
6261                        .or_else(|| selected_run_id.map(str::to_string)),
6262                    reason: "result_wait_timeout".to_string(),
6263                    failure_category: Some("client_timeout".to_string()),
6264                    failure_id: None,
6265                    exception_type: None,
6266                    exception_class: None,
6267                    non_retryable: None,
6268                    message: Some(format!(
6269                        "workflow result was not terminal within {:?}",
6270                        options.timeout
6271                    )),
6272                    exception: None,
6273                    raw: description.raw_value(),
6274                }));
6275            }
6276
6277            tokio::time::sleep(options.poll_interval).await;
6278        }
6279    }
6280}
6281
6282#[derive(Clone, Copy, Debug)]
6283pub struct WorkflowResultOptions {
6284    pub poll_interval: Duration,
6285    pub timeout: Duration,
6286}
6287
6288impl Default for WorkflowResultOptions {
6289    fn default() -> Self {
6290        Self {
6291            poll_interval: Duration::from_millis(500),
6292            timeout: Duration::from_secs(30),
6293        }
6294    }
6295}
6296
6297#[derive(Clone, Debug, Deserialize)]
6298pub struct WorkflowDescription {
6299    pub workflow_id: Option<String>,
6300    pub run_id: Option<String>,
6301    pub workflow_type: Option<String>,
6302    pub status: Option<String>,
6303    #[serde(default)]
6304    pub closed_reason: Option<String>,
6305    #[serde(default)]
6306    pub error: Option<String>,
6307    #[serde(default)]
6308    pub failure: Option<Value>,
6309    #[serde(default)]
6310    pub exception: Option<Value>,
6311    #[serde(default)]
6312    pub failures: Vec<Value>,
6313    #[serde(default)]
6314    pub output: Option<Value>,
6315    #[serde(default)]
6316    pub output_envelope: Option<Value>,
6317    #[serde(skip)]
6318    pub output_avro_value: Option<AvroValue>,
6319    #[serde(flatten)]
6320    pub raw: HashMap<String, Value>,
6321}
6322
6323/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
6324#[derive(Clone, Debug, Deserialize)]
6325pub struct WorkflowStreamDescription {
6326    pub stream_name: String,
6327    pub status: String,
6328    pub last_offset: i64,
6329    pub total_items: u64,
6330    pub pending_items: u64,
6331    #[serde(default)]
6332    pub opened_at: Option<String>,
6333    #[serde(default)]
6334    pub last_appended_at: Option<String>,
6335    #[serde(default)]
6336    pub closed_at: Option<String>,
6337    #[serde(default)]
6338    pub error_reason: Option<String>,
6339    #[serde(default)]
6340    pub retention_seconds: Option<u64>,
6341    #[serde(flatten)]
6342    pub raw: HashMap<String, Value>,
6343}
6344
6345impl WorkflowStreamDescription {
6346    pub fn is_terminal(&self) -> bool {
6347        matches!(self.status.as_str(), "closed" | "errored")
6348    }
6349}
6350
6351/// One item for direct or replay-safe append.
6352#[derive(Clone, Debug, Default)]
6353pub struct WorkflowStreamAppendItem {
6354    pub payload_envelope: Option<Value>,
6355    pub payload_reference: Option<String>,
6356    pub item_type: Option<String>,
6357    pub content_type: Option<String>,
6358    pub idempotency_key: Option<String>,
6359}
6360
6361impl WorkflowStreamAppendItem {
6362    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
6363    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
6364        let value = AvroValue::from_serialize(&payload)?;
6365        Ok(Self {
6366            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
6367            ..Self::default()
6368        })
6369    }
6370
6371    /// Preserve an external payload URI as an opaque service-contract reference.
6372    pub fn from_reference(reference: impl Into<String>) -> Self {
6373        Self {
6374            payload_reference: Some(reference.into()),
6375            ..Self::default()
6376        }
6377    }
6378
6379    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
6380        self.item_type = Some(item_type.into());
6381        self
6382    }
6383
6384    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
6385        self.content_type = Some(content_type.into());
6386        self
6387    }
6388
6389    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
6390        self.idempotency_key = Some(idempotency_key.into());
6391        self
6392    }
6393
6394    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
6395        let mut item = serde_json::Map::new();
6396        if let Some(payload) = &self.payload_envelope {
6397            item.insert("payload".to_string(), payload.clone());
6398            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
6399        }
6400        if let Some(reference) = &self.payload_reference {
6401            item.insert("payload_reference".to_string(), json!(reference));
6402        }
6403        if let Some(item_type) = &self.item_type {
6404            item.insert("item_type".to_string(), json!(item_type));
6405        }
6406        if let Some(content_type) = &self.content_type {
6407            item.insert("content_type".to_string(), json!(content_type));
6408        }
6409        if let Some(key) = derived_idempotency_key
6410            .as_ref()
6411            .or(self.idempotency_key.as_ref())
6412        {
6413            item.insert("idempotency_key".to_string(), json!(key));
6414        }
6415        Value::Object(item)
6416    }
6417}
6418
6419/// One durable item at its stable zero-based offset.
6420#[derive(Clone, Debug)]
6421pub struct WorkflowStreamItem {
6422    pub offset: u64,
6423    pub payload: Option<Value>,
6424    pub payload_envelope: Option<Value>,
6425    pub payload_reference: Option<String>,
6426    pub payload_codec: Option<String>,
6427    pub idempotency_key: Option<String>,
6428    pub item_type: Option<String>,
6429    pub content_type: Option<String>,
6430    pub origin: Option<String>,
6431    pub origin_reference: Option<String>,
6432    pub emitted_at: Option<String>,
6433    pub raw: Value,
6434}
6435
6436/// One bounded at-least-once subscription page.
6437#[derive(Clone, Debug)]
6438pub struct WorkflowStreamPage {
6439    pub stream: WorkflowStreamDescription,
6440    pub items: Vec<WorkflowStreamItem>,
6441    pub next_offset: u64,
6442    pub terminal: bool,
6443}
6444
6445/// Durable acceptance and deduplication outcome for an append request.
6446#[derive(Clone, Debug)]
6447pub struct WorkflowStreamAppendResult {
6448    pub stream: WorkflowStreamDescription,
6449    pub accepted_offsets: Vec<u64>,
6450    pub accepted: u64,
6451    pub deduped: u64,
6452}
6453
6454#[derive(Deserialize)]
6455struct WorkflowStreamListResponse {
6456    #[serde(default)]
6457    streams: Vec<WorkflowStreamDescription>,
6458}
6459
6460#[derive(Deserialize)]
6461struct WorkflowStreamDescriptionResponse {
6462    stream: WorkflowStreamDescription,
6463}
6464
6465#[derive(Deserialize)]
6466struct WorkflowStreamPageResponse {
6467    stream: WorkflowStreamDescription,
6468    #[serde(default)]
6469    items: Vec<Value>,
6470    next_offset: u64,
6471    terminal: bool,
6472}
6473
6474#[derive(Deserialize)]
6475struct WorkflowStreamAppendResponse {
6476    stream: WorkflowStreamDescription,
6477    #[serde(default)]
6478    accepted_offsets: Vec<u64>,
6479    accepted: u64,
6480    deduped: u64,
6481}
6482
6483impl WorkflowDescription {
6484    pub fn is_completed(&self) -> bool {
6485        matches!(self.status.as_deref(), Some("completed" | "Completed"))
6486    }
6487
6488    pub fn is_terminal(&self) -> bool {
6489        matches!(
6490            self.status.as_deref(),
6491            Some(
6492                "completed"
6493                    | "Completed"
6494                    | "failed"
6495                    | "Failed"
6496                    | "cancelled"
6497                    | "Cancelled"
6498                    | "terminated"
6499                    | "Terminated"
6500                    | "timed_out"
6501                    | "TimedOut",
6502            )
6503        )
6504    }
6505
6506    fn decode_payloads(&mut self) -> Result<()> {
6507        if let Some(envelope) = &self.output_envelope {
6508            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
6509            self.output = Some(value.clone().into_json()?);
6510            self.output_avro_value = Some(value);
6511        }
6512
6513        Ok(())
6514    }
6515
6516    fn raw_value(&self) -> Value {
6517        let mut data = self.raw.clone();
6518        data.insert(
6519            "workflow_id".to_string(),
6520            self.workflow_id
6521                .clone()
6522                .map(Value::String)
6523                .unwrap_or(Value::Null),
6524        );
6525        data.insert(
6526            "run_id".to_string(),
6527            self.run_id
6528                .clone()
6529                .map(Value::String)
6530                .unwrap_or(Value::Null),
6531        );
6532        data.insert(
6533            "workflow_type".to_string(),
6534            self.workflow_type
6535                .clone()
6536                .map(Value::String)
6537                .unwrap_or(Value::Null),
6538        );
6539        data.insert(
6540            "status".to_string(),
6541            self.status
6542                .clone()
6543                .map(Value::String)
6544                .unwrap_or(Value::Null),
6545        );
6546        data.insert(
6547            "closed_reason".to_string(),
6548            self.closed_reason
6549                .clone()
6550                .map(Value::String)
6551                .unwrap_or(Value::Null),
6552        );
6553        if let Some(failure) = &self.failure {
6554            data.insert("failure".to_string(), failure.clone());
6555        }
6556        if let Some(exception) = &self.exception {
6557            data.insert("exception".to_string(), exception.clone());
6558        }
6559        Value::Object(data.into_iter().collect())
6560    }
6561}
6562
6563fn workflow_terminal_outcome(
6564    description: &WorkflowDescription,
6565    workflow_id: &str,
6566    run_id: Option<&str>,
6567) -> WorkflowTerminalOutcome {
6568    let terminal_kind = description
6569        .closed_reason
6570        .as_deref()
6571        .or(description.status.as_deref())
6572        .unwrap_or("failed")
6573        .to_ascii_lowercase();
6574    let kind = match terminal_kind.as_str() {
6575        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
6576        "terminated" => WorkflowTerminalKind::Terminated,
6577        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
6578        _ => WorkflowTerminalKind::Failed,
6579    };
6580    let default_reason = match kind {
6581        WorkflowTerminalKind::Failed => "workflow_failed",
6582        WorkflowTerminalKind::Cancelled => "cancelled",
6583        WorkflowTerminalKind::Terminated => "terminated",
6584        WorkflowTerminalKind::TimedOut => "timed_out",
6585    };
6586    let failure = description
6587        .failure
6588        .as_ref()
6589        .filter(|value| value.is_object());
6590    let nested_failure = failure
6591        .and_then(|value| value.get("failures"))
6592        .and_then(Value::as_array)
6593        .and_then(|failures| failures.last())
6594        .or_else(|| description.failures.last());
6595    let exception = description
6596        .exception
6597        .clone()
6598        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
6599        .or_else(|| {
6600            nested_failure
6601                .and_then(|value| value.get("exception_payload"))
6602                .cloned()
6603        });
6604    let string_field = |name: &str| {
6605        failure
6606            .and_then(|value| value.get(name))
6607            .and_then(Value::as_str)
6608            .or_else(|| {
6609                nested_failure
6610                    .and_then(|value| value.get(name))
6611                    .and_then(Value::as_str)
6612            })
6613            .map(str::to_string)
6614    };
6615    let exception_field = |name: &str| {
6616        exception
6617            .as_ref()
6618            .and_then(|value| value.get(name))
6619            .and_then(Value::as_str)
6620            .map(str::to_string)
6621    };
6622    let message = description
6623        .error
6624        .clone()
6625        .or_else(|| string_field("message"))
6626        .or_else(|| exception_field("message"));
6627    let reason = description
6628        .raw
6629        .get("reason")
6630        .and_then(Value::as_str)
6631        .map(str::to_string)
6632        .or_else(|| {
6633            failure
6634                .and_then(|value| value.get("reason"))
6635                .and_then(Value::as_str)
6636                .map(str::to_string)
6637        })
6638        .or_else(|| description.closed_reason.clone())
6639        .unwrap_or_else(|| default_reason.to_string());
6640    let failure_id = string_field("failure_id").or_else(|| {
6641        nested_failure
6642            .and_then(|value| value.get("id"))
6643            .and_then(Value::as_str)
6644            .map(str::to_string)
6645    });
6646
6647    WorkflowTerminalOutcome {
6648        kind,
6649        workflow_id: description
6650            .workflow_id
6651            .clone()
6652            .unwrap_or_else(|| workflow_id.to_string()),
6653        run_id: description
6654            .run_id
6655            .clone()
6656            .or_else(|| run_id.map(str::to_string)),
6657        reason,
6658        failure_category: string_field("failure_category")
6659            .or_else(|| Some(default_reason.to_string())),
6660        failure_id,
6661        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
6662        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
6663        non_retryable: failure
6664            .and_then(|value| value.get("non_retryable"))
6665            .and_then(Value::as_bool)
6666            .or_else(|| {
6667                nested_failure
6668                    .and_then(|value| value.get("non_retryable"))
6669                    .and_then(Value::as_bool)
6670            }),
6671        message,
6672        exception,
6673        raw: description.raw_value(),
6674    }
6675}
6676
6677#[derive(Clone, Debug, Deserialize)]
6678pub struct RegisterWorkerResponse {
6679    pub worker_id: String,
6680    pub registered: bool,
6681    #[serde(default)]
6682    pub heartbeat_interval_seconds: Option<u64>,
6683    #[serde(default)]
6684    pub protocol_version: Option<String>,
6685    #[serde(default)]
6686    pub server_capabilities: Option<Value>,
6687}
6688
6689/// Result of gracefully removing a worker-plane registration.
6690#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6691pub struct WorkerDeregistrationEnvelope {
6692    pub worker_id: String,
6693    pub outcome: String,
6694    pub recovered_workflow_task_count: u64,
6695}
6696
6697#[derive(Clone, Debug, Deserialize)]
6698pub struct PollWorkflowTaskResponse {
6699    #[serde(default)]
6700    pub task: Option<WorkflowTask>,
6701    #[serde(default)]
6702    pub poll_status: Option<String>,
6703    #[serde(default)]
6704    pub reason: Option<String>,
6705    #[serde(default)]
6706    pub protocol_version: Option<String>,
6707    #[serde(default)]
6708    pub server_capabilities: Option<Value>,
6709}
6710
6711impl PollWorkflowTaskResponse {
6712    /// Classify this response without parsing server display text.
6713    pub fn outcome(&self) -> WorkerPollOutcome {
6714        worker_poll_outcome(
6715            self.task.is_some(),
6716            self.poll_status.as_deref(),
6717            self.reason.as_deref(),
6718        )
6719    }
6720}
6721
6722fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
6723    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
6724        return false;
6725    };
6726    let supported = capabilities
6727        .get("workflow_memo_updates")
6728        .and_then(Value::as_object)
6729        .and_then(|memo| memo.get("supported"))
6730        .and_then(Value::as_bool)
6731        == Some(true);
6732    let command_advertised = capabilities
6733        .get("supported_workflow_task_commands")
6734        .and_then(Value::as_array)
6735        .is_some_and(|commands| {
6736            commands
6737                .iter()
6738                .any(|command| command.as_str() == Some("upsert_memo"))
6739        });
6740    supported && command_advertised
6741}
6742
6743fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
6744    commands
6745        .iter()
6746        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
6747}
6748
6749#[derive(Clone, Debug, Deserialize)]
6750pub struct PollActivityTaskResponse {
6751    #[serde(default)]
6752    pub task: Option<ActivityTask>,
6753    #[serde(default)]
6754    pub poll_status: Option<String>,
6755    #[serde(default)]
6756    pub reason: Option<String>,
6757}
6758
6759impl PollActivityTaskResponse {
6760    /// Classify this response without parsing server display text.
6761    pub fn outcome(&self) -> WorkerPollOutcome {
6762        worker_poll_outcome(
6763            self.task.is_some(),
6764            self.poll_status.as_deref(),
6765            self.reason.as_deref(),
6766        )
6767    }
6768}
6769
6770#[derive(Clone, Debug, Deserialize)]
6771pub struct PollQueryTaskResponse {
6772    #[serde(default)]
6773    pub task: Option<QueryTask>,
6774    #[serde(default)]
6775    pub poll_status: Option<String>,
6776    #[serde(default)]
6777    pub reason: Option<String>,
6778}
6779
6780impl PollQueryTaskResponse {
6781    /// Classify this response without parsing server display text.
6782    pub fn outcome(&self) -> WorkerPollOutcome {
6783        worker_poll_outcome(
6784            self.task.is_some(),
6785            self.poll_status.as_deref(),
6786            self.reason.as_deref(),
6787        )
6788    }
6789}
6790
6791/// Stable classification for worker poll responses.
6792#[derive(Clone, Debug, PartialEq, Eq)]
6793pub enum WorkerPollOutcome {
6794    /// A task was leased and is available on the response.
6795    Task,
6796    /// No task was leased, but the worker should continue polling.
6797    Idle {
6798        poll_status: Option<String>,
6799        reason: Option<String>,
6800    },
6801    /// The server asked this worker to stop claiming new work.
6802    Stop {
6803        poll_status: Option<String>,
6804        reason: Option<String>,
6805    },
6806}
6807
6808impl WorkerPollOutcome {
6809    pub fn should_stop(&self) -> bool {
6810        matches!(self, Self::Stop { .. })
6811    }
6812}
6813
6814fn worker_poll_outcome(
6815    has_task: bool,
6816    poll_status: Option<&str>,
6817    reason: Option<&str>,
6818) -> WorkerPollOutcome {
6819    if worker_poll_is_stop(poll_status, reason) {
6820        return WorkerPollOutcome::Stop {
6821            poll_status: poll_status.map(str::to_string),
6822            reason: reason.map(str::to_string),
6823        };
6824    }
6825
6826    if has_task {
6827        WorkerPollOutcome::Task
6828    } else {
6829        WorkerPollOutcome::Idle {
6830            poll_status: poll_status.map(str::to_string),
6831            reason: reason.map(str::to_string),
6832        }
6833    }
6834}
6835
6836/// An ephemeral server-routed query task.
6837#[derive(Clone, Debug, Deserialize)]
6838pub struct QueryTask {
6839    pub query_task_id: String,
6840    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6841    #[serde(default)]
6842    pub observability_context: Option<Value>,
6843    #[serde(default)]
6844    pub dispatch_observability_context: Option<Value>,
6845    #[serde(default)]
6846    pub observability_links: Option<Value>,
6847    #[serde(default = "default_workflow_task_attempt")]
6848    pub query_task_attempt: u64,
6849    #[serde(default)]
6850    pub lease_owner: Option<String>,
6851    #[serde(default)]
6852    pub workflow_id: Option<String>,
6853    #[serde(default)]
6854    pub run_id: Option<String>,
6855    pub workflow_type: String,
6856    pub query_name: String,
6857    #[serde(
6858        default = "missing_task_payload_codec",
6859        deserialize_with = "deserialize_task_payload_codec"
6860    )]
6861    pub payload_codec: String,
6862    #[serde(default)]
6863    pub workflow_arguments: Option<Value>,
6864    #[serde(default)]
6865    pub query_arguments: Option<Value>,
6866    #[serde(default)]
6867    pub history_events: Vec<HistoryEvent>,
6868    #[serde(default)]
6869    pub history_export: Option<Value>,
6870    #[serde(default)]
6871    pub run_status: Option<String>,
6872}
6873
6874#[derive(Clone, Debug, Deserialize)]
6875pub struct WorkflowTask {
6876    pub task_id: String,
6877    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6878    #[serde(default)]
6879    pub observability_context: Option<Value>,
6880    #[serde(default)]
6881    pub dispatch_observability_context: Option<Value>,
6882    #[serde(default)]
6883    pub observability_links: Option<Value>,
6884    #[serde(default)]
6885    pub workflow_command_id: Option<String>,
6886    #[serde(default)]
6887    pub workflow_id: Option<String>,
6888    #[serde(default)]
6889    pub run_id: Option<String>,
6890    pub workflow_type: String,
6891    #[serde(default)]
6892    pub cancel_requested: bool,
6893    #[serde(
6894        default = "missing_task_payload_codec",
6895        deserialize_with = "deserialize_task_payload_codec"
6896    )]
6897    pub payload_codec: String,
6898    #[serde(default)]
6899    pub arguments: Option<Value>,
6900    #[serde(default)]
6901    pub history_events: Vec<HistoryEvent>,
6902    #[serde(default)]
6903    pub total_history_events: Option<u64>,
6904    #[serde(default)]
6905    pub history_size_bytes: Option<u64>,
6906    #[serde(default)]
6907    pub continue_as_new_recommended: Option<bool>,
6908    #[serde(default)]
6909    pub history_budget_pressure: Option<String>,
6910    #[serde(default)]
6911    pub next_history_page_token: Option<String>,
6912    #[serde(default = "default_workflow_task_attempt")]
6913    pub workflow_task_attempt: u64,
6914    #[serde(default)]
6915    pub workflow_signal_id: Option<String>,
6916    #[serde(default)]
6917    pub signal_name: Option<String>,
6918    #[serde(default)]
6919    pub signal_arguments: Option<Value>,
6920    #[serde(default)]
6921    pub workflow_update_id: Option<String>,
6922    #[serde(default)]
6923    pub update_name: Option<String>,
6924    #[serde(default)]
6925    pub lease_owner: Option<String>,
6926}
6927
6928impl WorkflowTask {
6929    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6930        self.history_events.extend(page.history_events);
6931
6932        if page.total_history_events.is_some() {
6933            self.total_history_events = page.total_history_events;
6934        }
6935
6936        self.next_history_page_token = page
6937            .next_history_page_token
6938            .filter(|token| !token.is_empty());
6939    }
6940}
6941
6942#[derive(Clone, Debug, Deserialize)]
6943struct WorkflowTaskHistoryPage {
6944    #[serde(default)]
6945    history_events: Vec<HistoryEvent>,
6946    #[serde(default)]
6947    total_history_events: Option<u64>,
6948    #[serde(default)]
6949    next_history_page_token: Option<String>,
6950}
6951
6952#[derive(Clone, Debug, Deserialize)]
6953pub struct ActivityTask {
6954    pub task_id: String,
6955    #[serde(default)]
6956    pub workflow_id: Option<String>,
6957    #[serde(default)]
6958    pub run_id: Option<String>,
6959    #[serde(default)]
6960    pub activity_execution_id: Option<String>,
6961    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6962    #[serde(default)]
6963    pub observability_context: Option<Value>,
6964    #[serde(default)]
6965    pub dispatch_observability_context: Option<Value>,
6966    #[serde(default)]
6967    pub observability_links: Option<Value>,
6968    #[serde(default)]
6969    pub activity_attempt_id: Option<String>,
6970    #[serde(default)]
6971    pub attempt_id: Option<String>,
6972    pub activity_type: String,
6973    #[serde(
6974        default = "missing_task_payload_codec",
6975        deserialize_with = "deserialize_task_payload_codec"
6976    )]
6977    pub payload_codec: String,
6978    #[serde(default)]
6979    pub arguments: Option<Value>,
6980    #[serde(default = "default_attempt_number")]
6981    pub attempt_number: u64,
6982    #[serde(default)]
6983    pub lease_owner: Option<String>,
6984}
6985
6986#[derive(Clone, Debug, Serialize, Deserialize)]
6987pub struct HistoryEvent {
6988    #[serde(alias = "type")]
6989    pub event_type: String,
6990    #[serde(default)]
6991    pub payload: Value,
6992    #[serde(flatten)]
6993    pub raw: HashMap<String, Value>,
6994}
6995
6996/// One decoded signal in the committed workflow-history snapshot.
6997#[derive(Clone, Debug, PartialEq)]
6998pub struct QuerySignal {
6999    pub id: Option<String>,
7000    pub name: String,
7001    pub arguments: Vec<Value>,
7002    avro_arguments: Vec<AvroValue>,
7003    pub workflow_sequence: Option<u64>,
7004}
7005
7006impl QuerySignal {
7007    /// Lossless fixed Avro Value arguments for this committed signal.
7008    pub fn arguments_avro_value(&self) -> &[AvroValue] {
7009        &self.avro_arguments
7010    }
7011}
7012
7013/// Immutable state supplied to a registered query handler.
7014///
7015/// This context intentionally exposes no activity, signal-wait, or command
7016/// APIs. Query handlers inspect committed history and return a value; query
7017/// completion does not append an event or advance deterministic execution.
7018#[derive(Clone, Debug)]
7019pub struct QueryContext {
7020    pub workflow_id: Option<String>,
7021    pub run_id: Option<String>,
7022    pub workflow_type: String,
7023    pub run_status: Option<String>,
7024    workflow_input: Value,
7025    workflow_input_avro_value: AvroValue,
7026    history_events: Arc<Vec<HistoryEvent>>,
7027    signal_events: Arc<Vec<QuerySignal>>,
7028}
7029
7030impl QueryContext {
7031    /// The normalized argument list used to start the workflow.
7032    pub fn workflow_input(&self) -> &Value {
7033        &self.workflow_input
7034    }
7035
7036    /// The lossless fixed Avro Value argument list used to start the workflow.
7037    pub fn workflow_input_avro_value(&self) -> &AvroValue {
7038        &self.workflow_input_avro_value
7039    }
7040
7041    /// The immutable committed history used for this query snapshot.
7042    pub fn history_events(&self) -> &[HistoryEvent] {
7043        self.history_events.as_slice()
7044    }
7045
7046    /// All decoded signals in committed workflow order.
7047    pub fn signal_events(&self) -> &[QuerySignal] {
7048        self.signal_events.as_slice()
7049    }
7050
7051    /// Decoded argument lists for each committed signal with `signal_name`.
7052    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
7053        self.signal_events
7054            .iter()
7055            .filter(|signal| signal.name == signal_name)
7056            .map(|signal| signal.arguments.clone())
7057            .collect()
7058    }
7059
7060    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
7061    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
7062        self.signal_events
7063            .iter()
7064            .filter(|signal| signal.name == signal_name)
7065            .map(|signal| signal.avro_arguments.clone())
7066            .collect()
7067    }
7068}
7069
7070#[derive(Clone, Debug, Deserialize)]
7071pub struct ActivityHeartbeatResponse {
7072    #[serde(default)]
7073    pub cancel_requested: bool,
7074    #[serde(default)]
7075    pub heartbeat_recorded: bool,
7076    #[serde(default)]
7077    pub can_continue: Option<bool>,
7078    #[serde(default)]
7079    pub reason: Option<String>,
7080    #[serde(default)]
7081    pub run_closed_reason: Option<String>,
7082    #[serde(default)]
7083    pub run_closed_at: Option<String>,
7084    #[serde(default)]
7085    pub lease_expires_at: Option<String>,
7086    #[serde(default)]
7087    pub last_heartbeat_at: Option<String>,
7088}
7089
7090impl ActivityHeartbeatResponse {
7091    /// Whether the activity should stop instead of attempting completion.
7092    pub fn should_stop(&self) -> bool {
7093        self.cancel_requested || self.can_continue == Some(false)
7094    }
7095}
7096
7097fn missing_task_payload_codec() -> String {
7098    MISSING_TASK_PAYLOAD_CODEC.to_string()
7099}
7100
7101fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
7102where
7103    D: Deserializer<'de>,
7104{
7105    Ok(match Value::deserialize(deserializer)? {
7106        Value::String(codec) => codec,
7107        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
7108        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
7109    })
7110}
7111
7112fn default_workflow_task_attempt() -> u64 {
7113    1
7114}
7115
7116fn default_attempt_number() -> u64 {
7117    1
7118}
7119
7120type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7121type WorkflowHandler =
7122    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<WorkflowFuture> + Send + Sync>;
7123type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
7124type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
7125type ReplayedWorkflowHandler =
7126    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<ReplayedWorkflowInvocation> + Send + Sync>;
7127type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7128type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
7129type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7130type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
7131type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
7132type ReplayedQueryHandler = Arc<
7133    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
7134        + Send
7135        + Sync,
7136>;
7137type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
7138
7139struct ReplayedWorkflowInvocation {
7140    future: WorkflowFuture,
7141    snapshot: WorkflowStateSnapshot,
7142}
7143
7144#[derive(Clone)]
7145struct RegisteredWorkflow {
7146    execute: WorkflowHandler,
7147    replay: Option<ReplayedWorkflowHandler>,
7148    state_type: Option<TypeId>,
7149    definition_fingerprint: Option<String>,
7150}
7151
7152fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
7153    names
7154        .iter()
7155        .map(|name| {
7156            json!({
7157                "name": name,
7158                "parameters": [{
7159                    "name": "args",
7160                    "position": 0,
7161                    "required": false,
7162                    "variadic": true,
7163                    "type": null,
7164                    "allows_null": true,
7165                    "default_available": false,
7166                    "default": null,
7167                }],
7168            })
7169        })
7170        .collect()
7171}
7172
7173#[derive(Debug)]
7174struct WorkflowTaskDecision {
7175    commands: Vec<Value>,
7176    message_stream_cursors: Vec<Value>,
7177    message_stream_waits: Vec<Value>,
7178    cancellation_delivery: Option<CancellationDelivery>,
7179    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
7180    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
7181}
7182
7183enum PreparedWorkflowTask {
7184    Decision(WorkflowTaskDecision),
7185    Execution {
7186        task: WorkflowTask,
7187        context: WorkflowContext,
7188        future: WorkflowFuture,
7189    },
7190}
7191
7192impl WorkflowTaskDecision {
7193    fn without_message_streams(commands: Vec<Value>) -> Self {
7194        Self {
7195            commands,
7196            message_stream_cursors: Vec::new(),
7197            message_stream_waits: Vec::new(),
7198            cancellation_delivery: None,
7199            cancellation_scope_opening: None,
7200            cancellation_scope_delivery: None,
7201        }
7202    }
7203}
7204
7205#[derive(Clone)]
7206enum RegisteredQuery {
7207    Snapshot(QueryHandler),
7208    Replayed {
7209        state_type: TypeId,
7210        handler: ReplayedQueryHandler,
7211    },
7212}
7213
7214#[derive(Clone, Debug)]
7215pub struct WorkerHeartbeatObservation {
7216    pub worker_id: String,
7217    pub task_queue: String,
7218    pub acknowledged_at_unix_millis: u64,
7219    pub acknowledgement: Value,
7220}
7221
7222/// Bounded retry policy for worker poll acquisition and worker heartbeats.
7223///
7224/// Expected empty long polls and explicit Server capacity backpressure are
7225/// normal worker states. Capacity backpressure honors the advertised retry
7226/// delay without consuming this retry budget. Other transport failures,
7227/// retryable HTTP 408/429 responses, and server errors are retried with capped
7228/// exponential backoff. Authentication, protocol, codec, and handler failures
7229/// are never retried by the worker.
7230/// Explicit storage admission pauses also preserve the already-serialized worker
7231/// request without consuming this budget or rerunning its handler. The delay is
7232/// capped by `max_backoff`, except an explicit completion deferral must honor
7233/// the Server's minimum delay. Shutdown interrupts storage waits; cooperative
7234/// completion retries remain bounded by the original cleanup deadline.
7235/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
7236/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
7237/// and `max_retries = 0` disables ordinary retries in either mode.
7238#[derive(Clone, Copy, Debug)]
7239pub struct WorkerRetryPolicy {
7240    /// Number of retries after the initial request fails.
7241    pub max_retries: usize,
7242    /// Delay before the first retry.
7243    pub initial_backoff: Duration,
7244    /// Maximum delay between retries.
7245    pub max_backoff: Duration,
7246}
7247
7248impl Default for WorkerRetryPolicy {
7249    fn default() -> Self {
7250        Self {
7251            max_retries: 5,
7252            initial_backoff: Duration::from_millis(100),
7253            max_backoff: Duration::from_secs(5),
7254        }
7255    }
7256}
7257
7258#[derive(Clone, Debug)]
7259struct WorkerStorageAdmission {
7260    policy: WorkerRetryPolicy,
7261    stop: Arc<AtomicBool>,
7262    workflow_completion_retry_deadline: Option<tokio::time::Instant>,
7263}
7264
7265struct StopWorkerOnDrop(Arc<AtomicBool>);
7266
7267impl Drop for StopWorkerOnDrop {
7268    fn drop(&mut self) {
7269        self.0.store(true, Ordering::SeqCst);
7270    }
7271}
7272
7273async fn wait_for_worker_stop(stop: &AtomicBool) {
7274    while !stop.load(Ordering::SeqCst) {
7275        tokio::time::sleep(Duration::from_millis(100)).await;
7276    }
7277}
7278
7279#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7280enum ManagedPollOutcome {
7281    Idle,
7282    Handled,
7283    Stop,
7284}
7285
7286#[derive(Clone)]
7287pub struct Worker {
7288    metrics: metrics::Metrics,
7289    #[cfg(feature = "telemetry")]
7290    telemetry: Option<telemetry::ExecutionTelemetry>,
7291    client: Client,
7292    worker_id: String,
7293    task_queue: String,
7294    workflows: HashMap<String, RegisteredWorkflow>,
7295    activities: HashMap<String, ActivityHandler>,
7296    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
7297    signals: HashMap<String, Vec<String>>,
7298    updates: HashMap<String, HashMap<String, UpdateHandler>>,
7299    registration_definitions:
7300        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
7301    registration_error: Option<DuplicateRegistrationError>,
7302    max_concurrent_workflow_tasks: usize,
7303    max_concurrent_activity_tasks: usize,
7304    workflow_capacity: Arc<worker_capacity::TaskCapacity>,
7305    activity_capacity: Arc<worker_capacity::TaskCapacity>,
7306    poll_timeout: Duration,
7307    heartbeat_interval: Duration,
7308    retry_policy: WorkerRetryPolicy,
7309    recover_transient_outages: bool,
7310    run_stop: Option<Arc<AtomicBool>>,
7311    heartbeat_observer: Option<WorkerHeartbeatObserver>,
7312    cooperative_cancellation_enabled: bool,
7313    nexus_cooperative_cancellation_enabled: bool,
7314    allow_cancellation_scope_authoring: bool,
7315    allow_cancellation_scope_delivery: bool,
7316    cooperative_registration_confirmed: Arc<AtomicBool>,
7317    nexus_registration_confirmed: Arc<AtomicBool>,
7318    local_registration_confirmed: Arc<AtomicBool>,
7319    session_registration_confirmed: Arc<AtomicBool>,
7320    sticky_registration_confirmed: Arc<AtomicBool>,
7321    require_query_task_authority: bool,
7322    query_authority_confirmed: Arc<AtomicBool>,
7323    resource_capabilities: Vec<String>,
7324    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
7325}
7326
7327impl Worker {
7328    /// Override worker poll/task metrics; client request metrics retain their client's recorder.
7329    pub fn metrics_recorder(mut self, recorder: Arc<dyn metrics::MetricsRecorder>) -> Self {
7330        self.metrics = metrics::Metrics::new(recorder);
7331        self
7332    }
7333    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
7334        Self {
7335            metrics: client.metrics.clone(),
7336            #[cfg(feature = "telemetry")]
7337            telemetry: None,
7338            client,
7339            worker_id: default_worker_id(),
7340            task_queue: task_queue.into(),
7341            workflows: HashMap::new(),
7342            activities: HashMap::new(),
7343            queries: HashMap::new(),
7344            signals: HashMap::new(),
7345            updates: HashMap::new(),
7346            registration_definitions: HashMap::new(),
7347            registration_error: None,
7348            max_concurrent_workflow_tasks: 10,
7349            max_concurrent_activity_tasks: 10,
7350            workflow_capacity: worker_capacity::TaskCapacity::new(10),
7351            activity_capacity: worker_capacity::TaskCapacity::new(10),
7352            poll_timeout: Duration::from_secs(30),
7353            heartbeat_interval: Duration::from_secs(60),
7354            retry_policy: WorkerRetryPolicy::default(),
7355            recover_transient_outages: false,
7356            run_stop: None,
7357            heartbeat_observer: None,
7358            cooperative_cancellation_enabled: false,
7359            nexus_cooperative_cancellation_enabled: false,
7360            allow_cancellation_scope_authoring: false,
7361            allow_cancellation_scope_delivery: false,
7362            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
7363            nexus_registration_confirmed: Arc::new(AtomicBool::new(false)),
7364            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
7365            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
7366            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
7367            require_query_task_authority: false,
7368            query_authority_confirmed: Arc::new(AtomicBool::new(false)),
7369            resource_capabilities: Vec::new(),
7370            sessions: Arc::new(Mutex::new(HashMap::new())),
7371        }
7372    }
7373
7374    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
7375        self.worker_id = worker_id.into();
7376        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
7377        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7378        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
7379        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
7380        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
7381        self.query_authority_confirmed = Arc::new(AtomicBool::new(false));
7382        self.client.reset_sticky_cache();
7383        self.sessions = Arc::new(Mutex::new(HashMap::new()));
7384        self
7385    }
7386
7387    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
7388        self.poll_timeout = timeout;
7389        self
7390    }
7391
7392    /// Opt in to execution spans using application-owned OpenTelemetry providers.
7393    /// No exporter, logging bridge, global provider or Server carrier is installed.
7394    #[cfg(feature = "telemetry")]
7395    pub fn telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
7396        self.client.execution_telemetry = Some(telemetry.clone());
7397        self.telemetry = Some(telemetry);
7398        self
7399    }
7400
7401    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
7402        self.heartbeat_interval = interval;
7403        self
7404    }
7405
7406    /// Require original query timing and non-renewing runtime observation.
7407    ///
7408    /// Registration refuses before creating a Worker unless protocol 1.20 and
7409    /// the runtime's `query_task_authority` capability are available. By default,
7410    /// older Servers retain their weaker, disclosed local-timing behavior.
7411    pub fn require_query_task_authority(mut self, required: bool) -> Self {
7412        self.require_query_task_authority = required;
7413        self
7414    }
7415
7416    /// Explicitly enable inline local activities in this workflow worker.
7417    ///
7418    /// The worker advertises the capability to Server only when enabled.
7419    /// These callbacks must yield to Tokio and have idempotent side effects.
7420    /// Cooperative prepared local supervision is a separate capability.
7421    pub fn local_activities(mut self, enabled: bool) -> Self {
7422        self.client.local_activities_enabled = enabled;
7423        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
7424        self
7425    }
7426
7427    /// Opt in to separate cooperative workflow cancellation requests.
7428    ///
7429    /// Registration requires the Server to acknowledge this exact worker,
7430    /// namespace, queue and capabilities with compatible protocol 1.20. Task
7431    /// processing uses canonical delivery and activity ownership fences.
7432    /// Existing terminal cancel and terminate operations remain terminal.
7433    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
7434    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
7435    /// and [`Worker::run_until`] register automatically.
7436    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
7437        self.cooperative_cancellation_enabled = enabled;
7438        self.client.cooperative_worker_protocol = enabled;
7439        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
7440        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7441        if !enabled {
7442            self.nexus_cooperative_cancellation_enabled = false;
7443        }
7444        self
7445    }
7446
7447    /// Opt in to cooperative Nexus completion waits on an installed workflow binding.
7448    ///
7449    /// This also enables ordinary cooperative cancellation. Registration checks
7450    /// protocol 1.20 and Server's installed `workflow_run` bridge before advertising.
7451    pub fn nexus_cooperative_cancellation(self, enabled: bool) -> Self {
7452        let mut worker = if enabled {
7453            self.cooperative_cancellation(true)
7454        } else {
7455            self
7456        };
7457        worker.nexus_cooperative_cancellation_enabled = enabled;
7458        worker.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7459        worker
7460    }
7461
7462    /// Enable candidate scope authoring without advertising scoped execution.
7463    #[doc(hidden)]
7464    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
7465        self.allow_cancellation_scope_authoring = enabled;
7466        self
7467    }
7468
7469    /// Enable the candidate scoped call consumer with canonical authoring.
7470    #[doc(hidden)]
7471    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
7472        self.allow_cancellation_scope_delivery = enabled;
7473        self
7474    }
7475
7476    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
7477    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
7478        self.retry_policy = policy;
7479        self
7480    }
7481
7482    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
7483    ///
7484    /// Retries preserve the poll request identity and use capped exponential
7485    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
7486    /// An in-flight poll is allowed to finish so leased work is not discarded.
7487    /// Authentication, protocol, codec, handler and task settlement failures
7488    /// remain errors. Registration and deregistration are not retried here.
7489    ///
7490    /// The default is disabled, preserving the bounded retry contract.
7491    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
7492    /// even when this option is enabled.
7493    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
7494        self.recover_transient_outages = enabled;
7495        self
7496    }
7497
7498    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
7499    where
7500        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
7501    {
7502        self.heartbeat_observer = Some(Arc::new(observer));
7503        self
7504    }
7505
7506    /// Bound simultaneous claimed workflow tasks, including loading and settlement.
7507    /// Defaults to 10. Use 1 for serial workflow-task execution.
7508    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
7509        self.max_concurrent_workflow_tasks = count.clamp(1, tokio::sync::Semaphore::MAX_PERMITS);
7510        self.workflow_capacity =
7511            worker_capacity::TaskCapacity::new(self.max_concurrent_workflow_tasks);
7512        self
7513    }
7514
7515    /// Bound simultaneous remote activity tasks, including loading and settlement.
7516    /// Defaults to 10. Use 1 for serial activity-task execution.
7517    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
7518        self.max_concurrent_activity_tasks = count.clamp(1, tokio::sync::Semaphore::MAX_PERMITS);
7519        self.activity_capacity =
7520            worker_capacity::TaskCapacity::new(self.max_concurrent_activity_tasks);
7521        self
7522    }
7523
7524    /// Validate local handler admission without making a Server request.
7525    ///
7526    /// Registration methods retain their existing signatures. A duplicate keeps
7527    /// the original handler and makes this Worker invalid, including its clones.
7528    /// `register`, `run`, `run_until` and `run_once` enforce this check before
7529    /// any network request. Build a new Worker to correct an invalid configuration.
7530    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
7531        match &self.registration_error {
7532            Some(error) => Err(error.clone()),
7533            None => Ok(()),
7534        }
7535    }
7536
7537    #[track_caller]
7538    fn admit_registration<F>(
7539        &mut self,
7540        handler_kind: RegistrationKind,
7541        workflow_type: Option<&str>,
7542        handler_name: &str,
7543        method: &'static str,
7544    ) -> bool {
7545        let location = std::panic::Location::caller();
7546        let definition = HandlerRegistration {
7547            method,
7548            handler_type: type_name::<F>(),
7549            file: location.file(),
7550            line: location.line(),
7551            column: location.column(),
7552        };
7553        let key = (
7554            handler_kind,
7555            workflow_type.map(str::to_owned),
7556            handler_name.to_owned(),
7557        );
7558        if let Some(first_definition) = self.registration_definitions.get(&key) {
7559            if self.registration_error.is_none() {
7560                self.registration_error = Some(DuplicateRegistrationError {
7561                    handler_kind,
7562                    workflow_type: key.1.clone(),
7563                    handler_name: key.2.clone(),
7564                    first_definition: first_definition.clone(),
7565                    second_definition: definition,
7566                });
7567            }
7568            return false;
7569        }
7570        self.registration_definitions.insert(key, definition);
7571        true
7572    }
7573
7574    /// Register a workflow handler.
7575    ///
7576    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
7577    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
7578    /// while acquiring or decoding a worker task remain worker-operation
7579    /// failures and do not get converted into workflow outcomes.
7580    #[track_caller]
7581    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
7582    where
7583        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
7584        Fut: Future<Output = Result<Value>> + Send + 'static,
7585    {
7586        let workflow_type = workflow_type.into();
7587        if !self.admit_registration::<F>(
7588            RegistrationKind::Workflow,
7589            None,
7590            &workflow_type,
7591            "register_workflow",
7592        ) {
7593            return;
7594        }
7595        let handler = Arc::new(handler);
7596        self.workflows.insert(
7597            workflow_type,
7598            RegisteredWorkflow {
7599                execute: Arc::new(move |ctx, input| {
7600                    let handler = Arc::clone(&handler);
7601                    Ok(Box::pin(async move {
7602                        let result = handler(ctx, input.into_json()?).await?;
7603                        AvroValue::from_serialize(&result)
7604                    }))
7605                }),
7606                replay: None,
7607                state_type: None,
7608                definition_fingerprint: None,
7609            },
7610        );
7611    }
7612
7613    /// Register a workflow with one Serde request value and a Serde result.
7614    ///
7615    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
7616    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
7617    /// workflow-specific schema. A task must contain zero arguments for a unit
7618    /// request or exactly one argument for every other request type.
7619    ///
7620    /// See the runnable
7621    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
7622    /// for typed workflow and activity contracts with retry and timeout policy.
7623    #[track_caller]
7624    pub fn register_typed_workflow<I, O, F, Fut>(
7625        &mut self,
7626        workflow_type: impl Into<String>,
7627        handler: F,
7628    ) where
7629        I: DeserializeOwned + Send + 'static,
7630        O: Serialize + Send + 'static,
7631        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
7632        Fut: Future<Output = Result<O>> + Send + 'static,
7633    {
7634        let workflow_type = workflow_type.into();
7635        if !self.admit_registration::<F>(
7636            RegistrationKind::Workflow,
7637            None,
7638            &workflow_type,
7639            "register_typed_workflow",
7640        ) {
7641            return;
7642        }
7643        let handler_name = workflow_type.clone();
7644        let handler = Arc::new(handler);
7645        self.workflows.insert(
7646            workflow_type,
7647            RegisteredWorkflow {
7648                execute: Arc::new(move |ctx, input| {
7649                    let input = decode_workflow_entry::<I>(input, &handler_name)?;
7650                    let handler = Arc::clone(&handler);
7651                    let handler_name = handler_name.clone();
7652                    Ok(Box::pin(async move {
7653                        let result = handler(ctx, input).await?;
7654                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7655                    }))
7656                }),
7657                replay: None,
7658                state_type: None,
7659                definition_fingerprint: None,
7660            },
7661        );
7662    }
7663
7664    /// Register a workflow on the lossless fixed Avro Value surface.
7665    #[track_caller]
7666    pub fn register_workflow_avro_value<F, Fut>(
7667        &mut self,
7668        workflow_type: impl Into<String>,
7669        handler: F,
7670    ) where
7671        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
7672        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7673    {
7674        let workflow_type = workflow_type.into();
7675        if !self.admit_registration::<F>(
7676            RegistrationKind::Workflow,
7677            None,
7678            &workflow_type,
7679            "register_workflow_avro_value",
7680        ) {
7681            return;
7682        }
7683        self.workflows.insert(
7684            workflow_type,
7685            RegisteredWorkflow {
7686                execute: Arc::new(move |ctx, input| Ok(Box::pin(handler(ctx, input)))),
7687                replay: None,
7688                state_type: None,
7689                definition_fingerprint: None,
7690            },
7691        );
7692    }
7693
7694    /// Register a workflow whose typed instance state can be reconstructed for queries.
7695    ///
7696    /// `state_factory` creates a fresh instance for every normal workflow task and
7697    /// query replay. The workflow handler is the single source of truth for state
7698    /// transitions: it updates [`WorkflowInstance`] after activities and signals
7699    /// resolve. Query replay runs this same handler over committed history and
7700    /// discards any commands it would emit.
7701    #[track_caller]
7702    pub fn register_replayed_workflow<S, Factory, F, Fut>(
7703        &mut self,
7704        workflow_type: impl Into<String>,
7705        state_factory: Factory,
7706        handler: F,
7707    ) where
7708        S: Clone + Send + Sync + 'static,
7709        Factory: Fn() -> S + Send + Sync + 'static,
7710        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7711        Fut: Future<Output = Result<Value>> + Send + 'static,
7712    {
7713        let workflow_type = workflow_type.into();
7714        if !self.admit_registration::<F>(
7715            RegistrationKind::Workflow,
7716            None,
7717            &workflow_type,
7718            "register_replayed_workflow",
7719        ) {
7720            return;
7721        }
7722        let state_factory = Arc::new(state_factory);
7723        let handler = Arc::new(handler);
7724
7725        let execute_factory = Arc::clone(&state_factory);
7726        let execute_handler = Arc::clone(&handler);
7727        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7728            let state = WorkflowInstance::new(execute_factory());
7729            let handler = Arc::clone(&execute_handler);
7730            Ok(Box::pin(async move {
7731                let result = handler(ctx, input.into_json()?, state).await?;
7732                AvroValue::from_serialize(&result)
7733            }) as WorkflowFuture)
7734        });
7735
7736        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7737            let state = WorkflowInstance::new(state_factory());
7738            let snapshot_state = state.clone();
7739            let snapshot: WorkflowStateSnapshot =
7740                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7741            let replay_handler = Arc::clone(&handler);
7742            let future = async move {
7743                let result = replay_handler(ctx, input.into_json()?, state).await?;
7744                AvroValue::from_serialize(&result)
7745            };
7746            Ok(ReplayedWorkflowInvocation {
7747                future: Box::pin(future),
7748                snapshot,
7749            })
7750        });
7751
7752        self.workflows.insert(
7753            workflow_type,
7754            RegisteredWorkflow {
7755                execute,
7756                replay: Some(replay),
7757                state_type: Some(TypeId::of::<S>()),
7758                definition_fingerprint: None,
7759            },
7760        );
7761    }
7762
7763    /// Register a replayable workflow with one Serde request value and result.
7764    ///
7765    /// Normal task execution and instance-state query replay both decode and
7766    /// encode through the fixed Avro Value codec. The state factory and handler
7767    /// otherwise follow [`Worker::register_replayed_workflow`].
7768    #[track_caller]
7769    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
7770        &mut self,
7771        workflow_type: impl Into<String>,
7772        state_factory: Factory,
7773        handler: F,
7774    ) where
7775        I: DeserializeOwned + Send + 'static,
7776        O: Serialize + Send + 'static,
7777        S: Clone + Send + Sync + 'static,
7778        Factory: Fn() -> S + Send + Sync + 'static,
7779        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7780        Fut: Future<Output = Result<O>> + Send + 'static,
7781    {
7782        let workflow_type = workflow_type.into();
7783        if !self.admit_registration::<F>(
7784            RegistrationKind::Workflow,
7785            None,
7786            &workflow_type,
7787            "register_typed_replayed_workflow",
7788        ) {
7789            return;
7790        }
7791        let state_factory = Arc::new(state_factory);
7792        let handler = Arc::new(handler);
7793
7794        let execute_name = workflow_type.clone();
7795        let execute_factory = Arc::clone(&state_factory);
7796        let execute_handler = Arc::clone(&handler);
7797        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7798            let input = decode_workflow_entry::<I>(input, &execute_name)?;
7799            let state = WorkflowInstance::new(execute_factory());
7800            let handler = Arc::clone(&execute_handler);
7801            let handler_name = execute_name.clone();
7802            Ok(Box::pin(async move {
7803                let result = handler(ctx, input, state).await?;
7804                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7805            }) as WorkflowFuture)
7806        });
7807
7808        let replay_name = workflow_type.clone();
7809        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7810            let input = decode_workflow_entry::<I>(input, &replay_name)?;
7811            let state = WorkflowInstance::new(state_factory());
7812            let snapshot_state = state.clone();
7813            let snapshot: WorkflowStateSnapshot =
7814                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7815            let handler = Arc::clone(&handler);
7816            let handler_name = replay_name.clone();
7817            let future = async move {
7818                let result = handler(ctx, input, state).await?;
7819                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7820            };
7821            Ok(ReplayedWorkflowInvocation {
7822                future: Box::pin(future),
7823                snapshot,
7824            })
7825        });
7826
7827        self.workflows.insert(
7828            workflow_type,
7829            RegisteredWorkflow {
7830                execute,
7831                replay: Some(replay),
7832                state_type: Some(TypeId::of::<S>()),
7833                definition_fingerprint: None,
7834            },
7835        );
7836    }
7837
7838    /// Declare the signal names consumed by a registered workflow.
7839    ///
7840    /// Call this after registering the workflow and before starting the worker.
7841    /// Names read through `wait_signal` or `signals` need a declaration for
7842    /// Server command admission. Arguments remain arbitrary positional values,
7843    /// including lossless Avro values. This replaces the previous declaration;
7844    /// an empty slice declares no signals. Names are sorted and deduplicated.
7845    /// Existing runs retain the declarations captured when they started.
7846    pub fn declare_workflow_signals(
7847        &mut self,
7848        workflow_type: &str,
7849        signal_names: &[&str],
7850    ) -> Result<()> {
7851        if !self.workflows.contains_key(workflow_type) {
7852            return Err(Error::Codec(format!(
7853                "workflow type {workflow_type:?} is not registered"
7854            )));
7855        }
7856        if signal_names
7857            .iter()
7858            .any(|name| name.is_empty() || *name != name.trim())
7859        {
7860            return Err(Error::Codec(
7861                "signal names must be non-empty and have no surrounding whitespace".into(),
7862            ));
7863        }
7864        let mut names = signal_names
7865            .iter()
7866            .map(|name| (*name).to_string())
7867            .collect::<Vec<_>>();
7868        names.sort();
7869        names.dedup();
7870        self.signals.insert(workflow_type.to_string(), names);
7871        Ok(())
7872    }
7873
7874    /// Bind a registered workflow to compile-time embedded source for safe redrive.
7875    ///
7876    /// Supply `include_str!` values for the workflow body and every helper whose
7877    /// behavior can affect replay. Register the workflow once, then set its
7878    /// identity before starting the worker. Duplicate registrations are invalid. The server
7879    /// rejects reusing a worker ID when its prior fingerprint disappears.
7880    /// Workflows without source identity remain runnable but cannot be safely redriven.
7881    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
7882    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
7883    pub fn set_workflow_definition_sources(
7884        &mut self,
7885        workflow_type: &str,
7886        sources: &[&str],
7887    ) -> Result<()> {
7888        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
7889            return Err(Error::Codec(
7890                "workflow definition sources must be non-empty".to_string(),
7891            ));
7892        }
7893        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
7894            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
7895        })?;
7896        let mut hasher = Sha256::new();
7897        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
7898        hasher.update((workflow_type.len() as u64).to_be_bytes());
7899        hasher.update(workflow_type.as_bytes());
7900        for source in sources {
7901            hasher.update((source.len() as u64).to_be_bytes());
7902            hasher.update(source.as_bytes());
7903        }
7904        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
7905        Ok(())
7906    }
7907
7908    /// Register a replayable workflow on the lossless fixed Avro Value surface.
7909    #[track_caller]
7910    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
7911        &mut self,
7912        workflow_type: impl Into<String>,
7913        state_factory: Factory,
7914        handler: F,
7915    ) where
7916        S: Clone + Send + Sync + 'static,
7917        Factory: Fn() -> S + Send + Sync + 'static,
7918        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7919        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7920    {
7921        let workflow_type = workflow_type.into();
7922        if !self.admit_registration::<F>(
7923            RegistrationKind::Workflow,
7924            None,
7925            &workflow_type,
7926            "register_replayed_workflow_avro_value",
7927        ) {
7928            return;
7929        }
7930        let state_factory = Arc::new(state_factory);
7931        let handler = Arc::new(handler);
7932
7933        let execute_factory = Arc::clone(&state_factory);
7934        let execute_handler = Arc::clone(&handler);
7935        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7936            let state = WorkflowInstance::new(execute_factory());
7937            Ok(Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture)
7938        });
7939
7940        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7941            let state = WorkflowInstance::new(state_factory());
7942            let snapshot_state = state.clone();
7943            let snapshot: WorkflowStateSnapshot =
7944                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7945            Ok(ReplayedWorkflowInvocation {
7946                future: Box::pin(handler(ctx, input, state)),
7947                snapshot,
7948            })
7949        });
7950
7951        self.workflows.insert(
7952            workflow_type,
7953            RegisteredWorkflow {
7954                execute,
7955                replay: Some(replay),
7956                state_type: Some(TypeId::of::<S>()),
7957                definition_fingerprint: None,
7958            },
7959        );
7960    }
7961
7962    #[track_caller]
7963    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
7964    where
7965        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
7966        Fut: Future<Output = Result<Value>> + Send + 'static,
7967    {
7968        let activity_type = activity_type.into();
7969        if !self.admit_registration::<F>(
7970            RegistrationKind::Activity,
7971            None,
7972            &activity_type,
7973            "register_activity",
7974        ) {
7975            return;
7976        }
7977        let handler = Arc::new(handler);
7978        self.activities.insert(
7979            activity_type,
7980            Arc::new(move |ctx, args| {
7981                let handler = Arc::clone(&handler);
7982                Box::pin(async move {
7983                    let result = handler(ctx, args.into_json()?).await?;
7984                    AvroValue::from_serialize(&result)
7985                })
7986            }),
7987        );
7988    }
7989
7990    /// Register an activity with one Serde request value and a Serde result.
7991    ///
7992    /// Inputs and results use the platform's fixed Avro Value schema. Shape
7993    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
7994    /// with the activity name and Rust type.
7995    #[track_caller]
7996    pub fn register_typed_activity<I, O, F, Fut>(
7997        &mut self,
7998        activity_type: impl Into<String>,
7999        handler: F,
8000    ) where
8001        I: DeserializeOwned + Send + 'static,
8002        O: Serialize + Send + 'static,
8003        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
8004        Fut: Future<Output = Result<O>> + Send + 'static,
8005    {
8006        let activity_type = activity_type.into();
8007        if !self.admit_registration::<F>(
8008            RegistrationKind::Activity,
8009            None,
8010            &activity_type,
8011            "register_typed_activity",
8012        ) {
8013            return;
8014        }
8015        let handler_name = activity_type.clone();
8016        let handler = Arc::new(handler);
8017        self.activities.insert(
8018            activity_type,
8019            Arc::new(move |ctx, input| {
8020                let handler = Arc::clone(&handler);
8021                let handler_name = handler_name.clone();
8022                Box::pin(async move {
8023                    let input =
8024                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
8025                    let result = handler(ctx, input).await?;
8026                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
8027                })
8028            }),
8029        );
8030    }
8031
8032    /// Register an activity on the lossless fixed Avro Value surface.
8033    #[track_caller]
8034    pub fn register_activity_avro_value<F, Fut>(
8035        &mut self,
8036        activity_type: impl Into<String>,
8037        handler: F,
8038    ) where
8039        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
8040        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8041    {
8042        let activity_type = activity_type.into();
8043        if !self.admit_registration::<F>(
8044            RegistrationKind::Activity,
8045            None,
8046            &activity_type,
8047            "register_activity_avro_value",
8048        ) {
8049            return;
8050        }
8051        self.activities.insert(
8052            activity_type,
8053            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
8054        );
8055    }
8056
8057    /// Register a named, read-only query handler for a workflow type.
8058    ///
8059    /// The workflow type must also be registered with [`Worker::register_workflow`]
8060    /// before the worker runs. The handler receives only an immutable committed
8061    /// state snapshot and normalized query arguments.
8062    #[track_caller]
8063    pub fn register_query<F, Fut>(
8064        &mut self,
8065        workflow_type: impl Into<String>,
8066        query_name: impl Into<String>,
8067        handler: F,
8068    ) where
8069        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
8070        Fut: Future<Output = Result<Value>> + Send + 'static,
8071    {
8072        let workflow_type = workflow_type.into();
8073        let query_name = query_name.into();
8074        if !self.admit_registration::<F>(
8075            RegistrationKind::Query,
8076            Some(&workflow_type),
8077            &query_name,
8078            "register_query",
8079        ) {
8080            return;
8081        }
8082        let handler = Arc::new(handler);
8083        self.queries.entry(workflow_type).or_default().insert(
8084            query_name,
8085            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
8086                let handler = Arc::clone(&handler);
8087                Box::pin(async move {
8088                    let result = handler(ctx, args.into_json()?).await?;
8089                    AvroValue::from_serialize(&result)
8090                })
8091            })),
8092        );
8093    }
8094
8095    /// Register a query handler on the lossless fixed Avro Value surface.
8096    #[track_caller]
8097    pub fn register_query_avro_value<F, Fut>(
8098        &mut self,
8099        workflow_type: impl Into<String>,
8100        query_name: impl Into<String>,
8101        handler: F,
8102    ) where
8103        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
8104        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8105    {
8106        let workflow_type = workflow_type.into();
8107        let query_name = query_name.into();
8108        if !self.admit_registration::<F>(
8109            RegistrationKind::Query,
8110            Some(&workflow_type),
8111            &query_name,
8112            "register_query_avro_value",
8113        ) {
8114            return;
8115        }
8116        self.queries.entry(workflow_type).or_default().insert(
8117            query_name,
8118            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
8119        );
8120    }
8121
8122    /// Register a named query against deterministically replayed instance state.
8123    ///
8124    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
8125    /// same state type `S`. The handler receives an immutable, detached state
8126    /// clone, so successful and failed queries cannot affect workflow execution
8127    /// or the state reconstructed by a later query.
8128    #[track_caller]
8129    pub fn register_replayed_query<S, F, Fut>(
8130        &mut self,
8131        workflow_type: impl Into<String>,
8132        query_name: impl Into<String>,
8133        handler: F,
8134    ) where
8135        S: Clone + Send + Sync + 'static,
8136        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
8137        Fut: Future<Output = Result<Value>> + Send + 'static,
8138    {
8139        let workflow_type = workflow_type.into();
8140        let query_name = query_name.into();
8141        if !self.admit_registration::<F>(
8142            RegistrationKind::Query,
8143            Some(&workflow_type),
8144            &query_name,
8145            "register_replayed_query",
8146        ) {
8147            return;
8148        }
8149        let handler = Arc::new(handler);
8150        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
8151            let state = state.downcast::<S>().map_err(|_| {
8152                "registered query state type does not match the replayed workflow state".to_string()
8153            })?;
8154            let handler = Arc::clone(&handler);
8155            Ok(Box::pin(async move {
8156                let result = handler(ctx, state, args.into_json()?).await?;
8157                AvroValue::from_serialize(&result)
8158            }))
8159        });
8160
8161        self.queries.entry(workflow_type).or_default().insert(
8162            query_name,
8163            RegisteredQuery::Replayed {
8164                state_type: TypeId::of::<S>(),
8165                handler: erased_handler,
8166            },
8167        );
8168    }
8169
8170    /// Register a replayed-state query on the lossless fixed Avro Value surface.
8171    #[track_caller]
8172    pub fn register_replayed_query_avro_value<S, F, Fut>(
8173        &mut self,
8174        workflow_type: impl Into<String>,
8175        query_name: impl Into<String>,
8176        handler: F,
8177    ) where
8178        S: Clone + Send + Sync + 'static,
8179        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
8180        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8181    {
8182        let workflow_type = workflow_type.into();
8183        let query_name = query_name.into();
8184        if !self.admit_registration::<F>(
8185            RegistrationKind::Query,
8186            Some(&workflow_type),
8187            &query_name,
8188            "register_replayed_query_avro_value",
8189        ) {
8190            return;
8191        }
8192        let handler = Arc::new(handler);
8193        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
8194            let state = state.downcast::<S>().map_err(|_| {
8195                "registered query state type does not match the replayed workflow state".to_string()
8196            })?;
8197            Ok(Box::pin(handler(ctx, state, args)))
8198        });
8199
8200        self.queries.entry(workflow_type).or_default().insert(
8201            query_name,
8202            RegisteredQuery::Replayed {
8203                state_type: TypeId::of::<S>(),
8204                handler: erased_handler,
8205            },
8206        );
8207    }
8208
8209    /// Register a synchronous workflow update handler.
8210    #[track_caller]
8211    pub fn register_update<F, Fut>(
8212        &mut self,
8213        workflow_type: impl Into<String>,
8214        update_name: impl Into<String>,
8215        handler: F,
8216    ) where
8217        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
8218        Fut: Future<Output = Result<Value>> + Send + 'static,
8219    {
8220        let workflow_type = workflow_type.into();
8221        let update_name = update_name.into();
8222        if !self.admit_registration::<F>(
8223            RegistrationKind::Update,
8224            Some(&workflow_type),
8225            &update_name,
8226            "register_update",
8227        ) {
8228            return;
8229        }
8230        let handler = Arc::new(handler);
8231        self.updates.entry(workflow_type).or_default().insert(
8232            update_name,
8233            Arc::new(move |ctx, args| {
8234                let handler = Arc::clone(&handler);
8235                Box::pin(async move {
8236                    let result = handler(ctx, args.into_json()?).await?;
8237                    AvroValue::from_serialize(&result)
8238                })
8239            }),
8240        );
8241    }
8242
8243    /// Register an update handler on the lossless fixed Avro Value surface.
8244    #[track_caller]
8245    pub fn register_update_avro_value<F, Fut>(
8246        &mut self,
8247        workflow_type: impl Into<String>,
8248        update_name: impl Into<String>,
8249        handler: F,
8250    ) where
8251        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
8252        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8253    {
8254        let workflow_type = workflow_type.into();
8255        let update_name = update_name.into();
8256        if !self.admit_registration::<F>(
8257            RegistrationKind::Update,
8258            Some(&workflow_type),
8259            &update_name,
8260            "register_update_avro_value",
8261        ) {
8262            return;
8263        }
8264        self.updates.entry(workflow_type).or_default().insert(
8265            update_name,
8266            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
8267        );
8268    }
8269
8270    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
8271        self.validate_registration()?;
8272        self.nexus_registration_confirmed
8273            .store(false, Ordering::SeqCst);
8274        self.query_authority_confirmed
8275            .store(false, Ordering::SeqCst);
8276        if self.nexus_cooperative_cancellation_enabled {
8277            let info: Value = self
8278                .client
8279                .request_json(
8280                    reqwest::Method::GET,
8281                    "/cluster/info",
8282                    RequestProtocol::Worker("1.20"),
8283                    Option::<&Value>::None,
8284                )
8285                .await?;
8286            if !nexus::installed_cooperation(&info["worker_protocol"]["server_capabilities"]) {
8287                return Err(Error::CooperativeCancellationUnavailable(
8288                    "nexus_cooperative_cancellation_not_supported: Server must advertise the installed workflow_run bridge".into(),
8289                ));
8290            }
8291        }
8292        if self.require_query_task_authority {
8293            if self.client.worker_protocol_version != WorkerProtocolVersion::V120 {
8294                return Err(Error::WorkerLoop(
8295                    "query authority requires worker protocol 1.20".into(),
8296                ));
8297            }
8298            // Discovery uses the Worker credential, including worker-only Clients.
8299            let discovery: Value = self
8300                .client
8301                .request_json_unresolved_with_timeout::<Value, Value>(
8302                    reqwest::Method::GET,
8303                    "/cluster/info",
8304                    RequestProtocol::Worker("1.20"),
8305                    None,
8306                    Duration::from_secs(5),
8307                )
8308                .await?;
8309            if discovery["worker_protocol"]["server_capabilities"]["query_task_authority"] != true {
8310                return Err(Error::WorkerLoop(
8311                    "runtime does not advertise query_task_authority".into(),
8312                ));
8313            }
8314        }
8315        self.sticky_registration_confirmed
8316            .store(false, Ordering::SeqCst);
8317        self.session_registration_confirmed
8318            .store(false, Ordering::SeqCst);
8319        for capability in &self.resource_capabilities {
8320            worker_session::validate_resource_capability(capability)?;
8321        }
8322        self.local_registration_confirmed
8323            .store(false, Ordering::SeqCst);
8324        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
8325            return Err(Error::CooperativeCancellationUnavailable(
8326                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
8327            ));
8328        }
8329        let mut command_contracts = serde_json::Map::new();
8330        for workflow_type in self.workflows.keys() {
8331            let mut queries = self
8332                .queries
8333                .get(workflow_type)
8334                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
8335                .unwrap_or_default();
8336            queries.sort();
8337            let mut updates = self
8338                .updates
8339                .get(workflow_type)
8340                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
8341                .unwrap_or_default();
8342            updates.sort();
8343            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
8344            command_contracts.insert(
8345                workflow_type.clone(),
8346                json!({
8347                    "queries": queries,
8348                    "query_contracts": argument_vector_contracts(&queries),
8349                    "signals": signals,
8350                    "signal_contracts": argument_vector_contracts(&signals),
8351                    "updates": updates,
8352                    "update_contracts": argument_vector_contracts(&updates),
8353                    "update_validators": [],
8354                }),
8355            );
8356        }
8357
8358        self.cooperative_registration_confirmed
8359            .store(false, Ordering::SeqCst);
8360        #[cfg(feature = "telemetry")]
8361        if self
8362            .telemetry
8363            .as_ref()
8364            .is_some_and(telemetry::ExecutionTelemetry::is_enabled)
8365            && !self
8366                .client
8367                .observability_context_supported
8368                .load(Ordering::SeqCst)
8369        {
8370            // Optional startup discovery is bounded and cached. Its failure
8371            // cannot refuse registration or add retries to a business command.
8372            let _ = self
8373                .client
8374                .request_json_unresolved_with_timeout::<Value, Value>(
8375                    reqwest::Method::GET,
8376                    "/cluster/info",
8377                    RequestProtocol::DefaultWorker,
8378                    None,
8379                    Duration::from_secs(5),
8380                )
8381                .await;
8382        }
8383        let response = self
8384            .client
8385            .register_worker_with_definition_fingerprints(
8386                &self.worker_id,
8387                &self.task_queue,
8388                self.workflows.keys().cloned().collect(),
8389                self.activities.keys().cloned().collect(),
8390                self.max_concurrent_workflow_tasks,
8391                self.max_concurrent_activity_tasks,
8392                [
8393                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
8394                    Some("workflow_entry_arguments_validation".to_string()),
8395                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
8396                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
8397                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
8398                    self.client
8399                        .local_activities_enabled
8400                        .then(|| "local_activities".to_string()),
8401                    self.client
8402                        .worker_sessions_enabled
8403                        .then(|| "worker_sessions".to_string()),
8404                    self.client
8405                        .sticky_cache
8406                        .is_some()
8407                        .then(|| "sticky_execution".to_string()),
8408                    self.cooperative_cancellation_enabled
8409                        .then(|| "cooperative_cancellation".to_string()),
8410                    self.nexus_cooperative_cancellation_enabled
8411                        .then(|| "nexus_cooperative_cancellation".to_string()),
8412                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
8413                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
8414                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
8415                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
8416                ]
8417                .into_iter()
8418                .flatten()
8419                .chain(self.resource_capabilities.iter().cloned())
8420                .collect(),
8421                Value::Object(command_contracts),
8422                Some(
8423                    self.workflows
8424                        .iter()
8425                        .filter_map(|(workflow_type, workflow)| {
8426                            workflow
8427                                .definition_fingerprint
8428                                .as_ref()
8429                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
8430                        })
8431                        .collect(),
8432                ),
8433            )
8434            .await?;
8435        if self.cooperative_cancellation_enabled && response.registered {
8436            self.cooperative_registration_confirmed
8437                .store(true, Ordering::SeqCst);
8438        }
8439        if self.nexus_cooperative_cancellation_enabled && response.registered {
8440            self.nexus_registration_confirmed
8441                .store(true, Ordering::SeqCst);
8442        }
8443        if self.client.local_activities_enabled && response.registered {
8444            self.local_registration_confirmed
8445                .store(true, Ordering::SeqCst);
8446        }
8447        if self.client.worker_sessions_enabled && response.registered {
8448            self.session_registration_confirmed
8449                .store(true, Ordering::SeqCst);
8450        }
8451        if self.client.sticky_cache.is_some() && response.registered {
8452            self.sticky_registration_confirmed
8453                .store(true, Ordering::SeqCst);
8454        }
8455        self.query_authority_confirmed.store(
8456            response.registered
8457                && self.client.worker_protocol_version == WorkerProtocolVersion::V120
8458                && response
8459                    .server_capabilities
8460                    .as_ref()
8461                    .is_some_and(|capabilities| capabilities["query_task_authority"] == true),
8462            Ordering::SeqCst,
8463        );
8464        Ok(response)
8465    }
8466
8467    /// Run until shutdown or a terminal worker error occurs.
8468    ///
8469    /// Empty long-poll expirations do not stop the worker. Retryable poll and
8470    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
8471    /// authentication, protocol, and other non-retryable failures are returned.
8472    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
8473    /// poll and heartbeat outages beyond the ordinary retry budget.
8474    pub async fn run(&self) -> Result<()> {
8475        self.run_until(std::future::pending::<()>()).await
8476    }
8477
8478    /// Run until `shutdown` resolves or a terminal worker error occurs.
8479    ///
8480    /// This has the same liveness and terminal-error contract as [`Worker::run`].
8481    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
8482    where
8483        F: Future<Output = ()>,
8484    {
8485        let _clear_cache_on_drop =
8486            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
8487        let stop = Arc::new(AtomicBool::new(false));
8488        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
8489        let mut worker = self.with_storage_admission(Arc::clone(&stop));
8490        worker.run_stop = Some(Arc::clone(&stop));
8491        let run = worker.run_with_storage_admission(Arc::clone(&stop));
8492        tokio::pin!(run);
8493        tokio::pin!(shutdown);
8494        tokio::select! {
8495            result = &mut run => result,
8496            _ = &mut shutdown => {
8497                stop.store(true, Ordering::SeqCst);
8498                run.await
8499            }
8500        }
8501    }
8502
8503    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
8504        let mut worker = self.clone();
8505        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
8506            policy: self.retry_policy,
8507            stop,
8508            workflow_completion_retry_deadline: None,
8509        });
8510        worker
8511    }
8512
8513    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
8514        let registration = self.register().await?;
8515        if !registration.registered {
8516            return Err(Error::WorkerLoop(format!(
8517                "worker registration for {:?} was not accepted",
8518                self.worker_id
8519            )));
8520        }
8521        let registered_worker_id = registration.worker_id.clone();
8522        let primary = self.run_registered_until(stop, registration).await;
8523        let primary = match (primary, self.close_worker_sessions().await) {
8524            (Ok(()), result) => result,
8525            (Err(error), Ok(())) => Err(error),
8526            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
8527                primary: Box::new(primary),
8528                deregistration: Box::new(close),
8529            }),
8530        };
8531        self.session_registration_confirmed
8532            .store(false, Ordering::SeqCst);
8533        self.cooperative_registration_confirmed
8534            .store(false, Ordering::SeqCst);
8535        self.local_registration_confirmed
8536            .store(false, Ordering::SeqCst);
8537        let deregistration = self
8538            .client
8539            .deregister_worker_registration(&registered_worker_id)
8540            .await;
8541        self.sticky_registration_confirmed
8542            .store(false, Ordering::SeqCst);
8543        self.client.clear_sticky_cache()?;
8544
8545        match (primary, deregistration) {
8546            (Ok(()), Ok(_)) => Ok(()),
8547            (Ok(()), Err(deregistration)) => Err(deregistration),
8548            (Err(primary), Ok(_)) => Err(primary),
8549            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
8550                primary: Box::new(primary),
8551                deregistration: Box::new(deregistration),
8552            }),
8553        }
8554    }
8555
8556    async fn run_registered_until(
8557        &self,
8558        stop: Arc<AtomicBool>,
8559        registration: RegisterWorkerResponse,
8560    ) -> Result<()> {
8561        if self.require_query_task_authority
8562            && !self.query_authority_confirmed.load(Ordering::SeqCst)
8563        {
8564            return Err(Error::WorkerLoop(
8565                "registration did not confirm query_task_authority".into(),
8566            ));
8567        }
8568        let heartbeat_interval = Duration::from_secs(
8569            registration
8570                .heartbeat_interval_seconds
8571                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
8572        );
8573        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
8574        // from the completion of the preceding attempt, including its bounded
8575        // retries. A fixed-epoch interval can leave an already-due tick queued
8576        // while an acknowledgement is slow, producing a catch-up heartbeat as
8577        // soon as that request completes.
8578        let heartbeat = tokio::time::sleep(Duration::ZERO);
8579        tokio::pin!(heartbeat);
8580        // Poll responses may already have leased server-side work by the time
8581        // they become ready, so each poller owns its responses through
8582        // completion or failure instead of racing raw polls in this select.
8583        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
8584            let worker = self.clone();
8585            let stop = Arc::clone(&stop);
8586            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
8587        });
8588        let mut activity_poller = (!self.activities.is_empty()).then(|| {
8589            let worker = self.clone();
8590            let stop = Arc::clone(&stop);
8591            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
8592        });
8593        let mut query_poller = (!self.queries.is_empty()).then(|| {
8594            let worker = self.clone();
8595            let stop = Arc::clone(&stop);
8596            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
8597        });
8598
8599        loop {
8600            tokio::select! {
8601                _ = wait_for_worker_stop(&stop) => {
8602                    stop.store(true, Ordering::SeqCst);
8603                    break;
8604                }
8605                _ = &mut heartbeat => {
8606                    let result = self.retry_worker_operation(|| {
8607                        self.client.heartbeat_worker_with_sessions(
8608                            &self.worker_id,
8609                            self.workflow_capacity.available(),
8610                            self.activity_capacity.available(),
8611                            self.client.worker_sessions_enabled.then(|| self.session_available()),
8612                        )
8613                    }).await;
8614                    heartbeat
8615                        .as_mut()
8616                        .reset(tokio::time::Instant::now() + heartbeat_interval);
8617                    match result {
8618                        Ok(Some(acknowledgement)) => {
8619                            if let Some(observer) = &self.heartbeat_observer {
8620                                observer(&WorkerHeartbeatObservation {
8621                                    worker_id: self.worker_id.clone(),
8622                                    task_queue: self.task_queue.clone(),
8623                                    acknowledged_at_unix_millis: SystemTime::now()
8624                                        .duration_since(UNIX_EPOCH)
8625                                        .unwrap_or_default()
8626                                        .as_millis()
8627                                        .min(u64::MAX as u128)
8628                                        as u64,
8629                                    acknowledgement,
8630                                });
8631                            }
8632                        }
8633                        Ok(None) => break,
8634                        Err(error) => {
8635                            stop.store(true, Ordering::SeqCst);
8636                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
8637                            return Err(error);
8638                        }
8639                    }
8640                }
8641                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
8642                    workflow_poller = None;
8643                    let stopped_by_server = stop.load(Ordering::SeqCst);
8644                    stop.store(true, Ordering::SeqCst);
8645                    let poller_result = optional_poller_result("workflow", result);
8646                    let join_result =
8647                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8648                    poller_result?;
8649                    join_result?;
8650                    if stopped_by_server {
8651                        return Ok(());
8652                    }
8653                    return Err(Error::WorkerLoop(
8654                        "workflow poller stopped unexpectedly".to_string(),
8655                    ));
8656                }
8657                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
8658                    activity_poller = None;
8659                    let stopped_by_server = stop.load(Ordering::SeqCst);
8660                    stop.store(true, Ordering::SeqCst);
8661                    let poller_result = optional_poller_result("activity", result);
8662                    let join_result =
8663                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8664                    poller_result?;
8665                    join_result?;
8666                    if stopped_by_server {
8667                        return Ok(());
8668                    }
8669                    return Err(Error::WorkerLoop(
8670                        "activity poller stopped unexpectedly".to_string(),
8671                    ));
8672                }
8673                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
8674                    query_poller = None;
8675                    let stopped_by_server = stop.load(Ordering::SeqCst);
8676                    stop.store(true, Ordering::SeqCst);
8677                    let poller_result = optional_poller_result("query", result);
8678                    let join_result =
8679                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8680                    poller_result?;
8681                    join_result?;
8682                    if stopped_by_server {
8683                        return Ok(());
8684                    }
8685                    return Err(Error::WorkerLoop(
8686                        "query poller stopped unexpectedly".to_string(),
8687                    ));
8688                }
8689            }
8690        }
8691
8692        join_pollers(
8693            workflow_poller.take(),
8694            activity_poller.take(),
8695            query_poller.take(),
8696        )
8697        .await
8698    }
8699
8700    /// Poll and settle at most one task from each enabled task family.
8701    ///
8702    /// A workflow may reach its server-enforced run deadline while this worker
8703    /// holds a task. When the completion endpoint authoritatively rejects that
8704    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
8705    /// terminal `run_status=failed`, the workflow tick is considered settled:
8706    /// the late command was not recorded and cannot replace the terminal run.
8707    /// Every other completion rejection remains an error. This worker-level
8708    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
8709    /// only bounds how long a client waits for a result.
8710    ///
8711    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
8712    /// the original [`Error::Http`] status and response body.
8713    pub async fn run_once(&self) -> Result<usize> {
8714        self.validate_registration()?;
8715        if self.client.worker_sessions_enabled {
8716            self.require_session_registration()?;
8717        }
8718        if self.cooperative_cancellation_enabled
8719            && !self
8720                .cooperative_registration_confirmed
8721                .load(Ordering::SeqCst)
8722        {
8723            return Err(Error::CooperativeCancellationUnavailable(
8724                "register this cooperative worker before polling tasks".into(),
8725            ));
8726        }
8727        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
8728        let mut handled = 0;
8729        match worker.poll_workflow_once().await? {
8730            ManagedPollOutcome::Handled => handled += 1,
8731            ManagedPollOutcome::Stop => return Ok(handled),
8732            ManagedPollOutcome::Idle => {}
8733        }
8734        match worker.poll_activity_once().await? {
8735            ManagedPollOutcome::Handled => handled += 1,
8736            ManagedPollOutcome::Stop => return Ok(handled),
8737            ManagedPollOutcome::Idle => {}
8738        }
8739        if !self.queries.is_empty() {
8740            match worker.poll_query_once().await? {
8741                ManagedPollOutcome::Handled => handled += 1,
8742                ManagedPollOutcome::Stop => return Ok(handled),
8743                ManagedPollOutcome::Idle => {}
8744            }
8745        }
8746        Ok(handled)
8747    }
8748
8749    async fn poll_workflow_once_reserved(&self) -> Result<ManagedPollOutcome> {
8750        if self.client.sticky_cache.is_some()
8751            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
8752        {
8753            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
8754        }
8755        if self.client.local_activities_enabled
8756            && !self.local_registration_confirmed.load(Ordering::SeqCst)
8757        {
8758            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
8759        }
8760        if self.cooperative_cancellation_enabled {
8761            return self.poll_cooperative_workflow_once().await;
8762        }
8763        let mut poll_metrics = self.metrics.worker(false, "workflow", &self.task_queue);
8764        let poll_request_id = unique_request_id("rust-workflow-poll");
8765        let response = self
8766            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
8767            .await;
8768        poll_metrics.poll(&response, |value| value.0.outcome());
8769        drop(poll_metrics);
8770        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
8771            return Ok(ManagedPollOutcome::Idle);
8772        };
8773        if response.outcome().should_stop() {
8774            return Ok(ManagedPollOutcome::Stop);
8775        }
8776        let memo_updates_supported =
8777            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
8778        let Some(task) = response.task else {
8779            return Ok(ManagedPollOutcome::Idle);
8780        };
8781
8782        let mut task_metrics = self.metrics.worker(true, "workflow", &self.task_queue);
8783        task_metrics.outcome("failed");
8784        let task_id = task.task_id.clone();
8785        let attempt = task.workflow_task_attempt;
8786        let run_id = task.run_id.clone();
8787        let lease_owner = task
8788            .lease_owner
8789            .clone()
8790            .unwrap_or_else(|| self.worker_id.clone());
8791
8792        let decision = match self.execute_workflow_with_local_activities(task).await {
8793            Ok(Some(decision)) => Ok(decision),
8794            Ok(None) => {
8795                task_metrics.outcome("expired");
8796                return Ok(ManagedPollOutcome::Handled);
8797            }
8798            Err(error) => Err(error),
8799        };
8800        let task_outcome = metrics::workflow_task_outcome(decision.as_ref().ok());
8801        let settled = self
8802            .settle_workflow_task_decision(
8803                &task_id,
8804                &lease_owner,
8805                attempt,
8806                run_id.as_deref(),
8807                decision,
8808                memo_updates_supported,
8809                snapshot,
8810            )
8811            .await;
8812        if settled.is_ok() {
8813            task_metrics.outcome(task_outcome);
8814        }
8815        settled
8816    }
8817
8818    #[allow(clippy::too_many_arguments)]
8819    async fn settle_workflow_task_decision(
8820        &self,
8821        task_id: &str,
8822        lease_owner: &str,
8823        attempt: u64,
8824        run_id: Option<&str>,
8825        decision: Result<WorkflowTaskDecision>,
8826        memo_updates_supported: bool,
8827        snapshot: Option<sticky_worker::StickySnapshot>,
8828    ) -> Result<ManagedPollOutcome> {
8829        match decision {
8830            Ok(decision)
8831                if decision.cancellation_delivery.is_some()
8832                    || decision.cancellation_scope_delivery.is_some()
8833                    || decision.cancellation_scope_opening.is_some() =>
8834            {
8835                return Err(Error::CooperativeCancellationUnavailable(
8836                    "worker cancellation delivery has not been negotiated".into(),
8837                ));
8838            }
8839            Ok(decision)
8840                if commands_use_workflow_memo_updates(&decision.commands)
8841                    && !memo_updates_supported =>
8842            {
8843                self.client
8844                    .fail_workflow_task(
8845                        task_id,
8846                        lease_owner,
8847                        attempt,
8848                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
8849                    )
8850                    .await?;
8851            }
8852            Ok(decision) if decision.commands.is_empty() => {
8853                // A replay can consume a recorded pending durable command
8854                // without producing a new command. The standalone protocol
8855                // acknowledges that state through the typed waiting outcome;
8856                // an empty completion is rejected by servers that require at
8857                // least one executable command.
8858                self.client
8859                    .fail_workflow_task_with_type(
8860                        task_id,
8861                        lease_owner,
8862                        attempt,
8863                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
8864                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
8865                    )
8866                    .await?;
8867            }
8868            Ok(decision) => {
8869                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
8870                let completion = self
8871                    .client
8872                    .complete_workflow_task_with_message_streams(
8873                        task_id,
8874                        lease_owner,
8875                        attempt,
8876                        decision.commands,
8877                        decision.message_stream_cursors,
8878                        decision.message_stream_waits,
8879                        sticky_claim,
8880                    )
8881                    .await;
8882                if let Err(error) = completion {
8883                    self.discard_sticky_snapshot(snapshot.as_ref())?;
8884                    if !workflow_task_completion_is_terminal_timeout(
8885                        &error, task_id, attempt, run_id,
8886                    ) {
8887                        return Err(error);
8888                    }
8889                }
8890            }
8891            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
8892            Err(error) => {
8893                self.discard_sticky_snapshot(snapshot.as_ref())?;
8894                if matches!(
8895                    error,
8896                    Error::HandlerType {
8897                        handler_kind: HandlerKind::Workflow,
8898                        value_kind: HandlerValueKind::Input,
8899                        ..
8900                    }
8901                ) {
8902                    self.client
8903                        .fail_workflow_task_with_failure(
8904                            task_id,
8905                            lease_owner,
8906                            attempt,
8907                            json!({
8908                                "message": error.to_string(),
8909                                "type": "WorkflowEntryArgumentsMismatch",
8910                                "reason": "workflow_entry_arguments_mismatch",
8911                            }),
8912                        )
8913                        .await?;
8914                } else {
8915                    self.client
8916                        .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
8917                        .await?;
8918                }
8919            }
8920        }
8921
8922        Ok(ManagedPollOutcome::Handled)
8923    }
8924
8925    async fn poll_activity_once_reserved(&self) -> Result<ManagedPollOutcome> {
8926        if self.client.worker_sessions_enabled {
8927            self.require_session_registration()?;
8928        }
8929        let mut poll_metrics = self.metrics.worker(false, "activity", &self.task_queue);
8930        let poll_request_id = unique_request_id("rust-activity-poll");
8931        let response = self
8932            .retry_worker_operation(|| {
8933                self.client.poll_activity_task_response_with_request_id(
8934                    &self.worker_id,
8935                    &self.task_queue,
8936                    self.poll_timeout,
8937                    &poll_request_id,
8938                    0,
8939                )
8940            })
8941            .await;
8942        poll_metrics.poll(&response, |value| value.outcome());
8943        drop(poll_metrics);
8944        let response = match response {
8945            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
8946            response => response,
8947        };
8948        let Some(response) = self.settle_worker_poll_response(response).await? else {
8949            return Ok(ManagedPollOutcome::Idle);
8950        };
8951        if response.outcome().should_stop() {
8952            return Ok(ManagedPollOutcome::Stop);
8953        }
8954        let Some(task) = response.task else {
8955            return Ok(ManagedPollOutcome::Idle);
8956        };
8957
8958        self.settle_polled_activity(task).await
8959    }
8960
8961    async fn settle_polled_activity(
8962        &self,
8963        task: worker_session::SessionActivityTask,
8964    ) -> Result<ManagedPollOutcome> {
8965        let mut task_metrics = self.metrics.worker(true, "activity", &self.task_queue);
8966        task_metrics.outcome("failed");
8967        let lease = task.activity_lease.clone();
8968        let mut worker = self.clone();
8969        worker.client = self.client.with_activity_lease_authority(
8970            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
8971        );
8972        let operation = worker.execute_polled_activity(task, &mut task_metrics);
8973        let result = match lease.as_ref() {
8974            Some(lease) => lease.authority.protect(operation).await,
8975            None => operation.await,
8976        };
8977        match result {
8978            Err(Error::ActivityExecutionAbandoned(_)) => {
8979                task_metrics.outcome("expired");
8980                Ok(ManagedPollOutcome::Handled)
8981            }
8982            result => result,
8983        }
8984    }
8985
8986    async fn execute_polled_activity(
8987        &self,
8988        task: worker_session::SessionActivityTask,
8989        task_metrics: &mut metrics::WorkerObservation,
8990    ) -> Result<ManagedPollOutcome> {
8991        if self.cooperative_cancellation_enabled {
8992            return self.settle_cooperative_activity(task, task_metrics).await;
8993        }
8994        let session = self.track_session_task(task.worker_session.as_ref())?;
8995        let hydration_claim = task.hydration_claim;
8996        let task = task.task;
8997
8998        let task_id = task.task_id.clone();
8999        let attempt_id = task
9000            .activity_attempt_id
9001            .clone()
9002            .or(task.attempt_id.clone())
9003            .unwrap_or_default();
9004        let lease_owner = task
9005            .lease_owner
9006            .clone()
9007            .unwrap_or_else(|| self.worker_id.clone());
9008        let codec = task.payload_codec.clone();
9009        let result = self
9010            .execute_session_activity_task(task, session, hydration_claim.as_ref())
9011            .await;
9012        let task_outcome = if result.is_ok() {
9013            "completed"
9014        } else if matches!(result, Err(Error::ActivityExecutionAbandoned(_))) {
9015            "expired"
9016        } else {
9017            "failed"
9018        };
9019        match result {
9020            Err(Error::ActivityExecutionAbandoned(_)) => {}
9021            Err(error) if activity_hydration::stopped(&error) => {}
9022            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
9023            Ok(value) => {
9024                let completion = self
9025                    .client
9026                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
9027                    .await;
9028                if let Err(error) = completion {
9029                    if !activity_task_rejection_is_final(&error) {
9030                        return Err(error);
9031                    }
9032                }
9033            }
9034            Err(error) => {
9035                let failure = self
9036                    .client
9037                    .fail_activity_task_with_error(
9038                        &task_id,
9039                        &attempt_id,
9040                        &lease_owner,
9041                        &ActivityError::from_error(&error, "RustActivityFailure"),
9042                    )
9043                    .await;
9044                if let Err(error) = failure {
9045                    if !activity_task_rejection_is_final(&error) {
9046                        return Err(error);
9047                    }
9048                }
9049            }
9050        }
9051
9052        task_metrics.outcome(task_outcome);
9053        Ok(ManagedPollOutcome::Handled)
9054    }
9055
9056    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
9057        let mut poll_metrics = self.metrics.worker(false, "query", &self.task_queue);
9058        let poll_request_id = unique_request_id("rust-query-poll");
9059        let response = self
9060            .retry_worker_operation(|| {
9061                let body = json!({"worker_id":self.worker_id,"task_queue":self.task_queue,
9062                    "poll_request_id":poll_request_id,
9063                    "timeout_seconds":long_poll_timeout_seconds(self.poll_timeout)});
9064                async move {
9065                    self.client
9066                        .poll_request_json_unresolved::<Value, Value>(
9067                            "/worker/query-tasks/poll",
9068                            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
9069                            &body,
9070                            self.poll_timeout + Duration::from_secs(5),
9071                            0,
9072                        )
9073                        .await
9074                }
9075            })
9076            .await;
9077        poll_metrics.poll(&response, |value| {
9078            worker_poll_outcome(
9079                value.get("task").is_some_and(|task| !task.is_null()),
9080                value.get("poll_status").and_then(Value::as_str),
9081                value.get("reason").and_then(Value::as_str),
9082            )
9083        });
9084        drop(poll_metrics);
9085        let Some(mut wire) = self.settle_worker_poll_response(response).await? else {
9086            return Ok(ManagedPollOutcome::Idle);
9087        };
9088        let authority = if wire.get("task").is_some_and(|task| !task.is_null()) {
9089            match query_authority::Authority::capture(&wire["task"], self) {
9090                Ok(authority) => authority,
9091                Err(_) => return Ok(ManagedPollOutcome::Handled),
9092            }
9093        } else {
9094            None
9095        };
9096        let loading = self.client.resolve_runtime_payloads(
9097            &mut wire,
9098            "/worker/query-tasks/poll",
9099            RequestProtocol::Worker(self.client.worker_protocol_version.as_str()),
9100        );
9101        match query_authority::Authority::protect(authority.as_ref(), self, loading).await {
9102            Err(_) => return Ok(ManagedPollOutcome::Handled),
9103            Ok(result) => result?,
9104        }
9105        let response: PollQueryTaskResponse = serde_json::from_value(wire)?;
9106        if response.outcome().should_stop() {
9107            return Ok(ManagedPollOutcome::Stop);
9108        }
9109        let Some(task) = response.task else {
9110            return Ok(ManagedPollOutcome::Idle);
9111        };
9112
9113        let mut task_metrics = self.metrics.worker(true, "query", &self.task_queue);
9114        task_metrics.outcome("failed");
9115        let query_task_id = task.query_task_id.clone();
9116        let attempt = task.query_task_attempt;
9117        let lease_owner = task
9118            .lease_owner
9119            .clone()
9120            .unwrap_or_else(|| self.worker_id.clone());
9121        let codec = task.payload_codec.clone();
9122
9123        let execution = query_authority::Authority::protect(
9124            authority.as_ref(),
9125            self,
9126            self.execute_query_task_with_authority(task, authority.as_ref()),
9127        )
9128        .await;
9129        let execution = match execution {
9130            Err(_) => return Ok(ManagedPollOutcome::Handled),
9131            Ok(Err(failure)) if failure.reason == "query_authority_lost" => {
9132                return Ok(ManagedPollOutcome::Handled)
9133            }
9134            Ok(result) => result,
9135        };
9136        let task_outcome = if execution.is_ok() {
9137            "completed"
9138        } else {
9139            "failed"
9140        };
9141        match execution {
9142            Ok(value) => {
9143                let result_envelope = match encode_typed_envelope(&value, &codec) {
9144                    Ok(result_envelope) => result_envelope,
9145                    Err(error) => {
9146                        let failure = query_authority::Authority::protect(
9147                            authority.as_ref(),
9148                            self,
9149                            self.client.fail_query_task(
9150                                &query_task_id,
9151                                &lease_owner,
9152                                attempt,
9153                                error.to_string(),
9154                                "query_result_encode_failed",
9155                                "QueryResultEncodeFailed",
9156                            ),
9157                        )
9158                        .await;
9159                        let Ok(failure) = failure else {
9160                            return Ok(ManagedPollOutcome::Handled);
9161                        };
9162                        if let Err(error) = failure {
9163                            if !query_task_rejection_is_final(&error) {
9164                                return Err(error);
9165                            }
9166                        }
9167                        return Ok(ManagedPollOutcome::Handled);
9168                    }
9169                };
9170
9171                let completion = query_authority::Authority::protect(
9172                    authority.as_ref(),
9173                    self,
9174                    self.client.complete_query_task_with_envelope(
9175                        &query_task_id,
9176                        &lease_owner,
9177                        attempt,
9178                        value.clone().into_json()?,
9179                        result_envelope,
9180                    ),
9181                )
9182                .await;
9183                let Ok(completion) = completion else {
9184                    return Ok(ManagedPollOutcome::Handled);
9185                };
9186                if let Err(error) = completion {
9187                    if !query_task_rejection_is_final(&error) {
9188                        return Err(error);
9189                    }
9190                }
9191            }
9192            Err(failure) => {
9193                let result = query_authority::Authority::protect(
9194                    authority.as_ref(),
9195                    self,
9196                    self.client.fail_query_task(
9197                        &query_task_id,
9198                        &lease_owner,
9199                        attempt,
9200                        failure.message,
9201                        failure.reason,
9202                        failure.failure_type,
9203                    ),
9204                )
9205                .await;
9206                let Ok(result) = result else {
9207                    return Ok(ManagedPollOutcome::Handled);
9208                };
9209                if let Err(error) = result {
9210                    if !query_task_rejection_is_final(&error) {
9211                        return Err(error);
9212                    }
9213                }
9214            }
9215        }
9216
9217        task_metrics.outcome(task_outcome);
9218        Ok(ManagedPollOutcome::Handled)
9219    }
9220
9221    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
9222        while !stop.load(Ordering::SeqCst) {
9223            match self.poll_query_once().await {
9224                Ok(ManagedPollOutcome::Stop) => {
9225                    stop.store(true, Ordering::SeqCst);
9226                    break;
9227                }
9228                Err(error) => {
9229                    stop.store(true, Ordering::SeqCst);
9230                    return Err(error);
9231                }
9232                _ => {}
9233            }
9234        }
9235
9236        Ok(())
9237    }
9238
9239    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
9240    where
9241        F: FnMut() -> Fut,
9242        Fut: Future<Output = Result<T>>,
9243    {
9244        let mut retries = 0;
9245
9246        loop {
9247            if self
9248                .run_stop
9249                .as_ref()
9250                .is_some_and(|stop| stop.load(Ordering::SeqCst))
9251            {
9252                return Ok(None);
9253            }
9254            match operation().await {
9255                Err(error)
9256                    if (workflow_hydration::stopped(&error)
9257                        || activity_hydration::stopped(&error))
9258                        && self
9259                            .run_stop
9260                            .as_ref()
9261                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
9262                {
9263                    return Ok(None);
9264                }
9265                Err(error)
9266                    if worker_operation_is_retryable(&error)
9267                        && (retries < self.retry_policy.max_retries
9268                            || (self.recover_transient_outages
9269                                && self.run_stop.is_some()
9270                                && self.retry_policy.max_retries > 0)) =>
9271                {
9272                    retries = retries.saturating_add(1);
9273                    let delay = worker_retry_delay(self.retry_policy, retries)
9274                        .max(Duration::from_millis(1));
9275                    if let Some(stop) = &self.run_stop {
9276                        tokio::select! {
9277                            _ = tokio::time::sleep(delay) => {}
9278                            _ = wait_for_worker_stop(stop) => return Ok(None),
9279                        }
9280                    } else {
9281                        tokio::time::sleep(delay).await;
9282                    }
9283                }
9284                result => return result.map(Some),
9285            }
9286        }
9287    }
9288
9289    async fn settle_worker_poll_response<T>(
9290        &self,
9291        response: Result<Option<T>>,
9292    ) -> Result<Option<T>> {
9293        match response {
9294            Ok(response) => Ok(response),
9295            Err(error) => {
9296                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
9297                    return Err(error);
9298                };
9299                let minimum_delay = self
9300                    .retry_policy
9301                    .initial_backoff
9302                    .max(Duration::from_millis(1));
9303                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
9304                tokio::time::sleep(advertised_delay.max(minimum_delay).min(maximum_delay)).await;
9305                Ok(None)
9306            }
9307        }
9308    }
9309
9310    #[cfg(test)]
9311    async fn execute_query_task(
9312        &self,
9313        task: QueryTask,
9314    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9315        self.execute_query_task_with_authority(task, None).await
9316    }
9317
9318    async fn execute_query_task_with_authority(
9319        &self,
9320        task: QueryTask,
9321        authority: Option<&query_authority::Authority>,
9322    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9323        #[cfg(feature = "telemetry")]
9324        if let Some(telemetry) = &self.telemetry {
9325            return telemetry
9326                .run_observed(
9327                    "durable.query.task",
9328                    self.query_telemetry_fields(&task),
9329                    false,
9330                    authority.and_then(|_| self.query_observations(&task)),
9331                    self.execute_query_task_inner(task, authority),
9332                )
9333                .await;
9334        }
9335        self.execute_query_task_inner(task, authority).await
9336    }
9337
9338    async fn execute_query_task_inner(
9339        &self,
9340        mut task: QueryTask,
9341        authority: Option<&query_authority::Authority>,
9342    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9343        validate_query_task_payloads(&task).map_err(|error| {
9344            QueryTaskExecutionFailure::new(
9345                "query_payload_decode_failed",
9346                error.to_string(),
9347                "QueryPayloadDecodeFailed",
9348            )
9349        })?;
9350
9351        if !self.workflows.contains_key(&task.workflow_type) {
9352            return Err(QueryTaskExecutionFailure::new(
9353                "query_workflow_type_not_registered",
9354                format!("no workflow registered for type {:?}", task.workflow_type),
9355                "WorkflowTypeNotRegistered",
9356            ));
9357        }
9358
9359        let Some(handlers) = self.queries.get(&task.workflow_type) else {
9360            return Err(QueryTaskExecutionFailure::new(
9361                "query_handler_unavailable",
9362                format!(
9363                    "query handlers are unavailable for workflow type {:?}",
9364                    task.workflow_type
9365                ),
9366                "QueryHandlerUnavailable",
9367            ));
9368        };
9369        let Some(query) = handlers.get(&task.query_name) else {
9370            return Err(QueryTaskExecutionFailure::new(
9371                "rejected_unknown_query",
9372                format!("unknown query {:?}", task.query_name),
9373                "QueryFailed",
9374            ));
9375        };
9376
9377        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
9378            .map_err(|error| {
9379            QueryTaskExecutionFailure::new(
9380                "query_payload_decode_failed",
9381                format!("cannot decode query arguments: {error}"),
9382                "QueryPayloadDecodeFailed",
9383            )
9384        })?;
9385        let workflow_input_typed =
9386            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
9387                .map_err(|error| {
9388                    QueryTaskExecutionFailure::new(
9389                        "query_workflow_state_unavailable",
9390                        format!("cannot decode workflow start input: {error}"),
9391                        "QueryWorkflowStateUnavailable",
9392                    )
9393                })?;
9394        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
9395            QueryTaskExecutionFailure::new(
9396                "query_workflow_state_unavailable",
9397                format!("cannot project workflow start input: {error}"),
9398                "QueryWorkflowStateUnavailable",
9399            )
9400        })?;
9401        hydrate_query_history_from_export(&mut task).map_err(|error| {
9402            QueryTaskExecutionFailure::new(
9403                "query_workflow_state_unavailable",
9404                format!("cannot restore query history snapshot: {error}"),
9405                "QueryWorkflowStateUnavailable",
9406            )
9407        })?;
9408        enrich_query_history_from_export(&mut task).map_err(|error| {
9409            QueryTaskExecutionFailure::new(
9410                "query_workflow_state_unavailable",
9411                format!("cannot restore compact query history payloads: {error}"),
9412                "QueryWorkflowStateUnavailable",
9413            )
9414        })?;
9415        let signal_events = query_signal_events(&task).map_err(|error| {
9416            QueryTaskExecutionFailure::new(
9417                "query_workflow_state_unavailable",
9418                format!("cannot decode committed workflow signals: {error}"),
9419                "QueryWorkflowStateUnavailable",
9420            )
9421        })?;
9422        let history_events = Arc::new(std::mem::take(&mut task.history_events));
9423        let context = QueryContext {
9424            workflow_id: task.workflow_id,
9425            run_id: task.run_id,
9426            workflow_type: task.workflow_type.clone(),
9427            run_status: task.run_status,
9428            workflow_input,
9429            workflow_input_avro_value: workflow_input_typed.clone(),
9430            history_events: Arc::clone(&history_events),
9431            signal_events: Arc::new(signal_events),
9432        };
9433
9434        let future = match query {
9435            RegisteredQuery::Snapshot(handler) => {
9436                query_authority::before_handler(authority, &self.client).await?;
9437                handler(context, args)
9438            }
9439            RegisteredQuery::Replayed {
9440                state_type,
9441                handler,
9442            } => {
9443                let workflow = self
9444                    .workflows
9445                    .get(&task.workflow_type)
9446                    .expect("workflow registration was checked above");
9447                if workflow.state_type != Some(*state_type) {
9448                    return Err(QueryTaskExecutionFailure::new(
9449                        "query_workflow_state_unavailable",
9450                        "replayed query state type does not match its workflow registration",
9451                        "QueryWorkflowStateUnavailable",
9452                    ));
9453                }
9454                let replay = workflow.replay.as_ref().ok_or_else(|| {
9455                    QueryTaskExecutionFailure::new(
9456                        "query_workflow_state_unavailable",
9457                        format!(
9458                            "workflow type {:?} is not registered for instance-state replay",
9459                            task.workflow_type
9460                        ),
9461                        "QueryWorkflowStateUnavailable",
9462                    )
9463                })?;
9464                let workflow_state = Arc::new(Mutex::new(
9465                    WorkflowState::new_with_identity(
9466                        history_events.as_ref().clone(),
9467                        context.workflow_id.clone(),
9468                        context.run_id.clone(),
9469                        self.task_queue.clone(),
9470                        task.payload_codec,
9471                        None,
9472                    )
9473                    .map_err(|error| {
9474                        QueryTaskExecutionFailure::new(
9475                            "query_workflow_state_unavailable",
9476                            format!("workflow replay failed before query: {error}"),
9477                            "QueryWorkflowStateUnavailable",
9478                        )
9479                    })?,
9480                ));
9481                let workflow_context = WorkflowContext {
9482                    state: workflow_state,
9483                    cancellation_scope_id: "root".into(),
9484                };
9485                query_authority::before_handler(authority, &self.client).await?;
9486                let mut invocation = replay(workflow_context.clone(), workflow_input_typed.clone())
9487                    .map_err(|error| {
9488                        QueryTaskExecutionFailure::new(
9489                            "query_workflow_state_unavailable",
9490                            error.to_string(),
9491                            "QueryWorkflowStateUnavailable",
9492                        )
9493                    })?;
9494                let outcome = {
9495                    let mut cx = TaskContext::from_waker(noop_waker_ref());
9496                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
9497                        .map_err(|error| {
9498                            QueryTaskExecutionFailure::new(
9499                                "query_workflow_state_unavailable",
9500                                error.to_string(),
9501                                "QueryWorkflowStateUnavailable",
9502                            )
9503                        })?;
9504                    invocation.future.as_mut().poll(&mut cx)
9505                };
9506                match outcome {
9507                    Poll::Ready(Ok(_)) => {
9508                        workflow_context
9509                            .ensure_history_consumed()
9510                            .map_err(|error| {
9511                                QueryTaskExecutionFailure::new(
9512                                    "query_workflow_state_unavailable",
9513                                    format!("workflow replay failed before query: {error}"),
9514                                    "QueryWorkflowStateUnavailable",
9515                                )
9516                            })?;
9517                    }
9518                    Poll::Ready(Err(error)) => {
9519                        return Err(QueryTaskExecutionFailure::new(
9520                            "query_workflow_state_unavailable",
9521                            format!("workflow replay failed before query: {error}"),
9522                            "QueryWorkflowStateUnavailable",
9523                        ));
9524                    }
9525                    Poll::Pending => {
9526                        let commands = workflow_context.take_commands().map_err(|error| {
9527                            QueryTaskExecutionFailure::new(
9528                                "query_workflow_state_unavailable",
9529                                format!("workflow replay failed before query: {error}"),
9530                                "QueryWorkflowStateUnavailable",
9531                            )
9532                        })?;
9533                        if commands.is_empty()
9534                            && !workflow_context
9535                                .matched_recorded_pending()
9536                                .map_err(|error| {
9537                                    QueryTaskExecutionFailure::new(
9538                                        "query_workflow_state_unavailable",
9539                                        format!("workflow replay failed before query: {error}"),
9540                                        "QueryWorkflowStateUnavailable",
9541                                    )
9542                                })?
9543                        {
9544                            return Err(QueryTaskExecutionFailure::new(
9545                                "query_workflow_state_unavailable",
9546                                "workflow replay yielded without a durable command",
9547                                "QueryWorkflowStateUnavailable",
9548                            ));
9549                        }
9550                    }
9551                }
9552                let state = (invocation.snapshot)().map_err(|error| {
9553                    QueryTaskExecutionFailure::new(
9554                        "query_workflow_state_unavailable",
9555                        format!("cannot snapshot replayed workflow state: {error}"),
9556                        "QueryWorkflowStateUnavailable",
9557                    )
9558                })?;
9559                query_authority::before_handler(authority, &self.client).await?;
9560                handler(context, state, args).map_err(|message| {
9561                    QueryTaskExecutionFailure::new(
9562                        "query_workflow_state_unavailable",
9563                        message,
9564                        "QueryWorkflowStateUnavailable",
9565                    )
9566                })?
9567            }
9568        };
9569
9570        future.await.map_err(|error| {
9571            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
9572        })
9573    }
9574
9575    #[cfg(test)]
9576    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
9577        Ok(self.execute_workflow_task_decision(task)?.commands)
9578    }
9579
9580    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
9581        self.execute_workflow_task_decision_with_cancellation(task, None)
9582    }
9583
9584    fn execute_workflow_task_decision_with_cancellation(
9585        &self,
9586        task: WorkflowTask,
9587        observation: Option<&CancellationRequest>,
9588    ) -> Result<WorkflowTaskDecision> {
9589        #[cfg(feature = "telemetry")]
9590        if let Some(telemetry) = &self.telemetry {
9591            return telemetry.run_sync_observed(
9592                "durable.workflow.task",
9593                self.workflow_telemetry_fields(&task),
9594                self.workflow_observations(&task),
9595                || {
9596                    let mut decision =
9597                        self.execute_workflow_task_decision_inner(task, observation)?;
9598                    self.stamp_observability_commands(&mut decision.commands);
9599                    Ok(decision)
9600                },
9601            );
9602        }
9603        self.execute_workflow_task_decision_inner(task, observation)
9604    }
9605
9606    fn execute_workflow_task_decision_inner(
9607        &self,
9608        task: WorkflowTask,
9609        observation: Option<&CancellationRequest>,
9610    ) -> Result<WorkflowTaskDecision> {
9611        match self.prepare_workflow_task_execution(task, observation)? {
9612            PreparedWorkflowTask::Decision(decision) => Ok(decision),
9613            PreparedWorkflowTask::Execution {
9614                task,
9615                context,
9616                mut future,
9617            } => {
9618                let outcome = Self::poll_workflow_future(&context, &mut future)?;
9619                self.finish_workflow_task_execution(&task, &context, outcome)
9620            }
9621        }
9622    }
9623
9624    fn prepare_workflow_task_execution(
9625        &self,
9626        task: WorkflowTask,
9627        observation: Option<&CancellationRequest>,
9628    ) -> Result<PreparedWorkflowTask> {
9629        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
9630            && !self.cooperative_cancellation_enabled
9631        {
9632            return Err(Error::CancellationScopeExecutionUnavailable);
9633        }
9634        validate_workflow_task_payloads(&task)?;
9635        cooperative_cancellation::assert_cancellation_scope_replay_supported(
9636            &task.history_events,
9637            self.allow_cancellation_scope_authoring,
9638            self.allow_cancellation_scope_delivery,
9639        )?;
9640        let cancellation_history = if let Some(observation) = observation {
9641            observation.validate_observation()?;
9642            cooperative_cancellation::cancellation_claim(&task)?;
9643            let canonical = CancellationHistory::from_events(
9644                &task.history_events,
9645                task.run_id.as_deref().unwrap_or_default(),
9646                Some(observation),
9647            )?;
9648            if canonical.request_index >= task.history_events.len() {
9649                return Err(Error::InvalidCooperativeCancellation(
9650                    "workflow replay requires the observed canonical request".into(),
9651                ));
9652            }
9653            Some(canonical)
9654        } else {
9655            None
9656        };
9657        if let Some(update_id) = task
9658            .workflow_update_id
9659            .as_deref()
9660            .filter(|update_id| !update_id.is_empty())
9661        {
9662            if self.allow_cancellation_scope_delivery {
9663                return Err(Error::CancellationScopeExecutionUnavailable);
9664            }
9665            CancellationHistory::from_events(
9666                &task.history_events,
9667                task.run_id.as_deref().unwrap_or_default(),
9668                None,
9669            )?;
9670            return self
9671                .execute_update_task(&task, update_id)
9672                .map(WorkflowTaskDecision::without_message_streams)
9673                .map(PreparedWorkflowTask::Decision);
9674        }
9675
9676        let workflow = self
9677            .workflows
9678            .get(&task.workflow_type)
9679            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
9680        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9681        let resume_signal = decode_resume_signal(&task)?;
9682        let history_budget = WorkflowHistoryBudget {
9683            event_count: task
9684                .total_history_events
9685                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
9686            size_bytes: task.history_size_bytes,
9687            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
9688            pressure: task.history_budget_pressure.clone(),
9689        };
9690        let workflow_command_identity = task
9691            .workflow_command_id
9692            .clone()
9693            .filter(|identity| !identity.is_empty())
9694            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
9695            .unwrap_or_default();
9696        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
9697            task.history_events.clone(),
9698            task.workflow_id.clone(),
9699            task.run_id.clone(),
9700            self.task_queue.clone(),
9701            task.payload_codec.clone(),
9702            resume_signal,
9703            self.allow_cancellation_scope_authoring,
9704            self.allow_cancellation_scope_delivery,
9705        )?;
9706        workflow_state.history_budget = history_budget;
9707        workflow_state.workflow_command_identity = workflow_command_identity;
9708        if let Some(canonical) = cancellation_history {
9709            workflow_state.cancellation_history = canonical;
9710            workflow_state.cancellation_delivery_enabled = true;
9711        }
9712        if workflow_state.cancellation_history.request.is_none() {
9713            workflow_state.cancel_requested = task.cancel_requested;
9714        }
9715        let state = Arc::new(Mutex::new(workflow_state));
9716        let ctx = WorkflowContext {
9717            state,
9718            cancellation_scope_id: "root".into(),
9719        };
9720        let future = (workflow.execute)(ctx.clone(), input)?;
9721        Ok(PreparedWorkflowTask::Execution {
9722            task,
9723            context: ctx,
9724            future,
9725        })
9726    }
9727
9728    fn poll_workflow_future(
9729        ctx: &WorkflowContext,
9730        future: &mut WorkflowFuture,
9731    ) -> Result<Poll<Result<AvroValue>>> {
9732        let mut cx = TaskContext::from_waker(noop_waker_ref());
9733        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
9734        Ok(future.as_mut().poll(&mut cx))
9735    }
9736
9737    fn finish_workflow_task_execution(
9738        &self,
9739        task: &WorkflowTask,
9740        ctx: &WorkflowContext,
9741        outcome: Poll<Result<AvroValue>>,
9742    ) -> Result<WorkflowTaskDecision> {
9743        if !ctx
9744            .state
9745            .lock()
9746            .map_err(|_| Error::WorkflowStatePoisoned)?
9747            .local_activity_requests
9748            .is_empty()
9749        {
9750            return Err(Error::CooperativeCancellationUnavailable(
9751                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
9752            ));
9753        }
9754        let awaiting_canonical_boundary = {
9755            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9756            state.cancellation_delivery_intent.is_some()
9757                || state.cancellation_scope_opening.is_some()
9758                || state
9759                    .scope_delivery
9760                    .as_ref()
9761                    .is_some_and(|replay| replay.intent.is_some())
9762        };
9763        if awaiting_canonical_boundary {
9764            // A private delivery intent never becomes an application error.
9765            // Even a custom future which ignores a pending durable call cannot
9766            // publish terminal commands before canonical delivery and replay.
9767            if let Poll::Ready(Err(error)) = outcome {
9768                if workflow_task_integrity_error(&error) {
9769                    return Err(error);
9770                }
9771            }
9772            return self.message_stream_decision(&ctx, ctx.take_commands()?);
9773        }
9774
9775        match outcome {
9776            Poll::Ready(Ok(result)) => {
9777                ctx.ensure_history_consumed()?;
9778                let result = encode_typed_envelope(&result, &task.payload_codec)?;
9779                let mut commands = ctx.take_commands()?;
9780                commands.push(json!({
9781                    "type": "complete_workflow",
9782                    "result": result
9783                }));
9784                self.message_stream_decision(&ctx, commands)
9785            }
9786            Poll::Ready(Err(error)) => {
9787                if let Error::ContinueAsNew(request) = error {
9788                    let mut commands = ctx.take_commands()?;
9789                    if let Some(command) = ctx.continue_as_new_command(request)? {
9790                        commands.push(command);
9791                    }
9792                    ctx.ensure_history_consumed()?;
9793                    return self.message_stream_decision(&ctx, commands);
9794                }
9795                if workflow_task_integrity_error(&error) {
9796                    // Replay and protocol failures describe the workflow-task
9797                    // decision itself. Preserve their specific failure reason
9798                    // instead of replacing it with the derivative fact that
9799                    // recorded commands remain unconsumed.
9800                    return Err(error);
9801                }
9802                // A handler error must not hide a committed durable command that
9803                // upgraded workflow code no longer consumes.
9804                ctx.ensure_history_consumed()?;
9805                let mut commands = ctx.take_commands()?;
9806                commands.push(workflow_failure_command(
9807                    &error,
9808                    recorded_activity_failure_boundary(&ctx, &error),
9809                ));
9810                self.message_stream_decision(&ctx, commands)
9811            }
9812            Poll::Pending => {
9813                let commands = ctx.take_commands()?;
9814                if commands.is_empty() && !ctx.matched_recorded_pending()? {
9815                    Err(Error::WorkflowYieldedWithoutCommand)
9816                } else {
9817                    self.message_stream_decision(&ctx, commands)
9818                }
9819            }
9820        }
9821    }
9822
9823    fn message_stream_decision(
9824        &self,
9825        ctx: &WorkflowContext,
9826        commands: Vec<Value>,
9827    ) -> Result<WorkflowTaskDecision> {
9828        if !self.cooperative_cancellation_enabled
9829            && commands.iter().any(|command| {
9830                command["type"] == "schedule_activity"
9831                    && command.get("cancellation_policy").is_some()
9832            })
9833        {
9834            return Err(Error::CooperativeCancellationUnavailable(format!(
9835                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9836                self.worker_id,
9837            )));
9838        }
9839        if !self.cooperative_cancellation_enabled
9840            && commands.iter().any(|command| {
9841                command["type"] == "start_child_workflow"
9842                    && (command["parent_close_policy"] == "request_cancellation"
9843                        || matches!(
9844                            command["cancellation_policy"].as_str(),
9845                            Some("try_cancel" | "wait_cancellation_completed")
9846                        ))
9847            })
9848        {
9849            return Err(Error::CooperativeCancellationUnavailable(format!(
9850                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
9851                self.worker_id,
9852            )));
9853        }
9854        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
9855        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
9856        let scope_delivery = state
9857            .scope_delivery
9858            .as_ref()
9859            .and_then(|replay| replay.intent.clone());
9860        if scope_delivery
9861            .as_ref()
9862            .is_some_and(|intent| commands.len() != intent.command_count)
9863        {
9864            return Err(invalid_recorded_history(
9865                "cancellation_scope_pending_call_escaped",
9866                scope_delivery.as_ref().unwrap().boundary.sequence,
9867                "commands preceding the pending scoped call",
9868                "commands after suspension",
9869                "workflow cannot publish beyond an uncommitted scope delivery",
9870            ));
9871        }
9872        if let Some(opening) = &state.cancellation_scope_opening {
9873            if commands.len() != opening.command_count {
9874                return Err(invalid_recorded_history(
9875                    "cancellation_scope_pending_call_escaped",
9876                    opening.sequence,
9877                    "commands before original scope opening",
9878                    "commands after suspended opening",
9879                    "workflow cannot publish beyond an uncommitted scope opening",
9880                ));
9881            }
9882        }
9883        if state.cancellation_delivery_intent.is_some()
9884            && commands.len() != state.cancellation_delivery_command_count
9885        {
9886            return Err(invalid_recorded_history(
9887                "cooperative_cancellation_pending_call_escaped",
9888                state
9889                    .cancellation_delivery_intent
9890                    .as_ref()
9891                    .expect("pending delivery")
9892                    .sequence,
9893                "only commands preceding the pending cancellation call",
9894                "commands authored after a suspended call",
9895                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
9896            ));
9897        }
9898        Ok(WorkflowTaskDecision {
9899            commands,
9900            message_stream_cursors,
9901            message_stream_waits,
9902            cancellation_delivery: state.cancellation_delivery_intent.clone(),
9903            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
9904            cancellation_scope_delivery: scope_delivery,
9905        })
9906    }
9907
9908    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
9909        if !self.workflows.contains_key(&task.workflow_type) {
9910            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
9911        }
9912
9913        let accepted = task.history_events.iter().rev().find_map(|event| {
9914            (event.event_type == "UpdateAccepted"
9915                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
9916            .then_some(&event.payload)
9917        });
9918        let update_name = accepted
9919            .and_then(|payload| payload.get("update_name"))
9920            .and_then(Value::as_str)
9921            .or(task.update_name.as_deref())
9922            .unwrap_or_default();
9923        let Some(handler) = self
9924            .updates
9925            .get(&task.workflow_type)
9926            .and_then(|handlers| handlers.get(update_name))
9927        else {
9928            return Ok(vec![json!({
9929                "type": "fail_update",
9930                "update_id": update_id,
9931                "message": format!(
9932                    "no update handler is registered for {}.{update_name}",
9933                    task.workflow_type
9934                ),
9935                "exception_type": "UnknownUpdate",
9936                "non_retryable": true,
9937            })]);
9938        };
9939        let arguments = accepted
9940            .and_then(|payload| payload.get("arguments"))
9941            .or(task.arguments.as_ref());
9942        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
9943        let workflow_input_avro_value =
9944            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
9945        let workflow_input = workflow_input_avro_value.clone().into_json()?;
9946        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
9947        let context = QueryContext {
9948            workflow_id: task.workflow_id.clone(),
9949            run_id: task.run_id.clone(),
9950            workflow_type: task.workflow_type.clone(),
9951            run_status: Some("running".to_string()),
9952            workflow_input,
9953            workflow_input_avro_value,
9954            history_events: Arc::new(task.history_events.clone()),
9955            signal_events: Arc::new(signal_events),
9956        };
9957        let mut future = handler(context, arguments);
9958        let mut cx = TaskContext::from_waker(noop_waker_ref());
9959
9960        match future.as_mut().poll(&mut cx) {
9961            Poll::Ready(Ok(result)) => Ok(vec![json!({
9962                "type": "complete_update",
9963                "update_id": update_id,
9964                "result": encode_typed_envelope(&result, &task.payload_codec)?,
9965            })]),
9966            Poll::Ready(Err(error)) => Ok(vec![json!({
9967                "type": "fail_update",
9968                "update_id": update_id,
9969                "message": error.to_string(),
9970                "exception_type": "UpdateFailed",
9971                "non_retryable": true,
9972            })]),
9973            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
9974        }
9975    }
9976
9977    #[cfg(test)]
9978    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
9979        self.execute_session_activity_task(task, None, None).await
9980    }
9981
9982    async fn execute_session_activity_task(
9983        &self,
9984        task: ActivityTask,
9985        worker_session: Option<WorkerSession>,
9986        hydration_claim: Option<&activity_hydration::HydrationClaim>,
9987    ) -> Result<AvroValue> {
9988        #[cfg(feature = "telemetry")]
9989        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
9990            !self
9991                .client
9992                .observability_context_supported
9993                .load(Ordering::SeqCst)
9994        }) {
9995            return telemetry
9996                .run(
9997                    "durable.activity.task",
9998                    self.activity_telemetry_fields(&task),
9999                    false,
10000                    self.execute_session_activity_task_inner(task, worker_session, hydration_claim),
10001                )
10002                .await;
10003        }
10004        self.execute_session_activity_task_inner(task, worker_session, hydration_claim)
10005            .await
10006    }
10007
10008    async fn execute_session_activity_task_inner(
10009        &self,
10010        task: ActivityTask,
10011        worker_session: Option<WorkerSession>,
10012        hydration_claim: Option<&activity_hydration::HydrationClaim>,
10013    ) -> Result<AvroValue> {
10014        validate_activity_task_payloads(&task)?;
10015        if worker_session.is_some() {
10016            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
10017                || task
10018                    .activity_attempt_id
10019                    .as_deref()
10020                    .or(task.attempt_id.as_deref())
10021                    .is_none_or(str::is_empty)
10022                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
10023            {
10024                return Err(Error::ActivityExecutionAbandoned(
10025                    "session activity requires this worker's exact immutable claim".into(),
10026                ));
10027            }
10028        }
10029
10030        let handler = self
10031            .activities
10032            .get(&task.activity_type)
10033            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
10034        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
10035        let attempt_id = task
10036            .activity_attempt_id
10037            .clone()
10038            .or(task.attempt_id.clone())
10039            .unwrap_or_default();
10040        let lease_owner = task
10041            .lease_owner
10042            .clone()
10043            .unwrap_or_else(|| self.worker_id.clone());
10044        let session = worker_session.clone();
10045        if let Some(claim) = hydration_claim {
10046            claim.confirm(&self.client).await?;
10047        }
10048        #[cfg(feature = "telemetry")]
10049        let observations = self.activity_observations(&task);
10050        #[cfg(feature = "telemetry")]
10051        let fields = self.activity_telemetry_fields(&task);
10052        let ctx = ActivityContext {
10053            client: self.client.clone(),
10054            task_id: task.task_id,
10055            activity_attempt_id: attempt_id,
10056            lease_owner,
10057            activity_type: task.activity_type,
10058            attempt_number: task.attempt_number,
10059            task_queue: self.task_queue.clone(),
10060            worker_id: self.worker_id.clone(),
10061            claim_guard: None,
10062            local_heartbeats: None,
10063            worker_session,
10064        };
10065
10066        let operation = async {
10067            let callback = self.activity_callback(handler, ctx, args, false);
10068            if let Some(session) = session {
10069                tokio::select! {
10070                    biased;
10071                    _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
10072                    result = callback => if session.active() { result } else {
10073                        Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
10074                    },
10075                }
10076            } else {
10077                callback.await
10078            }
10079        };
10080        #[cfg(feature = "telemetry")]
10081        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
10082            self.client
10083                .observability_context_supported
10084                .load(Ordering::SeqCst)
10085        }) {
10086            return telemetry
10087                .run_observed(
10088                    "durable.activity.task",
10089                    fields,
10090                    false,
10091                    observations,
10092                    operation,
10093                )
10094                .await;
10095        }
10096        operation.await
10097    }
10098
10099    fn activity_callback(
10100        &self,
10101        handler: &ActivityHandler,
10102        context: ActivityContext,
10103        args: AvroValue,
10104        local: bool,
10105    ) -> ActivityFuture {
10106        #[cfg(feature = "telemetry")]
10107        if let Some(telemetry) = &self.telemetry {
10108            let telemetry = telemetry.clone();
10109            let fields = self.callback_telemetry_fields(&context, local);
10110            let handler = handler.clone();
10111            let name = if local {
10112                "durable.local_activity.attempt"
10113            } else {
10114                "durable.activity.attempt"
10115            };
10116            return Box::pin(async move {
10117                telemetry
10118                    .run(
10119                        name,
10120                        fields,
10121                        true,
10122                        async move { handler(context, args).await },
10123                    )
10124                    .await
10125            });
10126        }
10127        #[cfg(not(feature = "telemetry"))]
10128        let _ = local;
10129        handler(context, args)
10130    }
10131}
10132
10133fn poller_result(
10134    kind: &str,
10135    result: std::result::Result<Result<()>, tokio::task::JoinError>,
10136) -> Result<()> {
10137    match result {
10138        Ok(result) => result,
10139        Err(error) => Err(Error::WorkerLoop(format!(
10140            "{kind} poller join error: {error}"
10141        ))),
10142    }
10143}
10144
10145fn optional_poller_result(
10146    kind: &str,
10147    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
10148) -> Result<()> {
10149    match result {
10150        Some(result) => poller_result(kind, result),
10151        None => Ok(()),
10152    }
10153}
10154
10155async fn join_pollers(
10156    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10157    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10158    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10159) -> Result<()> {
10160    let mut first_error = None;
10161
10162    if let Some(handle) = workflow_poller {
10163        if let Err(error) = poller_result("workflow", handle.await) {
10164            first_error.get_or_insert(error);
10165        }
10166    }
10167
10168    if let Some(handle) = activity_poller {
10169        if let Err(error) = poller_result("activity", handle.await) {
10170            first_error.get_or_insert(error);
10171        }
10172    }
10173
10174    if let Some(handle) = query_poller {
10175        if let Err(error) = poller_result("query", handle.await) {
10176            first_error.get_or_insert(error);
10177        }
10178    }
10179
10180    if let Some(error) = first_error {
10181        Err(error)
10182    } else {
10183        Ok(())
10184    }
10185}
10186
10187fn default_worker_id() -> String {
10188    let millis = SystemTime::now()
10189        .duration_since(UNIX_EPOCH)
10190        .unwrap_or_default()
10191        .as_millis();
10192    format!("rust-worker-{}-{millis}", std::process::id())
10193}
10194
10195fn percent_encode_path_segment(segment: &str) -> String {
10196    const HEX: &[u8; 16] = b"0123456789ABCDEF";
10197    let mut encoded = String::with_capacity(segment.len());
10198
10199    for byte in segment.bytes() {
10200        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
10201            encoded.push(char::from(byte));
10202        } else {
10203            encoded.push('%');
10204            encoded.push(char::from(HEX[(byte >> 4) as usize]));
10205            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
10206        }
10207    }
10208
10209    encoded
10210}
10211
10212fn unique_request_id(prefix: &str) -> String {
10213    let nanos = SystemTime::now()
10214        .duration_since(UNIX_EPOCH)
10215        .unwrap_or_default()
10216        .as_nanos();
10217    format!("{prefix}-{}-{nanos}", std::process::id())
10218}
10219
10220#[derive(Debug)]
10221struct QueryTaskExecutionFailure {
10222    reason: String,
10223    message: String,
10224    failure_type: String,
10225}
10226
10227impl QueryTaskExecutionFailure {
10228    fn new(
10229        reason: impl Into<String>,
10230        message: impl Into<String>,
10231        failure_type: impl Into<String>,
10232    ) -> Self {
10233        Self {
10234            reason: reason.into(),
10235            message: message.into(),
10236            failure_type: failure_type.into(),
10237        }
10238    }
10239}
10240
10241/// Typed local state owned by one deterministic workflow invocation.
10242///
10243/// Use [`WorkflowInstance::update`] for the same state transitions during
10244/// ordinary execution and replay. A replayed query receives a detached
10245/// immutable `Arc<S>` rather than this mutation-capable handle.
10246#[derive(Clone, Debug)]
10247pub struct WorkflowInstance<S> {
10248    state: Arc<Mutex<S>>,
10249}
10250
10251impl<S> WorkflowInstance<S> {
10252    fn new(state: S) -> Self {
10253        Self {
10254            state: Arc::new(Mutex::new(state)),
10255        }
10256    }
10257
10258    /// Read the current workflow-instance state without changing it.
10259    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
10260        let state = self
10261            .state
10262            .lock()
10263            .map_err(|_| Error::WorkflowStatePoisoned)?;
10264        Ok(reader(&state))
10265    }
10266
10267    /// Apply one deterministic workflow-instance state transition.
10268    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
10269        let mut state = self
10270            .state
10271            .lock()
10272            .map_err(|_| Error::WorkflowStatePoisoned)?;
10273        Ok(transition(&mut state))
10274    }
10275}
10276
10277impl<S: Clone> WorkflowInstance<S> {
10278    fn snapshot(&self) -> Result<S> {
10279        self.read(Clone::clone)
10280    }
10281}
10282
10283#[derive(Clone, Debug, PartialEq)]
10284pub struct MessageStreamMessage {
10285    pub stream_name: String,
10286    pub message_id: String,
10287    pub position: u64,
10288    pub arguments: Vec<AvroValue>,
10289}
10290
10291#[derive(Clone, Debug)]
10292pub struct MessageStream {
10293    ctx: WorkflowContext,
10294    name: String,
10295}
10296
10297impl MessageStream {
10298    /// Wait for one message, then return a bounded currently-available batch.
10299    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
10300        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
10301            return Err(Error::Codec(format!(
10302                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
10303            )));
10304        }
10305        loop {
10306            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
10307                return Ok(batch);
10308            }
10309
10310            self.ctx.record_message_stream_wait(&self.name)?;
10311            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
10312            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
10313            self.ctx.buffer_message_stream_delivery(arguments)?;
10314            if let Some(sequence) = replay_wait_sequence {
10315                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
10316            }
10317        }
10318    }
10319
10320    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
10321        self.receive(1)
10322            .await?
10323            .into_iter()
10324            .next()
10325            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
10326    }
10327}
10328
10329#[derive(Clone, Debug)]
10330pub struct WorkflowContext {
10331    state: Arc<Mutex<WorkflowState>>,
10332    cancellation_scope_id: String,
10333}
10334
10335fn valid_memo_key(key: &str) -> bool {
10336    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
10337
10338    !key.is_empty()
10339        && key.len() <= 64
10340        && (numeric_candidate.is_empty()
10341            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
10342        && key
10343            .bytes()
10344            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
10345}
10346
10347fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
10348    BASE64
10349        .decode(encode_avro_value(value)?.blob)
10350        .map(|bytes| bytes.len())
10351        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
10352}
10353
10354fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
10355    let AvroValue::Map(entries) = value else {
10356        return Err(Error::InvalidMemoUpdate(
10357            "entries must serialize to an Avro string-keyed map".to_string(),
10358        ));
10359    };
10360    if require_entries && entries.is_empty() {
10361        return Err(Error::InvalidMemoUpdate(
10362            "at least one entry is required".to_string(),
10363        ));
10364    }
10365    if entries.len() > MAX_MEMO_ENTRIES {
10366        return Err(Error::InvalidMemoUpdate(format!(
10367            "at most {MAX_MEMO_ENTRIES} entries are allowed"
10368        )));
10369    }
10370
10371    for (key, value) in &entries {
10372        if !valid_memo_key(&key) {
10373            return Err(Error::InvalidMemoUpdate(
10374                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
10375            ));
10376        }
10377        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
10378            return Err(Error::InvalidMemoUpdate(format!(
10379                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
10380            )));
10381        }
10382    }
10383
10384    let value = AvroValue::Map(entries);
10385    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
10386        return Err(Error::InvalidMemoUpdate(format!(
10387            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
10388        )));
10389    }
10390    Ok(value)
10391}
10392
10393fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
10394    let object = envelope.as_object().ok_or_else(|| {
10395        Error::InvalidMemoUpdate(
10396            "history field must use the public {codec, blob} payload envelope".to_string(),
10397        )
10398    })?;
10399    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
10400        return Err(Error::InvalidMemoUpdate(
10401            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
10402        ));
10403    }
10404
10405    canonical_memo_entries(
10406        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
10407        require_entries,
10408    )
10409}
10410
10411impl WorkflowContext {
10412    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
10413        let name = name.into();
10414        if name.is_empty()
10415            || name.len() > 128
10416            || !name.bytes().all(|byte| {
10417                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
10418            })
10419        {
10420            return Err(Error::Codec(
10421                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
10422                    .to_string(),
10423            ));
10424        }
10425        Ok(MessageStream {
10426            ctx: self.clone(),
10427            name,
10428        })
10429    }
10430
10431    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
10432        let mut state = self
10433            .state
10434            .lock()
10435            .map_err(|_| Error::WorkflowStatePoisoned)?;
10436        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
10437        state
10438            .message_stream_waits
10439            .insert(name.to_string(), position);
10440        Ok(())
10441    }
10442
10443    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
10444        let mut state = self
10445            .state
10446            .lock()
10447            .map_err(|_| Error::WorkflowStatePoisoned)?;
10448        let cursor = state
10449            .message_stream_cursors
10450            .get(&message.stream_name)
10451            .copied()
10452            .unwrap_or(0);
10453        if message.position <= cursor {
10454            return Ok(());
10455        }
10456        let pending = state
10457            .message_stream_messages
10458            .entry(message.stream_name.clone())
10459            .or_default();
10460        if pending.iter().any(|candidate| {
10461            candidate.position == message.position || candidate.message_id == message.message_id
10462        }) {
10463            return Ok(());
10464        }
10465        pending.push(message);
10466        pending.sort_by_key(|candidate| candidate.position);
10467        Ok(())
10468    }
10469
10470    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
10471        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
10472            match delivery {
10473                MessageStreamDelivery::Message(message) => {
10474                    let stream_name = message.stream_name.clone();
10475                    self.buffer_message_stream(message)?;
10476                    return Ok(Some(stream_name));
10477                }
10478                MessageStreamDelivery::Cursor {
10479                    stream_name,
10480                    through_position,
10481                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
10482            }
10483        }
10484        Ok(None)
10485    }
10486
10487    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
10488        let state = self
10489            .state
10490            .lock()
10491            .map_err(|_| Error::WorkflowStatePoisoned)?;
10492        Ok(match state.recorded_commands.get(state.command_cursor) {
10493            Some(RecordedCommand::SignalWait {
10494                sequence,
10495                signal_name,
10496                ..
10497            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
10498            _ => None,
10499        })
10500    }
10501
10502    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
10503        let (history, payload_codec) = {
10504            let state = self
10505                .state
10506                .lock()
10507                .map_err(|_| Error::WorkflowStatePoisoned)?;
10508            (
10509                Arc::clone(&state.history_events),
10510                state.payload_codec.clone(),
10511            )
10512        };
10513
10514        let Some(opened_index) = history.iter().position(|event| {
10515            event.event_type == "SignalWaitOpened"
10516                && durable_event_sequence(event) == Some(wait_sequence)
10517                && event.payload.get("signal_name").and_then(Value::as_str)
10518                    == Some(MESSAGE_STREAM_SIGNAL)
10519        }) else {
10520            return Ok(());
10521        };
10522        let boundary_index = history
10523            .iter()
10524            .enumerate()
10525            .skip(opened_index + 1)
10526            .find_map(|(index, event)| {
10527                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
10528                    && is_authored_command_open_event(event))
10529                .then_some(index)
10530            })
10531            .unwrap_or(history.len());
10532
10533        for event in history[opened_index + 1..boundary_index]
10534            .iter()
10535            .filter(|event| {
10536                event.event_type == "SignalReceived"
10537                    && event.payload.get("signal_name").and_then(Value::as_str)
10538                        == Some(MESSAGE_STREAM_SIGNAL)
10539            })
10540        {
10541            let arguments = decode_signal_event_arguments(event, &payload_codec)?
10542                .into_iter()
10543                .map(AvroValue::into_json)
10544                .collect::<Result<Vec<_>>>()?;
10545            self.buffer_message_stream_delivery(arguments)?;
10546        }
10547        Ok(())
10548    }
10549
10550    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
10551        let mut state = self
10552            .state
10553            .lock()
10554            .map_err(|_| Error::WorkflowStatePoisoned)?;
10555        let cursor = state
10556            .message_stream_cursors
10557            .entry(name.to_string())
10558            .or_default();
10559        *cursor = (*cursor).max(through_position);
10560        if let Some(pending) = state.message_stream_messages.get_mut(name) {
10561            pending.retain(|message| message.position > through_position);
10562        }
10563        Ok(())
10564    }
10565
10566    fn take_message_stream_batch(
10567        &self,
10568        name: &str,
10569        max_items: usize,
10570    ) -> Result<Option<Vec<MessageStreamMessage>>> {
10571        let mut state = self
10572            .state
10573            .lock()
10574            .map_err(|_| Error::WorkflowStatePoisoned)?;
10575        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
10576        let pending = state
10577            .message_stream_messages
10578            .entry(name.to_string())
10579            .or_default();
10580        let count = contiguous_message_stream_count(pending, cursor, max_items);
10581        if count == 0 {
10582            return Ok(None);
10583        }
10584        let batch = pending.drain(..count).collect::<Vec<_>>();
10585        let position = batch.last().map(|message| message.position).unwrap_or(0);
10586        state
10587            .message_stream_cursors
10588            .insert(name.to_string(), position);
10589        state.message_stream_waits.remove(name);
10590        Ok(Some(batch))
10591    }
10592
10593    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
10594        let state = self
10595            .state
10596            .lock()
10597            .map_err(|_| Error::WorkflowStatePoisoned)?;
10598        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
10599        cursors.sort_by_key(|(name, _)| *name);
10600        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
10601        waits.sort_by_key(|(name, _)| *name);
10602        Ok((
10603            cursors
10604                .into_iter()
10605                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
10606                .collect(),
10607            waits
10608                .into_iter()
10609                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
10610                .collect(),
10611        ))
10612    }
10613    /// Identity of the parent workflow currently being replayed.
10614    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
10615        let state = self
10616            .state
10617            .lock()
10618            .map_err(|_| Error::WorkflowStatePoisoned)?;
10619        Ok(WorkflowIdentity {
10620            workflow_id: state.workflow_id.clone(),
10621            run_id: state.run_id.clone(),
10622        })
10623    }
10624
10625    /// Return the server-published history budget for this workflow task.
10626    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
10627        let state = self
10628            .state
10629            .lock()
10630            .map_err(|_| Error::WorkflowStatePoisoned)?;
10631        Ok(state.history_budget.clone())
10632    }
10633
10634    /// Continue this workflow instance as a fresh run with replacement arguments.
10635    ///
10636    /// Return this value directly from the workflow handler. The worker converts
10637    /// it to the terminal protocol command only after replay has consumed every
10638    /// recorded durable command.
10639    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
10640        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
10641    }
10642
10643    /// Continue as new with optional workflow-type and task-queue overrides.
10644    pub fn continue_as_new_with_options<T: Serialize>(
10645        &self,
10646        options: ContinueAsNewOptions,
10647        args: T,
10648    ) -> Result<Value> {
10649        options.validate()?;
10650        Err(Error::ContinueAsNew(ContinueAsNewRequest {
10651            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
10652            options,
10653        }))
10654    }
10655
10656    pub fn activity<T: Serialize>(
10657        &self,
10658        activity_type: impl Into<String>,
10659        args: T,
10660    ) -> ActivityCall {
10661        self.activity_with_options(activity_type, ActivityOptions::new(), args)
10662    }
10663
10664    pub fn activity_on_queue<T, Q>(
10665        &self,
10666        activity_type: impl Into<String>,
10667        task_queue: Option<Q>,
10668        args: T,
10669    ) -> ActivityCall
10670    where
10671        T: Serialize,
10672        Q: Into<String>,
10673    {
10674        let mut options = ActivityOptions::new();
10675        options.task_queue = task_queue.map(Into::into);
10676        self.activity_with_options(activity_type, options, args)
10677    }
10678
10679    /// Schedule one durable activity with retry, routing, and timeout options.
10680    ///
10681    /// Options are validated before the command is emitted. Once the command is
10682    /// recorded, replay consumes the same activity lifecycle at this command
10683    /// position and never emits a duplicate schedule.
10684    ///
10685    /// ```no_run
10686    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
10687    /// # use std::time::Duration;
10688    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
10689    /// let result = ctx
10690    ///     .activity_with_options(
10691    ///         "charge-card",
10692    ///         ActivityOptions::new()
10693    ///             .task_queue("payments")
10694    ///             .retry_policy(
10695    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
10696    ///                     Duration::from_secs(1),
10697    ///                     2,
10698    ///                     Some(Duration::from_secs(30)),
10699    ///                 ),
10700    ///             )
10701    ///             .start_to_close_timeout(Duration::from_secs(60))
10702    ///             .schedule_to_close_timeout(Duration::from_secs(180))
10703    ///             .heartbeat_timeout(Duration::from_secs(15)),
10704    ///         json!([{"order_id": "order-42"}]),
10705    ///     )
10706    ///     .await;
10707    /// match result {
10708    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
10709    ///         "reason": failure.reason,
10710    ///         "timeout_kind": failure.timeout_kind,
10711    ///     })),
10712    ///     other => other,
10713    /// }
10714    /// # }
10715    /// ```
10716    pub fn activity_with_options<T: Serialize>(
10717        &self,
10718        activity_type: impl Into<String>,
10719        options: ActivityOptions,
10720        args: T,
10721    ) -> ActivityCall {
10722        ActivityCall {
10723            ctx: self.clone(),
10724            activity_type: activity_type.into(),
10725            options,
10726            worker_session: None,
10727            args: Some(AvroValue::from_serialize(&args)),
10728            scheduled: false,
10729            local: false,
10730            local_result: None,
10731            parallel_group_path: Vec::new(),
10732        }
10733    }
10734
10735    pub async fn activity_avro_value<T: Serialize>(
10736        &self,
10737        activity_type: impl Into<String>,
10738        args: T,
10739    ) -> Result<AvroValue> {
10740        let mut call = self.activity(activity_type, args);
10741        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10742    }
10743
10744    pub async fn activity_avro_value_with_options<T: Serialize>(
10745        &self,
10746        activity_type: impl Into<String>,
10747        options: ActivityOptions,
10748        args: T,
10749    ) -> Result<AvroValue> {
10750        let mut call = self.activity_with_options(activity_type, options, args);
10751        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10752    }
10753
10754    /// Schedule an activity with a Serde request and decode its Serde result.
10755    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
10756    where
10757        I: Serialize,
10758        O: DeserializeOwned,
10759    {
10760        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
10761            .await
10762    }
10763
10764    /// Schedule an activity with options and decode its result into `O`.
10765    ///
10766    /// Both directions use the fixed Avro Value codec. In particular, this
10767    /// method does not deserialize the JSON-safe inspection projection returned
10768    /// by the dynamic [`ActivityCall`] future.
10769    pub async fn activity_typed_with_options<I, O>(
10770        &self,
10771        activity_type: impl Into<String>,
10772        options: ActivityOptions,
10773        args: I,
10774    ) -> Result<O>
10775    where
10776        I: Serialize,
10777        O: DeserializeOwned,
10778    {
10779        let activity_type = activity_type.into();
10780        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
10781            handler_type_error::<I>(
10782                HandlerKind::Activity,
10783                &activity_type,
10784                HandlerValueKind::Input,
10785                error.to_string(),
10786            )
10787        });
10788        let mut call = ActivityCall {
10789            ctx: self.clone(),
10790            activity_type: activity_type.clone(),
10791            options,
10792            worker_session: None,
10793            args: Some(encoded),
10794            scheduled: false,
10795            local: false,
10796            local_result: None,
10797            parallel_group_path: Vec::new(),
10798        };
10799        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
10800        decode_handler_result(result, HandlerKind::Activity, &activity_type)
10801    }
10802
10803    /// Schedule and join a deterministic activity/child/timer group.
10804    ///
10805    /// Nested groups retain their input shape. Every durable leaf is scheduled
10806    /// before this future yields, results are assembled by declaration order,
10807    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
10808    /// declaration path, stable group metadata, and completed siblings.
10809    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10810        ParallelCall::new(self.clone(), operations)
10811    }
10812
10813    /// Alias for [`WorkflowContext::parallel`].
10814    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10815        self.parallel(operations)
10816    }
10817
10818    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
10819    pub async fn parallel_avro_value(
10820        &self,
10821        operations: Vec<ParallelOperation>,
10822    ) -> Result<Vec<ParallelAvroResult>> {
10823        let mut call = self.parallel(operations);
10824        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10825    }
10826
10827    /// Start every durable operation and resume from the one winner persisted
10828    /// by Server. Non-winning operations continue and remain addressable.
10829    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
10830        let operations = operations
10831            .into_iter()
10832            .enumerate()
10833            .map(|(index, operation)| (SelectionKey::Index(index), operation))
10834            .collect();
10835        SelectCall::new(self.clone(), operations)
10836    }
10837
10838    /// Named-key variant of [`WorkflowContext::select`].
10839    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
10840    where
10841        K: Into<SelectionKey>,
10842    {
10843        SelectCall::new(
10844            self.clone(),
10845            operations
10846                .into_iter()
10847                .map(|(key, operation)| (key.into(), operation))
10848                .collect(),
10849        )
10850    }
10851
10852    /// Create a workflow-local deterministic compensation registry.
10853    pub fn saga(&self) -> Saga {
10854        Saga::new(self.clone())
10855    }
10856
10857    /// Whether cancellation has reached this replay's authored boundary.
10858    ///
10859    /// Server's current `/cancel` route is terminal and does not set this flag.
10860    /// A canonical service request remains pending until its committed delivery
10861    /// is consumed. Request observation alone does not authorize an exception.
10862    pub fn is_cancellation_requested(&self) -> Result<bool> {
10863        let state = self
10864            .state
10865            .lock()
10866            .map_err(|_| Error::WorkflowStatePoisoned)?;
10867        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10868            return Ok(state
10869                .scope_delivery
10870                .as_ref()
10871                .unwrap()
10872                .contexts
10873                .contains_key(&self.cancellation_scope_id));
10874        }
10875        Ok(state.cancel_requested
10876            || state
10877                .scope_delivery
10878                .as_ref()
10879                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
10880    }
10881
10882    /// Raise a typed cooperative cancellation at an author-controlled point.
10883    ///
10884    /// Passing this result to [`Saga::finish`] compensates already registered
10885    /// forward steps before the cancellation remains the initiating outcome.
10886    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
10887        let mut state = self
10888            .state
10889            .lock()
10890            .map_err(|_| Error::WorkflowStatePoisoned)?;
10891        if state.cancellation_shield_depth == 0 {
10892            if let Some(replay) = &state.scope_delivery {
10893                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
10894                    let delivered = replay
10895                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
10896                        .ok_or_else(|| {
10897                            Error::InvalidCooperativeCancellation(
10898                                "scoped request lacks its consumed original delivery".into(),
10899                            )
10900                        })?;
10901                    return Err(Error::CancellationScopeRequested(
10902                        CancellationScopeRequested {
10903                            context: context
10904                                .clone()
10905                                .with_replay(Some(Arc::downgrade(&self.state))),
10906                            delivery: delivered.boundary.clone(),
10907                        },
10908                    ));
10909                }
10910            }
10911        }
10912        if state.cancel_requested && state.cancellation_shield_depth == 0 {
10913            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10914                return Ok(());
10915            }
10916            return Err(state.cancellation_error());
10917        }
10918        Ok(())
10919    }
10920
10921    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10922        SignalCall {
10923            ctx: self.clone(),
10924            signal_name: signal_name.into(),
10925            runtime_reserved_allowed: false,
10926            opened_wait: false,
10927            matched_pending: false,
10928            parallel_group_path: Vec::new(),
10929        }
10930    }
10931
10932    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10933        SignalCall {
10934            ctx: self.clone(),
10935            signal_name: signal_name.into(),
10936            runtime_reserved_allowed: true,
10937            opened_wait: false,
10938            matched_pending: false,
10939            parallel_group_path: Vec::new(),
10940        }
10941    }
10942
10943    pub async fn wait_signal_avro_value(
10944        &self,
10945        signal_name: impl Into<String>,
10946    ) -> Result<Vec<AvroValue>> {
10947        let mut call = self.wait_signal(signal_name);
10948        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10949    }
10950
10951    /// Return every committed signal argument list with the given name.
10952    ///
10953    /// This history-backed view is deterministic and is intended for
10954    /// condition predicates that must be re-evaluated after a signal while the
10955    /// workflow is blocked on [`WorkflowContext::wait_condition`].
10956    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
10957        self.signals_avro_value(signal_name)?
10958            .into_iter()
10959            .map(|arguments| {
10960                arguments
10961                    .into_iter()
10962                    .map(AvroValue::into_json)
10963                    .collect::<Result<Vec<_>>>()
10964            })
10965            .collect()
10966    }
10967
10968    /// Lossless fixed Avro Value view of committed signals with the given name.
10969    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10970        let state = self
10971            .state
10972            .lock()
10973            .map_err(|_| Error::WorkflowStatePoisoned)?;
10974        state
10975            .history_events
10976            .iter()
10977            .filter(|event| {
10978                event.event_type == "SignalReceived"
10979                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
10980            })
10981            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
10982            .collect()
10983    }
10984
10985    /// Return every committed update argument list with the given name.
10986    ///
10987    /// Accepted and applied records for the same update ID are de-duplicated.
10988    /// A Server task created after an update therefore replays the workflow and
10989    /// re-evaluates an open condition without application polling.
10990    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
10991        self.updates_avro_value(update_name)?
10992            .into_iter()
10993            .map(|arguments| {
10994                arguments
10995                    .into_iter()
10996                    .map(AvroValue::into_json)
10997                    .collect::<Result<Vec<_>>>()
10998            })
10999            .collect()
11000    }
11001
11002    /// Lossless fixed Avro Value view of committed updates with the given name.
11003    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
11004        let state = self
11005            .state
11006            .lock()
11007            .map_err(|_| Error::WorkflowStatePoisoned)?;
11008        let mut seen = Vec::new();
11009        let mut updates = Vec::new();
11010        for event in state.history_events.iter() {
11011            if !matches!(
11012                event.event_type.as_str(),
11013                "UpdateAccepted" | "UpdateApplied"
11014            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
11015                || event.payload.get("arguments").is_none()
11016            {
11017                continue;
11018            }
11019            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
11020                if seen.iter().any(|recorded| recorded == update_id) {
11021                    continue;
11022                }
11023                seen.push(update_id.to_string());
11024            }
11025            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
11026        }
11027        Ok(updates)
11028    }
11029
11030    /// Wait for a deterministic predicate to become true or for its durable
11031    /// timeout to elapse.
11032    ///
11033    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
11034    /// predicate tokens automatically change the recorded definition
11035    /// fingerprint. Direct callers must provide an equally stable identity in
11036    /// [`ConditionWaitOptions`].
11037    pub fn wait_condition<F>(
11038        &self,
11039        options: ConditionWaitOptions,
11040        predicate: F,
11041    ) -> ConditionWaitCall
11042    where
11043        F: Fn() -> Result<bool> + Send + 'static,
11044    {
11045        ConditionWaitCall {
11046            ctx: self.clone(),
11047            options,
11048            predicate: Box::new(predicate),
11049            occurrence_id: None,
11050            opened_wait: false,
11051            parallel_group_path: Vec::new(),
11052        }
11053    }
11054
11055    /// Wait for server-backed durable time without blocking the worker executor.
11056    ///
11057    /// Polling this future emits one `start_timer` command and yields. The
11058    /// server records the deadline, so neither worker nor server restarts reset
11059    /// the wait. Replay resolves the future only from a `TimerScheduled` and
11060    /// `TimerFired` pair at the same position in the shared durable-command
11061    /// stream, with matching sequence, timer identity, and delay. Sub-second
11062    /// durations round up because protocol deadlines use whole seconds.
11063    ///
11064    /// ```no_run
11065    /// # use durable_workflow::{json, Client, Worker};
11066    /// # use std::time::Duration;
11067    /// # fn configure(client: Client) {
11068    /// let mut worker = Worker::new(client, "rust-workers");
11069    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
11070    ///     ctx.sleep(Duration::from_secs(5)).await?;
11071    ///     Ok(json!({"status": "timer fired"}))
11072    /// });
11073    /// # }
11074    /// ```
11075    pub fn sleep(&self, duration: Duration) -> TimerCall {
11076        let delay_seconds = duration
11077            .as_secs()
11078            .checked_add(u64::from(duration.subsec_nanos() > 0));
11079        TimerCall {
11080            ctx: self.clone(),
11081            delay_seconds,
11082            scheduled: false,
11083            matched_pending: false,
11084            parallel_group_path: Vec::new(),
11085        }
11086    }
11087
11088    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
11089    pub fn start_timer(&self, duration: Duration) -> TimerCall {
11090        self.sleep(duration)
11091    }
11092
11093    /// Evaluate a non-deterministic callback once and durably record its typed value.
11094    ///
11095    /// On replay the callback is not invoked: the value is decoded from the
11096    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
11097    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
11098    /// small values that must remain fixed for the lifetime of a workflow run.
11099    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
11100    where
11101        T: Serialize + DeserializeOwned,
11102        F: FnOnce() -> T,
11103    {
11104        {
11105            let mut state = self
11106                .state
11107                .lock()
11108                .map_err(|_| Error::WorkflowStatePoisoned)?;
11109            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11110                return match recorded {
11111                    RecordedCommand::SideEffect { sequence, value } => {
11112                        state.command_cursor += 1;
11113                        value.deserialize().map_err(|error| {
11114                            Error::NonDeterministicReplay(ReplayFailure::new(
11115                                "side_effect_type_mismatch",
11116                                Some(sequence),
11117                                Some(std::any::type_name::<T>().to_string()),
11118                                Some(error.to_string()),
11119                                "recorded side-effect value is incompatible with the requested Rust type",
11120                            ))
11121                        })
11122                    }
11123                    other => Err(command_mismatch(&other, "side effect")),
11124                };
11125            }
11126        }
11127
11128        let value = callback();
11129        let avro_value = AvroValue::from_serialize(&value)?;
11130        let mut state = self
11131            .state
11132            .lock()
11133            .map_err(|_| Error::WorkflowStatePoisoned)?;
11134        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
11135        state.commands.push(json!({
11136            "type": "record_side_effect",
11137            "result": result,
11138        }));
11139        Ok(value)
11140    }
11141
11142    /// Record or replay a lossless fixed Avro Value side effect.
11143    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
11144    where
11145        F: FnOnce() -> AvroValue,
11146    {
11147        {
11148            let mut state = self
11149                .state
11150                .lock()
11151                .map_err(|_| Error::WorkflowStatePoisoned)?;
11152            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11153                return match recorded {
11154                    RecordedCommand::SideEffect { value, .. } => {
11155                        state.command_cursor += 1;
11156                        Ok(value)
11157                    }
11158                    other => Err(command_mismatch(&other, "side effect")),
11159                };
11160            }
11161        }
11162
11163        let value = callback();
11164        let mut state = self
11165            .state
11166            .lock()
11167            .map_err(|_| Error::WorkflowStatePoisoned)?;
11168        let result = encode_typed_envelope(&value, &state.payload_codec)?;
11169        state.commands.push(json!({
11170            "type": "record_side_effect",
11171            "result": result,
11172        }));
11173        Ok(value)
11174    }
11175
11176    /// Append output items at a deterministic workflow command boundary.
11177    ///
11178    /// Stable idempotency keys are derived from the server-provided durable
11179    /// workflow command identity, command ordinal, and item index. Replay
11180    /// consumes the recorded side effect and never emits another append.
11181    pub fn append_workflow_stream(
11182        &self,
11183        stream_name: impl Into<String>,
11184        items: &[WorkflowStreamAppendItem],
11185        max_pending_items: Option<u64>,
11186    ) -> Result<()> {
11187        if items.is_empty() {
11188            return Err(Error::Codec(
11189                "workflow_stream_items_empty: append requires at least one item".to_string(),
11190            ));
11191        }
11192        if max_pending_items == Some(0) {
11193            return Err(Error::Codec(
11194                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
11195                    .to_string(),
11196            ));
11197        }
11198        let stream_name = stream_name.into();
11199        if stream_name.is_empty() {
11200            return Err(Error::Codec(
11201                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11202            ));
11203        }
11204
11205        let mut state = self
11206            .state
11207            .lock()
11208            .map_err(|_| Error::WorkflowStatePoisoned)?;
11209        let command_ordinal = state.workflow_stream_command_counter;
11210        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11211            state.workflow_stream_command_counter += 1;
11212            return match recorded {
11213                RecordedCommand::SideEffect { .. } => {
11214                    state.command_cursor += 1;
11215                    Ok(())
11216                }
11217                other => Err(command_mismatch(&other, "workflow stream append")),
11218            };
11219        }
11220
11221        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11222        state.workflow_stream_command_counter += 1;
11223        let wire_items = items
11224            .iter()
11225            .enumerate()
11226            .map(|(item_index, item)| {
11227                item.wire_value(Some(format!(
11228                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
11229                )))
11230            })
11231            .collect::<Vec<_>>();
11232        let mut directive = json!({
11233            "operation": "append",
11234            "stream_name": stream_name,
11235            "command_identity": identity,
11236            "command_ordinal": command_ordinal,
11237            "items": wire_items,
11238        });
11239        if let Some(max_pending_items) = max_pending_items {
11240            directive["max_pending_items"] = json!(max_pending_items);
11241        }
11242        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11243        state.commands.push(json!({
11244            "type": "record_side_effect",
11245            "result": result,
11246            "workflow_stream": directive,
11247        }));
11248        Ok(())
11249    }
11250
11251    /// Close a run-scoped output stream at a deterministic command boundary.
11252    pub fn close_workflow_stream(
11253        &self,
11254        stream_name: impl Into<String>,
11255        retention_seconds: Option<u64>,
11256    ) -> Result<()> {
11257        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
11258    }
11259
11260    /// Mark a run-scoped output stream errored at a deterministic command boundary.
11261    pub fn error_workflow_stream(
11262        &self,
11263        stream_name: impl Into<String>,
11264        error_reason: impl Into<String>,
11265        retention_seconds: Option<u64>,
11266    ) -> Result<()> {
11267        let error_reason = error_reason.into();
11268        if error_reason.is_empty() {
11269            return Err(Error::Codec(
11270                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
11271            ));
11272        }
11273        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
11274    }
11275
11276    fn finish_workflow_stream(
11277        &self,
11278        stream_name: String,
11279        error_reason: Option<String>,
11280        retention_seconds: Option<u64>,
11281    ) -> Result<()> {
11282        if stream_name.is_empty() {
11283            return Err(Error::Codec(
11284                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11285            ));
11286        }
11287        if retention_seconds == Some(0) {
11288            return Err(Error::Codec(
11289                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
11290            ));
11291        }
11292        let mut state = self
11293            .state
11294            .lock()
11295            .map_err(|_| Error::WorkflowStatePoisoned)?;
11296        let command_ordinal = state.workflow_stream_command_counter;
11297        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11298            state.workflow_stream_command_counter += 1;
11299            return match recorded {
11300                RecordedCommand::SideEffect { .. } => {
11301                    state.command_cursor += 1;
11302                    Ok(())
11303                }
11304                other => Err(command_mismatch(&other, "workflow stream close")),
11305            };
11306        }
11307        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11308        state.workflow_stream_command_counter += 1;
11309        let mut directive = json!({
11310            "operation": if error_reason.is_some() { "error" } else { "close" },
11311            "stream_name": stream_name,
11312            "command_identity": identity,
11313            "command_ordinal": command_ordinal,
11314        });
11315        if let Some(error_reason) = error_reason {
11316            directive["error_reason"] = json!(error_reason);
11317        }
11318        if let Some(retention_seconds) = retention_seconds {
11319            directive["retention_seconds"] = json!(retention_seconds);
11320        }
11321        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11322        state.commands.push(json!({
11323            "type": "record_side_effect",
11324            "result": result,
11325            "workflow_stream": directive,
11326        }));
11327        Ok(())
11328    }
11329
11330    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
11331        let identity = state.workflow_command_identity.as_str();
11332        if identity.is_empty() {
11333            return Err(Error::MissingWorkflowCommandIdentity);
11334        }
11335        Ok(identity)
11336    }
11337
11338    /// Validate, emit, or replay a typed workflow search-attribute update.
11339    ///
11340    /// The command is non-blocking within a workflow decision, but its
11341    /// `SearchAttributesUpserted` event occupies the same deterministic command
11342    /// stream as activities, timers, conditions, and other durable operations.
11343    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
11344        update.validate()?;
11345        let (attributes, attribute_types) = update.into_wire_parts();
11346        let mut state = self
11347            .state
11348            .lock()
11349            .map_err(|_| Error::WorkflowStatePoisoned)?;
11350
11351        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11352            return match recorded {
11353                RecordedCommand::SearchAttributes {
11354                    sequence,
11355                    attributes: recorded_attributes,
11356                    attribute_types: recorded_attribute_types,
11357                } => {
11358                    if recorded_attributes != attributes {
11359                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11360                            "search_attribute_value_mismatch",
11361                            Some(sequence),
11362                            Some(recorded_attributes.to_string()),
11363                            Some(attributes.to_string()),
11364                            "search-attribute values differ from the recorded durable command",
11365                        )));
11366                    }
11367                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
11368                        if recorded_types != attribute_types {
11369                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11370                                "search_attribute_type_mismatch",
11371                                Some(sequence),
11372                                Some(json!(recorded_types).to_string()),
11373                                Some(json!(attribute_types).to_string()),
11374                                "search-attribute declared types differ from the recorded durable command",
11375                            )));
11376                        }
11377                    }
11378                    state.command_cursor += 1;
11379                    Ok(())
11380                }
11381                other => Err(command_mismatch(&other, "search-attribute update")),
11382            };
11383        }
11384
11385        let mut command = serde_json::Map::from_iter([
11386            ("type".to_string(), json!("upsert_search_attributes")),
11387            ("attributes".to_string(), attributes),
11388        ]);
11389        if !attribute_types.is_empty() {
11390            command.insert("attribute_types".to_string(), json!(attribute_types));
11391        }
11392        state.commands.push(Value::Object(command));
11393        Ok(())
11394    }
11395
11396    /// Record a UUIDv4 once and return the same UUID on every replay.
11397    pub fn uuid_v4(&self) -> Result<Uuid> {
11398        self.side_effect(Uuid::new_v4)
11399    }
11400
11401    /// Select the newest supported version for a change, or replay the version
11402    /// already committed for that stable change ID.
11403    ///
11404    /// An unmarked old history that reached its next durable operation, or
11405    /// already completed, selects `-1` when that version is supported. This
11406    /// leaves the original operation available and writes no additional marker.
11407    /// Consistent markers written by older workers retain their original ordered
11408    /// positions. Repeated calls consume a matching marker at the current cursor.
11409    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
11410    pub fn get_version(
11411        &self,
11412        change_id: impl Into<String>,
11413        min_supported: i32,
11414        max_supported: i32,
11415    ) -> Result<i32> {
11416        let change_id = change_id.into();
11417        if change_id.trim().is_empty() {
11418            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11419                "version_change_id_invalid",
11420                None,
11421                Some("non-empty change ID".to_string()),
11422                Some(change_id),
11423                "version markers require a stable non-empty change ID",
11424            )));
11425        }
11426        if min_supported > max_supported {
11427            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11428                "version_range_invalid",
11429                None,
11430                Some("min_supported <= max_supported".to_string()),
11431                Some(format!("{min_supported}..={max_supported}")),
11432                "version marker supported range is invalid",
11433            )));
11434        }
11435
11436        let mut state = self
11437            .state
11438            .lock()
11439            .map_err(|_| Error::WorkflowStatePoisoned)?;
11440        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
11441            if let Some(RecordedCommand::VersionMarker {
11442                sequence: alias_sequence,
11443                change_id: alias_change_id,
11444                version: alias_version,
11445            }) = state.recorded_commands.get(state.command_cursor)
11446            {
11447                if alias_change_id == &change_id {
11448                    if *alias_version != version {
11449                        return Err(invalid_recorded_history(
11450                            "version_marker_conflict",
11451                            *alias_sequence,
11452                            &format!("selected version {version} for change ID {change_id:?}"),
11453                            &format!("recorded version {alias_version}"),
11454                            "recorded marker conflicts with the decision already selected during replay",
11455                        ));
11456                    }
11457                    ensure_version_supported(
11458                        &change_id,
11459                        version,
11460                        min_supported,
11461                        max_supported,
11462                        *alias_sequence,
11463                    )?;
11464                    // Older workers could record the same decision again. Keep
11465                    // each physical boundary without skipping intervening work.
11466                    state.command_cursor += 1;
11467                    return Ok(version);
11468                }
11469            }
11470            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
11471            return Ok(version);
11472        }
11473
11474        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11475            return match recorded {
11476                RecordedCommand::VersionMarker {
11477                    sequence,
11478                    change_id: recorded_change_id,
11479                    version,
11480                    ..
11481                } => {
11482                    if recorded_change_id != change_id {
11483                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11484                            "version_change_id_mismatch",
11485                            Some(sequence),
11486                            Some(recorded_change_id),
11487                            Some(change_id),
11488                            "recorded version marker change ID differs from current workflow code",
11489                        )));
11490                    }
11491                    ensure_version_supported(
11492                        &change_id,
11493                        version,
11494                        min_supported,
11495                        max_supported,
11496                        sequence,
11497                    )?;
11498                    state.command_cursor += 1;
11499                    state.version_markers.insert(change_id, (version, sequence));
11500                    Ok(version)
11501                }
11502                other => {
11503                    let version = -1;
11504                    let sequence = other.sequence();
11505                    ensure_version_supported(
11506                        &change_id,
11507                        version,
11508                        min_supported,
11509                        max_supported,
11510                        sequence,
11511                    )?;
11512                    // The existing operation proves this patch site was reached
11513                    // before its marker existed. Keep its original cursor.
11514                    state.version_markers.insert(change_id, (version, sequence));
11515                    Ok(version)
11516                }
11517            };
11518        }
11519
11520        if state
11521            .history_events
11522            .iter()
11523            .any(|event| event.event_type == "WorkflowCompleted")
11524        {
11525            let version = -1;
11526            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
11527            state.version_markers.insert(change_id, (version, 0));
11528            return Ok(version);
11529        }
11530
11531        let version = max_supported;
11532        state.commands.push(json!({
11533            "type": "record_version_marker",
11534            "change_id": change_id,
11535            "version": version,
11536            "min_supported": min_supported,
11537            "max_supported": max_supported,
11538        }));
11539        // Sequence numbers are assigned by the server. Zero identifies a marker
11540        // selected in this uncommitted decision batch for duplicate-call checks.
11541        state.version_markers.insert(change_id, (version, 0));
11542        Ok(version)
11543    }
11544
11545    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
11546    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
11547        Ok(self.get_version(change_id, -1, 1)? == 1)
11548    }
11549
11550    /// Keep a patch marker in history after the legacy branch has been removed.
11551    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
11552        self.get_version(change_id, -1, 1).map(|_| ())
11553    }
11554
11555    /// Merge non-indexed workflow memo metadata through durable history.
11556    ///
11557    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
11558    /// public Avro payload envelope consumed by Server and Cloud runtimes.
11559    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
11560        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
11561        let mut state = self
11562            .state
11563            .lock()
11564            .map_err(|_| Error::WorkflowStatePoisoned)?;
11565
11566        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11567            return match recorded {
11568                RecordedCommand::Memo {
11569                    sequence,
11570                    entries: recorded_entries,
11571                } => {
11572                    if recorded_entries != entries {
11573                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11574                            "memo_update_mismatch",
11575                            Some(sequence),
11576                            Some(format!("{recorded_entries:?}")),
11577                            Some(format!("{entries:?}")),
11578                            "recorded memo entries differ from the current workflow update",
11579                        )));
11580                    }
11581                    state.command_cursor += 1;
11582                    Ok(())
11583                }
11584                other => Err(command_mismatch(&other, "memo upsert")),
11585            };
11586        }
11587
11588        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
11589        state.commands.push(json!({
11590            "type": "upsert_memo",
11591            "entries": entries_envelope,
11592        }));
11593        Ok(())
11594    }
11595
11596    /// Start a named durable child on an explicit queue and await its result.
11597    ///
11598    /// The command is recorded in the parent's sequence-ordered durable command
11599    /// stream. Replay keeps a scheduled child pending without emitting another
11600    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
11601    /// values preserve the history payload codec and include both sides of the
11602    /// durable relationship; failures are returned as
11603    /// [`Error::ChildWorkflowFailed`].
11604    ///
11605    /// ```no_run
11606    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
11607    /// # fn configure(client: Client) {
11608    /// let mut worker = Worker::new(client, "parent-workers");
11609    /// worker.register_workflow("order-parent", |ctx, _input| async move {
11610    ///     let child = ctx
11611    ///         .start_child_workflow(
11612    ///             "fulfil-order",
11613    ///             ChildWorkflowOptions::new("fulfilment-workers")
11614    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
11615    ///             json!([{"order_id": "order-42"}]),
11616    ///         )
11617    ///         .await?;
11618    ///     Ok(child.result)
11619    /// });
11620    /// # }
11621    /// ```
11622    pub fn start_child_workflow<T: Serialize>(
11623        &self,
11624        workflow_type: impl Into<String>,
11625        options: ChildWorkflowOptions,
11626        args: T,
11627    ) -> ChildWorkflowCall {
11628        ChildWorkflowCall {
11629            ctx: self.clone(),
11630            workflow_type: workflow_type.into(),
11631            options,
11632            args: Some(AvroValue::from_serialize(&args)),
11633            scheduled: false,
11634            matched_pending: false,
11635            parallel_group_path: Vec::new(),
11636        }
11637    }
11638
11639    pub async fn start_child_workflow_avro_value<T: Serialize>(
11640        &self,
11641        workflow_type: impl Into<String>,
11642        options: ChildWorkflowOptions,
11643        args: T,
11644    ) -> Result<ChildWorkflowAvroResult> {
11645        let mut call = self.start_child_workflow(workflow_type, options, args);
11646        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
11647    }
11648
11649    fn take_commands(&self) -> Result<Vec<Value>> {
11650        let mut state = self
11651            .state
11652            .lock()
11653            .map_err(|_| Error::WorkflowStatePoisoned)?;
11654        Ok(std::mem::take(&mut state.commands))
11655    }
11656
11657    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
11658        let mut state = self
11659            .state
11660            .lock()
11661            .map_err(|_| Error::WorkflowStatePoisoned)?;
11662
11663        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11664            return Err(command_mismatch(&recorded, "continue as new"));
11665        }
11666        if state.recorded_continue_as_new_sequence.is_some() {
11667            state.continue_as_new_consumed = true;
11668            return Ok(None);
11669        }
11670
11671        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
11672        let mut command = serde_json::Map::from_iter([
11673            ("type".to_string(), json!("continue_as_new")),
11674            ("arguments".to_string(), arguments),
11675            ("queue".to_string(), json!(state.task_queue.clone())),
11676        ]);
11677        if let Some(workflow_type) = request.options.workflow_type {
11678            command.insert("workflow_type".to_string(), json!(workflow_type));
11679        }
11680        if let Some(task_queue) = request.options.task_queue {
11681            command.insert("queue".to_string(), json!(task_queue));
11682        }
11683        Ok(Some(Value::Object(command)))
11684    }
11685
11686    fn matched_recorded_pending(&self) -> Result<bool> {
11687        let state = self
11688            .state
11689            .lock()
11690            .map_err(|_| Error::WorkflowStatePoisoned)?;
11691        Ok(state.matched_recorded_pending)
11692    }
11693
11694    fn ensure_history_consumed(&self) -> Result<()> {
11695        let state = self
11696            .state
11697            .lock()
11698            .map_err(|_| Error::WorkflowStatePoisoned)?;
11699        if let Some(replay) = &state.scope_delivery {
11700            if let Some((&sequence, _)) = replay
11701                .canonical
11702                .deliveries
11703                .iter()
11704                .find(|(sequence, _)| !replay.consumed.contains(sequence))
11705            {
11706                return Err(invalid_recorded_history(
11707                    "cancellation_scope_delivery_unconsumed",
11708                    sequence,
11709                    "original scoped delivery",
11710                    "workflow completion",
11711                    "workflow completed without consuming its committed scope delivery",
11712                ));
11713            }
11714        }
11715        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
11716            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11717                "recorded_commands_unconsumed",
11718                Some(command.sequence()),
11719                Some(command.shape().to_string()),
11720                Some("workflow completion".to_string()),
11721                "workflow completed before consuming all recorded durable commands",
11722            )));
11723        }
11724        if let Some(delivery) = state
11725            .cancellation_history
11726            .delivery
11727            .as_ref()
11728            .filter(|_| !state.cancellation_consumed)
11729        {
11730            return Err(invalid_recorded_history(
11731                "cooperative_cancellation_unconsumed",
11732                delivery.sequence,
11733                "committed cancellation call",
11734                "workflow completion",
11735                "workflow completed without reaching its committed cancellation boundary",
11736            ));
11737        }
11738        if let Some(sequence) = state
11739            .recorded_continue_as_new_sequence
11740            .filter(|_| !state.continue_as_new_consumed)
11741        {
11742            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11743                "recorded_continue_as_new_unconsumed",
11744                Some(sequence),
11745                Some("continue as new".to_string()),
11746                Some("workflow completion".to_string()),
11747                "workflow completed without consuming its recorded continue-as-new transition",
11748            )));
11749        }
11750        Ok(())
11751    }
11752}
11753
11754fn contiguous_message_stream_count(
11755    pending: &[MessageStreamMessage],
11756    cursor: u64,
11757    max_items: usize,
11758) -> usize {
11759    pending
11760        .iter()
11761        .take(max_items)
11762        .enumerate()
11763        .take_while(|(offset, message)| {
11764            u64::try_from(*offset)
11765                .ok()
11766                .and_then(|offset| cursor.checked_add(offset + 1))
11767                == Some(message.position)
11768        })
11769        .count()
11770}
11771
11772fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
11773    matches!(
11774        event.event_type.as_str(),
11775        "ActivityScheduled"
11776            | "TimerScheduled"
11777            | "ChildWorkflowScheduled"
11778            | "SignalWaitOpened"
11779            | "ConditionWaitOpened"
11780            | "SearchAttributesUpserted"
11781            | "SideEffectRecorded"
11782            | "VersionMarkerRecorded"
11783            | "MemoUpserted"
11784            | "WorkflowContinuedAsNew"
11785    )
11786}
11787
11788#[derive(Debug)]
11789struct WorkflowState {
11790    workflow_id: Option<String>,
11791    run_id: Option<String>,
11792    task_queue: String,
11793    payload_codec: String,
11794    history_events: Arc<Vec<HistoryEvent>>,
11795    history_budget: WorkflowHistoryBudget,
11796    cancel_requested: bool,
11797    cancellation_history: CancellationHistory,
11798    cancellation_consumed: bool,
11799    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
11800    cancellation_shield_depth: u64,
11801    cancellation_delivery_enabled: bool,
11802    cancellation_delivery_intent: Option<CancellationDelivery>,
11803    cancellation_delivery_command_count: usize,
11804    allow_cancellation_scope_authoring: bool,
11805    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
11806    cancellation_scope_memberships: BTreeMap<u64, String>,
11807    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
11808    resume_signal: Option<ResumeSignal>,
11809    recorded_commands: Vec<RecordedCommand>,
11810    selection_markers: Vec<SelectionMarker>,
11811    selection_marker_cursor: usize,
11812    cancelled_selection_members: Vec<SelectionCancellation>,
11813    recorded_continue_as_new_sequence: Option<u64>,
11814    continue_as_new_consumed: bool,
11815    command_cursor: usize,
11816    condition_wait_occurrence_counter: u64,
11817    matched_recorded_pending: bool,
11818    version_markers: HashMap<String, (i32, u64)>,
11819    workflow_command_identity: String,
11820    workflow_stream_command_counter: u64,
11821    commands: Vec<Value>,
11822    local_activity_requests: Vec<local_activity::Request>,
11823    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
11824    message_stream_cursors: HashMap<String, u64>,
11825    message_stream_waits: HashMap<String, u64>,
11826}
11827
11828impl WorkflowState {
11829    #[cfg(test)]
11830    fn new(
11831        history: Vec<HistoryEvent>,
11832        task_queue: String,
11833        payload_codec: String,
11834        resume_signal: Option<ResumeSignal>,
11835    ) -> Result<Self> {
11836        Self::new_with_identity(
11837            history,
11838            None,
11839            None,
11840            task_queue,
11841            payload_codec,
11842            resume_signal,
11843        )
11844    }
11845
11846    fn new_with_identity(
11847        history: Vec<HistoryEvent>,
11848        workflow_id: Option<String>,
11849        run_id: Option<String>,
11850        task_queue: String,
11851        payload_codec: String,
11852        resume_signal: Option<ResumeSignal>,
11853    ) -> Result<Self> {
11854        Self::new_with_identity_and_scopes(
11855            history,
11856            workflow_id,
11857            run_id,
11858            task_queue,
11859            payload_codec,
11860            resume_signal,
11861            false,
11862        )
11863    }
11864
11865    fn new_with_identity_and_scopes(
11866        history: Vec<HistoryEvent>,
11867        workflow_id: Option<String>,
11868        run_id: Option<String>,
11869        task_queue: String,
11870        payload_codec: String,
11871        resume_signal: Option<ResumeSignal>,
11872        allow_cancellation_scope_authoring: bool,
11873    ) -> Result<Self> {
11874        Self::new_with_identity_and_scope_delivery(
11875            history,
11876            workflow_id,
11877            run_id,
11878            task_queue,
11879            payload_codec,
11880            resume_signal,
11881            allow_cancellation_scope_authoring,
11882            false,
11883        )
11884    }
11885
11886    fn new_with_identity_and_scope_delivery(
11887        history: Vec<HistoryEvent>,
11888        workflow_id: Option<String>,
11889        run_id: Option<String>,
11890        task_queue: String,
11891        payload_codec: String,
11892        resume_signal: Option<ResumeSignal>,
11893        allow_cancellation_scope_authoring: bool,
11894        allow_cancellation_scope_delivery: bool,
11895    ) -> Result<Self> {
11896        cooperative_cancellation::assert_cancellation_scope_replay_supported(
11897            &history,
11898            allow_cancellation_scope_authoring,
11899            allow_cancellation_scope_delivery,
11900        )?;
11901        let scopes = if allow_cancellation_scope_authoring {
11902            cancellation_scope::CancellationScopeHistory::read(
11903                &history,
11904                run_id.as_deref().unwrap_or_default(),
11905            )?
11906        } else {
11907            cancellation_scope::CancellationScopeHistory::default()
11908        };
11909        let cancellation_history = CancellationHistory::from_events(
11910            &history,
11911            run_id.as_deref().unwrap_or_default(),
11912            None,
11913        )?;
11914        if allow_cancellation_scope_authoring
11915            && cancellation_history.request.is_some()
11916            && !allow_cancellation_scope_delivery
11917        {
11918            return Err(Error::CancellationScopeExecutionUnavailable);
11919        }
11920        let scope_delivery = if allow_cancellation_scope_delivery {
11921            Some(cancellation_scope_replay::ScopeReplay::read(
11922                &history,
11923                &scopes,
11924                run_id.as_deref().unwrap_or_default(),
11925                workflow_id.as_deref().unwrap_or_default(),
11926            )?)
11927        } else {
11928            None
11929        };
11930        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
11931            &history,
11932            &payload_codec,
11933            WorkflowIdentity {
11934                workflow_id: workflow_id.clone(),
11935                run_id: run_id.clone(),
11936            },
11937        )?)?;
11938        for (sequence, opening) in &scopes.openings {
11939            if recorded_commands
11940                .iter()
11941                .any(|command| command.sequence() == *sequence)
11942            {
11943                return Err(invalid_recorded_history(
11944                    "invalid_cancellation_scope_history",
11945                    *sequence,
11946                    "distinct authored scope opening",
11947                    "operation collision",
11948                    "scope opening collides with a command",
11949                ));
11950            }
11951            recorded_commands.push(RecordedCommand::CancellationScope {
11952                sequence: *sequence,
11953                scope_id: opening.scope_id.clone(),
11954                parent_scope_id: opening.parent_scope_id.clone(),
11955                shield_parent: opening.shield_parent,
11956            });
11957        }
11958        recorded_commands.sort_by_key(RecordedCommand::sequence);
11959        if let Some(replay) = &scope_delivery {
11960            replay.bind_commands(&mut recorded_commands)?;
11961        }
11962        let selection_markers = recorded_selection_markers(&history)?;
11963        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
11964        let recorded_continue_as_new = history
11965            .iter()
11966            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
11967            .collect::<Vec<_>>();
11968        if recorded_continue_as_new.len() > 1 {
11969            return Err(invalid_recorded_history(
11970                "duplicate_continue_as_new_transition",
11971                recorded_continue_as_new
11972                    .last()
11973                    .and_then(|event| durable_event_sequence(event))
11974                    .unwrap_or(0),
11975                "one WorkflowContinuedAsNew event",
11976                &format!(
11977                    "{} WorkflowContinuedAsNew events",
11978                    recorded_continue_as_new.len()
11979                ),
11980                "workflow history records one continue-as-new transition more than once",
11981            ));
11982        }
11983        let recorded_continue_as_new_sequence = recorded_continue_as_new
11984            .first()
11985            .map(|event| {
11986                durable_event_sequence(event).ok_or_else(|| {
11987                    Error::NonDeterministicReplay(ReplayFailure::new(
11988                        "continue_as_new_sequence_missing",
11989                        None,
11990                        Some("recorded transition sequence".to_string()),
11991                        Some("missing sequence".to_string()),
11992                        "WorkflowContinuedAsNew history is missing its recorded sequence",
11993                    ))
11994                })
11995            })
11996            .transpose()?;
11997        let mut message_stream_cursors = HashMap::new();
11998        for event in &history {
11999            if !matches!(
12000                event.event_type.as_str(),
12001                "SignalReceived" | "SignalApplied"
12002            ) || event.payload.get("signal_name").and_then(Value::as_str)
12003                != Some(MESSAGE_STREAM_SIGNAL)
12004            {
12005                continue;
12006            }
12007            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
12008            if arguments.len() != 1 {
12009                continue;
12010            }
12011            let envelope = arguments[0].clone().into_json()?;
12012            let Some(envelope) = envelope.as_object() else {
12013                continue;
12014            };
12015            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
12016            {
12017                continue;
12018            }
12019            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
12020                continue;
12021            };
12022            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
12023            else {
12024                continue;
12025            };
12026            let cursor = message_stream_cursors
12027                .entry(stream_name.to_string())
12028                .or_insert(0);
12029            *cursor = (*cursor).max(through_position);
12030        }
12031        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
12032        let cancel_requested = history.iter().any(|event| {
12033            matches!(
12034                event.event_type.as_str(),
12035                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
12036            )
12037        });
12038        let cancellation_clock = cancellation_history
12039            .request
12040            .as_ref()
12041            .and_then(|request| request.context.as_ref())
12042            .map(|_| {
12043                cancellation_replay_clock::ReplayClock::new(
12044                    &history,
12045                    &recorded_commands,
12046                    cancellation_history.delivery_index,
12047                )
12048            })
12049            .or_else(|| {
12050                scope_delivery.as_ref().map(|_| {
12051                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
12052                })
12053            });
12054        Ok(Self {
12055            workflow_command_identity: String::new(),
12056            workflow_stream_command_counter: 0,
12057            workflow_id,
12058            run_id,
12059            task_queue,
12060            payload_codec,
12061            history_events: Arc::new(history),
12062            history_budget: WorkflowHistoryBudget {
12063                event_count,
12064                ..WorkflowHistoryBudget::default()
12065            },
12066            cancel_requested,
12067            cancellation_history,
12068            cancellation_consumed: false,
12069            cancellation_clock,
12070            cancellation_shield_depth: 0,
12071            cancellation_delivery_enabled: false,
12072            cancellation_delivery_intent: None,
12073            cancellation_delivery_command_count: 0,
12074            allow_cancellation_scope_authoring,
12075            cancellation_scope_opening: None,
12076            cancellation_scope_memberships: scopes.memberships,
12077            scope_delivery,
12078            resume_signal,
12079            recorded_commands,
12080            selection_markers,
12081            selection_marker_cursor: 0,
12082            cancelled_selection_members,
12083            recorded_continue_as_new_sequence,
12084            continue_as_new_consumed: false,
12085            command_cursor: 0,
12086            condition_wait_occurrence_counter: 0,
12087            matched_recorded_pending: false,
12088            version_markers: HashMap::new(),
12089            commands: Vec::new(),
12090            local_activity_requests: Vec::new(),
12091            message_stream_messages: HashMap::new(),
12092            message_stream_cursors,
12093            message_stream_waits: HashMap::new(),
12094        })
12095    }
12096}
12097
12098enum MessageStreamDelivery {
12099    Message(MessageStreamMessage),
12100    Cursor {
12101        stream_name: String,
12102        through_position: u64,
12103    },
12104}
12105
12106fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
12107    if arguments.len() != 1 {
12108        return Ok(None);
12109    }
12110    let envelope = arguments
12111        .into_iter()
12112        .next()
12113        .expect("one argument was checked");
12114    let Some(envelope) = envelope.as_object() else {
12115        return Ok(None);
12116    };
12117    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
12118        return Ok(None);
12119    };
12120    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
12121        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
12122        else {
12123            return Ok(None);
12124        };
12125        return Ok(Some(MessageStreamDelivery::Cursor {
12126            stream_name: stream_name.to_string(),
12127            through_position,
12128        }));
12129    }
12130    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
12131        return Ok(None);
12132    }
12133    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
12134        return Ok(None);
12135    };
12136    let Some(position) = envelope
12137        .get("position")
12138        .and_then(Value::as_u64)
12139        .filter(|value| *value > 0)
12140    else {
12141        return Ok(None);
12142    };
12143    let Some(payload_envelope) = envelope.get("payload_envelope") else {
12144        return Ok(None);
12145    };
12146    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
12147    else {
12148        return Ok(None);
12149    };
12150    let decoded = decode_avro_value(&payload_envelope)?;
12151    let AvroValue::Array(values) = decoded else {
12152        return Ok(None);
12153    };
12154    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
12155        stream_name: stream_name.to_string(),
12156        message_id: message_id.to_string(),
12157        position,
12158        arguments: values,
12159    })))
12160}
12161
12162#[derive(Clone, Debug)]
12163enum RecordedCommand {
12164    ServiceOperation {
12165        sequence: u64,
12166        call: nexus::RecordedServiceCall,
12167    },
12168    CancellationScope {
12169        sequence: u64,
12170        scope_id: String,
12171        parent_scope_id: String,
12172        shield_parent: bool,
12173    },
12174    CancellationGroup {
12175        sequence: u64,
12176        span: u64,
12177        original: Vec<RecordedCommand>,
12178    },
12179    CancellationBoundary {
12180        sequence: u64,
12181        call_kind: CancellationCallKind,
12182        original: Option<Box<RecordedCommand>>,
12183    },
12184    Activity {
12185        sequence: u64,
12186        activity_type: Option<String>,
12187        cancellation_policy: String,
12188        options: Option<RecordedActivityOptions>,
12189        outcome: Option<ActivityOutcome>,
12190        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12191    },
12192    Timer {
12193        sequence: u64,
12194        delay_seconds: u64,
12195        fired: bool,
12196        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12197    },
12198    ChildWorkflow {
12199        sequence: u64,
12200        workflow_type: Option<String>,
12201        policies: RecordedChildPolicies,
12202        outcome: Option<ChildWorkflowOutcome>,
12203        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12204    },
12205    SignalWait {
12206        sequence: u64,
12207        signal_name: String,
12208        value: Option<Vec<AvroValue>>,
12209        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12210    },
12211    ConditionWait {
12212        sequence: u64,
12213        occurrence_id: String,
12214        condition_key: Option<String>,
12215        predicate_identity: String,
12216        timeout_seconds: Option<u64>,
12217        result: Option<ConditionWaitResult>,
12218        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12219    },
12220    SearchAttributes {
12221        sequence: u64,
12222        attributes: Value,
12223        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
12224    },
12225    SideEffect {
12226        sequence: u64,
12227        value: AvroValue,
12228    },
12229    VersionMarker {
12230        sequence: u64,
12231        change_id: String,
12232        version: i32,
12233    },
12234    Memo {
12235        sequence: u64,
12236        entries: AvroValue,
12237    },
12238}
12239
12240#[derive(Clone, Debug, PartialEq, Eq)]
12241struct SelectionMarker {
12242    selection_group_id: String,
12243    selection_group_base_sequence: u64,
12244    selection_group_size: usize,
12245    member_key: SelectionKey,
12246    member_index: usize,
12247    member_base_sequence: u64,
12248    member_size: usize,
12249    operation_kind: String,
12250    operation_identity: String,
12251    outcome: String,
12252    resolution_event_id: String,
12253    resolution_event_type: String,
12254}
12255
12256#[derive(Clone, Debug, PartialEq, Eq)]
12257struct SelectionCancellation {
12258    selection_group_id: String,
12259    member_key: SelectionKey,
12260    member_index: usize,
12261    member_base_sequence: u64,
12262    member_size: usize,
12263    operation_kind: String,
12264    operation_identity: String,
12265}
12266
12267fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
12268    let mut markers: Vec<SelectionMarker> = Vec::new();
12269    for event in events
12270        .iter()
12271        .filter(|event| event.event_type == "SelectionResolved")
12272    {
12273        let payload = &event.payload;
12274        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
12275        let group_size = required_selection_usize(payload, "selection_group_size")?;
12276        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
12277        let member_size = required_selection_usize(payload, "member_size")?;
12278        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
12279        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
12280            invalid_recorded_history(
12281                "selection_marker_invalid",
12282                base_sequence,
12283                "non-empty selection_group_id",
12284                &payload.to_string(),
12285                "selection winner history is missing its durable group identity",
12286            )
12287        })?;
12288        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
12289        if group_id != expected_group_id {
12290            return Err(invalid_recorded_history(
12291                "selection_marker_invalid",
12292                base_sequence,
12293                &expected_group_id,
12294                &group_id,
12295                "selection winner history contains an incompatible group identity",
12296            ));
12297        }
12298        let group_end = base_sequence
12299            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
12300            .unwrap_or(u64::MAX);
12301        let member_end = member_base_sequence
12302            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
12303            .unwrap_or(u64::MAX);
12304        if member_index >= group_size
12305            || member_base_sequence < base_sequence
12306            || member_end > group_end
12307        {
12308            return Err(invalid_recorded_history(
12309                "selection_marker_invalid",
12310                base_sequence,
12311                "winner member within selection group bounds",
12312                &payload.to_string(),
12313                "selection winner history contains an invalid member range",
12314            ));
12315        }
12316        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
12317            invalid_recorded_history(
12318                "selection_marker_invalid",
12319                base_sequence,
12320                "selection operation kind",
12321                &payload.to_string(),
12322                "selection winner history is missing its operation kind",
12323            )
12324        })?;
12325        if !matches!(
12326            operation_kind.as_str(),
12327            "activity" | "child" | "timer" | "signal" | "condition" | "group"
12328        ) {
12329            return Err(invalid_recorded_history(
12330                "selection_marker_invalid",
12331                base_sequence,
12332                "activity, child, timer, signal, condition, or group",
12333                &operation_kind,
12334                "selection winner history contains an unsupported operation kind",
12335            ));
12336        }
12337        let operation_identity =
12338            payload_string(payload, "operation_identity").ok_or_else(|| {
12339                invalid_recorded_history(
12340                    "selection_marker_invalid",
12341                    base_sequence,
12342                    "non-empty operation identity",
12343                    &payload.to_string(),
12344                    "selection winner history is missing its durable operation identity",
12345                )
12346            })?;
12347        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
12348            invalid_recorded_history(
12349                "selection_marker_invalid",
12350                base_sequence,
12351                "completed or failed selection outcome",
12352                &payload.to_string(),
12353                "selection winner history is missing its outcome",
12354            )
12355        })?;
12356        if !matches!(outcome.as_str(), "completed" | "failed") {
12357            return Err(invalid_recorded_history(
12358                "selection_marker_invalid",
12359                base_sequence,
12360                "completed or failed selection outcome",
12361                &outcome,
12362                "selection winner history contains an unsupported outcome",
12363            ));
12364        }
12365        let marker = SelectionMarker {
12366            selection_group_id: group_id,
12367            selection_group_base_sequence: base_sequence,
12368            selection_group_size: group_size,
12369            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
12370            member_index,
12371            member_base_sequence,
12372            member_size,
12373            operation_kind,
12374            operation_identity,
12375            outcome,
12376            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
12377                || {
12378                    invalid_recorded_history(
12379                        "selection_marker_invalid",
12380                        base_sequence,
12381                        "durable resolution_event_id",
12382                        &payload.to_string(),
12383                        "selection winner history is missing its terminal event identity",
12384                    )
12385                },
12386            )?,
12387            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
12388                || {
12389                    invalid_recorded_history(
12390                        "selection_marker_invalid",
12391                        base_sequence,
12392                        "durable resolution_event_type",
12393                        &payload.to_string(),
12394                        "selection winner history is missing its terminal event type",
12395                    )
12396                },
12397            )?,
12398        };
12399        if let Some(existing) = markers
12400            .iter()
12401            .find(|existing| existing.selection_group_id == marker.selection_group_id)
12402        {
12403            if existing != &marker {
12404                return Err(invalid_recorded_history(
12405                    "selection_marker_conflict",
12406                    base_sequence,
12407                    &format!("one winner for {}", marker.selection_group_id),
12408                    &payload.to_string(),
12409                    "selection history records conflicting winners for one durable group",
12410                ));
12411            }
12412            continue;
12413        }
12414        markers.push(marker);
12415    }
12416    Ok(markers)
12417}
12418
12419fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
12420    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
12421    for event in events
12422        .iter()
12423        .filter(|event| event.event_type == "SelectionOperationCancelled")
12424    {
12425        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
12426            invalid_recorded_history(
12427                "selection_cancellation_invalid",
12428                0,
12429                "non-empty selection_group_id",
12430                &event.payload.to_string(),
12431                "selection cancellation history is missing its group identity",
12432            )
12433        })?;
12434        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
12435        let marker = SelectionCancellation {
12436            selection_group_id: group_id,
12437            member_key: selection_key_from_value(
12438                event.payload.get("member_key"),
12439                member_base_sequence,
12440            )?,
12441            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
12442            member_base_sequence,
12443            member_size: required_selection_usize(&event.payload, "member_size")?,
12444            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
12445                invalid_recorded_history(
12446                    "selection_cancellation_invalid",
12447                    member_base_sequence,
12448                    "selection operation kind",
12449                    &event.payload.to_string(),
12450                    "selection cancellation is missing its operation kind",
12451                )
12452            })?,
12453            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
12454                || {
12455                    invalid_recorded_history(
12456                        "selection_cancellation_invalid",
12457                        member_base_sequence,
12458                        "selection operation identity",
12459                        &event.payload.to_string(),
12460                        "selection cancellation is missing its operation identity",
12461                    )
12462                },
12463            )?,
12464        };
12465        if let Some(existing) = cancelled.iter().find(|recorded| {
12466            recorded.selection_group_id == marker.selection_group_id
12467                && recorded.member_base_sequence == marker.member_base_sequence
12468        }) {
12469            if existing != &marker {
12470                return Err(invalid_recorded_history(
12471                    "selection_cancellation_conflict",
12472                    member_base_sequence,
12473                    "one stable SelectionOperationCancelled marker",
12474                    &event.payload.to_string(),
12475                    "selection cancellation history contains conflicting member metadata",
12476                ));
12477            }
12478        } else {
12479            cancelled.push(marker);
12480        }
12481    }
12482    Ok(cancelled)
12483}
12484
12485fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
12486    payload
12487        .get(field)
12488        .and_then(value_as_u64)
12489        .filter(|value| *value > 0)
12490        .ok_or_else(|| {
12491            invalid_recorded_history(
12492                "selection_marker_invalid",
12493                0,
12494                &format!("positive integer {field}"),
12495                &payload.to_string(),
12496                "selection history contains invalid durable identity metadata",
12497            )
12498        })
12499}
12500
12501fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
12502    required_selection_usize_allow_zero(payload, field).and_then(|value| {
12503        if value > 0 {
12504            Ok(value)
12505        } else {
12506            Err(invalid_recorded_history(
12507                "selection_marker_invalid",
12508                0,
12509                &format!("positive integer {field}"),
12510                &payload.to_string(),
12511                "selection history contains invalid durable identity metadata",
12512            ))
12513        }
12514    })
12515}
12516
12517fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
12518    payload
12519        .get(field)
12520        .and_then(value_as_u64)
12521        .and_then(|value| usize::try_from(value).ok())
12522        .ok_or_else(|| {
12523            invalid_recorded_history(
12524                "selection_marker_invalid",
12525                0,
12526                &format!("non-negative integer {field}"),
12527                &payload.to_string(),
12528                "selection history contains invalid durable identity metadata",
12529            )
12530        })
12531}
12532
12533#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12534struct RecordedActivityOptions {
12535    task_queue: RecordedSnapshotValue<Option<String>>,
12536    execution_mode: RecordedSnapshotValue<Option<String>>,
12537    retry_policy: ActivityRetrySnapshot,
12538    worker_session: Option<Value>,
12539}
12540
12541#[derive(Clone, Debug)]
12542struct RecordedChildPolicies {
12543    parent_close_policy: String,
12544    cancellation_policy: String,
12545}
12546
12547fn recorded_activity_cancellation_policy(
12548    events: &[&HistoryEvent],
12549    sequence: u64,
12550) -> Result<String> {
12551    let mut policy: Option<String> = None;
12552    for event in events.iter().filter(|event| {
12553        matches!(
12554            event.event_type.as_str(),
12555            "ActivityScheduled"
12556                | "ActivityStarted"
12557                | "ActivityCompleted"
12558                | "ActivityFailed"
12559                | "ActivityTimedOut"
12560                | "ActivityCancelled"
12561        )
12562    }) {
12563        for source in [Some(&event.payload), event.payload.get("activity")]
12564            .into_iter()
12565            .flatten()
12566        {
12567            let Some(value) = source.get("cancellation_policy") else {
12568                continue;
12569            };
12570            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
12571                value.as_str()
12572            else {
12573                return Err(invalid_recorded_history(
12574                    "invalid_activity_cancellation_policy_history",
12575                    sequence,
12576                    "supported Activity cancellation policy",
12577                    &value.to_string(),
12578                    "Activity history contains an invalid cancellation policy",
12579                ));
12580            };
12581            if let Some(previous) = policy.as_deref() {
12582                if previous != incoming {
12583                    return Err(invalid_recorded_history(
12584                        "activity_cancellation_policy_history_conflict",
12585                        sequence,
12586                        previous,
12587                        incoming,
12588                        "Activity cancellation policy changed between history events",
12589                    ));
12590                }
12591            }
12592            policy = Some(incoming.to_string());
12593        }
12594        policy.get_or_insert_with(|| "try_cancel".to_string());
12595    }
12596    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
12597}
12598
12599fn recorded_child_policy_value<'a>(
12600    payload: &'a Value,
12601    field: &str,
12602    sequence: u64,
12603) -> Result<Option<&'a str>> {
12604    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
12605        return Ok(None);
12606    };
12607    let valid = match (field, value.as_str()) {
12608        (
12609            "parent_close_policy",
12610            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
12611        ) => true,
12612        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
12613            true
12614        }
12615        _ => false,
12616    };
12617    if !valid {
12618        return Err(invalid_recorded_history(
12619            "invalid_child_workflow_policy_history",
12620            sequence,
12621            "supported child workflow policy",
12622            &value.to_string(),
12623            "child workflow history contains an invalid policy",
12624        ));
12625    }
12626    Ok(value.as_str())
12627}
12628
12629fn recorded_child_policies(
12630    events: &[&HistoryEvent],
12631    scheduled: &HistoryEvent,
12632    sequence: u64,
12633) -> Result<RecordedChildPolicies> {
12634    let parent_close_policy =
12635        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
12636            .unwrap_or("abandon")
12637            .to_string();
12638    let cancellation_policy =
12639        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
12640            .unwrap_or("abandon")
12641            .to_string();
12642    for event in events {
12643        for (field, expected) in [
12644            ("parent_close_policy", parent_close_policy.as_str()),
12645            ("cancellation_policy", cancellation_policy.as_str()),
12646        ] {
12647            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
12648                if actual != expected {
12649                    return Err(invalid_recorded_history(
12650                        "child_workflow_policy_history_conflict",
12651                        sequence,
12652                        expected,
12653                        actual,
12654                        "child workflow policy changed between history events",
12655                    ));
12656                }
12657            }
12658        }
12659    }
12660    Ok(RecordedChildPolicies {
12661        parent_close_policy,
12662        cancellation_policy,
12663    })
12664}
12665
12666fn ensure_child_policies_match(
12667    sequence: u64,
12668    recorded: &RecordedChildPolicies,
12669    current: &ChildWorkflowOptions,
12670) -> Result<()> {
12671    for (field, expected, actual) in [
12672        (
12673            "parent_close_policy",
12674            recorded.parent_close_policy.as_str(),
12675            current.parent_close_policy.as_str(),
12676        ),
12677        (
12678            "cancellation_policy",
12679            recorded.cancellation_policy.as_str(),
12680            current.cancellation_policy.as_str(),
12681        ),
12682    ] {
12683        if expected != actual {
12684            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
12685                "child_workflow_policy_changed",
12686                Some(sequence),
12687                Some(expected.to_string()),
12688                Some(actual.to_string()),
12689                format!("child workflow {field} changed during replay"),
12690            )));
12691        }
12692    }
12693    Ok(())
12694}
12695
12696#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12697enum RecordedSnapshotValue<T> {
12698    /// Older history did not persist this field, so it cannot constrain replay.
12699    Unknown,
12700    Known(T),
12701}
12702
12703impl<T: PartialEq> RecordedSnapshotValue<T> {
12704    fn matches_current(&self, current: &Self) -> bool {
12705        match self {
12706            Self::Unknown => true,
12707            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
12708        }
12709    }
12710}
12711
12712#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12713struct ActivityRetrySnapshot {
12714    snapshot_version: RecordedSnapshotValue<Option<u64>>,
12715    max_attempts: RecordedSnapshotValue<Option<u64>>,
12716    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
12717    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12718    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
12719    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12720    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
12721    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
12722}
12723
12724impl ActivityRetrySnapshot {
12725    fn matches_current(&self, current: &Self) -> bool {
12726        self.snapshot_version
12727            .matches_current(&current.snapshot_version)
12728            && self.max_attempts.matches_current(&current.max_attempts)
12729            && self
12730                .backoff_seconds
12731                .matches_current(&current.backoff_seconds)
12732            && self
12733                .start_to_close_timeout
12734                .matches_current(&current.start_to_close_timeout)
12735            && self
12736                .schedule_to_start_timeout
12737                .matches_current(&current.schedule_to_start_timeout)
12738            && self
12739                .schedule_to_close_timeout
12740                .matches_current(&current.schedule_to_close_timeout)
12741            && self
12742                .heartbeat_timeout
12743                .matches_current(&current.heartbeat_timeout)
12744            && self
12745                .non_retryable_error_types
12746                .matches_current(&current.non_retryable_error_types)
12747    }
12748}
12749
12750fn recorded_optional_u64(
12751    object: Option<&serde_json::Map<String, Value>>,
12752    field: &str,
12753) -> RecordedSnapshotValue<Option<u64>> {
12754    match object.and_then(|object| object.get(field)) {
12755        None => RecordedSnapshotValue::Unknown,
12756        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12757        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
12758    }
12759}
12760
12761fn recorded_optional_string(
12762    object: &serde_json::Map<String, Value>,
12763    field: &str,
12764) -> RecordedSnapshotValue<Option<String>> {
12765    match object.get(field) {
12766        None => RecordedSnapshotValue::Unknown,
12767        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12768        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
12769    }
12770}
12771
12772fn recorded_activity_execution_mode(
12773    events: &[&HistoryEvent],
12774    sequence: u64,
12775) -> Result<RecordedSnapshotValue<Option<String>>> {
12776    let mut recorded = RecordedSnapshotValue::Unknown;
12777    for event in events {
12778        for object in [
12779            event.payload.as_object(),
12780            event.payload.get("activity").and_then(Value::as_object),
12781        ]
12782        .into_iter()
12783        .flatten()
12784        {
12785            let mode = match object.get("execution_mode") {
12786                None => None,
12787                Some(Value::Null) => Some(None),
12788                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
12789                Some(_) => {
12790                    return Err(invalid_recorded_history(
12791                        "activity_execution_mode_invalid",
12792                        sequence,
12793                        "null or a non-empty execution mode",
12794                        "invalid execution_mode",
12795                        "activity history contains an invalid execution mode",
12796                    ))
12797                }
12798            };
12799            let legacy_mode = match object.get("local_activity") {
12800                None => None,
12801                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
12802                Some(_) => {
12803                    return Err(invalid_recorded_history(
12804                        "activity_execution_mode_invalid",
12805                        sequence,
12806                        "boolean local_activity",
12807                        "invalid local_activity",
12808                        "activity history contains an invalid local-activity marker",
12809                    ))
12810                }
12811            };
12812            for mode in [mode, legacy_mode].into_iter().flatten() {
12813                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
12814                {
12815                    return Err(invalid_recorded_history(
12816                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
12817                        "activity lifecycle events at one workflow sequence disagree on execution mode",
12818                    ));
12819                }
12820                recorded = RecordedSnapshotValue::Known(mode);
12821            }
12822        }
12823    }
12824    Ok(recorded)
12825}
12826
12827fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
12828    let policy = policy.and_then(Value::as_object);
12829    let backoff_seconds = policy
12830        .and_then(|policy| policy.get("backoff_seconds"))
12831        .and_then(Value::as_array)
12832        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12833        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
12834    let mut non_retryable_error_types = Vec::new();
12835    for error_type in policy
12836        .and_then(|policy| policy.get("non_retryable_error_types"))
12837        .and_then(Value::as_array)
12838        .into_iter()
12839        .flatten()
12840        .filter_map(Value::as_str)
12841        .map(str::trim)
12842        .filter(|error_type| !error_type.is_empty())
12843    {
12844        if !non_retryable_error_types
12845            .iter()
12846            .any(|recorded| recorded == error_type)
12847        {
12848            non_retryable_error_types.push(error_type.to_string());
12849        }
12850    }
12851
12852    ActivityRetrySnapshot {
12853        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
12854        max_attempts: recorded_optional_u64(policy, "max_attempts"),
12855        backoff_seconds,
12856        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
12857        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
12858        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
12859        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
12860        non_retryable_error_types: if policy
12861            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
12862        {
12863            RecordedSnapshotValue::Known(non_retryable_error_types)
12864        } else {
12865            RecordedSnapshotValue::Unknown
12866        },
12867    }
12868}
12869
12870fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
12871    let policy = options.retry_policy.as_ref();
12872    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
12873        Some(Value::Null) => None,
12874        Some(value) => value_as_u64(value),
12875        None => Some(1),
12876    };
12877    let backoff_seconds = policy
12878        .and_then(|policy| policy.get("backoff_seconds"))
12879        .and_then(Value::as_array)
12880        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12881        .unwrap_or_default();
12882    let non_retryable_error_types = policy
12883        .and_then(|policy| policy.get("non_retryable_error_types"))
12884        .and_then(Value::as_array)
12885        .into_iter()
12886        .flatten()
12887        .filter_map(Value::as_str)
12888        .map(str::to_string)
12889        .collect();
12890
12891    ActivityRetrySnapshot {
12892        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
12893        max_attempts: RecordedSnapshotValue::Known(max_attempts),
12894        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
12895        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
12896        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
12897        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
12898        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
12899        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
12900    }
12901}
12902
12903fn activity_options_description(options: &RecordedActivityOptions) -> String {
12904    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
12905}
12906
12907impl RecordedCommand {
12908    fn sequence(&self) -> u64 {
12909        match self {
12910            Self::CancellationGroup { sequence, .. }
12911            | Self::CancellationScope { sequence, .. }
12912            | Self::CancellationBoundary { sequence, .. }
12913            | Self::Activity { sequence, .. }
12914            | Self::Timer { sequence, .. }
12915            | Self::ChildWorkflow { sequence, .. }
12916            | Self::SignalWait { sequence, .. }
12917            | Self::ConditionWait { sequence, .. }
12918            | Self::SearchAttributes { sequence, .. }
12919            | Self::SideEffect { sequence, .. }
12920            | Self::VersionMarker { sequence, .. }
12921            | Self::Memo { sequence, .. } => *sequence,
12922            Self::ServiceOperation { sequence, .. } => *sequence,
12923        }
12924    }
12925
12926    fn shape(&self) -> &'static str {
12927        match self {
12928            Self::CancellationScope { .. } => "cancellation scope",
12929            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
12930                "cooperative cancellation"
12931            }
12932            Self::Activity { .. } => "activity",
12933            Self::Timer { .. } => "timer",
12934            Self::ChildWorkflow { .. } => "child workflow",
12935            Self::SignalWait { .. } => "signal wait",
12936            Self::ConditionWait { .. } => "condition wait",
12937            Self::SearchAttributes { .. } => "search-attribute update",
12938            Self::SideEffect { .. } => "side effect",
12939            Self::VersionMarker { .. } => "version marker",
12940            Self::Memo { .. } => "memo upsert",
12941            Self::ServiceOperation { .. } => "service operation",
12942        }
12943    }
12944}
12945
12946fn ensure_version_supported(
12947    change_id: &str,
12948    version: i32,
12949    min_supported: i32,
12950    max_supported: i32,
12951    sequence: u64,
12952) -> Result<()> {
12953    if (min_supported..=max_supported).contains(&version) {
12954        return Ok(());
12955    }
12956    Err(Error::NonDeterministicReplay(ReplayFailure::new(
12957        "version_marker_incompatible_range",
12958        (sequence != 0).then_some(sequence),
12959        Some(format!("{min_supported}..={max_supported}")),
12960        Some(format!("{change_id}:{version}")),
12961        "recorded workflow version is outside the range supported by current code",
12962    )))
12963}
12964
12965#[derive(Clone, Debug)]
12966struct ResumeSignal {
12967    signal_name: String,
12968    arguments: Vec<AvroValue>,
12969}
12970
12971const MAX_PARALLEL_OPERATIONS: usize = 1000;
12972
12973fn parallel_group_prefix(kind: &str) -> &'static str {
12974    match kind {
12975        "activity" => "parallel-activities",
12976        "child" => "parallel-children",
12977        "timer" => "parallel-timers",
12978        _ => "parallel-calls",
12979    }
12980}
12981
12982fn parallel_group_entry(
12983    base_sequence: u64,
12984    size: usize,
12985    index: usize,
12986    kind: &str,
12987) -> ParallelGroupMetadata {
12988    ParallelGroupMetadata {
12989        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
12990        parallel_group_kind: kind.to_string(),
12991        parallel_group_base_sequence: base_sequence,
12992        parallel_group_size: size,
12993        parallel_group_index: index,
12994        parallel_group_mode: None,
12995        selection_member_key: None,
12996        selection_member_index: None,
12997        selection_member_base_sequence: None,
12998        selection_member_size: None,
12999        selection_member_kind: None,
13000    }
13001}
13002
13003struct SelectionMemberMetadata {
13004    key: SelectionKey,
13005    index: usize,
13006    base_sequence: u64,
13007    size: usize,
13008    kind: String,
13009}
13010
13011fn selection_group_entry(
13012    base_sequence: u64,
13013    size: usize,
13014    index: usize,
13015    kind: &str,
13016    member: &SelectionMemberMetadata,
13017) -> ParallelGroupMetadata {
13018    ParallelGroupMetadata {
13019        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
13020        parallel_group_kind: kind.to_string(),
13021        parallel_group_base_sequence: base_sequence,
13022        parallel_group_size: size,
13023        parallel_group_index: index,
13024        parallel_group_mode: Some("select".to_string()),
13025        selection_member_key: Some(member.key.clone()),
13026        selection_member_index: Some(member.index),
13027        selection_member_base_sequence: Some(member.base_sequence),
13028        selection_member_size: Some(member.size),
13029        selection_member_kind: Some(member.kind.clone()),
13030    }
13031}
13032
13033fn apply_parallel_group_path(
13034    command: &mut serde_json::Map<String, Value>,
13035    path: &[ParallelGroupMetadata],
13036) {
13037    let Some(inner) = path.last() else {
13038        return;
13039    };
13040    command.insert(
13041        "parallel_group_id".to_string(),
13042        json!(inner.parallel_group_id),
13043    );
13044    command.insert(
13045        "parallel_group_kind".to_string(),
13046        json!(inner.parallel_group_kind),
13047    );
13048    command.insert(
13049        "parallel_group_base_sequence".to_string(),
13050        json!(inner.parallel_group_base_sequence),
13051    );
13052    command.insert(
13053        "parallel_group_size".to_string(),
13054        json!(inner.parallel_group_size),
13055    );
13056    command.insert(
13057        "parallel_group_index".to_string(),
13058        json!(inner.parallel_group_index),
13059    );
13060    if let Some(mode) = &inner.parallel_group_mode {
13061        command.insert("parallel_group_mode".to_string(), json!(mode));
13062    }
13063    if let Some(key) = &inner.selection_member_key {
13064        command.insert("selection_member_key".to_string(), json!(key));
13065    }
13066    if let Some(index) = inner.selection_member_index {
13067        command.insert("selection_member_index".to_string(), json!(index));
13068    }
13069    if let Some(base_sequence) = inner.selection_member_base_sequence {
13070        command.insert(
13071            "selection_member_base_sequence".to_string(),
13072            json!(base_sequence),
13073        );
13074    }
13075    if let Some(size) = inner.selection_member_size {
13076        command.insert("selection_member_size".to_string(), json!(size));
13077    }
13078    if let Some(kind) = &inner.selection_member_kind {
13079        command.insert("selection_member_kind".to_string(), json!(kind));
13080    }
13081    command.insert("parallel_group_path".to_string(), json!(path));
13082}
13083
13084fn ensure_parallel_path_matches(
13085    sequence: u64,
13086    recorded: Option<&[ParallelGroupMetadata]>,
13087    expected: &[ParallelGroupMetadata],
13088) -> Result<()> {
13089    match (recorded, expected.is_empty()) {
13090        (None, true) => Ok(()),
13091        (Some(recorded), false) if recorded == expected => Ok(()),
13092        (None, false) => Err(invalid_recorded_history(
13093            "parallel_group_metadata_missing",
13094            sequence,
13095            &serde_json::to_string(expected).unwrap_or_default(),
13096            "<missing>",
13097            "recorded parallel member is missing its durable group path",
13098        )),
13099        (Some(recorded), true) => Err(invalid_recorded_history(
13100            "parallel_group_shape_mismatch",
13101            sequence,
13102            "sequential command",
13103            &serde_json::to_string(recorded).unwrap_or_default(),
13104            "recorded command belonged to a parallel group but current code schedules it sequentially",
13105        )),
13106        (Some(recorded), false) => Err(invalid_recorded_history(
13107            "parallel_group_shape_mismatch",
13108            sequence,
13109            &serde_json::to_string(recorded).unwrap_or_default(),
13110            &serde_json::to_string(expected).unwrap_or_default(),
13111            "recorded parallel-group identity or path changed during replay",
13112        )),
13113    }
13114}
13115
13116#[derive(Clone, Debug)]
13117enum ParallelShape {
13118    Leaf,
13119    Group(Vec<ParallelShape>),
13120}
13121
13122struct ParallelDescriptor {
13123    operation: ParallelOperation,
13124    offset: usize,
13125    member_path: Vec<usize>,
13126    group_path: Vec<ParallelGroupMetadata>,
13127}
13128
13129fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
13130    operations
13131        .iter()
13132        .map(|operation| match operation {
13133            ParallelOperation::Group(children) => parallel_leaf_count(children),
13134            _ => 1,
13135        })
13136        .sum()
13137}
13138
13139fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
13140    match operation {
13141        ParallelOperation::Activity { .. } => Some("activity"),
13142        ParallelOperation::ChildWorkflow { .. } => Some("child"),
13143        ParallelOperation::Timer(_) => Some("timer"),
13144        ParallelOperation::Signal(_) => Some("signal"),
13145        ParallelOperation::Condition { .. } => Some("condition"),
13146        ParallelOperation::Group(children) => parallel_group_kind(children),
13147    }
13148}
13149
13150fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
13151    let mut kind = None;
13152    for operation in operations {
13153        let Some(operation_kind) = parallel_operation_kind(operation) else {
13154            continue;
13155        };
13156        match kind {
13157            None => kind = Some(operation_kind),
13158            Some(current) if current == operation_kind => {}
13159            Some(_) => return Some("mixed"),
13160        }
13161    }
13162    kind
13163}
13164
13165fn validate_parallel_operations(
13166    operations: &[ParallelOperation],
13167    member_path: &mut Vec<usize>,
13168    root: bool,
13169) -> Result<()> {
13170    let leaves = parallel_leaf_count(operations);
13171    if leaves > MAX_PARALLEL_OPERATIONS {
13172        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13173            reason: "fan_out_limit_exceeded",
13174            member_path: member_path.clone(),
13175            message: format!(
13176                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13177            ),
13178        }));
13179    }
13180    if !root && operations.is_empty() {
13181        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13182            reason: "nested_group_empty",
13183            member_path: member_path.clone(),
13184            message: "a nested group must contain at least one durable leaf".to_string(),
13185        }));
13186    }
13187
13188    for (index, operation) in operations.iter().enumerate() {
13189        member_path.push(index);
13190        match operation {
13191            ParallelOperation::Activity {
13192                options, arguments, ..
13193            } => {
13194                options
13195                    .validate()
13196                    .map_err(|error| Error::InvalidActivityOptions(error))?;
13197                if let Err(error) = arguments {
13198                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13199                        reason: "arguments_invalid",
13200                        member_path: member_path.clone(),
13201                        message: error.to_string(),
13202                    }));
13203                }
13204            }
13205            ParallelOperation::ChildWorkflow {
13206                options, arguments, ..
13207            } => {
13208                validate_parallel_child_options(options)?;
13209                if let Err(error) = arguments {
13210                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13211                        reason: "arguments_invalid",
13212                        member_path: member_path.clone(),
13213                        message: error.to_string(),
13214                    }));
13215                }
13216            }
13217            ParallelOperation::Timer(duration)
13218                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
13219            {
13220                return Err(Error::TimerDurationOverflow);
13221            }
13222            ParallelOperation::Timer(_) => {}
13223            ParallelOperation::Signal(signal_name) => {
13224                validate_user_signal_name(signal_name)?;
13225                if signal_name.trim().is_empty() {
13226                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13227                        reason: "signal_name_empty",
13228                        member_path: member_path.clone(),
13229                        message: "signal wait name must not be empty".to_string(),
13230                    }));
13231                }
13232            }
13233            ParallelOperation::Condition { options, .. } => {
13234                options.validate()?;
13235            }
13236            ParallelOperation::Group(children) => {
13237                validate_parallel_operations(children, member_path, false)?;
13238            }
13239        }
13240        member_path.pop();
13241    }
13242    Ok(())
13243}
13244
13245fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
13246    if options.task_queue.trim().is_empty() {
13247        return Err(Error::InvalidChildWorkflowOptions(
13248            "task_queue must not be empty".to_string(),
13249        ));
13250    }
13251    for (name, value) in [
13252        (
13253            "execution_timeout_seconds",
13254            options.execution_timeout_seconds,
13255        ),
13256        ("run_timeout_seconds", options.run_timeout_seconds),
13257    ] {
13258        if value == Some(0) {
13259            return Err(Error::InvalidChildWorkflowOptions(format!(
13260                "{name} must be at least 1"
13261            )));
13262        }
13263    }
13264    if options
13265        .retry_policy
13266        .as_ref()
13267        .is_some_and(|policy| policy.max_attempts == Some(0))
13268    {
13269        return Err(Error::InvalidChildWorkflowOptions(
13270            "retry_policy.max_attempts must be at least 1".to_string(),
13271        ));
13272    }
13273    Ok(())
13274}
13275
13276fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
13277    ParallelShape::Group(
13278        operations
13279            .iter()
13280            .map(|operation| match operation {
13281                ParallelOperation::Group(children) => parallel_shape(children),
13282                _ => ParallelShape::Leaf,
13283            })
13284            .collect(),
13285    )
13286}
13287
13288fn parallel_descriptors(
13289    operations: Vec<ParallelOperation>,
13290    base_sequence: u64,
13291) -> Result<Vec<ParallelDescriptor>> {
13292    let size = parallel_leaf_count(&operations);
13293    let kind = parallel_group_kind(&operations).unwrap_or("activity");
13294    let mut descriptors = Vec::with_capacity(size);
13295    let mut cursor = 0;
13296
13297    for (index, operation) in operations.into_iter().enumerate() {
13298        match operation {
13299            ParallelOperation::Group(children) => {
13300                let child_base = base_sequence
13301                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13302                    .ok_or(Error::TimerDurationOverflow)?;
13303                for mut descriptor in parallel_descriptors(children, child_base)? {
13304                    let outer_index = cursor + descriptor.offset;
13305                    descriptor.group_path.insert(
13306                        0,
13307                        parallel_group_entry(base_sequence, size, outer_index, kind),
13308                    );
13309                    descriptor.member_path.insert(0, index);
13310                    descriptor.offset = outer_index;
13311                    descriptors.push(descriptor);
13312                }
13313                cursor = descriptors.len();
13314            }
13315            operation => {
13316                descriptors.push(ParallelDescriptor {
13317                    operation,
13318                    offset: cursor,
13319                    member_path: vec![index],
13320                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
13321                });
13322                cursor += 1;
13323            }
13324        }
13325    }
13326    Ok(descriptors)
13327}
13328
13329enum ParallelLeafCall {
13330    Activity(ActivityCall),
13331    ChildWorkflow(ChildWorkflowCall),
13332    Timer(TimerCall),
13333    Signal(SignalCall),
13334    Condition(ConditionWaitCall),
13335}
13336
13337fn parallel_leaf_call(
13338    ctx: &WorkflowContext,
13339    operation: ParallelOperation,
13340    parallel_group_path: Vec<ParallelGroupMetadata>,
13341) -> ParallelLeafCall {
13342    match operation {
13343        ParallelOperation::Activity {
13344            activity_type,
13345            options,
13346            arguments,
13347        } => ParallelLeafCall::Activity(ActivityCall {
13348            ctx: ctx.clone(),
13349            activity_type,
13350            options,
13351            worker_session: None,
13352            args: Some(arguments),
13353            scheduled: false,
13354            local: false,
13355            local_result: None,
13356            parallel_group_path,
13357        }),
13358        ParallelOperation::ChildWorkflow {
13359            workflow_type,
13360            options,
13361            arguments,
13362        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
13363            ctx: ctx.clone(),
13364            workflow_type,
13365            options,
13366            args: Some(arguments),
13367            scheduled: false,
13368            matched_pending: false,
13369            parallel_group_path,
13370        }),
13371        ParallelOperation::Timer(duration) => {
13372            let delay_seconds = duration
13373                .as_secs()
13374                .checked_add(u64::from(duration.subsec_nanos() > 0));
13375            ParallelLeafCall::Timer(TimerCall {
13376                ctx: ctx.clone(),
13377                delay_seconds,
13378                scheduled: false,
13379                matched_pending: false,
13380                parallel_group_path,
13381            })
13382        }
13383        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
13384            ctx: ctx.clone(),
13385            signal_name,
13386            runtime_reserved_allowed: false,
13387            opened_wait: false,
13388            matched_pending: false,
13389            parallel_group_path,
13390        }),
13391        ParallelOperation::Condition { options, predicate } => {
13392            ParallelLeafCall::Condition(ConditionWaitCall {
13393                ctx: ctx.clone(),
13394                options,
13395                predicate,
13396                occurrence_id: None,
13397                opened_wait: false,
13398                parallel_group_path,
13399            })
13400        }
13401        ParallelOperation::Group(_) => {
13402            unreachable!("parallel descriptors contain only durable leaves")
13403        }
13404    }
13405}
13406
13407impl ParallelLeafCall {
13408    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
13409        match self {
13410            Self::Activity(call) => Pin::new(call)
13411                .poll_avro_value(cx)
13412                .map_ok(ParallelAvroResult::Activity),
13413            Self::ChildWorkflow(call) => Pin::new(call)
13414                .poll_avro_value(cx)
13415                .map_ok(ParallelAvroResult::ChildWorkflow),
13416            Self::Timer(call) => Pin::new(call)
13417                .poll(cx)
13418                .map_ok(|()| ParallelAvroResult::Timer),
13419            Self::Signal(call) => Pin::new(call)
13420                .poll_avro_value(cx)
13421                .map_ok(ParallelAvroResult::Signal),
13422            Self::Condition(call) => Pin::new(call)
13423                .poll(cx)
13424                .map_ok(ParallelAvroResult::Condition),
13425        }
13426    }
13427}
13428
13429struct ParallelLeaf {
13430    call: ParallelLeafCall,
13431    sequence: u64,
13432    member_path: Vec<usize>,
13433    group_path: Vec<ParallelGroupMetadata>,
13434    result: Option<ParallelAvroResult>,
13435}
13436
13437/// Future returned by [`WorkflowContext::parallel`].
13438pub struct ParallelCall {
13439    ctx: WorkflowContext,
13440    operations: Option<Vec<ParallelOperation>>,
13441    shape: Option<ParallelShape>,
13442    leaves: Vec<ParallelLeaf>,
13443    pending_scope_delivery: bool,
13444    worker_session: Option<WorkerSessionOptions>,
13445}
13446
13447impl ParallelCall {
13448    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
13449        Self {
13450            ctx,
13451            operations: Some(operations),
13452            shape: None,
13453            leaves: Vec::new(),
13454            pending_scope_delivery: false,
13455            worker_session: None,
13456        }
13457    }
13458
13459    fn initialize(&mut self) -> Result<()> {
13460        if let Some(session) = &self.worker_session {
13461            session.to_wire()?;
13462        }
13463        let operations = self.operations.take().unwrap_or_default();
13464        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
13465        self.shape = Some(parallel_shape(&operations));
13466        if operations.is_empty() {
13467            return Ok(());
13468        }
13469
13470        let base_sequence = {
13471            let state = self
13472                .ctx
13473                .state
13474                .lock()
13475                .map_err(|_| Error::WorkflowStatePoisoned)?;
13476            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13477                recorded.sequence()
13478            } else {
13479                let last = state
13480                    .recorded_commands
13481                    .last()
13482                    .map(RecordedCommand::sequence)
13483                    .unwrap_or(0);
13484                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
13485                    .and_then(|sequence| sequence.checked_add(1))
13486                    .ok_or_else(|| {
13487                        Error::InvalidParallelGroup(ParallelGroupError {
13488                            reason: "sequence_overflow",
13489                            member_path: Vec::new(),
13490                            message: "parallel group sequence identity overflowed u64".to_string(),
13491                        })
13492                    })?
13493            }
13494        };
13495
13496        let descriptors = parallel_descriptors(operations, base_sequence)?;
13497        {
13498            let mut state = self
13499                .ctx
13500                .state
13501                .lock()
13502                .map_err(|_| Error::WorkflowStatePoisoned)?;
13503            let cursor = state.command_cursor;
13504            self.ctx.validate_scope_membership(&mut state, cursor)?;
13505            if state.prepare_parallel_scope_cancellation(&descriptors)? {
13506                self.pending_scope_delivery = true;
13507                return Ok(());
13508            }
13509            state.expand_cancellation_group(&descriptors)?;
13510            state.prepare_group_cancellation(&descriptors)?;
13511        }
13512        self.leaves = descriptors
13513            .into_iter()
13514            .map(|descriptor| {
13515                let mut call = parallel_leaf_call(
13516                    &self.ctx,
13517                    descriptor.operation,
13518                    descriptor.group_path.clone(),
13519                );
13520                if let (Some(session), ParallelLeafCall::Activity(activity)) =
13521                    (&self.worker_session, &mut call)
13522                {
13523                    activity.worker_session = Some(session.clone());
13524                }
13525                ParallelLeaf {
13526                    call,
13527                    sequence: base_sequence + descriptor.offset as u64,
13528                    member_path: descriptor.member_path,
13529                    group_path: descriptor.group_path,
13530                    result: None,
13531                }
13532            })
13533            .collect();
13534        Ok(())
13535    }
13536
13537    fn poll_avro_value(
13538        mut self: Pin<&mut Self>,
13539        cx: &mut TaskContext<'_>,
13540    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
13541        if self.operations.is_some() {
13542            if let Err(error) = self.initialize() {
13543                return Poll::Ready(Err(error));
13544            }
13545        }
13546        if self.pending_scope_delivery {
13547            return Poll::Pending;
13548        }
13549        if self.leaves.is_empty() {
13550            return Poll::Ready(Ok(Vec::new()));
13551        }
13552
13553        let mut failures = Vec::new();
13554        let mut pending = false;
13555        for (index, leaf) in self.leaves.iter_mut().enumerate() {
13556            if leaf.result.is_some() {
13557                continue;
13558            }
13559            match leaf.call.poll_avro_value(cx) {
13560                Poll::Ready(Ok(result)) => leaf.result = Some(result),
13561                Poll::Ready(Err(error)) => failures.push((index, error)),
13562                Poll::Pending => pending = true,
13563            }
13564        }
13565
13566        if !failures.is_empty() {
13567            if let Some(position) = failures
13568                .iter()
13569                .position(|(_, error)| workflow_task_integrity_error(error))
13570            {
13571                return Poll::Ready(Err(failures.remove(position).1));
13572            }
13573            if self
13574                .ctx
13575                .state
13576                .lock()
13577                .map_err(|_| Error::WorkflowStatePoisoned)?
13578                .cancellation_delivery_intent
13579                .is_some()
13580            {
13581                return Poll::Pending;
13582            }
13583            if let Some(position) = failures
13584                .iter()
13585                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
13586            {
13587                return Poll::Ready(Err(failures.remove(position).1));
13588            }
13589            failures.sort_by_key(|(index, _)| *index);
13590            let (failed_index, cause) = failures.remove(0);
13591            let failed = &self.leaves[failed_index];
13592            let completed = self
13593                .leaves
13594                .iter()
13595                .filter_map(|leaf| {
13596                    leaf.result
13597                        .clone()
13598                        .and_then(|result| result.into_json_result().ok())
13599                        .map(|result| ParallelCompletion {
13600                            member_path: leaf.member_path.clone(),
13601                            result,
13602                        })
13603                })
13604                .collect();
13605            let group_id = failed
13606                .group_path
13607                .first()
13608                .map(|entry| entry.parallel_group_id.clone())
13609                .unwrap_or_default();
13610            let sequences = self
13611                .leaves
13612                .iter()
13613                .map(|leaf| leaf.sequence)
13614                .collect::<Vec<_>>();
13615            self.ctx
13616                .state
13617                .lock()
13618                .map_err(|_| Error::WorkflowStatePoisoned)?
13619                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
13620            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
13621                group_id,
13622                member_path: failed.member_path.clone(),
13623                group_path: failed.group_path.clone(),
13624                completed,
13625                cause: Box::new(cause),
13626            })));
13627        }
13628        if pending
13629            || self
13630                .ctx
13631                .state
13632                .lock()
13633                .map_err(|_| Error::WorkflowStatePoisoned)?
13634                .cancellation_delivery_intent
13635                .is_some()
13636        {
13637            return Poll::Pending;
13638        }
13639
13640        let mut flat_results = self
13641            .leaves
13642            .iter_mut()
13643            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
13644            .collect::<Vec<_>>()
13645            .into_iter();
13646        let results = parallel_results_for_shape(
13647            self.shape.as_ref().expect("initialized parallel shape"),
13648            &mut flat_results,
13649        );
13650        let sequences = self
13651            .leaves
13652            .iter()
13653            .map(|leaf| leaf.sequence)
13654            .collect::<Vec<_>>();
13655        self.ctx
13656            .state
13657            .lock()
13658            .map_err(|_| Error::WorkflowStatePoisoned)?
13659            .advance_cancellation_sequences(&sequences, None);
13660        Poll::Ready(Ok(match results {
13661            ParallelAvroResult::Group(results) => results,
13662            ParallelAvroResult::Activity(_)
13663            | ParallelAvroResult::ChildWorkflow(_)
13664            | ParallelAvroResult::Timer
13665            | ParallelAvroResult::Signal(_)
13666            | ParallelAvroResult::Condition(_) => {
13667                unreachable!("root parallel shape is a group")
13668            }
13669        }))
13670    }
13671}
13672
13673fn parallel_results_for_shape(
13674    shape: &ParallelShape,
13675    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
13676) -> ParallelAvroResult {
13677    match shape {
13678        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
13679        ParallelShape::Group(children) => ParallelAvroResult::Group(
13680            children
13681                .iter()
13682                .map(|child| parallel_results_for_shape(child, flat_results))
13683                .collect(),
13684        ),
13685    }
13686}
13687
13688impl Future for ParallelCall {
13689    type Output = Result<Vec<ParallelResult>>;
13690
13691    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13692        self.poll_avro_value(cx)
13693            .map_ok(|results| {
13694                results
13695                    .into_iter()
13696                    .map(ParallelAvroResult::into_json_result)
13697                    .collect::<Result<Vec<_>>>()
13698            })
13699            .map_ok(|result| result)
13700            .flatten_result()
13701    }
13702}
13703
13704#[derive(Clone, Debug)]
13705struct SelectionMemberPlan {
13706    key: SelectionKey,
13707    index: usize,
13708    base_sequence: u64,
13709    size: usize,
13710    kind: String,
13711    shape: ParallelShape,
13712    leaf_start: usize,
13713}
13714
13715fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
13716    match operation {
13717        ParallelOperation::Activity { .. } => "activity",
13718        ParallelOperation::ChildWorkflow { .. } => "child",
13719        ParallelOperation::Timer(_) => "timer",
13720        ParallelOperation::Signal(_) => "signal",
13721        ParallelOperation::Condition { .. } => "condition",
13722        ParallelOperation::Group(_) => "group",
13723    }
13724}
13725
13726fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
13727    match operation {
13728        ParallelOperation::Group(children) => parallel_shape(children),
13729        _ => ParallelShape::Leaf,
13730    }
13731}
13732
13733fn selection_descriptors(
13734    operations: Vec<(SelectionKey, ParallelOperation)>,
13735    base_sequence: u64,
13736) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
13737    if operations.is_empty() {
13738        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13739            reason: "selection_empty",
13740            member_path: Vec::new(),
13741            message: "durable selection requires at least one operation".to_string(),
13742        }));
13743    }
13744    let operation_refs = operations
13745        .iter()
13746        .map(|(_, operation)| operation)
13747        .collect::<Vec<_>>();
13748    let total_size = operation_refs
13749        .iter()
13750        .map(|operation| match operation {
13751            ParallelOperation::Group(children) => parallel_leaf_count(children),
13752            _ => 1,
13753        })
13754        .sum::<usize>();
13755    if total_size > MAX_PARALLEL_OPERATIONS {
13756        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13757            reason: "fan_out_limit_exceeded",
13758            member_path: Vec::new(),
13759            message: format!(
13760                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13761            ),
13762        }));
13763    }
13764    let group_kind = {
13765        let mut kind = None;
13766        for operation in &operation_refs {
13767            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
13768            match kind {
13769                None => kind = Some(operation_kind),
13770                Some(current) if current == operation_kind => {}
13771                Some(_) => {
13772                    kind = Some("mixed");
13773                    break;
13774                }
13775            }
13776        }
13777        kind.unwrap_or("mixed")
13778    };
13779
13780    let mut descriptors = Vec::with_capacity(total_size);
13781    let mut members = Vec::with_capacity(operations.len());
13782    let mut cursor = 0usize;
13783    let mut seen_keys: Vec<SelectionKey> = Vec::new();
13784    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
13785        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
13786            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13787                reason: "selection_key_invalid",
13788                member_path: vec![member_index],
13789                message: "selection member keys must be non-empty strings or non-negative integers"
13790                    .to_string(),
13791            }));
13792        }
13793        if seen_keys.contains(&key) {
13794            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13795                reason: "selection_key_duplicate",
13796                member_path: vec![member_index],
13797                message: format!("selection member key {key:?} is duplicated"),
13798            }));
13799        }
13800        seen_keys.push(key.clone());
13801        let member_size = match &operation {
13802            ParallelOperation::Group(children) => parallel_leaf_count(children),
13803            _ => 1,
13804        };
13805        if member_size == 0 {
13806            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13807                reason: "selection_member_empty",
13808                member_path: vec![member_index],
13809                message: "a selection member must contain at least one durable leaf".to_string(),
13810            }));
13811        }
13812        let member_base = base_sequence
13813            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13814            .ok_or(Error::TimerDurationOverflow)?;
13815        let member_kind = selection_operation_kind(&operation).to_string();
13816        let member_shape = selection_operation_shape(&operation);
13817        let leaf_start = descriptors.len();
13818        match operation {
13819            ParallelOperation::Group(children) => {
13820                validate_parallel_operations(&children, &mut vec![member_index], false)?;
13821                for mut descriptor in parallel_descriptors(children, member_base)? {
13822                    let flat_index = cursor + descriptor.offset;
13823                    descriptor.group_path.insert(
13824                        0,
13825                        selection_group_entry(
13826                            base_sequence,
13827                            total_size,
13828                            flat_index,
13829                            group_kind,
13830                            &SelectionMemberMetadata {
13831                                key: key.clone(),
13832                                index: member_index,
13833                                base_sequence: member_base,
13834                                size: member_size,
13835                                kind: member_kind.clone(),
13836                            },
13837                        ),
13838                    );
13839                    descriptor.member_path.insert(0, member_index);
13840                    descriptor.offset = flat_index;
13841                    descriptors.push(descriptor);
13842                }
13843            }
13844            operation => {
13845                validate_parallel_operations(
13846                    std::slice::from_ref(&operation),
13847                    &mut Vec::new(),
13848                    true,
13849                )?;
13850                descriptors.push(ParallelDescriptor {
13851                    operation,
13852                    offset: cursor,
13853                    member_path: vec![member_index],
13854                    group_path: vec![selection_group_entry(
13855                        base_sequence,
13856                        total_size,
13857                        cursor,
13858                        group_kind,
13859                        &SelectionMemberMetadata {
13860                            key: key.clone(),
13861                            index: member_index,
13862                            base_sequence: member_base,
13863                            size: member_size,
13864                            kind: member_kind.clone(),
13865                        },
13866                    )],
13867                });
13868            }
13869        }
13870        members.push(SelectionMemberPlan {
13871            key,
13872            index: member_index,
13873            base_sequence: member_base,
13874            size: member_size,
13875            kind: member_kind,
13876            shape: member_shape,
13877            leaf_start,
13878        });
13879        cursor += member_size;
13880    }
13881    Ok((descriptors, members))
13882}
13883
13884struct SelectionLeaf {
13885    call: ParallelLeafCall,
13886    outcome: Option<Result<ParallelAvroResult>>,
13887}
13888
13889/// Stable reference to one member of a durable selection group.
13890#[derive(Clone)]
13891pub struct DurableOperationHandle {
13892    ctx: WorkflowContext,
13893    pub key: SelectionKey,
13894    pub index: usize,
13895    pub kind: String,
13896    pub identity: String,
13897    pub base_sequence: u64,
13898    pub size: usize,
13899    pub selection_group_id: String,
13900    shape: ParallelShape,
13901}
13902
13903impl std::fmt::Debug for DurableOperationHandle {
13904    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13905        formatter
13906            .debug_struct("DurableOperationHandle")
13907            .field("key", &self.key)
13908            .field("index", &self.index)
13909            .field("kind", &self.kind)
13910            .field("identity", &self.identity)
13911            .field("base_sequence", &self.base_sequence)
13912            .field("size", &self.size)
13913            .field("selection_group_id", &self.selection_group_id)
13914            .finish()
13915    }
13916}
13917
13918impl DurableOperationHandle {
13919    /// Await this member after another member has already won the selection.
13920    pub fn await_result(&self) -> DurableOperationAwaitCall {
13921        DurableOperationAwaitCall {
13922            handle: self.clone(),
13923        }
13924    }
13925
13926    /// Request cancellation without affecting siblings. The future resolves
13927    /// to unit; only `SelectionOperationCancelled` history proves cancellation
13928    /// beat a concurrently committed terminal result.
13929    pub fn cancel(&self) -> CancelDurableOperationCall {
13930        CancelDurableOperationCall {
13931            handle: self.clone(),
13932            emitted: false,
13933        }
13934    }
13935}
13936
13937/// The one winner committed for a durable selection group.
13938#[derive(Debug)]
13939pub struct SelectionResult {
13940    pub key: SelectionKey,
13941    pub index: usize,
13942    pub kind: String,
13943    pub identity: String,
13944    pub value: Option<ParallelResult>,
13945    pub failure: Option<Error>,
13946    pub winner: DurableOperationHandle,
13947    pub handles: Vec<DurableOperationHandle>,
13948}
13949
13950impl SelectionResult {
13951    pub fn succeeded(&self) -> bool {
13952        self.failure.is_none()
13953    }
13954
13955    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
13956        self.handles.iter().find(|handle| &handle.key == key)
13957    }
13958
13959    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
13960        self.handles
13961            .iter()
13962            .filter(|handle| handle.index != self.index)
13963            .collect()
13964    }
13965
13966    pub fn into_result(self) -> Result<ParallelResult> {
13967        match (self.value, self.failure) {
13968            (Some(value), None) => Ok(value),
13969            (_, Some(error)) => Err(error),
13970            _ => Err(Error::WorkerLoop(
13971                "selection result contained neither a value nor a failure".to_string(),
13972            )),
13973        }
13974    }
13975}
13976
13977/// Future returned by [`WorkflowContext::select`].
13978pub struct SelectCall {
13979    ctx: WorkflowContext,
13980    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
13981    members: Vec<SelectionMemberPlan>,
13982    leaves: Vec<SelectionLeaf>,
13983    group_id: Option<String>,
13984}
13985
13986impl SelectCall {
13987    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
13988        Self {
13989            ctx,
13990            operations: Some(operations),
13991            members: Vec::new(),
13992            leaves: Vec::new(),
13993            group_id: None,
13994        }
13995    }
13996
13997    fn initialize(&mut self) -> Result<()> {
13998        let operations = self.operations.take().unwrap_or_default();
13999        let base_sequence = {
14000            let state = self
14001                .ctx
14002                .state
14003                .lock()
14004                .map_err(|_| Error::WorkflowStatePoisoned)?;
14005            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
14006                state.recorded_commands.get(state.command_cursor)
14007            {
14008                *sequence
14009            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
14010            {
14011                marker.selection_group_base_sequence
14012            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
14013                recorded.sequence()
14014            } else {
14015                let last = state
14016                    .recorded_commands
14017                    .last()
14018                    .map(RecordedCommand::sequence)
14019                    .unwrap_or(0);
14020                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
14021                    .and_then(|sequence| sequence.checked_add(1))
14022                    .ok_or(Error::TimerDurationOverflow)?
14023            }
14024        };
14025        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
14026        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
14027        {
14028            let mut state = self
14029                .ctx
14030                .state
14031                .lock()
14032                .map_err(|_| Error::WorkflowStatePoisoned)?;
14033            state.expand_cancellation_group(&descriptors)?;
14034            state.prepare_group_cancellation(&descriptors)?;
14035        }
14036        self.leaves = descriptors
14037            .into_iter()
14038            .map(|descriptor| SelectionLeaf {
14039                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
14040                outcome: None,
14041            })
14042            .collect();
14043        self.members = members;
14044        self.group_id = Some(group_id);
14045        Ok(())
14046    }
14047}
14048
14049impl Future for SelectCall {
14050    type Output = Result<SelectionResult>;
14051
14052    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14053        if self.operations.is_some() {
14054            if let Err(error) = self.initialize() {
14055                return Poll::Ready(Err(error));
14056            }
14057        }
14058
14059        for leaf in &mut self.leaves {
14060            if leaf.outcome.is_some() {
14061                continue;
14062            }
14063            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
14064                if outcome
14065                    .as_ref()
14066                    .err()
14067                    .is_some_and(workflow_task_integrity_error)
14068                {
14069                    return Poll::Ready(outcome.map(|_| unreachable!()));
14070                }
14071                leaf.outcome = Some(outcome);
14072            }
14073        }
14074
14075        if self
14076            .ctx
14077            .state
14078            .lock()
14079            .map_err(|_| Error::WorkflowStatePoisoned)?
14080            .cancellation_delivery_intent
14081            .is_some()
14082        {
14083            return Poll::Pending;
14084        }
14085
14086        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
14087            matches!(
14088                leaf.outcome,
14089                Some(Err(Error::CooperativeCancellationRequested(_)))
14090            )
14091        }) {
14092            return Poll::Ready(
14093                leaf.outcome
14094                    .take()
14095                    .expect("matched cancellation")
14096                    .map(|_| unreachable!()),
14097            );
14098        }
14099
14100        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
14101        let selection_member_range = self
14102            .members
14103            .first()
14104            .map(|member| member.base_sequence)
14105            .zip(self.leaves.len().try_into().ok())
14106            .map(|(base_sequence, size): (u64, u64)| {
14107                base_sequence..base_sequence.saturating_add(size)
14108            });
14109        let marker = {
14110            let mut state = match self.ctx.state.lock() {
14111                Ok(state) => state,
14112                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14113            };
14114            let marker = state
14115                .selection_markers
14116                .get(state.selection_marker_cursor)
14117                .cloned();
14118            if marker.is_none()
14119                && all_members_terminal
14120                && selection_member_range.as_ref().is_some_and(|member_range| {
14121                    state
14122                        .recorded_commands
14123                        .iter()
14124                        .any(|command| member_range.contains(&command.sequence()))
14125                })
14126            {
14127                // Terminal member history can be committed before the server's
14128                // SelectionResolved marker becomes visible to this task. That
14129                // marker is the durable barrier the selection is still waiting
14130                // on, so an otherwise commandless replay remains legitimately
14131                // pending instead of failing as an untracked yield.
14132                state.matched_recorded_pending = true;
14133            }
14134            marker
14135        };
14136        let Some(marker) = marker else {
14137            return Poll::Pending;
14138        };
14139        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
14140            || marker.selection_group_size != self.leaves.len()
14141            || self.members.first().map(|member| member.base_sequence)
14142                != Some(marker.selection_group_base_sequence)
14143        {
14144            return Poll::Ready(Err(invalid_recorded_history(
14145                "selection_group_shape_mismatch",
14146                marker.selection_group_base_sequence,
14147                self.group_id
14148                    .as_deref()
14149                    .unwrap_or("initialized selection group"),
14150                &marker.selection_group_id,
14151                "recorded selection group differs from current workflow code",
14152            )));
14153        }
14154        let Some(member_position) = self.members.iter().position(|member| {
14155            member.key == marker.member_key
14156                && member.index == marker.member_index
14157                && member.base_sequence == marker.member_base_sequence
14158                && member.size == marker.member_size
14159                && member.kind == marker.operation_kind
14160        }) else {
14161            return Poll::Ready(Err(invalid_recorded_history(
14162                "selection_member_shape_mismatch",
14163                marker.member_base_sequence,
14164                "winner member matching current workflow code",
14165                &format!("{:?}", marker.member_key),
14166                "recorded selection winner differs from the authored member identity",
14167            )));
14168        };
14169        let member = self.members[member_position].clone();
14170        let (handles, resolution_sequence) = {
14171            let mut state = match self.ctx.state.lock() {
14172                Ok(state) => state,
14173                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14174            };
14175            let identities = self
14176                .members
14177                .iter()
14178                .map(|candidate| {
14179                    selection_operation_identity(
14180                        &state,
14181                        &candidate.kind,
14182                        candidate.base_sequence,
14183                        candidate.size,
14184                    )
14185                })
14186                .collect::<Vec<_>>();
14187            if let Some((position, missing)) = identities
14188                .iter()
14189                .enumerate()
14190                .find(|(_, identity)| identity.is_empty())
14191                .map(|(position, identity)| (position, identity.clone()))
14192            {
14193                let candidate = &self.members[position];
14194                return Poll::Ready(Err(invalid_recorded_history(
14195                    "selection_operation_identity_missing",
14196                    candidate.base_sequence,
14197                    &format!(
14198                        "durable {} resource identity from scheduled/open history",
14199                        candidate.kind
14200                    ),
14201                    &missing,
14202                    "selection member history is missing its canonical durable identity",
14203                )));
14204            }
14205            let expected_winner_identity = &identities[member_position];
14206            let resolution_sequence = match validated_selection_resolution_sequence(
14207                &state,
14208                &marker,
14209                &member,
14210                expected_winner_identity,
14211            ) {
14212                Ok(sequence) => sequence,
14213                Err(error) => return Poll::Ready(Err(error)),
14214            };
14215            let handles = self
14216                .members
14217                .iter()
14218                .zip(identities)
14219                .map(|(member, identity)| DurableOperationHandle {
14220                    ctx: self.ctx.clone(),
14221                    key: member.key.clone(),
14222                    index: member.index,
14223                    kind: member.kind.clone(),
14224                    identity,
14225                    base_sequence: member.base_sequence,
14226                    size: member.size,
14227                    selection_group_id: marker.selection_group_id.clone(),
14228                    shape: member.shape.clone(),
14229                })
14230                .collect::<Vec<_>>();
14231            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
14232                return Poll::Ready(Err(error));
14233            }
14234            state.selection_marker_cursor += 1;
14235            (handles, resolution_sequence)
14236        };
14237
14238        let mut winner_failure = None;
14239        let mut flat_results = Vec::with_capacity(member.size);
14240        if marker.outcome == "failed" {
14241            let resolution_offset = match resolution_sequence
14242                .checked_sub(member.base_sequence)
14243                .and_then(|offset| usize::try_from(offset).ok())
14244            {
14245                Some(offset) if offset < member.size => offset,
14246                _ => {
14247                    return Poll::Ready(Err(invalid_recorded_history(
14248                        "selection_resolution_event_mismatch",
14249                        member.base_sequence,
14250                        "failure event within selected member bounds",
14251                        &resolution_sequence.to_string(),
14252                        "selection failure event is outside the authored member",
14253                    )))
14254                }
14255            };
14256            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
14257            match leaf.outcome.take() {
14258                Some(Err(error)) => winner_failure = Some(error),
14259                _ => {
14260                    return Poll::Ready(Err(invalid_recorded_history(
14261                        "selection_winner_outcome_mismatch",
14262                        member.base_sequence,
14263                        "exact failed terminal history referenced by SelectionResolved",
14264                        "missing or successful resolution event",
14265                        "selection winner marker disagrees with terminal operation history",
14266                    )))
14267                }
14268            }
14269        } else {
14270            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
14271                match leaf.outcome.take() {
14272                    Some(Ok(result)) => flat_results.push(result),
14273                    Some(Err(_)) => {
14274                        return Poll::Ready(Err(invalid_recorded_history(
14275                            "selection_winner_outcome_mismatch",
14276                            member.base_sequence,
14277                            "fully completed nested selection member",
14278                            "failed durable leaf",
14279                            "completed selection winner contains a failed leaf",
14280                        )))
14281                    }
14282                    None => {
14283                        return Poll::Ready(Err(invalid_recorded_history(
14284                            "selection_winner_unresolved",
14285                            member.base_sequence,
14286                            "terminal history for every completed winner leaf",
14287                            "pending member history",
14288                            "completed SelectionResolved member has an unfinished durable barrier",
14289                        )))
14290                    }
14291                }
14292            }
14293        }
14294        let value = if winner_failure.is_none() {
14295            let mut flat_results = flat_results.into_iter();
14296            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
14297            match value.into_json_result() {
14298                Ok(value) => Some(value),
14299                Err(error) => return Poll::Ready(Err(error)),
14300            }
14301        } else {
14302            None
14303        };
14304        let winner = handles[member_position].clone();
14305        self.ctx
14306            .state
14307            .lock()
14308            .map_err(|_| Error::WorkflowStatePoisoned)?
14309            .advance_cancellation_selection(&marker.selection_group_id);
14310        Poll::Ready(Ok(SelectionResult {
14311            key: winner.key.clone(),
14312            index: winner.index,
14313            kind: winner.kind.clone(),
14314            identity: winner.identity.clone(),
14315            value,
14316            failure: winner_failure,
14317            winner,
14318            handles,
14319        }))
14320    }
14321}
14322
14323fn selection_operation_identity(
14324    state: &WorkflowState,
14325    kind: &str,
14326    base_sequence: u64,
14327    size: usize,
14328) -> String {
14329    if kind == "group" {
14330        return format!("group:{base_sequence}:{size}");
14331    }
14332    let fields: &[&str] = match kind {
14333        "activity" => &["activity_execution_id"],
14334        "child" => &["child_workflow_run_id"],
14335        "timer" => &["timer_id"],
14336        "signal" => &["signal_wait_id"],
14337        "condition" => &["condition_wait_id"],
14338        _ => &[],
14339    };
14340    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
14341        for event in state
14342            .history_events
14343            .iter()
14344            .filter(|event| durable_event_sequence(event) == Some(sequence))
14345        {
14346            for field in fields {
14347                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
14348                    if !identity.is_empty() {
14349                        return identity.to_string();
14350                    }
14351                }
14352            }
14353        }
14354    }
14355    String::new()
14356}
14357
14358fn validated_selection_resolution_sequence(
14359    state: &WorkflowState,
14360    marker: &SelectionMarker,
14361    member: &SelectionMemberPlan,
14362    expected_identity: &str,
14363) -> Result<u64> {
14364    if expected_identity.is_empty() {
14365        return Err(invalid_recorded_history(
14366            "selection_operation_identity_missing",
14367            member.base_sequence,
14368            &format!(
14369                "durable {} resource identity from scheduled/open history",
14370                member.kind
14371            ),
14372            "missing operation identity",
14373            "selection member history is missing its canonical durable identity",
14374        ));
14375    }
14376    if marker.operation_identity != expected_identity {
14377        return Err(invalid_recorded_history(
14378            "selection_operation_identity_mismatch",
14379            member.base_sequence,
14380            expected_identity,
14381            &marker.operation_identity,
14382            "selection winner identity does not match durable scheduled/open history",
14383        ));
14384    }
14385
14386    let failure_types = [
14387        "ActivityFailed",
14388        "ActivityCancelled",
14389        "ActivityTimedOut",
14390        "ChildRunFailed",
14391        "ChildRunCancelled",
14392        "ChildRunTerminated",
14393    ];
14394    let success_types = [
14395        "ActivityCompleted",
14396        "ChildRunCompleted",
14397        "TimerFired",
14398        "SignalApplied",
14399        "ConditionWaitSatisfied",
14400        "ConditionWaitTimedOut",
14401    ];
14402    let terminal_types: &[&str] = if marker.outcome == "failed" {
14403        &failure_types
14404    } else {
14405        &success_types
14406    };
14407    let mut candidates = Vec::new();
14408    let member_commands = (member.base_sequence
14409        ..member.base_sequence.saturating_add(member.size as u64))
14410        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
14411        .map(|command| (command.sequence(), command))
14412        .collect::<BTreeMap<_, _>>();
14413    let mut resolved_conditions = BTreeSet::new();
14414    for event in state.history_events.iter() {
14415        let Some(sequence) = durable_event_sequence(event) else {
14416            continue;
14417        };
14418        let Some(command) = member_commands.get(&sequence) else {
14419            continue;
14420        };
14421        if !terminal_types.contains(&event.event_type.as_str()) {
14422            continue;
14423        }
14424        if matches!(command, RecordedCommand::ConditionWait { .. }) {
14425            if !matches!(
14426                event.event_type.as_str(),
14427                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
14428            ) && !(event.event_type == "TimerFired"
14429                && event.payload.get("timer_kind").and_then(Value::as_str)
14430                    == Some("condition_timeout"))
14431            {
14432                continue;
14433            }
14434            if !resolved_conditions.insert(sequence) {
14435                continue;
14436            }
14437        }
14438        let event_id = event
14439            .raw
14440            .get("id")
14441            .or_else(|| event.raw.get("event_id"))
14442            .and_then(Value::as_str)
14443            .filter(|value| !value.is_empty())
14444            .ok_or_else(|| {
14445                invalid_recorded_history(
14446                    "selection_resolution_event_id_missing",
14447                    member.base_sequence,
14448                    "terminal selection history with a durable event id",
14449                    &event.payload.to_string(),
14450                    "selection terminal history cannot be bound to its winner marker",
14451                )
14452            })?;
14453        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
14454    }
14455    let resolution = if marker.outcome == "failed" {
14456        candidates.first()
14457    } else {
14458        candidates.last()
14459    };
14460    let Some((event_id, event_type, sequence)) = resolution else {
14461        return Err(invalid_recorded_history(
14462            "selection_resolution_event_missing",
14463            member.base_sequence,
14464            "terminal history for the selected member",
14465            &format!("{:?}", marker.member_key),
14466            "selection winner marker has no matching durable terminal event",
14467        ));
14468    };
14469    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
14470        return Err(invalid_recorded_history(
14471            "selection_resolution_event_mismatch",
14472            member.base_sequence,
14473            &format!("{event_type}:{event_id}"),
14474            &format!(
14475                "{}:{}",
14476                marker.resolution_event_type, marker.resolution_event_id
14477            ),
14478            "selection winner marker does not reference the event that made its member terminal",
14479        ));
14480    }
14481    Ok(*sequence)
14482}
14483
14484fn selection_member_recorded_command(
14485    state: &WorkflowState,
14486    authored_sequence: u64,
14487) -> Option<&RecordedCommand> {
14488    let original = state
14489        .recorded_commands
14490        .iter()
14491        .find(|command| command.sequence() == authored_sequence)?;
14492    let RecordedCommand::ConditionWait {
14493        occurrence_id,
14494        parallel_group_path: Some(_),
14495        ..
14496    } = original
14497    else {
14498        return Some(original);
14499    };
14500    // Decoding proves each physical reopen has the same authored identity and
14501    // group path after a satisfied predecessor. Only its latest wait can make
14502    // this logical member terminal.
14503    state
14504        .recorded_commands
14505        .iter()
14506        .filter(|command| {
14507            matches!(command, RecordedCommand::ConditionWait {
14508                occurrence_id: candidate, ..
14509            } if candidate == occurrence_id)
14510        })
14511        .max_by_key(|command| command.sequence())
14512}
14513
14514fn recorded_selection_member_outcome(
14515    state: &WorkflowState,
14516    handle: &DurableOperationHandle,
14517) -> Result<Option<ParallelResult>> {
14518    for event in state.history_events.iter() {
14519        let Some(sequence) = durable_event_sequence(event) else {
14520            continue;
14521        };
14522        if sequence < handle.base_sequence
14523            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
14524            || !matches!(
14525                event.event_type.as_str(),
14526                "ActivityFailed"
14527                    | "ActivityCancelled"
14528                    | "ActivityTimedOut"
14529                    | "ChildRunFailed"
14530                    | "ChildRunCancelled"
14531                    | "ChildRunTerminated"
14532            )
14533        {
14534            continue;
14535        }
14536        let Some(command) = state
14537            .recorded_commands
14538            .iter()
14539            .find(|command| command.sequence() == sequence)
14540        else {
14541            continue;
14542        };
14543        match command {
14544            RecordedCommand::Activity {
14545                outcome: Some(Err(failure)),
14546                ..
14547            } => return Err(Error::ActivityFailed(failure.clone())),
14548            RecordedCommand::ChildWorkflow {
14549                outcome: Some(Err(failure)),
14550                ..
14551            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
14552            _ => {}
14553        }
14554    }
14555
14556    let mut results = Vec::with_capacity(handle.size);
14557    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
14558        let Some(command) = selection_member_recorded_command(state, sequence) else {
14559            return Ok(None);
14560        };
14561        let result = match command {
14562            RecordedCommand::Activity { outcome, .. } => match outcome {
14563                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
14564                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
14565                None => return Ok(None),
14566            },
14567            RecordedCommand::Timer { fired, .. } => {
14568                if !fired {
14569                    return Ok(None);
14570                }
14571                ParallelAvroResult::Timer
14572            }
14573            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
14574                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
14575                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
14576                None => return Ok(None),
14577            },
14578            RecordedCommand::SignalWait { value, .. } => match value {
14579                Some(value) => ParallelAvroResult::Signal(value.clone()),
14580                None => return Ok(None),
14581            },
14582            RecordedCommand::ConditionWait { result, .. } => match result {
14583                Some(result) => ParallelAvroResult::Condition(*result),
14584                None => return Ok(None),
14585            },
14586            other => {
14587                return Err(command_mismatch(
14588                    other,
14589                    format!("selected {} member", handle.kind),
14590                ))
14591            }
14592        };
14593        results.push(result);
14594    }
14595    let mut results = results.into_iter();
14596    parallel_results_for_shape(&handle.shape, &mut results)
14597        .into_json_result()
14598        .map(Some)
14599}
14600
14601fn recorded_selection_member_is_terminal(
14602    state: &WorkflowState,
14603    handle: &DurableOperationHandle,
14604) -> bool {
14605    let mut completed = 0usize;
14606    let mut all_completed = true;
14607    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
14608        let Some(command) = selection_member_recorded_command(state, sequence) else {
14609            all_completed = false;
14610            continue;
14611        };
14612        let terminal = match command {
14613            RecordedCommand::Activity {
14614                outcome: Some(Err(_)),
14615                ..
14616            }
14617            | RecordedCommand::ChildWorkflow {
14618                outcome: Some(Err(_)),
14619                ..
14620            } => return true,
14621            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
14622            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
14623            RecordedCommand::Timer { fired, .. } => *fired,
14624            RecordedCommand::SignalWait { value, .. } => value.is_some(),
14625            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
14626            RecordedCommand::SearchAttributes { .. }
14627            | RecordedCommand::CancellationScope { .. }
14628            | RecordedCommand::SideEffect { .. }
14629            | RecordedCommand::VersionMarker { .. }
14630            | RecordedCommand::Memo { .. }
14631            | RecordedCommand::CancellationBoundary { .. }
14632            | RecordedCommand::CancellationGroup { .. } => false,
14633            RecordedCommand::ServiceOperation { .. } => false,
14634        };
14635        if !terminal {
14636            all_completed = false;
14637            continue;
14638        }
14639        completed += 1;
14640    }
14641    all_completed && completed == handle.size
14642}
14643
14644fn selection_cancellation_for_handle(
14645    state: &WorkflowState,
14646    handle: &DurableOperationHandle,
14647) -> Result<bool> {
14648    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
14649        recorded.selection_group_id == handle.selection_group_id
14650            && recorded.member_base_sequence == handle.base_sequence
14651    }) else {
14652        return Ok(false);
14653    };
14654    validate_selection_cancellation_marker(marker, handle)?;
14655    Ok(true)
14656}
14657
14658fn validate_selection_cancellations_for_handles(
14659    state: &WorkflowState,
14660    handles: &[DurableOperationHandle],
14661) -> Result<()> {
14662    let Some(group_id) = handles
14663        .first()
14664        .map(|handle| handle.selection_group_id.as_str())
14665    else {
14666        return Ok(());
14667    };
14668    for marker in state
14669        .cancelled_selection_members
14670        .iter()
14671        .filter(|marker| marker.selection_group_id == group_id)
14672    {
14673        let Some(handle) = handles
14674            .iter()
14675            .find(|handle| handle.base_sequence == marker.member_base_sequence)
14676        else {
14677            return Err(invalid_recorded_history(
14678                "selection_cancellation_member_mismatch",
14679                marker.member_base_sequence,
14680                "SelectionOperationCancelled matching an authored selection handle",
14681                &format!("{marker:?}"),
14682                "selection cancellation member base does not name an authored member",
14683            ));
14684        };
14685        validate_selection_cancellation_marker(marker, handle)?;
14686    }
14687    Ok(())
14688}
14689
14690fn validate_selection_cancellation_marker(
14691    marker: &SelectionCancellation,
14692    handle: &DurableOperationHandle,
14693) -> Result<()> {
14694    if marker.selection_group_id != handle.selection_group_id
14695        || marker.member_key != handle.key
14696        || marker.member_index != handle.index
14697        || marker.member_base_sequence != handle.base_sequence
14698        || marker.member_size != handle.size
14699        || marker.operation_kind != handle.kind
14700        || marker.operation_identity != handle.identity
14701    {
14702        return Err(invalid_recorded_history(
14703            "selection_cancellation_member_mismatch",
14704            handle.base_sequence,
14705            "SelectionOperationCancelled matching the authored selection handle",
14706            &format!("{marker:?}"),
14707            "selection cancellation history targets different authored member metadata",
14708        ));
14709    }
14710    Ok(())
14711}
14712
14713/// Future returned by [`DurableOperationHandle::await_result`].
14714pub struct DurableOperationAwaitCall {
14715    handle: DurableOperationHandle,
14716}
14717
14718impl Future for DurableOperationAwaitCall {
14719    type Output = Result<ParallelResult>;
14720
14721    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14722        let mut state = match self.handle.ctx.state.lock() {
14723            Ok(state) => state,
14724            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14725        };
14726        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
14727            return Poll::Ready(Err(error));
14728        }
14729        match state.prepare_selection_handle_cancellation(&self.handle) {
14730            Ok(true) => return Poll::Pending,
14731            Ok(false) => {}
14732            Err(error) => return Poll::Ready(Err(error)),
14733        }
14734        match selection_cancellation_for_handle(&state, &self.handle) {
14735            Err(error) => return Poll::Ready(Err(error)),
14736            Ok(false) => {}
14737            Ok(true) => {
14738                state.advance_cancellation_receipt(
14739                    &self.handle.selection_group_id,
14740                    self.handle.base_sequence,
14741                );
14742                return Poll::Ready(Err(Error::DurableOperationCancelled(
14743                    DurableOperationCancelled {
14744                        selection_group_id: self.handle.selection_group_id.clone(),
14745                        member_key: self.handle.key.clone(),
14746                        member_index: self.handle.index,
14747                        operation_kind: self.handle.kind.clone(),
14748                        operation_identity: self.handle.identity.clone(),
14749                    },
14750                )));
14751            }
14752        }
14753        match recorded_selection_member_outcome(&state, &self.handle) {
14754            Ok(Some(result)) => {
14755                state.advance_cancellation_handle(&self.handle, false);
14756                Poll::Ready(Ok(result))
14757            }
14758            Ok(None) => Poll::Pending,
14759            Err(error) => {
14760                if !workflow_task_integrity_error(&error) {
14761                    state.advance_cancellation_handle(&self.handle, true);
14762                }
14763                Poll::Ready(Err(error))
14764            }
14765        }
14766    }
14767}
14768
14769fn validate_selection_delivery_handle(
14770    state: &WorkflowState,
14771    handle: &DurableOperationHandle,
14772) -> Result<()> {
14773    let path = state
14774        .recorded_commands
14775        .iter()
14776        .find(|command| command.sequence() == handle.base_sequence)
14777        .and_then(|command| match command {
14778            RecordedCommand::Activity {
14779                parallel_group_path,
14780                ..
14781            }
14782            | RecordedCommand::ChildWorkflow {
14783                parallel_group_path,
14784                ..
14785            }
14786            | RecordedCommand::Timer {
14787                parallel_group_path,
14788                ..
14789            }
14790            | RecordedCommand::SignalWait {
14791                parallel_group_path,
14792                ..
14793            }
14794            | RecordedCommand::ConditionWait {
14795                parallel_group_path,
14796                ..
14797            } => parallel_group_path.as_ref(),
14798            _ => None,
14799        })
14800        .and_then(|path| path.first());
14801    let matches = path.is_some_and(|entry| {
14802        entry.parallel_group_mode.as_deref() == Some("select")
14803            && entry.parallel_group_id == handle.selection_group_id
14804            && entry.selection_member_key.as_ref() == Some(&handle.key)
14805            && entry.selection_member_index == Some(handle.index)
14806            && entry.selection_member_base_sequence == Some(handle.base_sequence)
14807            && entry.selection_member_size == Some(handle.size)
14808            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
14809    });
14810    if !matches
14811        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
14812            != handle.identity
14813    {
14814        return Err(invalid_recorded_history(
14815            "cooperative_cancellation_call_mismatch",
14816            handle.base_sequence,
14817            "selection handle matching its authored durable identity",
14818            &format!("{handle:?}"),
14819            "selection handle identity or member metadata changed before cancellation replay",
14820        ));
14821    }
14822    Ok(())
14823}
14824
14825/// Future returned by [`DurableOperationHandle::cancel`].
14826pub struct CancelDurableOperationCall {
14827    handle: DurableOperationHandle,
14828    emitted: bool,
14829}
14830
14831impl Future for CancelDurableOperationCall {
14832    type Output = Result<()>;
14833
14834    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14835        let ctx = self.handle.ctx.clone();
14836        let mut state = match ctx.state.lock() {
14837            Ok(state) => state,
14838            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14839        };
14840        match selection_cancellation_for_handle(&state, &self.handle) {
14841            Err(error) => return Poll::Ready(Err(error)),
14842            Ok(true) => {
14843                state.advance_cancellation_receipt(
14844                    &self.handle.selection_group_id,
14845                    self.handle.base_sequence,
14846                );
14847                return Poll::Ready(Ok(()));
14848            }
14849            Ok(false) => {}
14850        }
14851        if recorded_selection_member_is_terminal(&state, &self.handle) {
14852            return Poll::Ready(Ok(()));
14853        }
14854        if !self.emitted {
14855            state.commands.push(json!({
14856                "type": "cancel_selection_operation",
14857                "selection_group_id": self.handle.selection_group_id,
14858                "member_key": self.handle.key,
14859                "member_index": self.handle.index,
14860                "member_base_sequence": self.handle.base_sequence,
14861                "member_size": self.handle.size,
14862                "operation_kind": self.handle.kind,
14863                "operation_identity": self.handle.identity,
14864            }));
14865            self.emitted = true;
14866        }
14867        // Unit completes the request, not the member's outcome. Following
14868        // workflow commands commit atomically with this cancellation request.
14869        // Waiting here would need another workflow task that cancellation
14870        // alone does not create. await_result still requires recorded history.
14871        Poll::Ready(Ok(()))
14872    }
14873}
14874
14875trait PollNestedResultExt<T> {
14876    fn flatten_result(self) -> Poll<Result<T>>;
14877}
14878
14879impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
14880    fn flatten_result(self) -> Poll<Result<T>> {
14881        match self {
14882            Poll::Ready(Ok(result)) => Poll::Ready(result),
14883            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14884            Poll::Pending => Poll::Pending,
14885        }
14886    }
14887}
14888
14889struct SagaCompensation {
14890    activity_type: String,
14891    options: ActivityOptions,
14892    arguments: AvroValue,
14893    registration_order: usize,
14894}
14895
14896/// Workflow-local deterministic saga compensation helper.
14897///
14898/// Register each compensation only after its forward step succeeds. Passing
14899/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
14900/// reverse registration order after any failure, including cooperative
14901/// cancellation. Each compensation is an ordinary durable activity, so replay,
14902/// duplicate delivery, and worker restart use existing history semantics.
14903pub struct Saga {
14904    ctx: WorkflowContext,
14905    compensations: Vec<SagaCompensation>,
14906}
14907
14908impl Saga {
14909    fn new(ctx: WorkflowContext) -> Self {
14910        Self {
14911            ctx,
14912            compensations: Vec::new(),
14913        }
14914    }
14915
14916    pub fn add_compensation<T: Serialize>(
14917        &mut self,
14918        activity_type: impl Into<String>,
14919        args: T,
14920    ) -> Result<&mut Self> {
14921        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
14922    }
14923
14924    pub fn add_compensation_with_options<T: Serialize>(
14925        &mut self,
14926        activity_type: impl Into<String>,
14927        options: ActivityOptions,
14928        args: T,
14929    ) -> Result<&mut Self> {
14930        let activity_type = activity_type.into();
14931        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
14932            return Err(Error::Codec(
14933                "saga compensation activity type must be non-empty without surrounding whitespace"
14934                    .to_string(),
14935            ));
14936        }
14937        options.validate().map_err(Error::InvalidActivityOptions)?;
14938        let arguments = AvroValue::from_serialize(&args)?;
14939        let registration_order = self.compensations.len() + 1;
14940        self.compensations.push(SagaCompensation {
14941            activity_type,
14942            options,
14943            arguments,
14944            registration_order,
14945        });
14946        Ok(self)
14947    }
14948
14949    /// Compensate `initiating_failure` and return the failure that must remain.
14950    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
14951        let _shield = match self.ctx.cancellation_shield() {
14952            Ok(shield) => shield,
14953            Err(error) => return error,
14954        };
14955        while let Some(compensation) = self.compensations.pop() {
14956            if let Err(compensation_failure) = self
14957                .ctx
14958                .activity_with_options(
14959                    compensation.activity_type.clone(),
14960                    compensation.options,
14961                    compensation.arguments,
14962                )
14963                .await
14964            {
14965                if workflow_task_integrity_error(&compensation_failure) {
14966                    return compensation_failure;
14967                }
14968                return Error::SagaCompensationFailed(SagaCompensationFailure {
14969                    initiating_failure: Box::new(initiating_failure),
14970                    compensation_failure: Box::new(compensation_failure),
14971                    compensation_activity_type: compensation.activity_type,
14972                    compensation_registration_order: compensation.registration_order,
14973                });
14974            }
14975        }
14976        initiating_failure
14977    }
14978
14979    /// Return a successful forward value or compensate and preserve its failure.
14980    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
14981        match outcome {
14982            Ok(value) => Ok(value),
14983            Err(error) => Err(self.compensate(error).await),
14984        }
14985    }
14986}
14987
14988pub struct ActivityCall {
14989    ctx: WorkflowContext,
14990    activity_type: String,
14991    options: ActivityOptions,
14992    worker_session: Option<WorkerSessionOptions>,
14993    args: Option<Result<AvroValue>>,
14994    scheduled: bool,
14995    local: bool,
14996    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
14997    parallel_group_path: Vec<ParallelGroupMetadata>,
14998}
14999
15000impl ActivityCall {
15001    fn poll_avro_value(
15002        mut self: Pin<&mut Self>,
15003        _cx: &mut TaskContext<'_>,
15004    ) -> Poll<Result<AvroValue>> {
15005        let ctx = self.ctx.clone();
15006        let mut state = match ctx.state.lock() {
15007            Ok(state) => state,
15008            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15009        };
15010
15011        if let Some(result) = &self.local_result {
15012            return match result.lock() {
15013                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
15014                    Poll::Ready(result.map_err(Error::ActivityFailed))
15015                }),
15016                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15017            };
15018        }
15019        if self.scheduled {
15020            return Poll::Pending;
15021        }
15022
15023        let options = match self.options.validate() {
15024            Ok(options) => options,
15025            Err(error) => {
15026                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
15027            }
15028        };
15029        if self.local {
15030            if self.worker_session.is_some() {
15031                return Poll::Ready(Err(Error::WorkerLoop(
15032                    "local activities cannot use worker-session routing".into(),
15033                )));
15034            }
15035            if let Err(error) = local_activity::validate(&options) {
15036                return Poll::Ready(Err(error));
15037            }
15038        }
15039        let session = match self
15040            .worker_session
15041            .as_ref()
15042            .map(WorkerSessionOptions::to_wire)
15043            .transpose()
15044        {
15045            Ok(value) => value,
15046            Err(error) => return Poll::Ready(Err(error)),
15047        };
15048        let session_queue = session
15049            .as_ref()
15050            .and_then(|session| session["queue"].as_str());
15051        let task_queue = options
15052            .task_queue
15053            .clone()
15054            .or_else(|| session_queue.map(str::to_owned))
15055            .unwrap_or_else(|| state.task_queue.clone());
15056        if session_queue.is_some_and(|queue| queue != task_queue) {
15057            return Poll::Ready(Err(Error::WorkerLoop(
15058                "worker-session queue must match the activity task queue".into(),
15059            )));
15060        }
15061        let current_recorded_options = RecordedActivityOptions {
15062            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
15063            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
15064            retry_policy: current_activity_retry_snapshot(&options),
15065            worker_session: session,
15066        };
15067
15068        let cursor = state.command_cursor;
15069        let call_kind = if self.local {
15070            CancellationCallKind::LocalActivity
15071        } else {
15072            CancellationCallKind::Activity
15073        };
15074        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15075            return Poll::Ready(Err(error));
15076        }
15077        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
15078            Ok(recorded) => recorded,
15079            Err(error) => return Poll::Ready(Err(error)),
15080        };
15081        if let Some(recorded) = recorded {
15082            let sequence = recorded.sequence();
15083            match recorded {
15084                RecordedCommand::Activity {
15085                    activity_type,
15086                    cancellation_policy,
15087                    options: recorded_options,
15088                    outcome,
15089                    parallel_group_path,
15090                    ..
15091                } => {
15092                    let current_policy = options
15093                        .cancellation_policy
15094                        .unwrap_or(CancellationPolicy::TryCancel)
15095                        .as_str();
15096                    if cancellation_policy != current_policy {
15097                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15098                            ReplayFailure::new(
15099                                "activity_cancellation_policy_changed",
15100                                Some(sequence),
15101                                Some(cancellation_policy),
15102                                Some(current_policy.to_string()),
15103                                "Activity cancellation policy changed during replay",
15104                            ),
15105                        )));
15106                    }
15107                    if let Err(error) = ensure_parallel_path_matches(
15108                        sequence,
15109                        parallel_group_path.as_deref(),
15110                        &self.parallel_group_path,
15111                    ) {
15112                        return Poll::Ready(Err(error));
15113                    }
15114                    if let Some(recorded_type) = activity_type {
15115                        if recorded_type != self.activity_type {
15116                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15117                                ReplayFailure::new(
15118                                    "recorded_command_detail_mismatch",
15119                                    Some(sequence),
15120                                    Some(format!("activity:{recorded_type}")),
15121                                    Some(format!("activity:{}", self.activity_type)),
15122                                    "recorded activity type differs from the current workflow command",
15123                                ),
15124                            )));
15125                        }
15126                    }
15127                    if let Some(recorded_options) = recorded_options {
15128                        if recorded_options.worker_session
15129                            != current_recorded_options.worker_session
15130                        {
15131                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15132                                "activity_worker_session_mismatch", Some(sequence),
15133                                Some(activity_options_description(&recorded_options)),
15134                                Some(activity_options_description(&current_recorded_options)),
15135                                "recorded worker-session routing differs from the current activity",
15136                            ))));
15137                        }
15138                        if !recorded_options
15139                            .task_queue
15140                            .matches_current(&current_recorded_options.task_queue)
15141                        {
15142                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15143                                ReplayFailure::new(
15144                                    "activity_task_queue_mismatch",
15145                                    Some(sequence),
15146                                    Some(activity_options_description(&recorded_options)),
15147                                    Some(activity_options_description(&current_recorded_options)),
15148                                    "recorded activity task queue differs from the current workflow command",
15149                                ),
15150                            )));
15151                        }
15152                        if (self.local
15153                            && matches!(
15154                                recorded_options.execution_mode,
15155                                RecordedSnapshotValue::Unknown
15156                            ))
15157                            || !recorded_options
15158                                .execution_mode
15159                                .matches_current(&current_recorded_options.execution_mode)
15160                        {
15161                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15162                                ReplayFailure::new(
15163                                    "activity_execution_mode_mismatch",
15164                                    Some(sequence),
15165                                    Some(activity_options_description(&recorded_options)),
15166                                    Some(activity_options_description(&current_recorded_options)),
15167                                    "recorded activity execution mode differs from the current workflow command",
15168                                ),
15169                            )));
15170                        }
15171                        if !recorded_options
15172                            .retry_policy
15173                            .matches_current(&current_recorded_options.retry_policy)
15174                        {
15175                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15176                                ReplayFailure::new(
15177                                    "activity_retry_policy_mismatch",
15178                                    Some(sequence),
15179                                    Some(activity_options_description(&recorded_options)),
15180                                    Some(activity_options_description(&current_recorded_options)),
15181                                    "recorded activity retry policy differs from the current workflow command",
15182                                ),
15183                            )));
15184                        }
15185                    }
15186                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
15187                        return Poll::Ready(Err(error));
15188                    }
15189                    match state.prepare_scalar_cancellation(
15190                        cursor,
15191                        call_kind,
15192                        &self.parallel_group_path,
15193                    ) {
15194                        Ok(true) => {
15195                            self.scheduled = true;
15196                            return Poll::Pending;
15197                        }
15198                        Ok(false) => {}
15199                        Err(error) => return Poll::Ready(Err(error)),
15200                    }
15201                    state.command_cursor += 1;
15202                    if let Some(outcome) = outcome {
15203                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15204                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
15205                    }
15206                    state.matched_recorded_pending = true;
15207                    self.scheduled = true;
15208                    return Poll::Pending;
15209                }
15210                other => {
15211                    return Poll::Ready(Err(command_mismatch(
15212                        &other,
15213                        format!("activity:{}", self.activity_type),
15214                    )));
15215                }
15216            }
15217        }
15218
15219        if !self.scheduled {
15220            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15221                Ok(args) => args,
15222                Err(error) => return Poll::Ready(Err(error)),
15223            };
15224            let arguments = normalize_avro_arguments(args);
15225            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
15226                Ok(envelope) => envelope,
15227                Err(error) => return Poll::Ready(Err(error)),
15228            };
15229
15230            let mut command = serde_json::Map::from_iter([
15231                (
15232                    "type".to_string(),
15233                    json!(if self.local {
15234                        "record_local_activity"
15235                    } else {
15236                        "schedule_activity"
15237                    }),
15238                ),
15239                (
15240                    "activity_type".to_string(),
15241                    json!(self.activity_type.clone()),
15242                ),
15243                ("queue".to_string(), json!(task_queue)),
15244                ("arguments".to_string(), envelope),
15245            ]);
15246            for (field, value) in [
15247                ("start_to_close_timeout", options.start_to_close_timeout),
15248                (
15249                    "schedule_to_start_timeout",
15250                    options.schedule_to_start_timeout,
15251                ),
15252                (
15253                    "schedule_to_close_timeout",
15254                    options.schedule_to_close_timeout,
15255                ),
15256                ("heartbeat_timeout", options.heartbeat_timeout),
15257            ] {
15258                if let Some(value) = value {
15259                    command.insert(field.to_string(), json!(value));
15260                }
15261            }
15262            if let Some(retry_policy) = &options.retry_policy {
15263                command.insert("retry_policy".to_string(), retry_policy.clone());
15264            }
15265            if let Some(policy) = options.cancellation_policy {
15266                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
15267            }
15268            if let Some(session) = current_recorded_options.worker_session {
15269                command.insert("worker_session".into(), session);
15270            }
15271            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15272            ctx.apply_scope_membership(&mut command);
15273            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
15274                Ok(true) => {
15275                    self.scheduled = true;
15276                    return Poll::Pending;
15277                }
15278                Ok(false) => {}
15279                Err(error) => return Poll::Ready(Err(error)),
15280            }
15281            if self.local {
15282                command.remove("queue");
15283                command.insert("execution_mode".into(), json!("local"));
15284                let result = Arc::new(Mutex::new(None));
15285                let command_index = state.commands.len();
15286                state.local_activity_requests.push(local_activity::Request {
15287                    command_index,
15288                    options,
15289                    arguments,
15290                    result: result.clone(),
15291                });
15292                self.local_result = Some(result);
15293            }
15294            state.commands.push(Value::Object(command));
15295            self.scheduled = true;
15296        }
15297
15298        Poll::Pending
15299    }
15300}
15301
15302impl Future for ActivityCall {
15303    type Output = Result<Value>;
15304
15305    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15306        match self.poll_avro_value(cx) {
15307            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
15308            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15309            Poll::Pending => Poll::Pending,
15310        }
15311    }
15312}
15313
15314/// Future returned by [`WorkflowContext::sleep`].
15315pub struct TimerCall {
15316    ctx: WorkflowContext,
15317    delay_seconds: Option<u64>,
15318    scheduled: bool,
15319    matched_pending: bool,
15320    parallel_group_path: Vec<ParallelGroupMetadata>,
15321}
15322
15323impl Future for TimerCall {
15324    type Output = Result<()>;
15325
15326    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15327        if self.matched_pending {
15328            return Poll::Pending;
15329        }
15330
15331        let ctx = self.ctx.clone();
15332        let Some(requested_delay) = self.delay_seconds else {
15333            return Poll::Ready(Err(Error::TimerDurationOverflow));
15334        };
15335        let mut state = match ctx.state.lock() {
15336            Ok(state) => state,
15337            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15338        };
15339
15340        let cursor = state.command_cursor;
15341        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15342            return Poll::Ready(Err(error));
15343        }
15344        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
15345        {
15346            Ok(recorded) => recorded,
15347            Err(error) => return Poll::Ready(Err(error)),
15348        };
15349        if let Some(recorded) = recorded {
15350            match recorded {
15351                RecordedCommand::Timer {
15352                    sequence,
15353                    delay_seconds,
15354                    fired,
15355                    parallel_group_path,
15356                    ..
15357                } => {
15358                    if let Err(error) =
15359                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
15360                    {
15361                        return Poll::Ready(Err(error));
15362                    }
15363                    if let Err(error) = ensure_parallel_path_matches(
15364                        sequence,
15365                        parallel_group_path.as_deref(),
15366                        &self.parallel_group_path,
15367                    ) {
15368                        return Poll::Ready(Err(error));
15369                    }
15370                    if delay_seconds != requested_delay {
15371                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15372                            ReplayFailure::new(
15373                                "timer_delay_mismatch",
15374                                Some(sequence),
15375                                Some(format!("timer:{delay_seconds}s")),
15376                                Some(format!("timer:{requested_delay}s")),
15377                                "recorded timer delay differs from the current workflow command",
15378                            ),
15379                        )));
15380                    }
15381                    if let Err(error) =
15382                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
15383                    {
15384                        return Poll::Ready(Err(error));
15385                    }
15386                    match state.prepare_scalar_cancellation(
15387                        cursor,
15388                        CancellationCallKind::Timer,
15389                        &self.parallel_group_path,
15390                    ) {
15391                        Ok(true) => {
15392                            self.scheduled = true;
15393                            self.matched_pending = true;
15394                            return Poll::Pending;
15395                        }
15396                        Ok(false) => {}
15397                        Err(error) => return Poll::Ready(Err(error)),
15398                    }
15399                    state.command_cursor += 1;
15400                    if fired {
15401                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15402                        return Poll::Ready(Ok(()));
15403                    }
15404                    state.matched_recorded_pending = true;
15405                    self.scheduled = true;
15406                    self.matched_pending = true;
15407                    return Poll::Pending;
15408                }
15409                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
15410            }
15411        }
15412
15413        if !self.scheduled {
15414            let mut command = serde_json::Map::from_iter([
15415                ("type".to_string(), json!("start_timer")),
15416                ("delay_seconds".to_string(), json!(requested_delay)),
15417            ]);
15418            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
15419                Ok(Some(proof)) => {
15420                    command.insert("cancellation_cleanup".into(), proof);
15421                }
15422                Ok(None) => {}
15423                Err(error) => return Poll::Ready(Err(error)),
15424            }
15425            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15426            ctx.apply_scope_membership(&mut command);
15427            match state.prepare_scalar_cancellation(
15428                cursor,
15429                CancellationCallKind::Timer,
15430                &self.parallel_group_path,
15431            ) {
15432                Ok(true) => {
15433                    self.scheduled = true;
15434                    self.matched_pending = true;
15435                    return Poll::Pending;
15436                }
15437                Ok(false) => {}
15438                Err(error) => return Poll::Ready(Err(error)),
15439            }
15440            state.commands.push(Value::Object(command));
15441            self.scheduled = true;
15442        }
15443
15444        Poll::Pending
15445    }
15446}
15447
15448/// Future returned by [`WorkflowContext::wait_condition`].
15449pub struct ConditionWaitCall {
15450    ctx: WorkflowContext,
15451    options: ConditionWaitOptions,
15452    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
15453    occurrence_id: Option<String>,
15454    opened_wait: bool,
15455    parallel_group_path: Vec<ParallelGroupMetadata>,
15456}
15457
15458impl Future for ConditionWaitCall {
15459    type Output = Result<ConditionWaitResult>;
15460
15461    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15462        if self.opened_wait {
15463            return Poll::Pending;
15464        }
15465
15466        let options = match self.options.validate() {
15467            Ok(options) => options,
15468            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
15469        };
15470        let ctx = self.ctx.clone();
15471        let occurrence_id = match self.occurrence_id.as_ref() {
15472            Some(occurrence_id) => occurrence_id.clone(),
15473            None => {
15474                let mut state = match ctx.state.lock() {
15475                    Ok(state) => state,
15476                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15477                };
15478                let ordinal = state.condition_wait_occurrence_counter;
15479                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
15480                    Some(next) => next,
15481                    None => {
15482                        return Poll::Ready(Err(Error::WorkerLoop(
15483                            "condition wait occurrence counter overflowed".to_string(),
15484                        )))
15485                    }
15486                };
15487                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
15488                drop(state);
15489                self.occurrence_id = Some(occurrence_id.clone());
15490                occurrence_id
15491            }
15492        };
15493
15494        let recorded_result = {
15495            let mut state = match ctx.state.lock() {
15496                Ok(state) => state,
15497                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15498            };
15499            let initial_cursor = state.command_cursor;
15500            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
15501                return Poll::Ready(Err(error));
15502            }
15503            let recorded = match state
15504                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
15505            {
15506                Ok(recorded) => recorded,
15507                Err(error) => return Poll::Ready(Err(error)),
15508            };
15509            let Some(recorded) = recorded else {
15510                drop(state);
15511                return self.poll_new_condition(options);
15512            };
15513            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
15514                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
15515            }
15516
15517            let mut cursor = state.command_cursor;
15518            let mut result = None;
15519            let mut pending_delivery = false;
15520            loop {
15521                if cursor > initial_cursor
15522                    && matches!(
15523                        state.recorded_commands.get(cursor),
15524                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
15525                    )
15526                {
15527                    break;
15528                }
15529                let recorded = match state
15530                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
15531                {
15532                    Ok(recorded) => recorded,
15533                    Err(error) => return Poll::Ready(Err(error)),
15534                };
15535                let Some(RecordedCommand::ConditionWait {
15536                    sequence,
15537                    occurrence_id: ref recorded_occurrence_id,
15538                    ref condition_key,
15539                    ref predicate_identity,
15540                    timeout_seconds,
15541                    result: recorded_result,
15542                    ref parallel_group_path,
15543                    ..
15544                }) = recorded
15545                else {
15546                    break;
15547                };
15548
15549                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
15550                    break;
15551                }
15552                if let Err(error) = ensure_parallel_path_matches(
15553                    sequence,
15554                    parallel_group_path.as_deref(),
15555                    &self.parallel_group_path,
15556                ) {
15557                    return Poll::Ready(Err(error));
15558                }
15559                if let Err(error) = validate_recorded_condition_wait(
15560                    sequence,
15561                    recorded_occurrence_id,
15562                    condition_key.as_deref(),
15563                    predicate_identity,
15564                    timeout_seconds,
15565                    &occurrence_id,
15566                    &options,
15567                ) {
15568                    return Poll::Ready(Err(error));
15569                }
15570                if result == Some(ConditionWaitResult::TimedOut) {
15571                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15572                        "condition_wait_reopened_after_timeout",
15573                        Some(sequence),
15574                        Some("timed-out condition is terminal".to_string()),
15575                        Some("another physical wait-open".to_string()),
15576                        "condition history reopened one logical wait after its durable timeout",
15577                    ))));
15578                }
15579                if let Err(error) =
15580                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
15581                {
15582                    return Poll::Ready(Err(error));
15583                }
15584                match state.prepare_scalar_cancellation(
15585                    cursor,
15586                    CancellationCallKind::Condition,
15587                    &self.parallel_group_path,
15588                ) {
15589                    Ok(pending) => pending_delivery |= pending,
15590                    Err(error) => return Poll::Ready(Err(error)),
15591                }
15592                result = recorded_result;
15593                if result.is_some() {
15594                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15595                }
15596                cursor += 1;
15597            }
15598            state.command_cursor = cursor;
15599            if pending_delivery {
15600                self.opened_wait = true;
15601                return Poll::Pending;
15602            }
15603            result
15604        };
15605
15606        if let Some(result) = recorded_result {
15607            return Poll::Ready(Ok(result));
15608        }
15609
15610        self.poll_open_condition(options, true)
15611    }
15612}
15613
15614impl ConditionWaitCall {
15615    fn poll_new_condition(
15616        self: Pin<&mut Self>,
15617        options: ValidatedConditionWaitOptions,
15618    ) -> Poll<Result<ConditionWaitResult>> {
15619        self.poll_open_condition(options, false)
15620    }
15621
15622    fn poll_open_condition(
15623        mut self: Pin<&mut Self>,
15624        options: ValidatedConditionWaitOptions,
15625        recorded_wait: bool,
15626    ) -> Poll<Result<ConditionWaitResult>> {
15627        {
15628            let ctx = self.ctx.clone();
15629            let mut state = match ctx.state.lock() {
15630                Ok(state) => state,
15631                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15632            };
15633            let cursor = state.command_cursor;
15634            match state.prepare_scalar_cancellation(
15635                cursor,
15636                CancellationCallKind::Condition,
15637                &self.parallel_group_path,
15638            ) {
15639                Ok(true) => {
15640                    self.opened_wait = true;
15641                    return Poll::Pending;
15642                }
15643                Ok(false) => {}
15644                Err(error) => return Poll::Ready(Err(error)),
15645            }
15646        }
15647        let selection_member = self
15648            .parallel_group_path
15649            .first()
15650            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
15651        match (self.predicate)() {
15652            Ok(true) if !selection_member || recorded_wait => {
15653                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
15654            }
15655            Ok(_) => {}
15656            Err(error) => return Poll::Ready(Err(error)),
15657        }
15658        if options.timeout_seconds == Some(0) && !selection_member {
15659            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
15660        }
15661
15662        let ctx = self.ctx.clone();
15663        let mut state = match ctx.state.lock() {
15664            Ok(state) => state,
15665            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15666        };
15667        let mut command = serde_json::Map::from_iter([
15668            ("type".to_string(), json!("open_condition_wait")),
15669            (
15670                "condition_wait_occurrence_id".to_string(),
15671                json!(self.occurrence_id.as_deref().unwrap_or_default()),
15672            ),
15673            ("condition_key".to_string(), json!(options.condition_key)),
15674            (
15675                "condition_definition_fingerprint".to_string(),
15676                json!(options.predicate_identity),
15677            ),
15678        ]);
15679        if let Some(timeout_seconds) = options.timeout_seconds {
15680            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
15681        }
15682        apply_parallel_group_path(&mut command, &self.parallel_group_path);
15683        ctx.apply_scope_membership(&mut command);
15684        state.commands.push(Value::Object(command));
15685        drop(state);
15686        self.opened_wait = true;
15687        Poll::Pending
15688    }
15689}
15690
15691fn validate_recorded_condition_wait(
15692    sequence: u64,
15693    recorded_occurrence_id: &str,
15694    recorded_key: Option<&str>,
15695    recorded_predicate_identity: &str,
15696    recorded_timeout_seconds: Option<u64>,
15697    current_occurrence_id: &str,
15698    current: &ValidatedConditionWaitOptions,
15699) -> Result<()> {
15700    if recorded_occurrence_id != current_occurrence_id {
15701        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15702            "condition_wait_occurrence_mismatch",
15703            Some(sequence),
15704            Some(recorded_occurrence_id.to_string()),
15705            Some(current_occurrence_id.to_string()),
15706            "recorded condition occurrence differs from the current authored wait position",
15707        )));
15708    }
15709    if recorded_key != Some(current.condition_key.as_str()) {
15710        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15711            "condition_wait_key_mismatch",
15712            Some(sequence),
15713            recorded_key.map(str::to_string),
15714            Some(current.condition_key.clone()),
15715            "recorded condition identity differs from the current workflow wait",
15716        )));
15717    }
15718    if recorded_predicate_identity != current.predicate_identity {
15719        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15720            "condition_wait_predicate_mismatch",
15721            Some(sequence),
15722            Some(recorded_predicate_identity.to_string()),
15723            Some(current.predicate_identity.clone()),
15724            "recorded condition predicate behavior differs from current workflow code",
15725        )));
15726    }
15727    if recorded_timeout_seconds != current.timeout_seconds {
15728        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15729            "condition_wait_timeout_mismatch",
15730            Some(sequence),
15731            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
15732            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
15733            "recorded condition timeout differs from the current workflow wait",
15734        )));
15735    }
15736    Ok(())
15737}
15738
15739/// Future returned by [`WorkflowContext::start_child_workflow`].
15740pub struct ChildWorkflowCall {
15741    ctx: WorkflowContext,
15742    workflow_type: String,
15743    options: ChildWorkflowOptions,
15744    args: Option<Result<AvroValue>>,
15745    scheduled: bool,
15746    matched_pending: bool,
15747    parallel_group_path: Vec<ParallelGroupMetadata>,
15748}
15749
15750impl ChildWorkflowCall {
15751    fn poll_avro_value(
15752        mut self: Pin<&mut Self>,
15753        _cx: &mut TaskContext<'_>,
15754    ) -> Poll<Result<ChildWorkflowAvroResult>> {
15755        if self.matched_pending {
15756            return Poll::Pending;
15757        }
15758
15759        let ctx = self.ctx.clone();
15760        let mut state = match ctx.state.lock() {
15761            Ok(state) => state,
15762            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15763        };
15764
15765        let cursor = state.command_cursor;
15766        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15767            return Poll::Ready(Err(error));
15768        }
15769        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
15770        {
15771            Ok(recorded) => recorded,
15772            Err(error) => return Poll::Ready(Err(error)),
15773        };
15774        if let Some(recorded) = recorded {
15775            let sequence = recorded.sequence();
15776            match recorded {
15777                RecordedCommand::ChildWorkflow {
15778                    workflow_type,
15779                    policies,
15780                    outcome,
15781                    parallel_group_path,
15782                    ..
15783                } => {
15784                    if let Err(error) = ensure_parallel_path_matches(
15785                        sequence,
15786                        parallel_group_path.as_deref(),
15787                        &self.parallel_group_path,
15788                    ) {
15789                        return Poll::Ready(Err(error));
15790                    }
15791                    if let Some(recorded_type) = workflow_type {
15792                        if recorded_type != self.workflow_type {
15793                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15794                                ReplayFailure::new(
15795                                    "recorded_command_detail_mismatch",
15796                                    Some(sequence),
15797                                    Some(format!("child workflow:{recorded_type}")),
15798                                    Some(format!("child workflow:{}", self.workflow_type)),
15799                                    "recorded child workflow type differs from the current workflow command",
15800                                ),
15801                            )));
15802                        }
15803                    }
15804                    if let Err(error) =
15805                        ensure_child_policies_match(sequence, &policies, &self.options)
15806                    {
15807                        return Poll::Ready(Err(error));
15808                    }
15809                    if let Err(error) =
15810                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
15811                    {
15812                        return Poll::Ready(Err(error));
15813                    }
15814                    match state.prepare_scalar_cancellation(
15815                        cursor,
15816                        CancellationCallKind::Child,
15817                        &self.parallel_group_path,
15818                    ) {
15819                        Ok(true) => {
15820                            self.scheduled = true;
15821                            self.matched_pending = true;
15822                            return Poll::Pending;
15823                        }
15824                        Ok(false) => {}
15825                        Err(error) => return Poll::Ready(Err(error)),
15826                    }
15827                    state.command_cursor += 1;
15828                    if let Some(outcome) = outcome {
15829                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15830                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
15831                    }
15832                    state.matched_recorded_pending = true;
15833                    self.scheduled = true;
15834                    self.matched_pending = true;
15835                    return Poll::Pending;
15836                }
15837                other => {
15838                    return Poll::Ready(Err(command_mismatch(
15839                        &other,
15840                        format!("child workflow:{}", self.workflow_type),
15841                    )));
15842                }
15843            }
15844        }
15845
15846        if !self.scheduled {
15847            if self.options.task_queue.trim().is_empty() {
15848                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15849                    "task_queue must not be empty".to_string(),
15850                )));
15851            }
15852            for (name, value) in [
15853                (
15854                    "execution_timeout_seconds",
15855                    self.options.execution_timeout_seconds,
15856                ),
15857                ("run_timeout_seconds", self.options.run_timeout_seconds),
15858            ] {
15859                if value == Some(0) {
15860                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
15861                        "{name} must be at least 1"
15862                    ))));
15863                }
15864            }
15865
15866            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15867                Ok(args) => args,
15868                Err(error) => return Poll::Ready(Err(error)),
15869            };
15870            let arguments = match encode_typed_envelope(
15871                &normalize_avro_arguments(args),
15872                &state.payload_codec,
15873            ) {
15874                Ok(arguments) => arguments,
15875                Err(error) => return Poll::Ready(Err(error)),
15876            };
15877            let mut command = json!({
15878                "type": "start_child_workflow",
15879                "workflow_type": self.workflow_type,
15880                "queue": self.options.task_queue,
15881                "parent_close_policy": self.options.parent_close_policy.as_str(),
15882                "arguments": arguments,
15883            });
15884            let object = command
15885                .as_object_mut()
15886                .expect("child workflow command is always an object");
15887            if self.options.cancellation_policy != CancellationPolicy::Abandon {
15888                object.insert(
15889                    "cancellation_policy".to_string(),
15890                    json!(self.options.cancellation_policy.as_str()),
15891                );
15892            }
15893            if let Some(policy) = &self.options.retry_policy {
15894                let mut retry_policy = serde_json::Map::new();
15895                if let Some(max_attempts) = policy.max_attempts {
15896                    if max_attempts == 0 {
15897                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15898                            "retry_policy.max_attempts must be at least 1".to_string(),
15899                        )));
15900                    }
15901                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
15902                }
15903                if !policy.backoff_seconds.is_empty() {
15904                    retry_policy
15905                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
15906                }
15907                if !policy.non_retryable_error_types.is_empty() {
15908                    retry_policy.insert(
15909                        "non_retryable_error_types".to_string(),
15910                        json!(policy.non_retryable_error_types),
15911                    );
15912                }
15913                if retry_policy.is_empty() {
15914                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15915                        "retry_policy must configure at least one field".to_string(),
15916                    )));
15917                }
15918                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
15919            }
15920            if let Some(seconds) = self.options.execution_timeout_seconds {
15921                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
15922            }
15923            if let Some(seconds) = self.options.run_timeout_seconds {
15924                object.insert("run_timeout_seconds".to_string(), json!(seconds));
15925            }
15926            apply_parallel_group_path(object, &self.parallel_group_path);
15927            ctx.apply_scope_membership(object);
15928            match state.prepare_scalar_cancellation(
15929                cursor,
15930                CancellationCallKind::Child,
15931                &self.parallel_group_path,
15932            ) {
15933                Ok(true) => {
15934                    self.scheduled = true;
15935                    self.matched_pending = true;
15936                    return Poll::Pending;
15937                }
15938                Ok(false) => {}
15939                Err(error) => return Poll::Ready(Err(error)),
15940            }
15941            state.commands.push(command);
15942            self.scheduled = true;
15943        }
15944
15945        Poll::Pending
15946    }
15947}
15948
15949impl Future for ChildWorkflowCall {
15950    type Output = Result<ChildWorkflowResult>;
15951
15952    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15953        match self.poll_avro_value(cx) {
15954            Poll::Ready(Ok(result)) => match result.result.into_json() {
15955                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
15956                    parent: result.parent,
15957                    child: result.child,
15958                    child_workflow_type: result.child_workflow_type,
15959                    result: projected,
15960                })),
15961                Err(error) => Poll::Ready(Err(error)),
15962            },
15963            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15964            Poll::Pending => Poll::Pending,
15965        }
15966    }
15967}
15968
15969fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
15970    Error::NonDeterministicReplay(ReplayFailure::new(
15971        "recorded_command_mismatch",
15972        Some(recorded.sequence()),
15973        Some(recorded.shape().to_string()),
15974        Some(actual.into()),
15975        "current workflow command does not match the recorded durable command sequence",
15976    ))
15977}
15978
15979pub struct SignalCall {
15980    ctx: WorkflowContext,
15981    signal_name: String,
15982    runtime_reserved_allowed: bool,
15983    opened_wait: bool,
15984    matched_pending: bool,
15985    parallel_group_path: Vec<ParallelGroupMetadata>,
15986}
15987
15988impl SignalCall {
15989    fn poll_avro_value(
15990        mut self: Pin<&mut Self>,
15991        _cx: &mut TaskContext<'_>,
15992    ) -> Poll<Result<Vec<AvroValue>>> {
15993        if self.matched_pending {
15994            return Poll::Pending;
15995        }
15996        if !self.runtime_reserved_allowed {
15997            if let Err(error) = validate_user_signal_name(&self.signal_name) {
15998                return Poll::Ready(Err(error));
15999            }
16000        }
16001
16002        let ctx = self.ctx.clone();
16003        let mut state = match ctx.state.lock() {
16004            Ok(state) => state,
16005            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16006        };
16007
16008        let cursor = state.command_cursor;
16009        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
16010            return Poll::Ready(Err(error));
16011        }
16012        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
16013        {
16014            Ok(recorded) => recorded,
16015            Err(error) => return Poll::Ready(Err(error)),
16016        };
16017        if let Some(recorded) = recorded {
16018            match recorded {
16019                RecordedCommand::SignalWait {
16020                    sequence,
16021                    signal_name,
16022                    value,
16023                    parallel_group_path,
16024                } => {
16025                    if let Err(error) = ensure_parallel_path_matches(
16026                        sequence,
16027                        parallel_group_path.as_deref(),
16028                        &self.parallel_group_path,
16029                    ) {
16030                        return Poll::Ready(Err(error));
16031                    }
16032                    if signal_name != self.signal_name {
16033                        return Poll::Ready(Err(Error::NonDeterministicReplay(
16034                            ReplayFailure::new(
16035                                "recorded_command_detail_mismatch",
16036                                Some(sequence),
16037                                Some(format!("signal wait:{signal_name}")),
16038                                Some(format!("signal wait:{}", self.signal_name)),
16039                                "recorded signal name differs from the current workflow command",
16040                            ),
16041                        )));
16042                    }
16043
16044                    if let Err(error) =
16045                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
16046                    {
16047                        return Poll::Ready(Err(error));
16048                    }
16049                    match state.prepare_scalar_cancellation(
16050                        cursor,
16051                        CancellationCallKind::Signal,
16052                        &self.parallel_group_path,
16053                    ) {
16054                        Ok(true) => {
16055                            self.opened_wait = true;
16056                            self.matched_pending = true;
16057                            return Poll::Pending;
16058                        }
16059                        Ok(false) => {}
16060                        Err(error) => return Poll::Ready(Err(error)),
16061                    }
16062                    state.command_cursor += 1;
16063                    if let Some(value) = value {
16064                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
16065                        return Poll::Ready(Ok(value));
16066                    }
16067                    if state
16068                        .resume_signal
16069                        .as_ref()
16070                        .is_some_and(|signal| signal.signal_name == self.signal_name)
16071                    {
16072                        let signal = state
16073                            .resume_signal
16074                            .take()
16075                            .expect("matching resume signal is present");
16076                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
16077                        return Poll::Ready(Ok(signal.arguments));
16078                    }
16079
16080                    state.matched_recorded_pending = true;
16081                    self.opened_wait = true;
16082                    self.matched_pending = true;
16083                    return Poll::Pending;
16084                }
16085                other => {
16086                    return Poll::Ready(Err(command_mismatch(
16087                        &other,
16088                        format!("signal wait:{}", self.signal_name),
16089                    )));
16090                }
16091            }
16092        }
16093
16094        match state.prepare_scalar_cancellation(
16095            cursor,
16096            CancellationCallKind::Signal,
16097            &self.parallel_group_path,
16098        ) {
16099            Ok(true) => {
16100                self.opened_wait = true;
16101                self.matched_pending = true;
16102                return Poll::Pending;
16103            }
16104            Ok(false) => {}
16105            Err(error) => return Poll::Ready(Err(error)),
16106        }
16107
16108        if state
16109            .resume_signal
16110            .as_ref()
16111            .is_some_and(|signal| signal.signal_name == self.signal_name)
16112        {
16113            let signal = state
16114                .resume_signal
16115                .take()
16116                .expect("matching resume signal is present");
16117            state.unavailable_cancellation_boundary(&self.parallel_group_path);
16118            return Poll::Ready(Ok(signal.arguments));
16119        }
16120
16121        if !self.opened_wait {
16122            let mut command = serde_json::Map::from_iter([
16123                ("type".to_string(), json!("open_signal_wait")),
16124                ("signal_name".to_string(), json!(self.signal_name)),
16125            ]);
16126            apply_parallel_group_path(&mut command, &self.parallel_group_path);
16127            ctx.apply_scope_membership(&mut command);
16128            state.commands.push(Value::Object(command));
16129            self.opened_wait = true;
16130        }
16131
16132        Poll::Pending
16133    }
16134}
16135
16136impl Future for SignalCall {
16137    type Output = Result<Vec<Value>>;
16138
16139    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
16140        match self.poll_avro_value(cx) {
16141            Poll::Ready(Ok(values)) => Poll::Ready(
16142                values
16143                    .into_iter()
16144                    .map(AvroValue::into_json)
16145                    .collect::<Result<Vec<_>>>(),
16146            ),
16147            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
16148            Poll::Pending => Poll::Pending,
16149        }
16150    }
16151}
16152
16153#[derive(Clone, Debug)]
16154pub struct ActivityContext {
16155    client: Client,
16156    pub task_id: String,
16157    pub activity_attempt_id: String,
16158    pub lease_owner: String,
16159    pub activity_type: String,
16160    pub attempt_number: u64,
16161    pub task_queue: String,
16162    pub worker_id: String,
16163    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
16164    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
16165    worker_session: Option<WorkerSession>,
16166}
16167
16168impl ActivityContext {
16169    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
16170        if let Some(heartbeats) = &self.local_heartbeats {
16171            return heartbeats
16172                .lock()
16173                .map_err(|_| Error::WorkflowStatePoisoned)?
16174                .record(details);
16175        }
16176        if let Some(guard) = &self.claim_guard {
16177            return guard.heartbeat(self, details).await;
16178        }
16179        if let Some(session) = &self.worker_session {
16180            if !session.active() {
16181                return Err(Error::ActivityExecutionAbandoned(
16182                    "worker-session lease or TTL is no longer active".into(),
16183                ));
16184            }
16185            let result = self
16186                .client
16187                .heartbeat_activity_task_value(
16188                    &self.task_id,
16189                    &self.activity_attempt_id,
16190                    &self.lease_owner,
16191                    details,
16192                )
16193                .await;
16194            return worker_session::settle_activity_heartbeat(
16195                session,
16196                result,
16197                &self.task_id,
16198                &self.activity_attempt_id,
16199                &self.lease_owner,
16200            );
16201        }
16202        self.client
16203            .heartbeat_activity_task(
16204                &self.task_id,
16205                &self.activity_attempt_id,
16206                &self.lease_owner,
16207                details,
16208            )
16209            .await
16210    }
16211}
16212
16213fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
16214    validate_payload_codec(codec)?;
16215    match value {
16216        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
16217            value, codec,
16218        )?)),
16219        None => Ok(AvroValue::Array(Vec::new())),
16220    }
16221}
16222
16223fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
16224    let Some(signal_name) = task
16225        .signal_name
16226        .as_deref()
16227        .filter(|value| !value.is_empty())
16228    else {
16229        return Ok(None);
16230    };
16231    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
16232    let AvroValue::Array(arguments) = decoded else {
16233        unreachable!("normalize_avro_arguments always returns an array");
16234    };
16235
16236    Ok(Some(ResumeSignal {
16237        signal_name: signal_name.to_string(),
16238        arguments,
16239    }))
16240}
16241
16242fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
16243    validate_payload_codec(&task.payload_codec)?;
16244    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
16245    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
16246    for event in &task.history_events {
16247        validate_history_event_payloads(event, &task.payload_codec)?;
16248    }
16249    Ok(())
16250}
16251
16252fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
16253    validate_payload_codec(&task.payload_codec)?;
16254    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
16255}
16256
16257fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
16258    validate_payload_codec(&task.payload_codec)?;
16259    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
16260    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
16261    for event in &task.history_events {
16262        validate_history_event_payloads(event, &task.payload_codec)?;
16263    }
16264
16265    let Some(export) = task.history_export.as_ref() else {
16266        return Ok(());
16267    };
16268    let export_codec = match export.get("payloads") {
16269        Some(payloads) => declared_payload_codec(payloads, "codec")?,
16270        None => None,
16271    }
16272    .unwrap_or(&task.payload_codec);
16273    validate_payload_codec(export_codec)?;
16274
16275    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
16276        for event in events {
16277            let event_type = event
16278                .get("event_type")
16279                .or_else(|| event.get("type"))
16280                .and_then(Value::as_str)
16281                .unwrap_or_default();
16282            if let Some(payload) = event.get("payload") {
16283                validate_history_payloads(event_type, payload, export_codec)?;
16284            }
16285        }
16286    }
16287    for signal in export
16288        .get("signals")
16289        .and_then(Value::as_array)
16290        .into_iter()
16291        .flatten()
16292    {
16293        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
16294        validate_payload_codec(codec)?;
16295        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
16296    }
16297    for activity in export
16298        .get("activities")
16299        .and_then(Value::as_array)
16300        .into_iter()
16301        .flatten()
16302    {
16303        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
16304        validate_payload_codec(codec)?;
16305        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
16306        validate_optional_inbound_payload(activity.get("result"), codec)?;
16307    }
16308    Ok(())
16309}
16310
16311fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
16312    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
16313}
16314
16315fn validate_history_payloads(
16316    event_type: &str,
16317    payload: &Value,
16318    fallback_codec: &str,
16319) -> Result<()> {
16320    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
16321    validate_payload_codec(codec)?;
16322    for field in history_payload_fields(event_type) {
16323        validate_optional_inbound_payload(payload.get(*field), codec)?;
16324    }
16325    Ok(())
16326}
16327
16328const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
16329
16330fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
16331    match event_type {
16332        "ActivityCompleted" => &["result"],
16333        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
16334        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
16335        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
16336        "ChildRunCompleted" => &["result", "output"],
16337        "WorkflowCompleted" => &["output"],
16338        "ServiceCallStarted"
16339        | "ServiceCallCompleted"
16340        | "ServiceCallFailed"
16341        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
16342        _ => &[],
16343    }
16344}
16345
16346fn signal_history_payload(payload: &Value) -> Option<&Value> {
16347    SIGNAL_HISTORY_PAYLOAD_FIELDS
16348        .iter()
16349        .find_map(|field| payload.get(*field))
16350}
16351
16352fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
16353    match value.get(field) {
16354        None => Ok(None),
16355        Some(Value::String(codec)) => Ok(Some(codec)),
16356        Some(_) => Err(invalid_payload_envelope()),
16357    }
16358}
16359
16360fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
16361    validate_payload_codec(codec)?;
16362    if let Some(value) = value.filter(|value| !value.is_null()) {
16363        decode_wire_avro_value(value, codec)?;
16364    }
16365    Ok(())
16366}
16367
16368fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
16369    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
16370        invalid_recorded_history(
16371            "parallel_group_metadata_invalid",
16372            sequence,
16373            "non-empty parallel_group_id",
16374            &payload.to_string(),
16375            "parallel-group history is missing its stable identity",
16376        )
16377    })?;
16378    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
16379        invalid_recorded_history(
16380            "parallel_group_metadata_invalid",
16381            sequence,
16382            "activity, child, timer, signal, condition, or mixed group kind",
16383            &payload.to_string(),
16384            "parallel-group history is missing its group kind",
16385        )
16386    })?;
16387    if !matches!(
16388        kind.as_str(),
16389        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
16390    ) {
16391        return Err(invalid_recorded_history(
16392            "parallel_group_metadata_invalid",
16393            sequence,
16394            "activity, child, timer, signal, condition, or mixed group kind",
16395            &kind,
16396            "parallel-group history contains an unsupported group kind",
16397        ));
16398    }
16399    let base_sequence = payload
16400        .get("parallel_group_base_sequence")
16401        .and_then(value_as_u64)
16402        .filter(|value| *value > 0)
16403        .ok_or_else(|| {
16404            invalid_recorded_history(
16405                "parallel_group_metadata_invalid",
16406                sequence,
16407                "positive parallel_group_base_sequence",
16408                &payload.to_string(),
16409                "parallel-group history contains an invalid base sequence",
16410            )
16411        })?;
16412    let size = payload
16413        .get("parallel_group_size")
16414        .and_then(value_as_u64)
16415        .and_then(|value| usize::try_from(value).ok())
16416        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
16417        .ok_or_else(|| {
16418            invalid_recorded_history(
16419                "parallel_group_metadata_invalid",
16420                sequence,
16421                "bounded positive parallel_group_size",
16422                &payload.to_string(),
16423                "parallel-group history contains an invalid group size",
16424            )
16425        })?;
16426    let index = payload
16427        .get("parallel_group_index")
16428        .and_then(value_as_u64)
16429        .and_then(|value| usize::try_from(value).ok())
16430        .filter(|value| *value < size)
16431        .ok_or_else(|| {
16432            invalid_recorded_history(
16433                "parallel_group_metadata_invalid",
16434                sequence,
16435                "parallel_group_index within group bounds",
16436                &payload.to_string(),
16437                "parallel-group history contains an invalid member index",
16438            )
16439        })?;
16440    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
16441        return Err(invalid_recorded_history(
16442            "parallel_group_metadata_invalid",
16443            sequence,
16444            "base sequence plus member index equals workflow sequence",
16445            &payload.to_string(),
16446            "parallel-group path does not preserve durable workflow position",
16447        ));
16448    }
16449    let mode = payload
16450        .get("parallel_group_mode")
16451        .and_then(Value::as_str)
16452        .unwrap_or("all");
16453    if !matches!(mode, "all" | "select") {
16454        return Err(invalid_recorded_history(
16455            "parallel_group_metadata_invalid",
16456            sequence,
16457            "parallel group mode all or select",
16458            mode,
16459            "parallel-group history contains an unsupported group mode",
16460        ));
16461    }
16462    let expected_id = if mode == "select" {
16463        format!("select-calls:{base_sequence}:{size}")
16464    } else {
16465        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
16466    };
16467    if group_id != expected_id {
16468        return Err(invalid_recorded_history(
16469            "parallel_group_metadata_invalid",
16470            sequence,
16471            &expected_id,
16472            &group_id,
16473            "parallel-group history contains an incompatible stable group ID",
16474        ));
16475    }
16476    let selection_member_key = if mode == "select" {
16477        Some(selection_key_from_value(
16478            payload.get("selection_member_key"),
16479            sequence,
16480        )?)
16481    } else {
16482        None
16483    };
16484    let selection_member_index = if mode == "select" {
16485        Some(required_parallel_usize(
16486            payload,
16487            "selection_member_index",
16488            sequence,
16489        )?)
16490    } else {
16491        None
16492    };
16493    let selection_member_base_sequence = if mode == "select" {
16494        Some(
16495            payload
16496                .get("selection_member_base_sequence")
16497                .and_then(value_as_u64)
16498                .filter(|value| *value >= base_sequence)
16499                .ok_or_else(|| {
16500                    invalid_recorded_history(
16501                        "parallel_group_metadata_invalid",
16502                        sequence,
16503                        "selection member base within its group",
16504                        &payload.to_string(),
16505                        "selection history contains an invalid member base sequence",
16506                    )
16507                })?,
16508        )
16509    } else {
16510        None
16511    };
16512    let selection_member_size = if mode == "select" {
16513        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
16514        if member_size == 0 {
16515            return Err(invalid_recorded_history(
16516                "parallel_group_metadata_invalid",
16517                sequence,
16518                "positive selection member size",
16519                &payload.to_string(),
16520                "selection history contains an invalid member size",
16521            ));
16522        }
16523        Some(member_size)
16524    } else {
16525        None
16526    };
16527    let selection_member_kind = if mode == "select" {
16528        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
16529            invalid_recorded_history(
16530                "parallel_group_metadata_invalid",
16531                sequence,
16532                "selection member operation kind",
16533                &payload.to_string(),
16534                "selection history is missing its authored member kind",
16535            )
16536        })?;
16537        if !matches!(
16538            kind.as_str(),
16539            "activity" | "child" | "timer" | "signal" | "condition" | "group"
16540        ) {
16541            return Err(invalid_recorded_history(
16542                "parallel_group_metadata_invalid",
16543                sequence,
16544                "activity, child, timer, signal, condition, or group selection member kind",
16545                &kind,
16546                "selection history contains an unsupported member kind",
16547            ));
16548        }
16549        Some(kind)
16550    } else {
16551        None
16552    };
16553    if let (Some(member_base), Some(member_size)) =
16554        (selection_member_base_sequence, selection_member_size)
16555    {
16556        let member_end = member_base
16557            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
16558            .ok_or_else(|| {
16559                invalid_recorded_history(
16560                    "parallel_group_metadata_invalid",
16561                    sequence,
16562                    "bounded selection member range",
16563                    &payload.to_string(),
16564                    "selection member range overflowed",
16565                )
16566            })?;
16567        let group_end = base_sequence
16568            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
16569            .unwrap_or(u64::MAX);
16570        if sequence < member_base || sequence >= member_end || member_end > group_end {
16571            return Err(invalid_recorded_history(
16572                "parallel_group_metadata_invalid",
16573                sequence,
16574                "workflow sequence within one bounded selection member",
16575                &payload.to_string(),
16576                "selection member range does not contain its durable leaf",
16577            ));
16578        }
16579    }
16580    Ok(ParallelGroupMetadata {
16581        parallel_group_id: group_id,
16582        parallel_group_kind: kind,
16583        parallel_group_base_sequence: base_sequence,
16584        parallel_group_size: size,
16585        parallel_group_index: index,
16586        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
16587        selection_member_key,
16588        selection_member_index,
16589        selection_member_base_sequence,
16590        selection_member_size,
16591        selection_member_kind,
16592    })
16593}
16594
16595fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
16596    payload
16597        .get(field)
16598        .and_then(value_as_u64)
16599        .and_then(|value| usize::try_from(value).ok())
16600        .ok_or_else(|| {
16601            invalid_recorded_history(
16602                "parallel_group_metadata_invalid",
16603                sequence,
16604                &format!("non-negative integer {field}"),
16605                &payload.to_string(),
16606                "selection history contains invalid member metadata",
16607            )
16608        })
16609}
16610
16611fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
16612    match value {
16613        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
16614        Some(value) => value_as_u64(value)
16615            .and_then(|value| usize::try_from(value).ok())
16616            .map(SelectionKey::Index)
16617            .ok_or_else(|| {
16618                invalid_recorded_history(
16619                    "selection_member_key_invalid",
16620                    sequence,
16621                    "non-empty string or non-negative integer member key",
16622                    &value.to_string(),
16623                    "selection history contains an invalid member key",
16624                )
16625            }),
16626        None => Err(invalid_recorded_history(
16627            "selection_member_key_missing",
16628            sequence,
16629            "selection_member_key",
16630            "<missing>",
16631            "selection history is missing its stable member key",
16632        )),
16633    }
16634}
16635
16636fn recorded_parallel_group_path(
16637    events: &[&HistoryEvent],
16638    sequence: u64,
16639) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16640    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
16641    for event in events {
16642        let payload = &event.payload;
16643        let has_metadata = payload.get("parallel_group_path").is_some()
16644            || payload.get("parallel_group_id").is_some()
16645            || payload.get("parallel_group_kind").is_some()
16646            || payload.get("parallel_group_base_sequence").is_some()
16647            || payload.get("parallel_group_size").is_some()
16648            || payload.get("parallel_group_index").is_some()
16649            || payload.get("parallel_group_mode").is_some()
16650            || payload.get("selection_member_key").is_some();
16651        if !has_metadata {
16652            continue;
16653        }
16654
16655        let top_level = recorded_parallel_group_entry(payload, sequence)?;
16656        let path = match payload.get("parallel_group_path") {
16657            None => vec![top_level.clone()],
16658            Some(Value::Array(entries)) if !entries.is_empty() => entries
16659                .iter()
16660                .map(|entry| recorded_parallel_group_entry(entry, sequence))
16661                .collect::<Result<Vec<_>>>()?,
16662            Some(value) => {
16663                return Err(invalid_recorded_history(
16664                    "parallel_group_metadata_invalid",
16665                    sequence,
16666                    "non-empty parallel_group_path list",
16667                    &value.to_string(),
16668                    "parallel-group history contains an invalid group path",
16669                ));
16670            }
16671        };
16672        if path.last() != Some(&top_level) {
16673            return Err(invalid_recorded_history(
16674                "parallel_group_metadata_invalid",
16675                sequence,
16676                &serde_json::to_string(&path.last()).unwrap_or_default(),
16677                &serde_json::to_string(&top_level).unwrap_or_default(),
16678                "parallel-group top-level fields do not match the innermost path entry",
16679            ));
16680        }
16681        if recorded.as_ref().is_some_and(|existing| existing != &path) {
16682            return Err(invalid_recorded_history(
16683                "parallel_group_history_conflict",
16684                sequence,
16685                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
16686                &serde_json::to_string(&path).unwrap_or_default(),
16687                "parallel-group metadata changed between scheduling and resolution history",
16688            ));
16689        }
16690        recorded = Some(path);
16691    }
16692    Ok(recorded)
16693}
16694
16695fn recorded_commands(
16696    events: &[HistoryEvent],
16697    fallback_codec: &str,
16698    parent: WorkflowIdentity,
16699) -> Result<Vec<RecordedCommand>> {
16700    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
16701    let mut last_new_sequence = None;
16702
16703    for event in events {
16704        let is_activity = matches!(
16705            event.event_type.as_str(),
16706            "ActivityScheduled"
16707                | "ActivityStarted"
16708                | "ActivityHeartbeatRecorded"
16709                | "ActivityRetryScheduled"
16710                | "ActivityCompleted"
16711                | "ActivityFailed"
16712                | "ActivityCancelled"
16713                | "ActivityTimedOut"
16714        );
16715        let is_workflow_timer = matches!(
16716            event.event_type.as_str(),
16717            "TimerScheduled" | "TimerCancelled" | "TimerFired"
16718        ) && !is_internal_timer_event(event);
16719        let is_child_workflow = matches!(
16720            event.event_type.as_str(),
16721            "ChildWorkflowScheduled"
16722                | "ChildRunStarted"
16723                | "ChildRunCompleted"
16724                | "ChildRunFailed"
16725                | "ChildRunCancelled"
16726                | "ChildRunTerminated"
16727        );
16728        let is_signal_wait = is_recorded_signal_wait_event(event);
16729        let is_condition_wait = is_recorded_condition_wait_event(event);
16730        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
16731        let is_side_effect = event.event_type == "SideEffectRecorded";
16732        let is_version_marker = event.event_type == "VersionMarkerRecorded";
16733        let is_memo = event.event_type == "MemoUpserted";
16734        let is_service_operation = nexus::is_service_event(event);
16735        if !is_activity
16736            && !is_workflow_timer
16737            && !is_child_workflow
16738            && !is_signal_wait
16739            && !is_condition_wait
16740            && !is_search_attributes
16741            && !is_side_effect
16742            && !is_version_marker
16743            && !is_memo
16744            && !is_service_operation
16745        {
16746            continue;
16747        }
16748
16749        let sequence = durable_event_sequence(event).ok_or_else(|| {
16750            Error::NonDeterministicReplay(ReplayFailure::new(
16751                "durable_command_sequence_missing",
16752                None,
16753                Some("positive workflow sequence".to_string()),
16754                Some(event.event_type.clone()),
16755                "durable command history event has no workflow sequence",
16756            ))
16757        })?;
16758        if sequence == 0 {
16759            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
16760                "durable_command_sequence_invalid",
16761                Some(sequence),
16762                Some("positive workflow sequence".to_string()),
16763                Some(sequence.to_string()),
16764                "durable command history uses an invalid workflow sequence",
16765            )));
16766        }
16767        if !events_by_sequence.contains_key(&sequence) {
16768            if let Some(previous) = last_new_sequence {
16769                if sequence < previous {
16770                    return Err(invalid_recorded_history(
16771                        "durable_command_sequence_mismatch",
16772                        sequence,
16773                        &format!("workflow sequence greater than {previous}"),
16774                        &sequence.to_string(),
16775                        "durable commands are not strictly ordered by their recorded workflow sequence",
16776                    ));
16777                }
16778            }
16779            last_new_sequence = Some(sequence);
16780        }
16781        events_by_sequence.entry(sequence).or_default().push(event);
16782    }
16783
16784    let commands: Vec<RecordedCommand> = events_by_sequence
16785        .into_iter()
16786        .map(|(sequence, sequence_events)| {
16787            let activity_events: Vec<_> = sequence_events
16788                .iter()
16789                .copied()
16790                .filter(|event| event.event_type.starts_with("Activity"))
16791                .collect();
16792            let timer_events: Vec<_> = sequence_events
16793                .iter()
16794                .copied()
16795                .filter(|event| event.event_type.starts_with("Timer"))
16796                .collect();
16797            let child_events: Vec<_> = sequence_events
16798                .iter()
16799                .copied()
16800                .filter(|event| {
16801                    event.event_type == "ChildWorkflowScheduled"
16802                        || event.event_type.starts_with("ChildRun")
16803                })
16804                .collect();
16805            let signal_wait_events: Vec<_> = sequence_events
16806                .iter()
16807                .copied()
16808                .filter(|event| is_recorded_signal_wait_event(event))
16809                .collect();
16810            let condition_wait_events: Vec<_> = sequence_events
16811                .iter()
16812                .copied()
16813                .filter(|event| is_recorded_condition_wait_event(event))
16814                .collect();
16815            let search_attribute_events: Vec<_> = sequence_events
16816                .iter()
16817                .copied()
16818                .filter(|event| event.event_type == "SearchAttributesUpserted")
16819                .collect();
16820            let side_effect_events: Vec<_> = sequence_events
16821                .iter()
16822                .copied()
16823                .filter(|event| event.event_type == "SideEffectRecorded")
16824                .collect();
16825            let version_marker_events: Vec<_> = sequence_events
16826                .iter()
16827                .copied()
16828                .filter(|event| event.event_type == "VersionMarkerRecorded")
16829                .collect();
16830            let memo_events: Vec<_> = sequence_events
16831                .iter()
16832                .copied()
16833                .filter(|event| event.event_type == "MemoUpserted")
16834                .collect();
16835            let service_events: Vec<_> = sequence_events.iter().copied()
16836                .filter(|event| nexus::is_service_event(event)).collect();
16837
16838            let command_kind_count = usize::from(!activity_events.is_empty())
16839                + usize::from(!timer_events.is_empty())
16840                + usize::from(!child_events.is_empty())
16841                + usize::from(!signal_wait_events.is_empty())
16842                + usize::from(!condition_wait_events.is_empty())
16843                + usize::from(!search_attribute_events.is_empty())
16844                + usize::from(!side_effect_events.is_empty())
16845                + usize::from(!version_marker_events.is_empty())
16846                + usize::from(!memo_events.is_empty())
16847                + usize::from(!service_events.is_empty());
16848            if command_kind_count > 1 {
16849                let actual = [
16850                    (!activity_events.is_empty()).then_some("activity"),
16851                    (!timer_events.is_empty()).then_some("timer"),
16852                    (!child_events.is_empty()).then_some("child workflow"),
16853                    (!signal_wait_events.is_empty()).then_some("signal wait"),
16854                    (!condition_wait_events.is_empty()).then_some("condition wait"),
16855                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
16856                    (!side_effect_events.is_empty()).then_some("side effect"),
16857                    (!version_marker_events.is_empty()).then_some("version marker"),
16858                    (!memo_events.is_empty()).then_some("memo upsert"),
16859                    (!service_events.is_empty()).then_some("service operation"),
16860                ]
16861                .into_iter()
16862                .flatten()
16863                .collect::<Vec<_>>()
16864                .join(" and ");
16865                return Err(invalid_recorded_history(
16866                    "durable_command_sequence_collision",
16867                    sequence,
16868                    "one durable command kind",
16869                    &actual,
16870                    "one workflow sequence records more than one durable command kind",
16871                ));
16872            }
16873
16874            if !service_events.is_empty() {
16875                return Ok(RecordedCommand::ServiceOperation {
16876                    sequence, call: nexus::recorded_call(&service_events, sequence, fallback_codec, &parent)?,
16877                });
16878            }
16879
16880            if !activity_events.is_empty() {
16881                let parallel_group_path =
16882                    recorded_parallel_group_path(&activity_events, sequence)?;
16883                let scheduled_count = activity_events
16884                    .iter()
16885                    .filter(|event| event.event_type == "ActivityScheduled")
16886                    .count();
16887                if scheduled_count > 1 {
16888                    return Err(invalid_recorded_history(
16889                        "duplicate_activity_schedule",
16890                        sequence,
16891                        "at most one ActivityScheduled event",
16892                        "multiple ActivityScheduled events",
16893                        "activity history schedules more than one command at one workflow sequence",
16894                    ));
16895                }
16896                let activity_type = activity_events.iter().find_map(|event| {
16897                    event
16898                        .payload
16899                        .get("activity_type")
16900                        .or_else(|| event.payload.get("activity_name"))
16901                        .and_then(Value::as_str)
16902                        .map(str::to_string)
16903                });
16904                if activity_events.iter().filter_map(|event| {
16905                    event
16906                        .payload
16907                        .get("activity_type")
16908                        .or_else(|| event.payload.get("activity_name"))
16909                        .and_then(Value::as_str)
16910                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
16911                    return Err(invalid_recorded_history(
16912                        "activity_identity_mismatch",
16913                        sequence,
16914                        activity_type.as_deref().unwrap_or("one activity identity"),
16915                        "conflicting activity identities",
16916                        "activity lifecycle events at one workflow sequence disagree on identity",
16917                    ));
16918                }
16919                let terminal: Vec<_> = activity_events
16920                    .iter()
16921                    .copied()
16922                    .filter(|event| {
16923                        matches!(
16924                            event.event_type.as_str(),
16925                            "ActivityCompleted"
16926                                | "ActivityFailed"
16927                                | "ActivityCancelled"
16928                                | "ActivityTimedOut"
16929                        )
16930                    })
16931                    .collect();
16932                let duplicate_delivery = terminal.first().is_some_and(|first| {
16933                    terminal.iter().all(|event| {
16934                        event.event_type == first.event_type && event.payload == first.payload
16935                    })
16936                });
16937                if terminal.len() > 1 && !duplicate_delivery {
16938                    return Err(invalid_recorded_history(
16939                        "duplicate_activity_terminal_event",
16940                        sequence,
16941                        "at most one terminal activity event",
16942                        "multiple terminal activity events",
16943                        "activity history settles one command more than once",
16944                    ));
16945                }
16946                let outcome = terminal
16947                    .first()
16948                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
16949                    .transpose()?;
16950                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
16951                let activity_snapshot = activity_events
16952                    .iter()
16953                    .find(|event| event.event_type == "ActivityScheduled")
16954                    .and_then(|event| event.payload.get("activity"))
16955                    .and_then(Value::as_object);
16956                let options = Some(match activity_snapshot {
16957                    Some(activity) => RecordedActivityOptions {
16958                        task_queue: recorded_optional_string(activity, "queue"),
16959                        execution_mode,
16960                        retry_policy: recorded_activity_retry_snapshot(
16961                            activity.get("retry_policy"),
16962                        ),
16963                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16964                    },
16965                    None => RecordedActivityOptions {
16966                        task_queue: RecordedSnapshotValue::Unknown,
16967                        execution_mode,
16968                        retry_policy: recorded_activity_retry_snapshot(None),
16969                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16970                    },
16971                });
16972                return Ok(RecordedCommand::Activity {
16973                    sequence,
16974                    activity_type,
16975                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
16976                    options,
16977                    outcome,
16978                    parallel_group_path,
16979                });
16980            }
16981
16982            if !child_events.is_empty() {
16983                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
16984                let scheduled: Vec<_> = child_events
16985                    .iter()
16986                    .copied()
16987                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
16988                    .collect();
16989                if scheduled.len() != 1 {
16990                    return Err(invalid_recorded_history(
16991                        "child_workflow_schedule_missing_or_duplicate",
16992                        sequence,
16993                        "one ChildWorkflowScheduled event",
16994                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
16995                        "child workflow replay requires exactly one recorded schedule event",
16996                    ));
16997                }
16998                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
16999                let workflow_type = child_events.iter().find_map(|event| {
17000                    event
17001                        .payload
17002                        .get("child_workflow_type")
17003                        .or_else(|| event.payload.get("workflow_type"))
17004                        .and_then(Value::as_str)
17005                        .filter(|value| !value.is_empty())
17006                        .map(str::to_string)
17007                });
17008                if child_events
17009                    .iter()
17010                    .filter_map(|event| {
17011                        event
17012                            .payload
17013                            .get("child_workflow_type")
17014                            .or_else(|| event.payload.get("workflow_type"))
17015                            .and_then(Value::as_str)
17016                    })
17017                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
17018                {
17019                    return Err(invalid_recorded_history(
17020                        "child_workflow_identity_mismatch",
17021                        sequence,
17022                        workflow_type
17023                            .as_deref()
17024                            .unwrap_or("one child workflow type"),
17025                        "conflicting child workflow types",
17026                        "child workflow lifecycle events at one sequence disagree on type",
17027                    ));
17028                }
17029                let mut outcomes = child_workflow_outcomes(
17030                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
17031                    fallback_codec,
17032                    parent.clone(),
17033                )?;
17034                let terminal_events = child_events
17035                    .iter()
17036                    .copied()
17037                    .filter(|event| event.event_type.starts_with("ChildRun"))
17038                    .collect::<Vec<_>>();
17039                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
17040                    terminal_events.iter().all(|event| {
17041                        event.event_type == first.event_type && event.payload == first.payload
17042                    })
17043                });
17044                if outcomes.len() > 1 && !duplicate_delivery {
17045                    return Err(invalid_recorded_history(
17046                        "duplicate_child_workflow_terminal_event",
17047                        sequence,
17048                        "at most one terminal child event",
17049                        "multiple terminal child events",
17050                        "child workflow history settles one command more than once",
17051                    ));
17052                }
17053                return Ok(RecordedCommand::ChildWorkflow {
17054                    sequence,
17055                    workflow_type,
17056                    policies,
17057                    outcome: outcomes.pop(),
17058                    parallel_group_path,
17059                });
17060            }
17061
17062            if !signal_wait_events.is_empty() {
17063                let opened: Vec<_> = signal_wait_events
17064                    .iter()
17065                    .copied()
17066                    .filter(|event| event.event_type == "SignalWaitOpened")
17067                    .collect();
17068                if opened.len() != 1 {
17069                    return Err(invalid_recorded_history(
17070                        "signal_wait_open_missing_or_duplicate",
17071                        sequence,
17072                        "one SignalWaitOpened event",
17073                        &format!("{} SignalWaitOpened events", opened.len()),
17074                        "signal replay requires exactly one canonical wait-open event",
17075                    ));
17076                }
17077
17078                let applied: Vec<_> = signal_wait_events
17079                    .iter()
17080                    .copied()
17081                    .filter(|event| event.event_type == "SignalApplied")
17082                    .collect();
17083                if applied.len() > 1 {
17084                    return Err(invalid_recorded_history(
17085                        "duplicate_signal_wait_apply",
17086                        sequence,
17087                        "at most one SignalApplied event",
17088                        "multiple SignalApplied events",
17089                        "signal history applies one durable wait more than once",
17090                    ));
17091                }
17092
17093                let signal_names = signal_wait_events
17094                    .iter()
17095                    .map(|event| required_signal_wait_name(event, sequence))
17096                    .collect::<Result<Vec<_>>>()?;
17097                let signal_name = signal_names
17098                    .first()
17099                    .expect("signal wait events are not empty")
17100                    .clone();
17101                if signal_names.iter().any(|candidate| candidate != &signal_name) {
17102                    return Err(invalid_recorded_history(
17103                        "signal_wait_identity_mismatch",
17104                        sequence,
17105                        &signal_name,
17106                        "conflicting signal names",
17107                        "signal wait lifecycle events at one workflow sequence disagree on identity",
17108                    ));
17109                }
17110                let value = applied
17111                    .first()
17112                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
17113                    .transpose()?;
17114                return Ok(RecordedCommand::SignalWait {
17115                    sequence,
17116                    signal_name,
17117                    value,
17118                    parallel_group_path: recorded_parallel_group_path(
17119                        &signal_wait_events,
17120                        sequence,
17121                    )?,
17122                });
17123            }
17124
17125            if !condition_wait_events.is_empty() {
17126                return recorded_condition_wait(
17127                    sequence,
17128                    &condition_wait_events,
17129                    events,
17130                );
17131            }
17132
17133            if !search_attribute_events.is_empty() {
17134                if search_attribute_events.len() != 1 {
17135                    return Err(invalid_recorded_history(
17136                        "duplicate_search_attribute_update",
17137                        sequence,
17138                        "one SearchAttributesUpserted event",
17139                        &format!(
17140                            "{} SearchAttributesUpserted events",
17141                            search_attribute_events.len()
17142                        ),
17143                        "search-attribute history records one workflow command more than once",
17144                    ));
17145                }
17146                let payload = &search_attribute_events[0].payload;
17147                let attributes = payload
17148                    .get("attributes")
17149                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
17150                    .cloned()
17151                    .ok_or_else(|| {
17152                        invalid_recorded_history(
17153                            "search_attribute_update_missing",
17154                            sequence,
17155                            "non-empty attributes object",
17156                            "missing or invalid attributes",
17157                            "search-attribute history is missing its recorded mutation",
17158                        )
17159                    })?;
17160                let attribute_types =
17161                    recorded_search_attribute_types(payload, &attributes, sequence)?;
17162                return Ok(RecordedCommand::SearchAttributes {
17163                    sequence,
17164                    attributes,
17165                    attribute_types,
17166                });
17167            }
17168
17169            if !side_effect_events.is_empty() {
17170                if side_effect_events.len() != 1 {
17171                    return Err(invalid_recorded_history(
17172                        "duplicate_side_effect_record",
17173                        sequence,
17174                        "one SideEffectRecorded event",
17175                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
17176                        "side-effect history records one workflow command more than once",
17177                    ));
17178                }
17179                let event = side_effect_events[0];
17180                let result = event.payload.get("result").ok_or_else(|| {
17181                    invalid_recorded_history(
17182                        "side_effect_result_missing",
17183                        sequence,
17184                        "recorded result payload",
17185                        "missing result",
17186                        "side-effect history is missing its recorded value",
17187                    )
17188                })?;
17189                let has_published_envelope = result.as_str().is_some()
17190                    || result.as_object().is_some_and(|envelope| {
17191                        envelope.get("codec").and_then(Value::as_str).is_some()
17192                            && envelope.get("blob").and_then(Value::as_str).is_some()
17193                    });
17194                if !has_published_envelope {
17195                    return Err(invalid_recorded_history(
17196                        "side_effect_payload_malformed",
17197                        sequence,
17198                        "payload blob or {codec, blob} envelope",
17199                        &result.to_string(),
17200                        "side-effect history result does not use a published payload envelope",
17201                    ));
17202                }
17203                let codec = event
17204                    .payload
17205                    .get("payload_codec")
17206                    .and_then(Value::as_str)
17207                    .unwrap_or(fallback_codec);
17208                let value = decode_wire_avro_value(result, codec).map_err(|error| {
17209                    if error.to_string().contains("unsupported_payload_codec") {
17210                        return error;
17211                    }
17212
17213                    invalid_recorded_history(
17214                        "side_effect_payload_incompatible",
17215                        sequence,
17216                        &format!("valid {codec} payload envelope"),
17217                        &error.to_string(),
17218                        "side-effect history payload cannot be decoded with its recorded codec",
17219                    )
17220                })?;
17221                return Ok(RecordedCommand::SideEffect { sequence, value });
17222            }
17223
17224            if !version_marker_events.is_empty() {
17225                if version_marker_events.len() != 1 {
17226                    return Err(invalid_recorded_history(
17227                        "duplicate_version_marker_record",
17228                        sequence,
17229                        "one VersionMarkerRecorded event",
17230                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
17231                        "version-marker history records one workflow command more than once",
17232                    ));
17233                }
17234                let payload = &version_marker_events[0].payload;
17235                let change_id = payload
17236                    .get("change_id")
17237                    .and_then(Value::as_str)
17238                    .filter(|value| !value.is_empty())
17239                    .map(str::to_string)
17240                    .ok_or_else(|| {
17241                        invalid_recorded_history(
17242                            "version_marker_field_missing",
17243                            sequence,
17244                            "non-empty change_id",
17245                            "missing or invalid change_id",
17246                            "version-marker history is missing its stable change ID",
17247                        )
17248                    })?;
17249                let version = required_version_i32(payload, "version", sequence)?;
17250                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
17251                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
17252                if min_supported > max_supported || version < min_supported || version > max_supported {
17253                    return Err(invalid_recorded_history(
17254                        "version_marker_history_range_invalid",
17255                        sequence,
17256                        "min_supported <= version <= max_supported",
17257                        &format!("{min_supported} <= {version} <= {max_supported}"),
17258                        "recorded version marker contains an internally incompatible range",
17259                    ));
17260                }
17261                return Ok(RecordedCommand::VersionMarker {
17262                    sequence,
17263                    change_id,
17264                    version,
17265                });
17266            }
17267
17268            if !memo_events.is_empty() {
17269                if memo_events.len() != 1 {
17270                    return Err(invalid_recorded_history(
17271                        "duplicate_memo_upsert_record",
17272                        sequence,
17273                        "one MemoUpserted event",
17274                        &format!("{} MemoUpserted events", memo_events.len()),
17275                        "memo history records one workflow update more than once",
17276                    ));
17277                }
17278                let payload = &memo_events[0].payload;
17279                let entries = payload.get("entries").cloned().ok_or_else(|| {
17280                    invalid_recorded_history(
17281                        "memo_entries_missing",
17282                        sequence,
17283                        "memo entries object",
17284                        "missing entries",
17285                        "MemoUpserted history is missing replay identity entries",
17286                    )
17287                })?;
17288                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
17289                    invalid_recorded_history(
17290                        "memo_entries_invalid",
17291                        sequence,
17292                        "valid canonical memo entries",
17293                        &error.to_string(),
17294                        "MemoUpserted history contains invalid replay identity entries",
17295                    )
17296                })?;
17297                let merged = payload.get("merged").cloned().ok_or_else(|| {
17298                    invalid_recorded_history(
17299                        "memo_merged_projection_missing",
17300                        sequence,
17301                        "merged memo projection",
17302                        "missing merged",
17303                        "MemoUpserted history is missing its merged projection",
17304                    )
17305                })?;
17306                decode_memo_history_map(&merged, false).map_err(|error| {
17307                    invalid_recorded_history(
17308                        "memo_merged_projection_invalid",
17309                        sequence,
17310                        "valid merged memo projection",
17311                        &error.to_string(),
17312                        "MemoUpserted history contains an invalid merged projection",
17313                    )
17314                })?;
17315
17316                return Ok(RecordedCommand::Memo { sequence, entries });
17317            }
17318            let scheduled: Vec<_> = timer_events
17319                .iter()
17320                .copied()
17321                .filter(|event| event.event_type == "TimerScheduled")
17322                .collect();
17323            let fired: Vec<_> = timer_events
17324                .iter()
17325                .copied()
17326                .filter(|event| event.event_type == "TimerFired")
17327                .collect();
17328            if scheduled.len() != 1 {
17329                return Err(invalid_recorded_history(
17330                    "timer_schedule_missing_or_duplicate",
17331                    sequence,
17332                    "one TimerScheduled event",
17333                    &format!("{} TimerScheduled events", scheduled.len()),
17334                    "timer replay requires exactly one recorded schedule event",
17335                ));
17336            }
17337            if fired.len() > 1 {
17338                return Err(invalid_recorded_history(
17339                    "duplicate_timer_fire",
17340                    sequence,
17341                    "at most one TimerFired event",
17342                    "multiple TimerFired events",
17343                    "timer history contains more than one fire event for a workflow sequence",
17344                ));
17345            }
17346
17347            let scheduled = scheduled[0];
17348            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
17349            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
17350            if let Some(fired) = fired.first() {
17351                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
17352                if fired_timer_id != timer_id {
17353                    return Err(invalid_recorded_history(
17354                        "timer_identity_mismatch",
17355                        sequence,
17356                        &timer_id,
17357                        &fired_timer_id,
17358                        "TimerFired does not correspond to the recorded TimerScheduled event",
17359                    ));
17360                }
17361                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
17362                if fired_delay != delay_seconds {
17363                    return Err(invalid_recorded_history(
17364                        "timer_history_delay_mismatch",
17365                        sequence,
17366                        &delay_seconds.to_string(),
17367                        &fired_delay.to_string(),
17368                        "TimerScheduled and TimerFired record different delays",
17369                    ));
17370                }
17371            }
17372
17373            Ok(RecordedCommand::Timer {
17374                sequence,
17375                delay_seconds,
17376                fired: !fired.is_empty(),
17377                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
17378            })
17379        })
17380        .collect::<Result<_>>()?;
17381
17382    let mut marker_decisions = HashMap::new();
17383    for command in &commands {
17384        if let RecordedCommand::VersionMarker {
17385            sequence,
17386            change_id,
17387            version,
17388        } = command
17389        {
17390            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
17391                if version != first_version {
17392                    return Err(invalid_recorded_history(
17393                        "version_marker_conflict",
17394                        *sequence,
17395                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
17396                        &format!("version {version} at sequence {sequence}"),
17397                        "workflow history contains conflicting decisions for one stable change ID",
17398                    ));
17399                }
17400            } else {
17401                marker_decisions.insert(change_id.clone(), (*version, *sequence));
17402            }
17403        }
17404    }
17405
17406    Ok(commands)
17407}
17408
17409fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
17410    payload
17411        .get(field)
17412        .and_then(Value::as_i64)
17413        .and_then(|value| i32::try_from(value).ok())
17414        .ok_or_else(|| {
17415            invalid_recorded_history(
17416                "version_marker_field_missing",
17417                sequence,
17418                &format!("integer {field}"),
17419                "missing or out-of-range integer",
17420                "version-marker history is missing a required integer field",
17421            )
17422        })
17423}
17424
17425fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
17426    event
17427        .payload
17428        .get("sequence")
17429        .or_else(|| event.payload.get("workflow_sequence"))
17430        .or_else(|| event.raw.get("sequence"))
17431        .or_else(|| event.raw.get("workflow_sequence"))
17432        .and_then(value_as_u64)
17433}
17434
17435fn is_internal_timer_event(event: &HistoryEvent) -> bool {
17436    matches!(
17437        event
17438            .payload
17439            .get("timer_kind")
17440            .or_else(|| event.raw.get("timer_kind"))
17441            .and_then(Value::as_str),
17442        Some("condition_timeout" | "signal_timeout")
17443    )
17444}
17445
17446fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
17447    matches!(
17448        event.event_type.as_str(),
17449        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
17450    )
17451}
17452
17453fn recorded_condition_wait(
17454    sequence: u64,
17455    condition_events: &[&HistoryEvent],
17456    all_events: &[HistoryEvent],
17457) -> Result<RecordedCommand> {
17458    let opened = condition_events
17459        .iter()
17460        .copied()
17461        .filter(|event| event.event_type == "ConditionWaitOpened")
17462        .collect::<Vec<_>>();
17463    if opened.len() != 1 {
17464        return Err(invalid_recorded_history(
17465            "condition_wait_open_missing_or_duplicate",
17466            sequence,
17467            "one ConditionWaitOpened event",
17468            &format!("{} ConditionWaitOpened events", opened.len()),
17469            "condition replay requires exactly one canonical wait-open event",
17470        ));
17471    }
17472    let terminal = condition_events
17473        .iter()
17474        .copied()
17475        .filter(|event| {
17476            matches!(
17477                event.event_type.as_str(),
17478                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
17479            )
17480        })
17481        .collect::<Vec<_>>();
17482    if terminal.len() > 1 {
17483        return Err(invalid_recorded_history(
17484            "duplicate_condition_wait_terminal_event",
17485            sequence,
17486            "at most one condition terminal event",
17487            "multiple condition terminal events",
17488            "condition history settles one durable wait more than once",
17489        ));
17490    }
17491
17492    let opened = opened[0];
17493    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
17494    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
17495    for event in condition_events
17496        .iter()
17497        .copied()
17498        .filter(|event| !std::ptr::eq(*event, opened))
17499    {
17500        let event_wait_id = required_condition_wait_id(event, sequence)?;
17501        if event_wait_id != condition_wait_id {
17502            return Err(invalid_recorded_history(
17503                "condition_wait_id_mismatch",
17504                sequence,
17505                &condition_wait_id,
17506                &event_wait_id,
17507                "condition lifecycle events at one sequence disagree on wait identity",
17508            ));
17509        }
17510        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
17511        if event_occurrence_id != occurrence_id {
17512            return Err(invalid_recorded_history(
17513                "condition_wait_occurrence_history_mismatch",
17514                sequence,
17515                &occurrence_id,
17516                &event_occurrence_id,
17517                "condition lifecycle events at one sequence disagree on authored occurrence identity",
17518            ));
17519        }
17520    }
17521
17522    let condition_key = optional_non_empty_history_string(opened, "condition_key");
17523    let predicate_identity = opened
17524        .payload
17525        .get("condition_definition_fingerprint")
17526        .and_then(Value::as_str)
17527        .filter(|value| !value.is_empty())
17528        .map(str::to_string)
17529        .ok_or_else(|| {
17530            invalid_recorded_history(
17531                "condition_wait_predicate_fingerprint_missing",
17532                sequence,
17533                "non-empty condition_definition_fingerprint",
17534                &opened.event_type,
17535                "canonical condition history is missing its predicate identity",
17536            )
17537        })?;
17538    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
17539    for event in condition_events
17540        .iter()
17541        .copied()
17542        .filter(|event| !std::ptr::eq(*event, opened))
17543    {
17544        for (field, opened_value) in [
17545            ("condition_key", condition_key.as_deref()),
17546            (
17547                "condition_definition_fingerprint",
17548                Some(predicate_identity.as_str()),
17549            ),
17550        ] {
17551            if let Some(value) = optional_non_empty_history_string(event, field) {
17552                if opened_value.is_some_and(|opened_value| opened_value != value) {
17553                    return Err(invalid_recorded_history(
17554                        "condition_wait_definition_history_mismatch",
17555                        sequence,
17556                        opened_value.unwrap_or_default(),
17557                        &value,
17558                        "condition lifecycle events disagree on the recorded definition",
17559                    ));
17560                }
17561            }
17562        }
17563        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
17564            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
17565                return Err(invalid_recorded_history(
17566                    "condition_wait_definition_history_mismatch",
17567                    sequence,
17568                    &format!("{}s", timeout_seconds.unwrap_or_default()),
17569                    &format!("{event_timeout}s"),
17570                    "condition lifecycle events disagree on the recorded timeout",
17571                ));
17572            }
17573        }
17574    }
17575
17576    let timeout_timer_events = all_events
17577        .iter()
17578        .filter(|event| {
17579            matches!(
17580                event.event_type.as_str(),
17581                "TimerScheduled" | "TimerCancelled" | "TimerFired"
17582            ) && event.payload.get("timer_kind").and_then(Value::as_str)
17583                == Some("condition_timeout")
17584                && event
17585                    .payload
17586                    .get("condition_wait_id")
17587                    .and_then(Value::as_str)
17588                    == Some(condition_wait_id.as_str())
17589        })
17590        .collect::<Vec<_>>();
17591    let scheduled = timeout_timer_events
17592        .iter()
17593        .copied()
17594        .filter(|event| event.event_type == "TimerScheduled")
17595        .collect::<Vec<_>>();
17596    let fired = timeout_timer_events
17597        .iter()
17598        .copied()
17599        .filter(|event| event.event_type == "TimerFired")
17600        .collect::<Vec<_>>();
17601    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
17602        return Err(invalid_recorded_history(
17603            "condition_wait_timeout_history_invalid",
17604            sequence,
17605            "one timeout schedule and at most one fire",
17606            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
17607            "condition timeout history has a missing or duplicate lifecycle event",
17608        ));
17609    }
17610    if let Some(scheduled) = scheduled.first() {
17611        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
17612        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
17613        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
17614            return Err(invalid_recorded_history(
17615                "condition_wait_timeout_delay_mismatch",
17616                sequence,
17617                &format!("{}s", timeout_seconds.unwrap_or_default()),
17618                &format!("{delay_seconds}s"),
17619                "condition timeout timer differs from the wait definition",
17620            ));
17621        }
17622        if let Some(fired) = fired.first() {
17623            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
17624            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
17625            if fired_timer_id != timer_id || fired_delay != delay_seconds {
17626                return Err(invalid_recorded_history(
17627                    "condition_wait_timeout_identity_mismatch",
17628                    sequence,
17629                    &format!("{timer_id}:{delay_seconds}s"),
17630                    &format!("{fired_timer_id}:{fired_delay}s"),
17631                    "condition timeout fire does not match its durable schedule",
17632                ));
17633            }
17634        }
17635    }
17636
17637    let result = terminal.first().map(|event| {
17638        if event.event_type == "ConditionWaitTimedOut" {
17639            ConditionWaitResult::TimedOut
17640        } else {
17641            ConditionWaitResult::Satisfied
17642        }
17643    });
17644    let result = if !fired.is_empty() {
17645        if result == Some(ConditionWaitResult::Satisfied) {
17646            return Err(invalid_recorded_history(
17647                "condition_wait_terminal_conflict",
17648                sequence,
17649                "one satisfied or timed-out outcome",
17650                "satisfied event and fired timeout",
17651                "condition history records conflicting terminal outcomes",
17652            ));
17653        }
17654        Some(ConditionWaitResult::TimedOut)
17655    } else {
17656        result
17657    };
17658
17659    Ok(RecordedCommand::ConditionWait {
17660        sequence,
17661        occurrence_id,
17662        condition_key,
17663        predicate_identity,
17664        timeout_seconds,
17665        result,
17666        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
17667    })
17668}
17669
17670fn recorded_condition_group_path(
17671    condition_events: &[&HistoryEvent],
17672    all_events: &[HistoryEvent],
17673    sequence: u64,
17674) -> Result<Option<Vec<ParallelGroupMetadata>>> {
17675    let opened = condition_events
17676        .iter()
17677        .copied()
17678        .find(|event| event.event_type == "ConditionWaitOpened")
17679        .expect("canonical condition opener is validated first");
17680    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
17681    let previous_events = all_events
17682        .iter()
17683        .take_while(|event| !std::ptr::eq(*event, opened))
17684        .collect::<Vec<_>>();
17685    let originals = previous_events
17686        .iter()
17687        .copied()
17688        .filter(|event| event.event_type == "ConditionWaitOpened")
17689        .filter(|event| {
17690            event
17691                .payload
17692                .get("condition_wait_occurrence_id")
17693                .and_then(Value::as_str)
17694                == Some(occurrence.as_str())
17695        })
17696        .collect::<Vec<_>>();
17697    let Some(original) = originals.first().copied() else {
17698        return recorded_parallel_group_path(condition_events, sequence);
17699    };
17700    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
17701    if authored_sequence == sequence {
17702        return recorded_parallel_group_path(condition_events, sequence);
17703    }
17704    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
17705    if original_path.is_none() {
17706        return recorded_parallel_group_path(condition_events, sequence);
17707    }
17708    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
17709    let identity_matches = [
17710        "condition_key",
17711        "condition_definition_fingerprint",
17712        "timeout_seconds",
17713    ]
17714    .iter()
17715    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
17716    let previous = originals
17717        .iter()
17718        .copied()
17719        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
17720        .max_by_key(|event| durable_event_sequence(event));
17721    let previously_satisfied = previous.is_some_and(|previous| {
17722        previous_events.iter().any(|event| {
17723            event.event_type == "ConditionWaitSatisfied"
17724                && event.payload.get("condition_wait_id")
17725                    == previous.payload.get("condition_wait_id")
17726                && event.payload.get("condition_wait_occurrence_id")
17727                    == previous.payload.get("condition_wait_occurrence_id")
17728                && durable_event_sequence(event) == durable_event_sequence(previous)
17729        })
17730    });
17731    if !identity_matches || reopened_path != original_path || !previously_satisfied {
17732        return Err(invalid_recorded_history(
17733            "condition_wait_group_reopen_mismatch",
17734            sequence,
17735            "same authored condition and group path after a satisfied physical wait",
17736            &opened.payload.to_string(),
17737            "grouped condition reopen has no matching recorded predecessor",
17738        ));
17739    }
17740    Ok(reopened_path)
17741}
17742
17743fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17744    event
17745        .payload
17746        .get("condition_wait_occurrence_id")
17747        .and_then(Value::as_str)
17748        .filter(|value| !value.is_empty())
17749        .map(str::to_string)
17750        .ok_or_else(|| {
17751            invalid_recorded_history(
17752                "condition_wait_occurrence_id_missing",
17753                sequence,
17754                "non-empty condition_wait_occurrence_id",
17755                &event.event_type,
17756                "condition history is missing authored occurrence identity",
17757            )
17758        })
17759}
17760
17761fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17762    event
17763        .payload
17764        .get("condition_wait_id")
17765        .and_then(Value::as_str)
17766        .filter(|value| !value.is_empty())
17767        .map(str::to_string)
17768        .ok_or_else(|| {
17769            invalid_recorded_history(
17770                "condition_wait_id_missing",
17771                sequence,
17772                "non-empty condition_wait_id",
17773                &event.event_type,
17774                "canonical condition history is missing its durable wait identity",
17775            )
17776        })
17777}
17778
17779fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
17780    event
17781        .payload
17782        .get(field)
17783        .and_then(Value::as_str)
17784        .filter(|value| !value.is_empty())
17785        .map(str::to_string)
17786}
17787
17788fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
17789    match event.payload.get(field) {
17790        None | Some(Value::Null) => Ok(None),
17791        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
17792            invalid_recorded_history(
17793                "condition_wait_definition_invalid",
17794                sequence,
17795                &format!("non-negative integer {field}"),
17796                &value.to_string(),
17797                "condition history contains an invalid numeric definition field",
17798            )
17799        }),
17800    }
17801}
17802
17803fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
17804    event
17805        .payload
17806        .get("signal_name")
17807        .or_else(|| event.raw.get("signal_name"))
17808        .and_then(Value::as_str)
17809        .filter(|value| !value.is_empty())
17810        .map(str::to_string)
17811        .ok_or_else(|| {
17812            invalid_recorded_history(
17813                "signal_wait_name_missing",
17814                sequence,
17815                "non-empty signal_name",
17816                &event.event_type,
17817                "canonical signal-wait history is missing its signal identity",
17818            )
17819        })
17820}
17821
17822fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
17823    // Applying a buffered control-plane signal has no authored call sequence.
17824    // Its outer sequence orders history events and must not become a wait.
17825    if event.event_type == "SignalApplied"
17826        && event
17827            .payload
17828            .get("signal_wait_id")
17829            .and_then(Value::as_str)
17830            .is_some_and(|id| id.starts_with("signal-command:"))
17831        && event.payload.get("sequence").is_none()
17832        && event.payload.get("workflow_sequence").is_none()
17833    {
17834        return false;
17835    }
17836    matches!(
17837        event.event_type.as_str(),
17838        "SignalWaitOpened" | "SignalApplied"
17839    )
17840}
17841
17842fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
17843    event
17844        .payload
17845        .get(field)
17846        .and_then(Value::as_str)
17847        .filter(|value| !value.is_empty())
17848        .map(str::to_string)
17849        .ok_or_else(|| {
17850            invalid_recorded_history(
17851                "timer_history_field_missing",
17852                sequence,
17853                field,
17854                &event.event_type,
17855                "timer history is missing a required identity field",
17856            )
17857        })
17858}
17859
17860fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
17861    event
17862        .payload
17863        .get(field)
17864        .and_then(value_as_u64)
17865        .ok_or_else(|| {
17866            invalid_recorded_history(
17867                "timer_history_field_missing",
17868                sequence,
17869                field,
17870                &event.event_type,
17871                "timer history is missing a required numeric field",
17872            )
17873        })
17874}
17875
17876fn recorded_search_attribute_types(
17877    payload: &Value,
17878    attributes: &Value,
17879    sequence: u64,
17880) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
17881    let Some(raw_types) = payload.get("attribute_types") else {
17882        // This is the explicit compatibility rule for histories recorded
17883        // before typed identity was persisted. Values still constrain replay;
17884        // the unknown type snapshot does not assert a typed match.
17885        return Ok(RecordedSnapshotValue::Unknown);
17886    };
17887    let Some(raw_types) = raw_types.as_object() else {
17888        return Err(invalid_recorded_history(
17889            "search_attribute_types_malformed",
17890            sequence,
17891            "canonical attribute type map",
17892            &raw_types.to_string(),
17893            "search-attribute history contains malformed type identity",
17894        ));
17895    };
17896    let attribute_keys = attributes
17897        .as_object()
17898        .expect("recorded search attributes were validated as an object");
17899    let mut types = BTreeMap::new();
17900    for (key, value) in raw_types {
17901        let Some(attribute_type) = value.as_str() else {
17902            return Err(invalid_recorded_history(
17903                "search_attribute_types_malformed",
17904                sequence,
17905                "canonical string type name",
17906                &value.to_string(),
17907                "search-attribute history contains a non-string type identity",
17908            ));
17909        };
17910        if !attribute_keys.contains_key(key)
17911            || !matches!(
17912                attribute_type,
17913                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
17914            )
17915        {
17916            return Err(invalid_recorded_history(
17917                "search_attribute_types_malformed",
17918                sequence,
17919                "canonical types for keys present in attributes",
17920                &format!("{key}:{attribute_type}"),
17921                "search-attribute history contains unsupported or orphaned type identity",
17922            ));
17923        }
17924        types.insert(key.clone(), attribute_type.to_string());
17925    }
17926    Ok(RecordedSnapshotValue::Known(types))
17927}
17928
17929fn invalid_recorded_history(
17930    reason: &str,
17931    sequence: u64,
17932    expected: &str,
17933    actual: &str,
17934    message: &str,
17935) -> Error {
17936    Error::NonDeterministicReplay(ReplayFailure::new(
17937        reason,
17938        Some(sequence),
17939        Some(expected.to_string()),
17940        Some(actual.to_string()),
17941        message,
17942    ))
17943}
17944
17945type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
17946
17947fn activity_outcome(
17948    event: &HistoryEvent,
17949    fallback_codec: &str,
17950    recorded_activity_type: Option<String>,
17951) -> Result<ActivityOutcome> {
17952    if event.event_type == "ActivityCompleted" {
17953        let codec = event
17954            .payload
17955            .get("payload_codec")
17956            .and_then(Value::as_str)
17957            .unwrap_or(fallback_codec);
17958        return Ok(Ok(decode_wire_avro_value(
17959            event.payload.get("result").unwrap_or(&Value::Null),
17960            codec,
17961        )?));
17962    }
17963
17964    let payload = &event.payload;
17965    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
17966        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
17967        "ActivityCancelled" => (
17968            ActivityFailureKind::Cancelled,
17969            "cancelled",
17970            "activity was cancelled",
17971        ),
17972        "ActivityTimedOut" => (
17973            ActivityFailureKind::TimedOut,
17974            "timeout",
17975            "activity timed out",
17976        ),
17977        _ => unreachable!("activity_outcome is called only for terminal activity events"),
17978    };
17979    let exception = payload
17980        .get("exception")
17981        .filter(|value| !value.is_null())
17982        .cloned();
17983    let failure_category = payload_string(payload, "failure_category");
17984    let timeout_kind = payload_string(payload, "timeout_kind");
17985    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
17986        ActivityFailureKind::Failed => failure_category
17987            .clone()
17988            .unwrap_or_else(|| fallback_reason.to_string()),
17989        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
17990        ActivityFailureKind::TimedOut => timeout_kind
17991            .clone()
17992            .unwrap_or_else(|| fallback_reason.to_string()),
17993    });
17994    let message = payload_string(payload, "message")
17995        .or_else(|| {
17996            exception
17997                .as_ref()
17998                .and_then(|value| payload_string(value, "message"))
17999        })
18000        .unwrap_or_else(|| fallback_message.to_string());
18001
18002    Ok(Err(ActivityFailure {
18003        kind,
18004        reason,
18005        message,
18006        activity_execution_id: payload_string(payload, "activity_execution_id"),
18007        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
18008        activity_type: payload_string(payload, "activity_type")
18009            .or_else(|| payload_string(payload, "activity_name"))
18010            .or(recorded_activity_type),
18011        activity_class: payload_string(payload, "activity_class"),
18012        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
18013        failure_id: payload_string(payload, "failure_id"),
18014        failure_category,
18015        timeout_kind,
18016        non_retryable: payload
18017            .get("non_retryable")
18018            .and_then(Value::as_bool)
18019            .unwrap_or(false),
18020        exception_type: payload_string(payload, "exception_type").or_else(|| {
18021            exception
18022                .as_ref()
18023                .and_then(|value| payload_string(value, "type"))
18024        }),
18025        exception_class: payload_string(payload, "exception_class").or_else(|| {
18026            exception
18027                .as_ref()
18028                .and_then(|value| payload_string(value, "class"))
18029        }),
18030        code: payload
18031            .get("code")
18032            .filter(|value| !value.is_null())
18033            .cloned(),
18034        exception,
18035    }))
18036}
18037
18038type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
18039
18040fn child_workflow_outcomes(
18041    events: &[HistoryEvent],
18042    fallback_codec: &str,
18043    parent: WorkflowIdentity,
18044) -> Result<Vec<ChildWorkflowOutcome>> {
18045    let mut outcomes = Vec::new();
18046
18047    for event in events {
18048        let kind = match event.event_type.as_str() {
18049            "ChildRunCompleted" => None,
18050            "ChildRunFailed" => Some((
18051                ChildWorkflowFailureKind::Failed,
18052                "child_workflow",
18053                "child workflow failed",
18054            )),
18055            "ChildRunCancelled" => Some((
18056                ChildWorkflowFailureKind::Cancelled,
18057                "cancelled",
18058                "child workflow was cancelled",
18059            )),
18060            "ChildRunTerminated" => Some((
18061                ChildWorkflowFailureKind::Terminated,
18062                "terminated",
18063                "child workflow was terminated",
18064            )),
18065            _ => continue,
18066        };
18067        let payload = &event.payload;
18068        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
18069        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
18070        let child_workflow_type = payload_string(payload, "child_workflow_type");
18071
18072        if let Some((kind, reason, fallback_message)) = kind {
18073            let exception = payload
18074                .get("exception")
18075                .filter(|value| !value.is_null())
18076                .cloned();
18077            let message = payload_string(payload, "message")
18078                .or_else(|| {
18079                    exception
18080                        .as_ref()
18081                        .and_then(|value| payload_string(value, "message"))
18082                })
18083                .unwrap_or_else(|| fallback_message.to_string());
18084            let exception_type = payload_string(payload, "exception_type").or_else(|| {
18085                exception
18086                    .as_ref()
18087                    .and_then(|value| payload_string(value, "type"))
18088            });
18089            let exception_class = payload_string(payload, "exception_class").or_else(|| {
18090                exception
18091                    .as_ref()
18092                    .and_then(|value| payload_string(value, "class"))
18093            });
18094            outcomes.push(Err(ChildWorkflowFailure {
18095                kind,
18096                reason: reason.to_string(),
18097                message,
18098                parent_workflow_id: parent.workflow_id.clone(),
18099                parent_workflow_run_id: parent.run_id.clone(),
18100                child_workflow_id,
18101                child_workflow_run_id,
18102                child_workflow_type,
18103                failure_id: payload_string(payload, "failure_id"),
18104                failure_category: payload_string(payload, "failure_category"),
18105                exception_type,
18106                exception_class,
18107                non_retryable: payload
18108                    .get("non_retryable")
18109                    .and_then(Value::as_bool)
18110                    .unwrap_or(false),
18111                code: payload
18112                    .get("code")
18113                    .filter(|value| !value.is_null())
18114                    .cloned(),
18115                exception,
18116            }));
18117            continue;
18118        }
18119
18120        let codec = payload
18121            .get("payload_codec")
18122            .and_then(Value::as_str)
18123            .unwrap_or(fallback_codec);
18124        let result = payload
18125            .get("result")
18126            .or_else(|| payload.get("output"))
18127            .unwrap_or(&Value::Null);
18128        outcomes.push(Ok(ChildWorkflowAvroResult {
18129            parent: parent.clone(),
18130            child: WorkflowIdentity {
18131                workflow_id: child_workflow_id,
18132                run_id: child_workflow_run_id,
18133            },
18134            child_workflow_type,
18135            result: decode_wire_avro_value(result, codec)?,
18136        }));
18137    }
18138
18139    Ok(outcomes)
18140}
18141
18142fn payload_string(payload: &Value, key: &str) -> Option<String> {
18143    payload
18144        .get(key)
18145        .and_then(Value::as_str)
18146        .filter(|value| !value.is_empty())
18147        .map(str::to_string)
18148}
18149
18150fn recorded_activity_failure_boundary(
18151    ctx: &WorkflowContext,
18152    error: &Error,
18153) -> Option<(u64, String)> {
18154    let Error::ActivityFailed(failure) = error else {
18155        return None;
18156    };
18157    if failure.kind != ActivityFailureKind::Failed {
18158        return None;
18159    }
18160    let activity_execution_id = failure
18161        .activity_execution_id
18162        .as_deref()
18163        .filter(|value| !value.is_empty())?;
18164    let state = ctx.state.lock().ok()?;
18165    let mut matches = state.recorded_commands.iter().filter_map(|command| {
18166        let RecordedCommand::Activity {
18167            sequence,
18168            outcome: Some(Err(recorded_failure)),
18169            ..
18170        } = command
18171        else {
18172            return None;
18173        };
18174        (*sequence > 0 && recorded_failure == failure)
18175            .then_some((*sequence, activity_execution_id.to_string()))
18176    });
18177    let boundary = matches.next()?;
18178    matches.next().is_none().then_some(boundary)
18179}
18180
18181fn workflow_failure_command(
18182    error: &Error,
18183    failed_activity_boundary: Option<(u64, String)>,
18184) -> Value {
18185    let (exception_type, exception_class, properties) = match error {
18186        Error::NexusOperationFailed(failure) => (
18187            "NexusOperationFailed",
18188            "durable_workflow::NexusOperationFailure",
18189            json!({"service_call_id":failure.service_call_id, "status":failure.status,
18190                "caller_observed_error_type":failure.exception_type, "service_exception":failure.exception}),
18191        ),
18192        Error::ActivityFailed(failure) => (
18193            match failure.kind {
18194                ActivityFailureKind::Failed => "ActivityFailed",
18195                ActivityFailureKind::Cancelled => "ActivityCancelled",
18196                ActivityFailureKind::TimedOut => "ActivityTimedOut",
18197            },
18198            "durable_workflow::ActivityFailure",
18199            json!({
18200                "reason": failure.reason,
18201                "activity_execution_id": failure.activity_execution_id,
18202                "activity_attempt_id": failure.activity_attempt_id,
18203                "activity_type": failure.activity_type,
18204                "activity_class": failure.activity_class,
18205                "attempt_number": failure.attempt_number,
18206                "failure_id": failure.failure_id,
18207                "failure_category": failure.failure_category,
18208                "timeout_kind": failure.timeout_kind,
18209                "activity_non_retryable": failure.non_retryable,
18210                "activity_exception_type": failure.exception_type,
18211                "activity_exception_class": failure.exception_class,
18212                "activity_code": failure.code,
18213                "activity_exception": failure.exception,
18214            }),
18215        ),
18216        Error::ChildWorkflowFailed(failure) => (
18217            match failure.kind {
18218                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
18219                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
18220                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
18221            },
18222            "durable_workflow::ChildWorkflowFailure",
18223            json!({
18224                "reason": failure.reason,
18225                "parent_workflow_id": failure.parent_workflow_id,
18226                "parent_workflow_run_id": failure.parent_workflow_run_id,
18227                "child_workflow_id": failure.child_workflow_id,
18228                "child_workflow_run_id": failure.child_workflow_run_id,
18229                "child_workflow_type": failure.child_workflow_type,
18230                "failure_id": failure.failure_id,
18231                "failure_category": failure.failure_category,
18232                "child_exception_type": failure.exception_type,
18233                "child_exception_class": failure.exception_class,
18234                "child_non_retryable": failure.non_retryable,
18235                "child_code": failure.code,
18236                "child_exception": failure.exception,
18237            }),
18238        ),
18239        Error::ParallelFailed(failure) => (
18240            "ParallelFailed",
18241            "durable_workflow::ParallelFailure",
18242            json!({
18243                "parallel_group_id": failure.group_id,
18244                "parallel_member_path": failure.member_path,
18245                "parallel_group_path": failure.group_path,
18246                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
18247                "cause_type": workflow_error_type(&failure.cause),
18248                "cause_message": failure.cause.to_string(),
18249            }),
18250        ),
18251        Error::SagaCompensationFailed(failure) => (
18252            "SagaCompensationFailed",
18253            "durable_workflow::SagaCompensationFailure",
18254            json!({
18255                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
18256                "initiating_failure_message": failure.initiating_failure.to_string(),
18257                "compensation_activity_type": failure.compensation_activity_type,
18258                "compensation_registration_order": failure.compensation_registration_order,
18259                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
18260                "compensation_failure_message": failure.compensation_failure.to_string(),
18261            }),
18262        ),
18263        Error::WorkflowCancellationRequested(_) => (
18264            "WorkflowCancellationRequested",
18265            "durable_workflow::WorkflowCancellationRequested",
18266            json!({"reason": "cancelled"}),
18267        ),
18268        Error::CooperativeCancellationRequested(cancellation) => (
18269            "WorkflowCancellationRequested",
18270            "durable_workflow::CooperativeCancellationRequested",
18271            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
18272                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
18273        ),
18274        Error::CancellationScopeRequested(cancellation) => (
18275            "WorkflowCancellationRequested",
18276            "durable_workflow::CancellationScopeRequested",
18277            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
18278                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
18279                "cancellation":cancellation.context.to_value()}),
18280        ),
18281        Error::NonDeterministicReplay(_) => (
18282            "NonDeterministicReplay",
18283            "durable_workflow::Error",
18284            Value::Null,
18285        ),
18286        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
18287    };
18288    let non_retryable = match error {
18289        Error::ActivityFailed(failure) => failure.non_retryable,
18290        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
18291        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
18292        Error::SagaCompensationFailed(failure) => {
18293            workflow_error_non_retryable(&failure.compensation_failure)
18294        }
18295        Error::WorkflowCancellationRequested(_)
18296        | Error::CooperativeCancellationRequested(_)
18297        | Error::CancellationScopeRequested(_) => true,
18298        Error::NonDeterministicReplay(_) => true,
18299        _ => false,
18300    };
18301
18302    let mut command = json!({
18303        "type": "fail_workflow",
18304        "message": error.to_string(),
18305        "exception_type": exception_type,
18306        "exception_class": exception_class,
18307        "non_retryable": non_retryable,
18308        "exception": {
18309            "type": exception_type,
18310            "class": exception_class,
18311            "message": error.to_string(),
18312            "properties": properties,
18313        }
18314    });
18315
18316    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
18317        command["failed_step_sequence"] = json!(sequence);
18318        command["failed_activity_execution_id"] = json!(activity_execution_id);
18319    }
18320
18321    command
18322}
18323
18324fn workflow_error_type(error: &Error) -> &'static str {
18325    match error {
18326        Error::NexusOperationFailed(_) => "NexusOperationFailed",
18327        Error::ActivityFailed(failure) => match failure.kind {
18328            ActivityFailureKind::Failed => "ActivityFailed",
18329            ActivityFailureKind::Cancelled => "ActivityCancelled",
18330            ActivityFailureKind::TimedOut => "ActivityTimedOut",
18331        },
18332        Error::ChildWorkflowFailed(failure) => match failure.kind {
18333            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
18334            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
18335            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
18336        },
18337        Error::ParallelFailed(_) => "ParallelFailed",
18338        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
18339        Error::WorkflowCancellationRequested(_)
18340        | Error::CooperativeCancellationRequested(_)
18341        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
18342        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
18343        _ => "RustWorkflowError",
18344    }
18345}
18346
18347fn workflow_error_non_retryable(error: &Error) -> bool {
18348    match error {
18349        Error::ActivityFailed(failure) => failure.non_retryable,
18350        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
18351        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
18352        Error::SagaCompensationFailed(failure) => {
18353            workflow_error_non_retryable(&failure.compensation_failure)
18354        }
18355        Error::WorkflowCancellationRequested(_)
18356        | Error::CooperativeCancellationRequested(_)
18357        | Error::CancellationScopeRequested(_)
18358        | Error::NonDeterministicReplay(_) => true,
18359        _ => false,
18360    }
18361}
18362
18363fn workflow_task_integrity_error(error: &Error) -> bool {
18364    matches!(
18365        error,
18366        Error::NonDeterministicReplay(_)
18367            | Error::Protocol(_)
18368            | Error::CancellationScopeExecutionUnavailable
18369            | Error::MissingWorkflowCommandIdentity
18370            | Error::WorkflowStatePoisoned
18371    )
18372}
18373
18374fn decode_signal_event_arguments(
18375    event: &HistoryEvent,
18376    fallback_codec: &str,
18377) -> Result<Vec<AvroValue>> {
18378    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
18379    validate_payload_codec(codec)?;
18380    let raw = signal_history_payload(&event.payload);
18381    let decoded = match raw.filter(|value| !value.is_null()) {
18382        Some(value) => decode_wire_avro_value(value, codec)?,
18383        None => AvroValue::Array(Vec::new()),
18384    };
18385    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
18386        unreachable!("normalize_avro_arguments always returns an array");
18387    };
18388    Ok(arguments)
18389}
18390
18391fn decode_update_event_arguments(
18392    event: &HistoryEvent,
18393    fallback_codec: &str,
18394) -> Result<Vec<AvroValue>> {
18395    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
18396    validate_payload_codec(codec)?;
18397    let decoded = match event
18398        .payload
18399        .get("arguments")
18400        .filter(|value| !value.is_null())
18401    {
18402        Some(value) => decode_wire_avro_value(value, codec)?,
18403        None => AvroValue::Array(Vec::new()),
18404    };
18405    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
18406        unreachable!("normalize_avro_arguments always returns an array");
18407    };
18408    Ok(arguments)
18409}
18410
18411fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
18412    let Some(export_events) = task
18413        .history_export
18414        .as_ref()
18415        .and_then(|export| export.get("history_events"))
18416        .and_then(Value::as_array)
18417    else {
18418        return Ok(());
18419    };
18420
18421    if export_events.len() > task.history_events.len() {
18422        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
18423    }
18424
18425    Ok(())
18426}
18427
18428fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
18429    let Some(export) = task.history_export.as_ref() else {
18430        return Ok(());
18431    };
18432    let signals = export
18433        .get("signals")
18434        .and_then(Value::as_array)
18435        .cloned()
18436        .unwrap_or_default();
18437    let activities = export
18438        .get("activities")
18439        .and_then(Value::as_array)
18440        .cloned()
18441        .unwrap_or_default();
18442    let export_codec = export
18443        .get("payloads")
18444        .and_then(|payloads| payloads.get("codec"))
18445        .and_then(Value::as_str)
18446        .unwrap_or(&task.payload_codec)
18447        .to_string();
18448    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
18449
18450    for event in &mut task.history_events {
18451        if event.event_type == "ActivityCompleted" {
18452            let sequence = event
18453                .payload
18454                .get("sequence")
18455                .or_else(|| event.payload.get("workflow_sequence"))
18456                .and_then(value_as_u64);
18457            let Some(activity) = sequence.and_then(|sequence| {
18458                activities.iter().find(|activity| {
18459                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
18460                })
18461            }) else {
18462                continue;
18463            };
18464            let Some(payload) = event.payload.as_object_mut() else {
18465                continue;
18466            };
18467            if missing_payload(payload.get("result")) {
18468                if let Some(result) = activity
18469                    .get("result")
18470                    .filter(|value| !missing_payload(Some(value)))
18471                {
18472                    payload.insert("result".to_string(), result.clone());
18473                }
18474            }
18475            for field in ["payload_codec", "activity_type"] {
18476                if payload
18477                    .get(field)
18478                    .and_then(Value::as_str)
18479                    .unwrap_or_default()
18480                    .is_empty()
18481                {
18482                    if let Some(value) = activity.get(field) {
18483                        payload.insert(field.to_string(), value.clone());
18484                    }
18485                }
18486            }
18487            continue;
18488        }
18489
18490        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
18491            continue;
18492        }
18493        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
18494        let command_id = event
18495            .payload
18496            .get("workflow_command_id")
18497            .or_else(|| event.raw.get("workflow_command_id"))
18498            .and_then(Value::as_str);
18499        let signal_name = event
18500            .payload
18501            .get("signal_name")
18502            .and_then(Value::as_str)
18503            .unwrap_or_default()
18504            .to_string();
18505        let matched = signals
18506            .iter()
18507            .find(|signal| {
18508                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
18509            })
18510            .or_else(|| {
18511                signals.iter().find(|signal| {
18512                    command_id.is_some()
18513                        && signal.get("command_id").and_then(Value::as_str) == command_id
18514                })
18515            })
18516            .or_else(|| {
18517                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
18518                let signal = signals
18519                    .iter()
18520                    .filter(|signal| {
18521                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
18522                    })
18523                    .nth(*offset);
18524                if signal.is_some() {
18525                    *offset += 1;
18526                }
18527                signal
18528            });
18529        let Some(signal) = matched else {
18530            continue;
18531        };
18532        let signal_codec = signal
18533            .get("payload_codec")
18534            .and_then(Value::as_str)
18535            .unwrap_or(&export_codec);
18536        let Some(payload) = event.payload.as_object_mut() else {
18537            continue;
18538        };
18539        if missing_payload(payload.get("arguments")) {
18540            if let Some(arguments) = signal
18541                .get("arguments")
18542                .filter(|value| !missing_payload(Some(value)))
18543            {
18544                let envelope = match arguments {
18545                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
18546                    other => other.clone(),
18547                };
18548                payload.insert("arguments".to_string(), envelope);
18549            }
18550        }
18551        if payload
18552            .get("payload_codec")
18553            .and_then(Value::as_str)
18554            .unwrap_or_default()
18555            .is_empty()
18556        {
18557            payload.insert("payload_codec".to_string(), json!(signal_codec));
18558        }
18559    }
18560
18561    Ok(())
18562}
18563
18564fn missing_payload(value: Option<&Value>) -> bool {
18565    match value {
18566        None | Some(Value::Null) => true,
18567        Some(Value::String(value)) => value.is_empty(),
18568        Some(_) => false,
18569    }
18570}
18571
18572fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
18573    history_signal_events(
18574        &task.history_events,
18575        task.history_export.as_ref(),
18576        &task.payload_codec,
18577    )
18578}
18579
18580fn history_signal_events(
18581    history_events: &[HistoryEvent],
18582    history_export: Option<&Value>,
18583    payload_codec: &str,
18584) -> Result<Vec<QuerySignal>> {
18585    let export_signals = history_export
18586        .and_then(|export| export.get("signals"))
18587        .and_then(Value::as_array)
18588        .cloned()
18589        .unwrap_or_default();
18590    let export_codec = history_export
18591        .and_then(|export| export.get("payloads"))
18592        .and_then(|payloads| payloads.get("codec"))
18593        .and_then(Value::as_str)
18594        .unwrap_or(payload_codec);
18595    let mut name_offsets: HashMap<String, usize> = HashMap::new();
18596    let mut signals: Vec<QuerySignal> = Vec::new();
18597    let mut signal_indices = HashMap::new();
18598    let mut command_indices = HashMap::new();
18599
18600    for event in history_events {
18601        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
18602            continue;
18603        }
18604
18605        let name = event
18606            .payload
18607            .get("signal_name")
18608            .and_then(Value::as_str)
18609            .unwrap_or_default();
18610        if name.is_empty() {
18611            continue;
18612        }
18613        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
18614        let command_id = event
18615            .payload
18616            .get("workflow_command_id")
18617            .or_else(|| event.raw.get("workflow_command_id"))
18618            .and_then(Value::as_str);
18619        let matched_export = export_signals
18620            .iter()
18621            .find(|candidate| {
18622                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
18623            })
18624            .or_else(|| {
18625                export_signals.iter().find(|candidate| {
18626                    command_id.is_some()
18627                        && candidate.get("command_id").and_then(Value::as_str) == command_id
18628                })
18629            })
18630            .or_else(|| {
18631                let offset = name_offsets.entry(name.to_string()).or_default();
18632                let candidate = export_signals
18633                    .iter()
18634                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
18635                    .nth(*offset);
18636                if candidate.is_some() {
18637                    *offset += 1;
18638                }
18639                candidate
18640            });
18641        let codec = event
18642            .payload
18643            .get("payload_codec")
18644            .and_then(Value::as_str)
18645            .or_else(|| {
18646                matched_export
18647                    .and_then(|signal| signal.get("payload_codec"))
18648                    .and_then(Value::as_str)
18649            })
18650            .unwrap_or(export_codec);
18651        let raw_arguments = signal_history_payload(&event.payload)
18652            .filter(|value| !value.is_null())
18653            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
18654        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
18655        let workflow_sequence = event
18656            .payload
18657            .get("workflow_sequence")
18658            .and_then(value_as_u64)
18659            .or_else(|| {
18660                matched_export
18661                    .and_then(|signal| signal.get("workflow_sequence"))
18662                    .and_then(value_as_u64)
18663            });
18664
18665        let id = signal_id.or_else(|| {
18666            matched_export
18667                .and_then(|signal| signal.get("id"))
18668                .and_then(Value::as_str)
18669        });
18670        let command_id = command_id.or_else(|| {
18671            matched_export
18672                .and_then(|signal| signal.get("command_id"))
18673                .and_then(Value::as_str)
18674        });
18675        let duplicate = id
18676            .and_then(|id| signal_indices.get(id))
18677            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
18678            .copied();
18679        let index = duplicate.unwrap_or(signals.len());
18680        if let Some(index) = duplicate {
18681            let original = &mut signals[index];
18682            let same_arguments = if event.event_type == "SignalApplied" {
18683                if let Some(value) = event.payload.get("value") {
18684                    let expected = match original.avro_arguments.as_slice() {
18685                        [] => AvroValue::Boolean(true),
18686                        [value] => value.clone(),
18687                        values => AvroValue::Array(values.to_vec()),
18688                    };
18689                    let applied = decode_wire_avro_value(value, codec)?;
18690                    applied == expected
18691                        || applied == AvroValue::Array(original.avro_arguments.clone())
18692                } else {
18693                    original.avro_arguments == avro_arguments
18694                }
18695            } else {
18696                original.avro_arguments == avro_arguments
18697            };
18698            if original.name != name
18699                || !same_arguments
18700                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
18701            {
18702                return Err(Error::Codec("conflicting committed signal identity".into()));
18703            }
18704            if original.id.is_none() {
18705                original.id = id.map(str::to_string);
18706            }
18707            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
18708        } else {
18709            signals.push(QuerySignal {
18710                id: id.map(str::to_string),
18711                name: name.to_string(),
18712                arguments,
18713                avro_arguments,
18714                workflow_sequence,
18715            });
18716        }
18717        if let Some(id) = id {
18718            signal_indices.insert(id.to_string(), index);
18719        }
18720        if let Some(id) = command_id {
18721            command_indices.insert(id.to_string(), index);
18722        }
18723    }
18724
18725    if signals.is_empty() {
18726        for signal in export_signals {
18727            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
18728                continue;
18729            }
18730            let Some(name) = signal.get("name").and_then(Value::as_str) else {
18731                continue;
18732            };
18733            let codec = signal
18734                .get("payload_codec")
18735                .and_then(Value::as_str)
18736                .unwrap_or(export_codec);
18737            let (arguments, avro_arguments) =
18738                decode_query_signal_arguments(signal.get("arguments"), codec)?;
18739            signals.push(QuerySignal {
18740                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
18741                name: name.to_string(),
18742                arguments,
18743                avro_arguments,
18744                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
18745            });
18746        }
18747        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
18748    }
18749
18750    Ok(signals)
18751}
18752
18753fn decode_query_signal_arguments(
18754    raw: Option<&Value>,
18755    codec: &str,
18756) -> Result<(Vec<Value>, Vec<AvroValue>)> {
18757    validate_payload_codec(codec)?;
18758    let decoded = match raw.filter(|value| !value.is_null()) {
18759        Some(value) => decode_wire_avro_value(value, codec)?,
18760        None => AvroValue::Array(Vec::new()),
18761    };
18762    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
18763        unreachable!("normalize_avro_arguments always returns an array");
18764    };
18765    let arguments = avro_arguments
18766        .iter()
18767        .cloned()
18768        .map(AvroValue::into_json)
18769        .collect::<Result<Vec<_>>>()?;
18770    Ok((arguments, avro_arguments))
18771}
18772
18773fn value_as_u64(value: &Value) -> Option<u64> {
18774    value
18775        .as_u64()
18776        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
18777}
18778
18779#[cfg(test)]
18780mod tests {
18781    use super::*;
18782    #[cfg(feature = "telemetry")]
18783    static OBSERVABILITY_PROPAGATOR_TEST_LOCK: tokio::sync::Mutex<()> =
18784        tokio::sync::Mutex::const_new(());
18785    mod activity_cancellation_policies;
18786    mod activity_lease_worker;
18787    mod cancellation_scope_admission;
18788    mod cancellation_scope_authoring;
18789    mod cancellation_scope_history;
18790    mod cancellation_scope_opening;
18791    mod cancellation_scope_replay;
18792    mod child_workflow_policies;
18793    mod cooperative_cancellation;
18794    mod local_activity;
18795    mod nexus;
18796    mod runtime_payloads;
18797    mod runtime_uploads;
18798    mod version_marker_contract;
18799    mod worker_capacity;
18800    mod worker_session;
18801    use std::{
18802        fs,
18803        io::{Read, Write},
18804        net::{SocketAddr, TcpListener, TcpStream},
18805        process::Command as ProcessCommand,
18806        sync::atomic::AtomicUsize,
18807        thread,
18808    };
18809
18810    #[derive(Clone, Copy, Debug)]
18811    enum InvalidTaskPayloadCodec {
18812        Missing,
18813        Null,
18814        NonString,
18815    }
18816
18817    impl InvalidTaskPayloadCodec {
18818        fn label(self) -> &'static str {
18819            match self {
18820                Self::Missing => "missing",
18821                Self::Null => "null",
18822                Self::NonString => "non-string",
18823            }
18824        }
18825
18826        fn apply(self, task: &mut Value) {
18827            let task = task.as_object_mut().expect("task fixture object");
18828            match self {
18829                Self::Missing => {
18830                    task.remove("payload_codec");
18831                }
18832                Self::Null => {
18833                    task.insert("payload_codec".to_string(), Value::Null);
18834                }
18835                Self::NonString => {
18836                    task.insert("payload_codec".to_string(), json!(42));
18837                }
18838            }
18839        }
18840    }
18841
18842    fn fixture_envelope(value: Value) -> Value {
18843        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
18844    }
18845
18846    fn fixture_blob(value: Value) -> String {
18847        encode_payload(&value, DEFAULT_CODEC)
18848            .expect("encode Avro test fixture")
18849            .blob
18850    }
18851
18852    #[test]
18853    fn client_builder_rejects_the_sdk_owned_api_suffix() {
18854        for base_url in [
18855            "http://127.0.0.1:8080/api",
18856            "http://localhost:8080/api/",
18857            "https://runtime.example.test/namespaces/orders/api",
18858        ] {
18859            let error = Client::builder(base_url)
18860                .build()
18861                .expect_err("SDK-owned /api suffix must be rejected during build");
18862
18863            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
18864            assert!(
18865                error.to_string().contains("SDK appends /api automatically"),
18866                "the validation error must explain how to fix the endpoint"
18867            );
18868        }
18869    }
18870
18871    #[test]
18872    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
18873        for (base_url, expected) in [
18874            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
18875            (
18876                "http://localhost:8080/durable-workflow/",
18877                "http://localhost:8080/durable-workflow",
18878            ),
18879            (
18880                "https://runtime.example.test/namespaces/orders",
18881                "https://runtime.example.test/namespaces/orders",
18882            ),
18883            (
18884                "https://runtime.example.test/gateway/api/namespaces/orders",
18885                "https://runtime.example.test/gateway/api/namespaces/orders",
18886            ),
18887            (
18888                "https://api.example.test/runtime/orders/",
18889                "https://api.example.test/runtime/orders",
18890            ),
18891        ] {
18892            let client = Client::builder(base_url)
18893                .build()
18894                .expect("Server and Cloud runtime base URL must remain valid");
18895
18896            assert_eq!(client.base_url, expected);
18897        }
18898    }
18899
18900    #[test]
18901    fn workflow_completion_uses_the_additive_command_protocol_floor() {
18902        assert_eq!(
18903            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
18904            MINIMUM_WORKER_PROTOCOL_VERSION
18905        );
18906        assert_eq!(
18907            workflow_completion_protocol_version(&[json!({
18908                "type": "upsert_search_attributes",
18909                "attributes": {"OrderStatus": "waiting"},
18910            })]),
18911            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
18912        );
18913        assert_eq!(
18914            workflow_completion_protocol_version(&[json!({
18915                "type": "upsert_search_attributes",
18916                "attributes": {"OrderStatus": "waiting"},
18917                "attribute_types": {"OrderStatus": "keyword"},
18918            })]),
18919            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
18920        );
18921        assert_eq!(
18922            workflow_completion_protocol_version(&[
18923                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
18924                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18925            ]),
18926            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
18927        );
18928        assert_eq!(
18929            workflow_completion_protocol_version(&[
18930                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
18931                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18932            ]),
18933            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
18934        );
18935        assert_eq!(
18936            workflow_completion_protocol_version(&[json!({
18937                "type": "open_condition_wait",
18938                "condition_wait_occurrence_id": "rust:condition-wait:0",
18939                "condition_key": "ready",
18940            })]),
18941            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18942        );
18943        assert_eq!(
18944            workflow_completion_protocol_version_with_message_streams(
18945                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
18946                true,
18947            ),
18948            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
18949        );
18950        assert_eq!(
18951            workflow_completion_protocol_version_with_message_streams(
18952                &[json!({
18953                    "type": "open_condition_wait",
18954                    "condition_wait_occurrence_id": "rust:condition-wait:0",
18955                    "condition_key": "ready",
18956                })],
18957                true,
18958            ),
18959            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18960        );
18961    }
18962
18963    #[test]
18964    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
18965        let manifest = portable_worker_affinity_capability_manifest();
18966
18967        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
18968            assert_eq!(manifest[capability]["supported"], json!(false));
18969            assert_eq!(
18970                manifest[capability]["minimum_protocol_version"],
18971                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
18972            );
18973            assert!(manifest[capability]["reason"]
18974                .as_str()
18975                .is_some_and(|reason| !reason.is_empty()));
18976        }
18977    }
18978
18979    fn typed_fidelity_probe() -> AvroValue {
18980        AvroValue::Map(BTreeMap::from([
18981            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
18982            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
18983            (
18984                "numeric".to_string(),
18985                AvroValue::Map(BTreeMap::from([
18986                    ("0".to_string(), AvroValue::String("zero".to_string())),
18987                    ("1".to_string(), AvroValue::String("one".to_string())),
18988                ])),
18989            ),
18990            (
18991                "nested".to_string(),
18992                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
18993                    "enabled".to_string(),
18994                    AvroValue::Boolean(true),
18995                )]))]),
18996            ),
18997            (
18998                "projection_collisions".to_string(),
18999                AvroValue::Array(projection_collision_probe()),
19000            ),
19001        ]))
19002    }
19003
19004    fn projection_collision_probe() -> Vec<AvroValue> {
19005        vec![
19006            AvroValue::Map(BTreeMap::from([
19007                ("$type".to_string(), AvroValue::String("bytes".to_string())),
19008                (
19009                    "base64".to_string(),
19010                    AvroValue::String("ordinary user text".to_string()),
19011                ),
19012            ])),
19013            AvroValue::Map(BTreeMap::from([
19014                ("$type".to_string(), AvroValue::String("map".to_string())),
19015                (
19016                    "entries".to_string(),
19017                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
19018                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
19019                        (
19020                            "value".to_string(),
19021                            AvroValue::String("user map".to_string()),
19022                        ),
19023                    ]))]),
19024                ),
19025            ])),
19026        ]
19027    }
19028
19029    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19030    struct TypedContract {
19031        nested: TypedNested,
19032        mode: TypedMode,
19033        optional: Option<String>,
19034        absent: Option<String>,
19035        items: Vec<i64>,
19036        labels: BTreeMap<String, String>,
19037        bytes: serde_bytes::ByteBuf,
19038        signed: i64,
19039        finite: f64,
19040    }
19041
19042    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19043    struct TypedNested {
19044        enabled: bool,
19045    }
19046
19047    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19048    enum TypedMode {
19049        Detailed { label: String },
19050    }
19051
19052    fn typed_contract() -> TypedContract {
19053        TypedContract {
19054            nested: TypedNested { enabled: true },
19055            mode: TypedMode::Detailed {
19056                label: "compiler-checked".to_string(),
19057            },
19058            optional: Some("present".to_string()),
19059            absent: None,
19060            items: vec![i64::MIN, 0, i64::MAX],
19061            labels: BTreeMap::from([
19062                ("language".to_string(), "rust".to_string()),
19063                ("wire".to_string(), "avro".to_string()),
19064            ]),
19065            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
19066            signed: -9_223_372_036_854_775_000,
19067            finite: 12.5,
19068        }
19069    }
19070
19071    #[derive(Clone, Debug, Default, PartialEq)]
19072    struct ReplayCounterState {
19073        loaded: Option<String>,
19074        count: i64,
19075        finished: bool,
19076    }
19077
19078    fn replay_counter_worker() -> Worker {
19079        let client = Client::new("http://127.0.0.1:8080").expect("client");
19080        let mut worker = Worker::new(client, "rust-workers");
19081        worker.register_replayed_workflow(
19082            "replay-counter",
19083            ReplayCounterState::default,
19084            |ctx, _input, state| async move {
19085                let loaded = ctx.activity("load-counter", json!([])).await?;
19086                state.update(|current| {
19087                    current.loaded = loaded.as_str().map(str::to_string);
19088                })?;
19089                for _ in 0..2 {
19090                    let signal = ctx.wait_signal("increment").await?;
19091                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
19092                    state.update(|current| current.count += amount)?;
19093                }
19094                state.update(|current| current.finished = true)?;
19095                state.read(|current| Ok(json!(current.count)))?
19096            },
19097        );
19098        worker.register_replayed_query::<ReplayCounterState, _, _>(
19099            "replay-counter",
19100            "current",
19101            |_ctx, state, _args| async move {
19102                Ok(json!({
19103                    "loaded": state.loaded,
19104                    "count": state.count,
19105                    "finished": state.finished,
19106                }))
19107            },
19108        );
19109        worker.register_replayed_query::<ReplayCounterState, _, _>(
19110            "replay-counter",
19111            "detached-mutation",
19112            |_ctx, state, _args| async move {
19113                let mut detached = (*state).clone();
19114                detached.count = 999;
19115                Ok(json!(detached.count))
19116            },
19117        );
19118        worker.register_replayed_query::<ReplayCounterState, _, _>(
19119            "replay-counter",
19120            "failed-mutation",
19121            |_ctx, state, _args| async move {
19122                let mut detached = (*state).clone();
19123                detached.count = 999;
19124                Err(Error::WorkerLoop("query refused".to_string()))
19125            },
19126        );
19127        worker
19128    }
19129
19130    fn replay_counter_query(
19131        query_name: &str,
19132        history_events: Value,
19133        run_status: &str,
19134    ) -> QueryTask {
19135        let arguments = fixture_envelope(json!([]));
19136        serde_json::from_value(json!({
19137            "query_task_id": format!("query-{query_name}"),
19138            "workflow_type": "replay-counter",
19139            "query_name": query_name,
19140            "payload_codec": DEFAULT_CODEC,
19141            "workflow_arguments": arguments.clone(),
19142            "query_arguments": arguments,
19143            "history_events": history_events,
19144            "run_status": run_status,
19145        }))
19146        .expect("query task")
19147    }
19148
19149    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
19150        workflow_context_with_codec(history, DEFAULT_CODEC)
19151    }
19152
19153    fn workflow_context_with_codec(
19154        history: Vec<HistoryEvent>,
19155        payload_codec: &str,
19156    ) -> WorkflowContext {
19157        WorkflowContext {
19158            cancellation_scope_id: "root".into(),
19159            state: Arc::new(Mutex::new(
19160                WorkflowState::new_with_identity(
19161                    history,
19162                    None,
19163                    None,
19164                    "rust-workers".to_string(),
19165                    payload_codec.to_string(),
19166                    None,
19167                )
19168                .expect("valid workflow history"),
19169            )),
19170        }
19171    }
19172
19173    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
19174        HistoryEvent {
19175            event_type: event_type.to_string(),
19176            payload,
19177            raw: HashMap::new(),
19178        }
19179    }
19180
19181    fn parallel_path_entry(
19182        kind: &str,
19183        base: u64,
19184        size: usize,
19185        index: usize,
19186    ) -> ParallelGroupMetadata {
19187        parallel_group_entry(base, size, index, kind)
19188    }
19189
19190    fn parallel_history_event(
19191        event_type: &str,
19192        sequence: u64,
19193        identity_field: &str,
19194        identity: &str,
19195        path: Vec<ParallelGroupMetadata>,
19196        result: Option<Value>,
19197    ) -> HistoryEvent {
19198        let mut payload = serde_json::Map::from_iter([
19199            ("sequence".to_string(), json!(sequence)),
19200            (identity_field.to_string(), json!(identity)),
19201        ]);
19202        let inner = path.last().expect("parallel history path");
19203        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
19204        payload.insert("parallel_group_path".to_string(), json!(path));
19205        if let Some(result) = result {
19206            let field = if event_type == "ChildRunCompleted" {
19207                "result"
19208            } else {
19209                "result"
19210            };
19211            payload.insert(field.to_string(), fixture_envelope(result));
19212            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
19213        }
19214        history_event(event_type, Value::Object(payload))
19215    }
19216
19217    fn nested_parallel_operations() -> Vec<ParallelOperation> {
19218        vec![
19219            ParallelOperation::activity("first", json!([])),
19220            ParallelOperation::group(vec![
19221                ParallelOperation::child_workflow(
19222                    "second",
19223                    ChildWorkflowOptions::new("child-workers"),
19224                    json!([]),
19225                ),
19226                ParallelOperation::activity("third", json!([])),
19227            ]),
19228        ]
19229    }
19230
19231    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
19232        let outer = [
19233            parallel_path_entry("mixed", 1, 3, 0),
19234            parallel_path_entry("mixed", 1, 3, 1),
19235            parallel_path_entry("mixed", 1, 3, 2),
19236        ];
19237        [
19238            vec![outer[0].clone()],
19239            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
19240            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
19241        ]
19242    }
19243
19244    #[test]
19245    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
19246        let ctx = workflow_context(Vec::new());
19247        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19248        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19249
19250        assert!(matches!(
19251            call.as_mut().poll(&mut task_context),
19252            Poll::Pending
19253        ));
19254        let commands = ctx.take_commands().expect("parallel commands");
19255        assert_eq!(
19256            commands
19257                .iter()
19258                .map(|command| command["type"].as_str().unwrap_or_default())
19259                .collect::<Vec<_>>(),
19260            [
19261                "schedule_activity",
19262                "start_child_workflow",
19263                "schedule_activity"
19264            ]
19265        );
19266        let paths = nested_parallel_paths();
19267        for (command, path) in commands.iter().zip(paths) {
19268            assert_eq!(command["parallel_group_path"], json!(path));
19269            assert_eq!(
19270                command["parallel_group_id"],
19271                json!(path.last().expect("inner group").parallel_group_id)
19272            );
19273        }
19274    }
19275
19276    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
19277        let paths = nested_parallel_paths();
19278        let third = parallel_history_event(
19279            "ActivityCompleted",
19280            3,
19281            "activity_type",
19282            "third",
19283            paths[2].clone(),
19284            Some(json!("three")),
19285        );
19286        vec![
19287            parallel_history_event(
19288                "ActivityCompleted",
19289                1,
19290                "activity_type",
19291                "first",
19292                paths[0].clone(),
19293                Some(json!("one")),
19294            ),
19295            parallel_history_event(
19296                "ChildWorkflowScheduled",
19297                2,
19298                "child_workflow_type",
19299                "second",
19300                paths[1].clone(),
19301                None,
19302            ),
19303            parallel_history_event(
19304                "ChildRunCompleted",
19305                2,
19306                "child_workflow_type",
19307                "second",
19308                paths[1].clone(),
19309                Some(json!("two")),
19310            ),
19311            third.clone(),
19312            third,
19313        ]
19314    }
19315
19316    #[test]
19317    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
19318        for _restart_or_completed_replay in 0..2 {
19319            let ctx = workflow_context(completed_nested_parallel_history());
19320            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19321            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19322            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
19323                panic!("completed nested parallel history must replay");
19324            };
19325            assert_eq!(
19326                results,
19327                vec![
19328                    ParallelResult::Activity(json!("one")),
19329                    ParallelResult::Group(vec![
19330                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
19331                            parent: WorkflowIdentity {
19332                                workflow_id: None,
19333                                run_id: None,
19334                            },
19335                            child: WorkflowIdentity {
19336                                workflow_id: None,
19337                                run_id: None,
19338                            },
19339                            child_workflow_type: Some("second".to_string()),
19340                            result: json!("two"),
19341                        }),
19342                        ParallelResult::Activity(json!("three")),
19343                    ]),
19344                ]
19345            );
19346            assert!(ctx.take_commands().expect("commands").is_empty());
19347            ctx.ensure_history_consumed().expect("history consumed");
19348        }
19349    }
19350
19351    #[test]
19352    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
19353        let paths = nested_parallel_paths();
19354        let history = vec![
19355            parallel_history_event(
19356                "ActivityCompleted",
19357                1,
19358                "activity_type",
19359                "first",
19360                paths[0].clone(),
19361                Some(json!("one")),
19362            ),
19363            parallel_history_event(
19364                "ChildWorkflowScheduled",
19365                2,
19366                "child_workflow_type",
19367                "second",
19368                paths[1].clone(),
19369                None,
19370            ),
19371            parallel_history_event(
19372                "ChildRunFailed",
19373                2,
19374                "child_workflow_type",
19375                "second",
19376                paths[1].clone(),
19377                None,
19378            ),
19379            parallel_history_event(
19380                "ActivityCompleted",
19381                3,
19382                "activity_type",
19383                "third",
19384                paths[2].clone(),
19385                Some(json!("late")),
19386            ),
19387        ];
19388        let ctx = workflow_context(history);
19389        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19390        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19391        let outcome = call.as_mut().poll(&mut task_context);
19392        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
19393            panic!("one failed child must return a typed partial failure: {outcome:?}");
19394        };
19395        assert_eq!(failure.member_path, [1, 0]);
19396        assert_eq!(failure.group_id, "parallel-calls:1:3");
19397        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
19398        assert_eq!(
19399            failure
19400                .completed
19401                .iter()
19402                .map(|completion| completion.member_path.clone())
19403                .collect::<Vec<_>>(),
19404            [vec![0], vec![1, 1]]
19405        );
19406    }
19407
19408    #[test]
19409    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
19410        let paths = nested_parallel_paths();
19411        let history = vec![
19412            parallel_history_event(
19413                "ActivityScheduled",
19414                1,
19415                "activity_type",
19416                "first",
19417                paths[0].clone(),
19418                None,
19419            ),
19420            parallel_history_event(
19421                "ChildWorkflowScheduled",
19422                2,
19423                "child_workflow_type",
19424                "second",
19425                paths[1].clone(),
19426                None,
19427            ),
19428            parallel_history_event(
19429                "ActivityScheduled",
19430                3,
19431                "activity_type",
19432                "third",
19433                paths[2].clone(),
19434                None,
19435            ),
19436        ];
19437        for _restart in 0..2 {
19438            let ctx = workflow_context(history.clone());
19439            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19440            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19441            let outcome = call.as_mut().poll(&mut task_context);
19442            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
19443            assert!(ctx.take_commands().expect("commands").is_empty());
19444        }
19445    }
19446
19447    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
19448        vec![selection_group_entry(
19449            1,
19450            2,
19451            index,
19452            "activity",
19453            &SelectionMemberMetadata {
19454                key: SelectionKey::Name(key.to_string()),
19455                index,
19456                base_sequence: index as u64 + 1,
19457                size: 1,
19458                kind: "activity".to_string(),
19459            },
19460        )]
19461    }
19462
19463    fn selection_activity_event(
19464        event_type: &str,
19465        index: usize,
19466        key: &str,
19467        result: Option<Value>,
19468    ) -> HistoryEvent {
19469        let sequence = index as u64 + 1;
19470        let mut event = parallel_history_event(
19471            event_type,
19472            sequence,
19473            "activity_type",
19474            &format!("{key}-activity"),
19475            selection_path(index, key),
19476            result,
19477        );
19478        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
19479        event.raw.insert(
19480            "id".to_string(),
19481            json!(if event_type == "ActivityCompleted" {
19482                format!("event-{key}")
19483            } else {
19484                format!("{event_type}-{key}")
19485            }),
19486        );
19487        event
19488    }
19489
19490    fn selection_winner_marker() -> HistoryEvent {
19491        history_event(
19492            "SelectionResolved",
19493            json!({
19494                "selection_group_id": "select-calls:1:2",
19495                "selection_group_base_sequence": 1,
19496                "selection_group_size": 2,
19497                "member_key": "fast",
19498                "member_index": 1,
19499                "member_base_sequence": 2,
19500                "member_size": 1,
19501                "operation_kind": "activity",
19502                "operation_identity": "activity-fast",
19503                "outcome": "completed",
19504                "resolution_event_id": "event-fast",
19505                "resolution_event_type": "ActivityCompleted",
19506            }),
19507        )
19508    }
19509
19510    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
19511        ctx.select_keyed(vec![
19512            (
19513                "slow",
19514                ParallelOperation::activity_with_options(
19515                    "slow-activity",
19516                    ActivityOptions::new().task_queue("default"),
19517                    json!([]),
19518                ),
19519            ),
19520            (
19521                "fast",
19522                ParallelOperation::activity_with_options(
19523                    "fast-activity",
19524                    ActivityOptions::new().task_queue("default"),
19525                    json!([]),
19526                ),
19527            ),
19528        ])
19529    }
19530
19531    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
19532        let ctx = workflow_context(history);
19533        let mut call = Box::pin(keyed_activity_selection(&ctx));
19534        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19535        let selected = match call.as_mut().poll(&mut task_context) {
19536            Poll::Ready(Ok(selected)) => selected,
19537            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
19538            Poll::Pending => panic!("persisted selection winner must replay without pending"),
19539        };
19540        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
19541        assert_eq!(
19542            selected.value,
19543            Some(ParallelResult::Activity(json!("winner-value")))
19544        );
19545        let slow = selected
19546            .handle(&SelectionKey::Name("slow".to_string()))
19547            .expect("slow handle")
19548            .clone();
19549        let mut await_slow = Box::pin(slow.await_result());
19550        assert!(matches!(
19551            await_slow.as_mut().poll(&mut task_context),
19552            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
19553        ));
19554        assert!(ctx.take_commands().expect("commands").is_empty());
19555    }
19556
19557    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
19558
19559    fn canonical_selection_history() -> Vec<HistoryEvent> {
19560        const FIXTURE: &[u8] =
19561            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
19562        assert_eq!(
19563            format!("{:x}", Sha256::digest(FIXTURE)),
19564            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
19565        );
19566        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
19567
19568        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
19569    }
19570
19571    #[test]
19572    fn selection_fresh_process_entrypoint() {
19573        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
19574            return;
19575        };
19576        let persisted = fs::read(path).expect("persisted selection history");
19577        assert_eq!(
19578            format!("{:x}", Sha256::digest(&persisted)),
19579            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
19580        );
19581        let fixture: Value =
19582            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
19583        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
19584            .expect("valid persisted selection history");
19585
19586        assert_persisted_selection_replay(history);
19587    }
19588
19589    #[test]
19590    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
19591        let ctx = workflow_context(Vec::new());
19592        let mut call = Box::pin(keyed_activity_selection(&ctx));
19593        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19594
19595        assert!(matches!(
19596            call.as_mut().poll(&mut task_context),
19597            Poll::Pending
19598        ));
19599        let commands = ctx.take_commands().expect("selection commands");
19600        assert_eq!(commands.len(), 2);
19601        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
19602        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
19603        assert!(commands.iter().all(|command| {
19604            command["parallel_group_id"] == json!("select-calls:1:2")
19605                && command["parallel_group_mode"] == json!("select")
19606        }));
19607    }
19608
19609    #[test]
19610    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
19611        let ctx = workflow_context(Vec::new());
19612        let mut invalid = Box::pin(ctx.select_keyed(vec![(
19613            "",
19614            ParallelOperation::activity("invalid", json!([])),
19615        )]));
19616        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19617        assert!(matches!(
19618            invalid.as_mut().poll(&mut task_context),
19619            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
19620                reason: "selection_key_invalid",
19621                ..
19622            })))
19623        ));
19624
19625        for invalid_key in [json!(""), json!(-1)] {
19626            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
19627            event.payload["selection_member_key"] = invalid_key.clone();
19628            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
19629            assert!(matches!(
19630                WorkflowState::new_with_identity(
19631                    vec![event],
19632                    None,
19633                    None,
19634                    "rust-workers".to_string(),
19635                    DEFAULT_CODEC.to_string(),
19636                    None,
19637                ),
19638                Err(Error::NonDeterministicReplay(_))
19639            ));
19640        }
19641    }
19642
19643    #[test]
19644    fn selection_preserves_valid_named_and_numeric_keys() {
19645        let ctx = workflow_context(Vec::new());
19646        let mut selection = Box::pin(ctx.select_keyed(vec![
19647            (
19648                SelectionKey::Index(0),
19649                ParallelOperation::activity("numeric", json!([])),
19650            ),
19651            (
19652                SelectionKey::Name("named".to_string()),
19653                ParallelOperation::timer(Duration::from_secs(1)),
19654            ),
19655        ]));
19656        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19657
19658        assert!(matches!(
19659            selection.as_mut().poll(&mut task_context),
19660            Poll::Pending
19661        ));
19662        let commands = ctx.take_commands().expect("selection commands");
19663        assert_eq!(commands[0]["selection_member_key"], json!(0));
19664        assert_eq!(commands[1]["selection_member_key"], json!("named"));
19665    }
19666
19667    #[test]
19668    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
19669        let history = canonical_selection_history();
19670        assert_persisted_selection_replay(history.clone());
19671
19672        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19673            .join("tests/fixtures/durable_selection_runtime_history.json");
19674        let output =
19675            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
19676                .args([
19677                    "--exact",
19678                    "tests::selection_fresh_process_entrypoint",
19679                    "--nocapture",
19680                ])
19681                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
19682                .output()
19683                .expect("run fresh selection replay process");
19684
19685        assert!(
19686            output.status.success(),
19687            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
19688            String::from_utf8_lossy(&output.stdout),
19689            String::from_utf8_lossy(&output.stderr),
19690        );
19691    }
19692
19693    #[test]
19694    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
19695        let mut history = canonical_selection_history();
19696        history.retain(|event| event.event_type != "SelectionResolved");
19697        let ctx = workflow_context(history);
19698        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19699        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19700
19701        assert!(matches!(
19702            selection.as_mut().poll(&mut task_context),
19703            Poll::Pending
19704        ));
19705        assert!(ctx.take_commands().expect("commands").is_empty());
19706        assert!(
19707            ctx.matched_recorded_pending()
19708                .expect("selection pending state"),
19709            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
19710        );
19711    }
19712
19713    #[test]
19714    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
19715        for (terminal_event, predicate_satisfied, timeout_seconds) in [
19716            ("ConditionWaitSatisfied", true, None),
19717            ("ConditionWaitTimedOut", false, Some(0)),
19718        ] {
19719            let member = SelectionMemberMetadata {
19720                key: SelectionKey::Name("condition".to_string()),
19721                index: 0,
19722                base_sequence: 1,
19723                size: 1,
19724                kind: "condition".to_string(),
19725            };
19726            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
19727            let mut payload = json!({
19728                "sequence": 1,
19729                "condition_wait_id": "condition-1",
19730                "condition_wait_occurrence_id": "rust:condition-wait:0",
19731                "condition_key": "ready",
19732                "condition_definition_fingerprint": "sha256:ready-v1",
19733                "parallel_group_path": path,
19734            });
19735            payload
19736                .as_object_mut()
19737                .expect("condition history payload")
19738                .extend(
19739                    serde_json::to_value(&path[0])
19740                        .expect("condition selection metadata")
19741                        .as_object()
19742                        .expect("condition selection metadata object")
19743                        .clone(),
19744                );
19745            if let Some(timeout_seconds) = timeout_seconds {
19746                payload["timeout_seconds"] = json!(timeout_seconds);
19747            }
19748            let history = vec![
19749                history_event("ConditionWaitOpened", payload.clone()),
19750                history_event(terminal_event, payload),
19751            ];
19752            let ctx = workflow_context(history);
19753            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
19754            if timeout_seconds.is_some() {
19755                options = options.timeout(Duration::ZERO);
19756            }
19757            let mut selection = Box::pin(ctx.select_keyed(vec![(
19758                "condition",
19759                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
19760            )]));
19761            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19762
19763            assert!(matches!(
19764                selection.as_mut().poll(&mut task_context),
19765                Poll::Pending
19766            ));
19767            assert!(ctx.take_commands().expect("commands").is_empty());
19768            assert!(
19769                ctx.matched_recorded_pending()
19770                    .expect("condition selection pending state"),
19771                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
19772            );
19773        }
19774    }
19775
19776    #[test]
19777    fn selection_immediate_condition_members_open_a_durable_wait() {
19778        for predicate_satisfied in [true, false] {
19779            let ctx = workflow_context(Vec::new());
19780            let mut selection = Box::pin(ctx.select_keyed(vec![(
19781                "condition",
19782                ParallelOperation::condition(
19783                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
19784                    move || Ok(predicate_satisfied),
19785                ),
19786            )]));
19787            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19788
19789            assert!(matches!(
19790                selection.as_mut().poll(&mut task_context),
19791                Poll::Pending
19792            ));
19793            let commands = ctx.take_commands().expect("condition selection command");
19794            assert_eq!(commands.len(), 1);
19795            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
19796            assert_eq!(commands[0]["timeout_seconds"], json!(0));
19797            assert_eq!(
19798                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
19799                json!("select")
19800            );
19801        }
19802    }
19803
19804    #[test]
19805    fn selection_loser_cancellation_is_explicit_and_idempotent() {
19806        let history = vec![
19807            selection_activity_event("ActivityScheduled", 0, "slow", None),
19808            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19809            selection_winner_marker(),
19810        ];
19811        let ctx = workflow_context(history.clone());
19812        let mut call = Box::pin(keyed_activity_selection(&ctx));
19813        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19814        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19815            panic!("winner must replay");
19816        };
19817        let slow = selected
19818            .handle(&SelectionKey::Name("slow".to_string()))
19819            .expect("slow handle")
19820            .clone();
19821        let mut cancel = Box::pin(slow.cancel());
19822        assert!(matches!(
19823            cancel.as_mut().poll(&mut task_context),
19824            Poll::Ready(Ok(()))
19825        ));
19826        assert!(matches!(
19827            cancel.as_mut().poll(&mut task_context),
19828            Poll::Ready(Ok(()))
19829        ));
19830        let mut outcome = Box::pin(slow.await_result());
19831        assert!(matches!(
19832            outcome.as_mut().poll(&mut task_context),
19833            Poll::Pending
19834        ));
19835        let commands = ctx.take_commands().expect("cancel command");
19836        assert_eq!(commands.len(), 1);
19837        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
19838        assert_eq!(commands[0]["member_key"], json!("slow"));
19839
19840        let mut cancelled_history = history;
19841        cancelled_history.push(history_event(
19842            "SelectionOperationCancelled",
19843            json!({
19844                "selection_group_id": "select-calls:1:2",
19845                "member_key": "slow",
19846                "member_index": 0,
19847                "member_base_sequence": 1,
19848                "member_size": 1,
19849                "operation_kind": "activity",
19850                "operation_identity": "activity-slow",
19851                "cancelled_at": "2026-08-27T00:00:00Z",
19852            }),
19853        ));
19854        let replayed = workflow_context(cancelled_history);
19855        let mut call = Box::pin(keyed_activity_selection(&replayed));
19856        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19857            panic!("winner must replay after cancellation");
19858        };
19859        let slow = selected
19860            .handle(&SelectionKey::Name("slow".to_string()))
19861            .expect("slow handle")
19862            .clone();
19863        let mut cancel = Box::pin(slow.cancel());
19864        assert!(matches!(
19865            cancel.as_mut().poll(&mut task_context),
19866            Poll::Ready(Ok(()))
19867        ));
19868        assert!(replayed.take_commands().expect("commands").is_empty());
19869    }
19870
19871    #[test]
19872    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
19873        let base_history = vec![
19874            selection_activity_event("ActivityScheduled", 0, "slow", None),
19875            selection_activity_event("ActivityScheduled", 1, "fast", None),
19876            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19877            selection_winner_marker(),
19878        ];
19879        for (field, corrupt) in [
19880            ("member_key", json!("fast")),
19881            ("member_index", json!(1)),
19882            ("member_base_sequence", json!(3)),
19883            ("member_size", json!(2)),
19884            ("operation_kind", json!("timer")),
19885            ("operation_identity", json!("forged")),
19886        ] {
19887            let mut cancellation = json!({
19888                "selection_group_id": "select-calls:1:2",
19889                "member_key": "slow",
19890                "member_index": 0,
19891                "member_base_sequence": 1,
19892                "member_size": 1,
19893                "operation_kind": "activity",
19894                "operation_identity": "activity-slow",
19895            });
19896            cancellation[field] = corrupt;
19897            let mut history = base_history.clone();
19898            history.push(history_event("SelectionOperationCancelled", cancellation));
19899            let ctx = workflow_context(history);
19900            let mut selection = Box::pin(keyed_activity_selection(&ctx));
19901            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19902
19903            assert!(matches!(
19904                selection.as_mut().poll(&mut task_context),
19905                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19906            ));
19907        }
19908    }
19909
19910    #[test]
19911    fn selection_child_identity_prefers_the_durable_run_id() {
19912        let ctx = workflow_context(vec![history_event(
19913            "ChildWorkflowScheduled",
19914            json!({
19915                "sequence": 1,
19916                "child_workflow_type": "child",
19917                "child_workflow_instance_id": "child-instance",
19918                "child_workflow_run_id": "child-run",
19919            }),
19920        )]);
19921        let state = ctx.state.lock().expect("workflow state");
19922
19923        assert_eq!(
19924            selection_operation_identity(&state, "child", 1, 1),
19925            "child-run"
19926        );
19927    }
19928
19929    #[test]
19930    fn selection_activity_identity_requires_canonical_execution_id() {
19931        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
19932        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
19933        let mut fast_completed =
19934            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
19935        for event in [&mut fast_open, &mut fast_completed] {
19936            event
19937                .payload
19938                .as_object_mut()
19939                .expect("activity payload")
19940                .remove("activity_execution_id");
19941            event.payload["activity_id"] = json!("forged-activity-id");
19942        }
19943        let mut marker = selection_winner_marker();
19944        marker.payload["operation_identity"] = json!("forged-activity-id");
19945        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
19946        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19947        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19948
19949        assert!(matches!(
19950            selection.as_mut().poll(&mut task_context),
19951            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19952        ));
19953    }
19954
19955    #[test]
19956    fn selection_completion_before_cancellation_remains_awaitable() {
19957        let history = vec![
19958            selection_activity_event("ActivityScheduled", 0, "slow", None),
19959            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19960            selection_winner_marker(),
19961            selection_activity_event(
19962                "ActivityCompleted",
19963                0,
19964                "slow",
19965                Some(json!("completed-first")),
19966            ),
19967        ];
19968        let ctx = workflow_context(history);
19969        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19970        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19971        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19972            panic!("winner must replay");
19973        };
19974        let slow = selected
19975            .handle(&SelectionKey::Name("slow".to_string()))
19976            .expect("slow handle")
19977            .clone();
19978        let mut cancel = Box::pin(slow.cancel());
19979        assert!(matches!(
19980            cancel.as_mut().poll(&mut task_context),
19981            Poll::Ready(Ok(()))
19982        ));
19983        let mut await_slow = Box::pin(slow.await_result());
19984        assert!(matches!(
19985            await_slow.as_mut().poll(&mut task_context),
19986            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
19987        ));
19988        let commands = ctx.take_commands().expect("commands");
19989        assert!(commands.is_empty());
19990    }
19991
19992    #[test]
19993    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
19994        let nested_member = SelectionMemberMetadata {
19995            key: SelectionKey::Name("nested".to_string()),
19996            index: 0,
19997            base_sequence: 1,
19998            size: 2,
19999            kind: "group".to_string(),
20000        };
20001        let deadline_member = SelectionMemberMetadata {
20002            key: SelectionKey::Name("deadline".to_string()),
20003            index: 1,
20004            base_sequence: 3,
20005            size: 1,
20006            kind: "timer".to_string(),
20007        };
20008        let nested_paths = [
20009            vec![
20010                selection_group_entry(1, 3, 0, "mixed", &nested_member),
20011                parallel_group_entry(1, 2, 0, "activity"),
20012            ],
20013            vec![
20014                selection_group_entry(1, 3, 1, "mixed", &nested_member),
20015                parallel_group_entry(1, 2, 1, "activity"),
20016            ],
20017        ];
20018        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
20019        let mut timer_fired = parallel_history_event(
20020            "TimerFired",
20021            3,
20022            "timer_id",
20023            "timer-3",
20024            deadline_path.clone(),
20025            None,
20026        );
20027        timer_fired.payload["delay_seconds"] = json!(0);
20028        timer_fired
20029            .raw
20030            .insert("id".to_string(), json!("timer-fired"));
20031        let mut timer_scheduled = parallel_history_event(
20032            "TimerScheduled",
20033            3,
20034            "timer_id",
20035            "timer-3",
20036            deadline_path,
20037            None,
20038        );
20039        timer_scheduled.payload["delay_seconds"] = json!(0);
20040        let history = vec![
20041            parallel_history_event(
20042                "ActivityScheduled",
20043                1,
20044                "activity_type",
20045                "nested-first",
20046                nested_paths[0].clone(),
20047                None,
20048            ),
20049            parallel_history_event(
20050                "ActivityScheduled",
20051                2,
20052                "activity_type",
20053                "nested-second",
20054                nested_paths[1].clone(),
20055                None,
20056            ),
20057            timer_scheduled,
20058            timer_fired,
20059            history_event(
20060                "SelectionResolved",
20061                json!({
20062                    "selection_group_id": "select-calls:1:3",
20063                    "selection_group_base_sequence": 1,
20064                    "selection_group_size": 3,
20065                    "member_key": "deadline",
20066                    "member_index": 1,
20067                    "member_base_sequence": 3,
20068                    "member_size": 1,
20069                    "operation_kind": "timer",
20070                    "operation_identity": "timer-3",
20071                    "outcome": "completed",
20072                    "resolution_event_id": "timer-fired",
20073                    "resolution_event_type": "TimerFired",
20074                }),
20075            ),
20076            parallel_history_event(
20077                "ActivityFailed",
20078                2,
20079                "activity_type",
20080                "nested-second",
20081                nested_paths[1].clone(),
20082                None,
20083            ),
20084        ];
20085        let ctx = workflow_context(history);
20086        let mut selection = Box::pin(ctx.select_keyed(vec![
20087            (
20088                "nested",
20089                ParallelOperation::group(vec![
20090                    ParallelOperation::activity("nested-first", json!([])),
20091                    ParallelOperation::activity("nested-second", json!([])),
20092                ]),
20093            ),
20094            ("deadline", ParallelOperation::timer(Duration::ZERO)),
20095        ]));
20096        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20097        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
20098            panic!("deadline winner must replay");
20099        };
20100        let nested = selected
20101            .handle(&SelectionKey::Name("nested".to_string()))
20102            .expect("nested handle")
20103            .clone();
20104        let mut cancel = Box::pin(nested.cancel());
20105        assert!(matches!(
20106            cancel.as_mut().poll(&mut task_context),
20107            Poll::Ready(Ok(()))
20108        ));
20109        let mut await_nested = Box::pin(nested.await_result());
20110
20111        assert!(matches!(
20112            await_nested.as_mut().poll(&mut task_context),
20113            Poll::Ready(Err(Error::ActivityFailed(_)))
20114        ));
20115        assert!(ctx.take_commands().expect("commands").is_empty());
20116    }
20117
20118    #[test]
20119    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
20120        let ctx = workflow_context(Vec::new());
20121        let mut call = Box::pin(ctx.select(vec![
20122            ParallelOperation::child_workflow(
20123                "child",
20124                ChildWorkflowOptions::new("children"),
20125                json!([]),
20126            ),
20127            ParallelOperation::timer(Duration::from_secs(30)),
20128            ParallelOperation::signal("approval"),
20129            ParallelOperation::condition(
20130                ConditionWaitOptions::new("ready", "sha256:ready"),
20131                || Ok(false),
20132            ),
20133            ParallelOperation::group(vec![
20134                ParallelOperation::activity("nested-one", json!([])),
20135                ParallelOperation::activity("nested-two", json!([])),
20136            ]),
20137        ]));
20138        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20139        assert!(matches!(
20140            call.as_mut().poll(&mut task_context),
20141            Poll::Pending
20142        ));
20143        let commands = ctx.take_commands().expect("selection commands");
20144        assert_eq!(
20145            commands
20146                .iter()
20147                .map(|command| command["type"].as_str().unwrap_or_default())
20148                .collect::<Vec<_>>(),
20149            [
20150                "start_child_workflow",
20151                "start_timer",
20152                "open_signal_wait",
20153                "open_condition_wait",
20154                "schedule_activity",
20155                "schedule_activity",
20156            ]
20157        );
20158        assert!(commands.iter().all(|command| {
20159            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
20160        }));
20161        assert_eq!(
20162            commands[4]["parallel_group_path"].as_array().map(Vec::len),
20163            Some(2)
20164        );
20165        assert_eq!(
20166            commands[4]["parallel_group_path"][0]["selection_member_kind"],
20167            json!("group")
20168        );
20169        assert_eq!(
20170            commands[5]["parallel_group_path"][0]["selection_member_kind"],
20171            json!("group")
20172        );
20173
20174        let one_leaf_ctx = workflow_context(Vec::new());
20175        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
20176            ParallelOperation::activity("nested-only", json!([])),
20177        ])]));
20178        assert!(matches!(
20179            one_leaf.as_mut().poll(&mut task_context),
20180            Poll::Pending
20181        ));
20182        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
20183        assert_eq!(one_leaf_commands.len(), 1);
20184        assert_eq!(
20185            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
20186            json!("group")
20187        );
20188        assert_eq!(
20189            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
20190            json!(1)
20191        );
20192    }
20193
20194    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
20195        let mut saga = ctx.saga();
20196        let outcome = async {
20197            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
20198            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
20199            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
20200            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
20201            ctx.activity("trip.charge", json!([])).await?;
20202            Ok(json!({"status": "booked"}))
20203        }
20204        .await;
20205        saga.finish(outcome).await
20206    }
20207
20208    fn saga_activity(
20209        event_type: &str,
20210        sequence: u64,
20211        activity_type: &str,
20212        result: Option<Value>,
20213    ) -> HistoryEvent {
20214        let mut payload = json!({
20215            "sequence": sequence,
20216            "activity_type": activity_type,
20217            "message": format!("{activity_type} failed"),
20218            "exception_type": "PlannedFailure",
20219            "non_retryable": true,
20220        });
20221        if let Some(result) = result {
20222            payload["result"] = fixture_envelope(result);
20223        }
20224        history_event(event_type, payload)
20225    }
20226
20227    #[test]
20228    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
20229        let completed_hotel_compensation = saga_activity(
20230            "ActivityCompleted",
20231            4,
20232            "trip.cancel-hotel",
20233            Some(Value::Null),
20234        );
20235        let history = vec![
20236            saga_activity(
20237                "ActivityCompleted",
20238                1,
20239                "trip.reserve-flight",
20240                Some(json!("flight-1")),
20241            ),
20242            saga_activity(
20243                "ActivityCompleted",
20244                2,
20245                "trip.reserve-hotel",
20246                Some(json!("hotel-1")),
20247            ),
20248            saga_activity("ActivityFailed", 3, "trip.charge", None),
20249            completed_hotel_compensation.clone(),
20250            completed_hotel_compensation,
20251        ];
20252
20253        for _restart in 0..2 {
20254            let ctx = workflow_context(history.clone());
20255            let mut future = Box::pin(trip_saga(ctx.clone()));
20256            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20257            assert!(matches!(
20258                future.as_mut().poll(&mut task_context),
20259                Poll::Pending
20260            ));
20261            let commands = ctx.take_commands().expect("compensation command");
20262            assert_eq!(commands.len(), 1);
20263            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
20264        }
20265    }
20266
20267    #[test]
20268    fn saga_compensation_failure_preserves_both_typed_failures() {
20269        let history = vec![
20270            saga_activity(
20271                "ActivityCompleted",
20272                1,
20273                "trip.reserve-flight",
20274                Some(json!("flight-1")),
20275            ),
20276            saga_activity(
20277                "ActivityCompleted",
20278                2,
20279                "trip.reserve-hotel",
20280                Some(json!("hotel-1")),
20281            ),
20282            saga_activity("ActivityFailed", 3, "trip.charge", None),
20283            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
20284        ];
20285        let ctx = workflow_context(history);
20286        let mut future = Box::pin(trip_saga(ctx));
20287        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20288        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
20289            future.as_mut().poll(&mut task_context)
20290        else {
20291            panic!("compensation failure must remain structured");
20292        };
20293        assert!(matches!(
20294            *failure.initiating_failure,
20295            Error::ActivityFailed(_)
20296        ));
20297        assert!(matches!(
20298            *failure.compensation_failure,
20299            Error::ActivityFailed(_)
20300        ));
20301        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
20302        assert_eq!(failure.compensation_registration_order, 2);
20303    }
20304
20305    #[test]
20306    fn saga_compensates_cooperative_cancellation() {
20307        let ctx = workflow_context(vec![saga_activity(
20308            "ActivityCompleted",
20309            1,
20310            "trip.reserve-flight",
20311            Some(json!("flight-1")),
20312        )]);
20313        ctx.state.lock().expect("state").cancel_requested = true;
20314        let run = {
20315            let ctx = ctx.clone();
20316            async move {
20317                let mut saga = ctx.saga();
20318                let outcome = async {
20319                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
20320                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
20321                    ctx.throw_if_cancellation_requested()?;
20322                    Ok(json!("unexpected"))
20323                }
20324                .await;
20325                saga.finish(outcome).await
20326            }
20327        };
20328        let mut future = Box::pin(run);
20329        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20330        assert!(matches!(
20331            future.as_mut().poll(&mut task_context),
20332            Poll::Pending
20333        ));
20334        let commands = ctx.take_commands().expect("cancellation compensation");
20335        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
20336    }
20337
20338    #[test]
20339    fn optional_task_observability_fields_round_trip_without_interpretation() {
20340        let context = json!({"schema": "unknown", "carrier": {"traceparent": "untrusted"}});
20341        let dispatch = json!({"task_id": "other-task"});
20342        let links = json!({"links": []});
20343        let mut value = json!({
20344            "task_id": "task", "query_task_id": "query", "workflow_type": "workflow",
20345            "activity_type": "activity", "query_name": "query", "payload_codec": "avro"
20346        });
20347        let workflow: WorkflowTask =
20348            serde_json::from_value(value.clone()).expect("legacy workflow task");
20349        let activity: ActivityTask =
20350            serde_json::from_value(value.clone()).expect("legacy activity task");
20351        let query: QueryTask = serde_json::from_value(value.clone()).expect("legacy query task");
20352        assert!(workflow.observability_context.is_none());
20353        assert!(activity.observability_context.is_none());
20354        assert!(query.observability_context.is_none());
20355        assert!(activity.workflow_id.is_none());
20356        assert!(activity.run_id.is_none());
20357        assert!(activity.activity_execution_id.is_none());
20358
20359        value["observability_context"] = context.clone();
20360        value["dispatch_observability_context"] = dispatch.clone();
20361        value["observability_links"] = links.clone();
20362        value["workflow_id"] = json!("workflow-id");
20363        value["run_id"] = json!("run-id");
20364        value["activity_execution_id"] = json!("activity-id");
20365        let workflow: WorkflowTask =
20366            serde_json::from_value(value.clone()).expect("workflow metadata");
20367        let activity: ActivityTask =
20368            serde_json::from_value(value.clone()).expect("activity metadata");
20369        let query: QueryTask = serde_json::from_value(value).expect("query metadata");
20370        for fields in [
20371            (
20372                workflow.observability_context,
20373                workflow.dispatch_observability_context,
20374                workflow.observability_links,
20375            ),
20376            (
20377                activity.observability_context,
20378                activity.dispatch_observability_context,
20379                activity.observability_links,
20380            ),
20381            (
20382                query.observability_context,
20383                query.dispatch_observability_context,
20384                query.observability_links,
20385            ),
20386        ] {
20387            assert_eq!(
20388                fields,
20389                (
20390                    Some(context.clone()),
20391                    Some(dispatch.clone()),
20392                    Some(links.clone())
20393                )
20394            );
20395        }
20396        assert_eq!(activity.workflow_id.as_deref(), Some("workflow-id"));
20397        assert_eq!(activity.run_id.as_deref(), Some("run-id"));
20398        assert_eq!(
20399            activity.activity_execution_id.as_deref(),
20400            Some("activity-id")
20401        );
20402    }
20403
20404    fn workflow_task(
20405        workflow_type: &str,
20406        history_events: Vec<HistoryEvent>,
20407        payload_codec: &str,
20408    ) -> WorkflowTask {
20409        WorkflowTask {
20410            task_id: format!("wft-{workflow_type}"),
20411            observability_context: None,
20412            dispatch_observability_context: None,
20413            observability_links: None,
20414            workflow_command_id: None,
20415            workflow_id: Some(format!("wf-{workflow_type}")),
20416            run_id: Some(format!("run-{workflow_type}")),
20417            workflow_type: workflow_type.to_string(),
20418            cancel_requested: false,
20419            payload_codec: payload_codec.to_string(),
20420            arguments: Some(
20421                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
20422            ),
20423            total_history_events: Some(history_events.len() as u64),
20424            history_size_bytes: None,
20425            continue_as_new_recommended: None,
20426            history_budget_pressure: None,
20427            history_events,
20428            next_history_page_token: None,
20429            workflow_task_attempt: 1,
20430            workflow_signal_id: None,
20431            signal_name: None,
20432            signal_arguments: None,
20433            workflow_update_id: None,
20434            update_name: None,
20435            lease_owner: Some("rust-worker".to_string()),
20436        }
20437    }
20438
20439    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
20440    struct SideEffectProbe {
20441        request_id: String,
20442        attempt: u32,
20443    }
20444
20445    #[test]
20446    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
20447        let calls = AtomicUsize::new(0);
20448        let ctx = workflow_context(Vec::new());
20449        let value = ctx
20450            .side_effect(|| {
20451                calls.fetch_add(1, Ordering::SeqCst);
20452                SideEffectProbe {
20453                    request_id: "request-42".to_string(),
20454                    attempt: 3,
20455                }
20456            })
20457            .expect("first side effect");
20458        assert_eq!(value.attempt, 3);
20459        assert_eq!(calls.load(Ordering::SeqCst), 1);
20460        let commands = ctx.take_commands().expect("commands");
20461        assert_eq!(commands.len(), 1);
20462        assert_eq!(commands[0]["type"], "record_side_effect");
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(vec![history_event(
20469            "SideEffectRecorded",
20470            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20471        )]);
20472        let replayed: SideEffectProbe = replay
20473            .side_effect(|| {
20474                calls.fetch_add(1, Ordering::SeqCst);
20475                panic!("committed side-effect callbacks must not run during replay")
20476            })
20477            .expect("replayed side effect");
20478        assert_eq!(replayed, value);
20479        assert_eq!(calls.load(Ordering::SeqCst), 1);
20480        assert!(replay.take_commands().expect("commands").is_empty());
20481        replay.ensure_history_consumed().expect("history consumed");
20482    }
20483
20484    #[test]
20485    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
20486        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
20487        let value = ctx
20488            .side_effect(|| SideEffectProbe {
20489                request_id: "avro-request".to_string(),
20490                attempt: 1,
20491            })
20492            .expect("Avro side effect");
20493        let uuid = ctx.uuid_v4().expect("deterministic UUID");
20494        let commands = ctx.take_commands().expect("commands");
20495        assert_eq!(commands.len(), 2);
20496        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
20497        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
20498        assert_eq!(
20499            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
20500            serde_json::to_value(&value).expect("value")
20501        );
20502
20503        let replay = workflow_context_with_codec(
20504            vec![
20505                history_event(
20506                    "SideEffectRecorded",
20507                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20508                ),
20509                history_event(
20510                    "SideEffectRecorded",
20511                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
20512                ),
20513            ],
20514            DEFAULT_CODEC,
20515        );
20516        let replayed: SideEffectProbe = replay
20517            .side_effect(|| panic!("Avro callback must not run"))
20518            .expect("replayed Avro value");
20519        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
20520        assert_eq!(replayed, value);
20521        assert_eq!(replayed_uuid, uuid);
20522        assert!(replay.take_commands().expect("commands").is_empty());
20523    }
20524
20525    #[test]
20526    fn typed_side_effect_replay_preserves_bytes_and_maps() {
20527        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
20528        let value = ctx
20529            .side_effect_avro_value(typed_fidelity_probe)
20530            .expect("typed side effect");
20531        let commands = ctx.take_commands().expect("side-effect command");
20532        assert_eq!(
20533            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20534                .expect("recorded side effect"),
20535            value
20536        );
20537
20538        let replay = workflow_context_with_codec(
20539            vec![history_event(
20540                "SideEffectRecorded",
20541                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20542            )],
20543            DEFAULT_CODEC,
20544        );
20545        assert_eq!(
20546            replay
20547                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
20548                .expect("replayed typed side effect"),
20549            value
20550        );
20551    }
20552
20553    #[test]
20554    fn ordered_side_effects_share_the_durable_command_stream() {
20555        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
20556        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
20557        let ctx = workflow_context(vec![
20558            history_event(
20559                "SideEffectRecorded",
20560                json!({"sequence": 1, "result": first}),
20561            ),
20562            history_event(
20563                "SideEffectRecorded",
20564                json!({"sequence": 2, "result": second}),
20565            ),
20566        ]);
20567        let first: String = ctx
20568            .side_effect(|| panic!("first callback must not run"))
20569            .expect("first replay");
20570        let second: i32 = ctx
20571            .side_effect(|| panic!("second callback must not run"))
20572            .expect("second replay");
20573        assert_eq!(first, "first");
20574        assert_eq!(second, 29);
20575        ctx.ensure_history_consumed().expect("ordered history");
20576
20577        let reordered = workflow_context(vec![history_event(
20578            "VersionMarkerRecorded",
20579            json!({
20580                "sequence": 1,
20581                "change_id": "before-side-effect",
20582                "version": 1,
20583                "min_supported": 1,
20584                "max_supported": 1,
20585            }),
20586        )]);
20587        let error = reordered
20588            .side_effect(|| "new".to_string())
20589            .expect_err("command reordering must fail");
20590        assert!(matches!(
20591            error,
20592            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20593                if reason == "recorded_command_mismatch"
20594        ));
20595    }
20596
20597    #[test]
20598    fn legacy_patch_preserves_pending_and_completed_activity_history() {
20599        for completed in [false, true] {
20600            let mut history = vec![history_event(
20601                "ActivityScheduled",
20602                json!({"sequence": 1, "activity_type": "old"}),
20603            )];
20604            if completed {
20605                history.push(history_event(
20606                    "ActivityCompleted",
20607                    json!({
20608                        "sequence": 1,
20609                        "activity_type": "old",
20610                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
20611                    }),
20612                ));
20613            }
20614            for _cold_replay in 0..2 {
20615                let ctx = workflow_context(history.clone());
20616                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
20617                assert!(!ctx.patched("added-step").expect("same frozen decision"));
20618                ctx.deprecate_patch("added-step")
20619                    .expect("retained boundary");
20620                let mut activity = Box::pin(ctx.activity("old", json!([])));
20621                let mut context = TaskContext::from_waker(noop_waker_ref());
20622                match activity.as_mut().poll(&mut context) {
20623                    Poll::Ready(result) => {
20624                        assert!(completed);
20625                        assert_eq!(result.expect("recorded result"), json!(41));
20626                        ctx.ensure_history_consumed().expect("old command retained");
20627                    }
20628                    Poll::Pending => assert!(!completed),
20629                }
20630                assert!(ctx.take_commands().expect("commands").is_empty());
20631            }
20632        }
20633    }
20634
20635    #[test]
20636    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
20637        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
20638        assert!(!ctx.patched("added-step").expect("legacy completed run"));
20639        ctx.deprecate_patch("added-step")
20640            .expect("same legacy decision");
20641        assert!(ctx.take_commands().expect("commands").is_empty());
20642        ctx.ensure_history_consumed().expect("completed history");
20643    }
20644
20645    #[test]
20646    fn legacy_patch_rejects_a_range_without_the_original_branch() {
20647        let ctx = workflow_context(vec![history_event(
20648            "ActivityScheduled",
20649            json!({"sequence": 1, "activity_type": "old"}),
20650        )]);
20651        let error = ctx
20652            .get_version("added-step", 0, 1)
20653            .expect_err("legacy is unsupported");
20654        assert!(matches!(
20655            error,
20656            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20657                if reason == "version_marker_incompatible_range"
20658        ));
20659        assert!(!ctx
20660            .patched("supported-step")
20661            .expect("failed check did not consume history"));
20662        assert!(ctx.take_commands().expect("commands").is_empty());
20663    }
20664
20665    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
20666        let mut event = history_event(
20667            "VersionMarkerRecorded",
20668            json!({
20669                "sequence": sequence,
20670                "change_id": "retained-patch",
20671                "version": version,
20672                "min_supported": -1,
20673                "max_supported": 1,
20674            }),
20675        );
20676        event.raw.insert("timestamp".into(), json!(time));
20677        event
20678    }
20679
20680    #[test]
20681    fn retained_patch_markers_preserve_each_original_boundary() {
20682        for completed in [false, true] {
20683            let mut history = vec![
20684                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20685                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20686                history_event(
20687                    "ActivityScheduled",
20688                    json!({"sequence": 3, "activity_type": "old"}),
20689                ),
20690            ];
20691            if completed {
20692                history.push(history_event(
20693                    "ActivityCompleted",
20694                    json!({
20695                        "sequence": 3,
20696                        "activity_type": "old",
20697                        "result": fixture_envelope(json!(41)),
20698                    }),
20699                ));
20700            }
20701            for _cold_replay in 0..2 {
20702                let ctx = workflow_context(history.clone());
20703                assert!(ctx.patched("retained-patch").unwrap());
20704                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20705                assert!(ctx.patched("retained-patch").unwrap());
20706                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20707                ctx.deprecate_patch("retained-patch").unwrap();
20708                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20709                let mut activity = Box::pin(ctx.activity("old", json!([])));
20710                let mut context = TaskContext::from_waker(noop_waker_ref());
20711                match activity.as_mut().poll(&mut context) {
20712                    Poll::Ready(result) => {
20713                        assert!(completed);
20714                        assert_eq!(result.unwrap(), json!(41));
20715                        ctx.ensure_history_consumed().unwrap();
20716                    }
20717                    Poll::Pending => assert!(!completed),
20718                }
20719                assert!(ctx.take_commands().unwrap().is_empty());
20720                let state = ctx.state.lock().unwrap();
20721                for (actual, original) in state.history_events.iter().zip(&history) {
20722                    assert_eq!(actual.payload, original.payload);
20723                    assert_eq!(actual.raw, original.raw);
20724                }
20725            }
20726        }
20727    }
20728
20729    #[test]
20730    fn retained_patch_aliases_do_not_skip_intervening_operations() {
20731        let ctx = workflow_context(vec![
20732            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20733            history_event(
20734                "SideEffectRecorded",
20735                json!({
20736                    "sequence": 2, "result": fixture_envelope(json!("between")),
20737                }),
20738            ),
20739            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
20740            history_event(
20741                "VersionMarkerRecorded",
20742                json!({
20743                    "sequence": 4, "change_id": "other-patch", "version": 1,
20744                    "min_supported": -1, "max_supported": 1,
20745                }),
20746            ),
20747        ]);
20748        assert!(ctx.patched("retained-patch").unwrap());
20749        assert!(ctx.patched("retained-patch").unwrap());
20750        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20751        assert_eq!(
20752            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
20753            "between"
20754        );
20755        ctx.deprecate_patch("retained-patch").unwrap();
20756        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20757        ctx.deprecate_patch("retained-patch").unwrap();
20758        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20759        assert!(ctx.patched("other-patch").unwrap());
20760        ctx.ensure_history_consumed().unwrap();
20761        assert!(ctx.take_commands().unwrap().is_empty());
20762    }
20763
20764    #[test]
20765    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
20766        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
20767        alias.payload["max_supported"] = json!(3);
20768        let ctx = workflow_context(vec![
20769            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20770            alias,
20771        ]);
20772        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
20773        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
20774        assert!(matches!(error,
20775            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20776                if reason == "version_marker_incompatible_range"));
20777        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20778        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
20779        ctx.ensure_history_consumed().unwrap();
20780        assert!(ctx.take_commands().unwrap().is_empty());
20781    }
20782
20783    #[test]
20784    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
20785        let ctx = workflow_context(Vec::new());
20786        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
20787        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
20788        assert!(ctx.patched("new-search").expect("patch"));
20789        ctx.deprecate_patch("new-search").expect("deprecate patch");
20790        let commands = ctx.take_commands().expect("commands");
20791        assert_eq!(commands.len(), 2);
20792        assert_eq!(commands[0]["type"], "record_version_marker");
20793        assert_eq!(commands[0]["version"], 2);
20794        assert_eq!(commands[1]["change_id"], "new-search");
20795
20796        let replay = workflow_context(vec![history_event(
20797            "VersionMarkerRecorded",
20798            json!({
20799                "sequence": 1,
20800                "change_id": "checkout-v2",
20801                "version": 2,
20802                "min_supported": 1,
20803                "max_supported": 2,
20804            }),
20805        )]);
20806        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
20807        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
20808        assert!(replay.take_commands().expect("commands").is_empty());
20809        replay.ensure_history_consumed().expect("history consumed");
20810    }
20811
20812    #[test]
20813    fn version_markers_reject_incompatible_or_malformed_history() {
20814        let incompatible = workflow_context(vec![history_event(
20815            "VersionMarkerRecorded",
20816            json!({
20817                "sequence": 1,
20818                "change_id": "checkout-v2",
20819                "version": 1,
20820                "min_supported": 1,
20821                "max_supported": 2,
20822            }),
20823        )]);
20824        let error = incompatible
20825            .get_version("checkout-v2", 2, 3)
20826            .expect_err("old version is unsupported");
20827        assert!(matches!(
20828            error,
20829            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20830                if reason == "version_marker_incompatible_range"
20831        ));
20832
20833        for (history, reason) in [
20834            (
20835                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
20836                "side_effect_result_missing",
20837            ),
20838            (
20839                vec![history_event(
20840                    "SideEffectRecorded",
20841                    json!({
20842                        "sequence": 1,
20843                        "result": {"codec": "avro", "blob": "not-base64"},
20844                    }),
20845                )],
20846                "side_effect_payload_incompatible",
20847            ),
20848            (
20849                vec![history_event(
20850                    "SideEffectRecorded",
20851                    json!({"sequence": 1, "result": {"unwrapped": true}}),
20852                )],
20853                "side_effect_payload_malformed",
20854            ),
20855            (
20856                vec![history_event(
20857                    "VersionMarkerRecorded",
20858                    json!({
20859                        "sequence": 1,
20860                        "change_id": "change",
20861                        "version": 1,
20862                        "min_supported": 2,
20863                        "max_supported": 1,
20864                    }),
20865                )],
20866                "version_marker_history_range_invalid",
20867            ),
20868        ] {
20869            let error = WorkflowState::new(
20870                history,
20871                "rust-workers".to_string(),
20872                DEFAULT_CODEC.to_string(),
20873                None,
20874            )
20875            .expect_err("malformed history must fail");
20876            assert!(matches!(
20877                error,
20878                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
20879                    if actual == reason
20880            ));
20881        }
20882    }
20883
20884    #[test]
20885    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
20886        let history = vec![history_event(
20887            "SearchAttributesUpserted",
20888            json!({
20889                "sequence": 1,
20890                "attributes": {"customer_tier": "gold"},
20891                "attribute_types": {"customer_tier": "keyword"},
20892                "merged": {"customer_tier": "gold"}
20893            }),
20894        )];
20895
20896        let matching = workflow_context(history.clone());
20897        matching
20898            .upsert_search_attributes(
20899                SearchAttributeUpdate::new()
20900                    .keyword("customer_tier", "gold")
20901                    .expect("keyword update"),
20902            )
20903            .expect("matching typed update must replay");
20904        matching
20905            .ensure_history_consumed()
20906            .expect("history consumed");
20907
20908        let changed_type = workflow_context(history.clone());
20909        let error = changed_type
20910            .upsert_search_attributes(
20911                SearchAttributeUpdate::new()
20912                    .string("customer_tier", "gold")
20913                    .expect("string update"),
20914            )
20915            .expect_err("same JSON value with a different declaration must be nondeterministic");
20916        let Error::NonDeterministicReplay(failure) = error else {
20917            panic!("typed identity drift must be a replay failure");
20918        };
20919        assert_eq!(failure.reason, "search_attribute_type_mismatch");
20920        assert_eq!(failure.sequence, Some(1));
20921
20922        let changed_value = workflow_context(history);
20923        let error = changed_value
20924            .upsert_search_attributes(
20925                SearchAttributeUpdate::new()
20926                    .keyword("customer_tier", "platinum")
20927                    .expect("keyword update"),
20928            )
20929            .expect_err("changed values must be nondeterministic");
20930        let Error::NonDeterministicReplay(failure) = error else {
20931            panic!("value drift must be a replay failure");
20932        };
20933        assert_eq!(failure.reason, "search_attribute_value_mismatch");
20934    }
20935
20936    #[test]
20937    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
20938        let history = vec![history_event(
20939            "SearchAttributesUpserted",
20940            json!({
20941                "sequence": 1,
20942                "attributes": {"customer_tier": "gold"},
20943                "merged": {"customer_tier": "gold"}
20944            }),
20945        )];
20946
20947        for update in [
20948            SearchAttributeUpdate::new()
20949                .keyword("customer_tier", "gold")
20950                .expect("keyword update"),
20951            SearchAttributeUpdate::new()
20952                .string("customer_tier", "gold")
20953                .expect("string update"),
20954        ] {
20955            let restarted = workflow_context(history.clone());
20956            restarted
20957                .upsert_search_attributes(update)
20958                .expect("legacy history constrains values but has unknown type identity");
20959            restarted
20960                .ensure_history_consumed()
20961                .expect("history consumed");
20962        }
20963    }
20964
20965    #[test]
20966    fn search_attribute_command_emits_canonical_types() {
20967        let ctx = workflow_context(Vec::new());
20968        ctx.upsert_search_attributes(
20969            SearchAttributeUpdate::new()
20970                .keyword("customer_tier", "gold")
20971                .expect("keyword update")
20972                .int("attempts", 3)
20973                .expect("int update")
20974                .delete("obsolete")
20975                .expect("delete update"),
20976        )
20977        .expect("valid search attributes");
20978
20979        assert_eq!(
20980            ctx.take_commands().expect("commands"),
20981            vec![json!({
20982                "type": "upsert_search_attributes",
20983                "attributes": {
20984                    "attempts": 3,
20985                    "customer_tier": "gold",
20986                    "obsolete": null
20987                },
20988                "attribute_types": {
20989                    "attempts": "int",
20990                    "customer_tier": "keyword"
20991                }
20992            })]
20993        );
20994    }
20995
20996    #[test]
20997    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
20998        let duplicate_side_effect = WorkflowState::new(
20999            vec![
21000                history_event(
21001                    "SideEffectRecorded",
21002                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
21003                ),
21004                history_event(
21005                    "SideEffectRecorded",
21006                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
21007                ),
21008            ],
21009            "rust-workers".to_string(),
21010            DEFAULT_CODEC.to_string(),
21011            None,
21012        )
21013        .expect_err("duplicate side effect");
21014        assert!(matches!(
21015            duplicate_side_effect,
21016            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21017                if reason == "duplicate_side_effect_record"
21018        ));
21019
21020        let marker = |sequence, version| {
21021            history_event(
21022                "VersionMarkerRecorded",
21023                json!({
21024                    "sequence": sequence,
21025                    "change_id": "same-change",
21026                    "version": version,
21027                    "min_supported": -1,
21028                    "max_supported": 1,
21029                }),
21030            )
21031        };
21032        let duplicate_marker = WorkflowState::new(
21033            vec![marker(1, 1), marker(3, -1)],
21034            "rust-workers".to_string(),
21035            DEFAULT_CODEC.to_string(),
21036            None,
21037        )
21038        .expect_err("conflicting marker");
21039        assert!(matches!(
21040            duplicate_marker,
21041            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21042                if reason == "version_marker_conflict"
21043        ));
21044    }
21045
21046    #[test]
21047    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
21048        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
21049        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
21050        invalid_alias.payload["max_supported"] = json!(0);
21051        for (history, expected_reason) in [
21052            (
21053                vec![marker.clone(), marker.clone()],
21054                "duplicate_version_marker_record",
21055            ),
21056            (
21057                vec![marker, invalid_alias],
21058                "version_marker_history_range_invalid",
21059            ),
21060        ] {
21061            let error =
21062                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
21063                    .expect_err("invalid historical alias");
21064            assert!(matches!(error,
21065                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
21066                    if reason == expected_reason));
21067        }
21068    }
21069
21070    #[test]
21071    fn retained_patch_aliases_require_the_original_call_boundary() {
21072        let ctx = workflow_context(vec![
21073            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
21074            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21075        ]);
21076        assert!(ctx.patched("retained-patch").unwrap());
21077        assert!(ctx.ensure_history_consumed().is_err());
21078        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21079        ctx.deprecate_patch("retained-patch").unwrap();
21080        ctx.ensure_history_consumed().unwrap();
21081        assert!(ctx.take_commands().unwrap().is_empty());
21082    }
21083
21084    #[test]
21085    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
21086        let ctx = workflow_context(vec![
21087            history_event(
21088                "SideEffectRecorded",
21089                json!({
21090                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
21091                }),
21092            ),
21093            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21094        ]);
21095        assert!(!ctx.patched("retained-patch").unwrap());
21096        assert_eq!(
21097            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
21098            "old-operation"
21099        );
21100        let error = ctx.patched("retained-patch").unwrap_err();
21101        assert!(matches!(error,
21102            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21103                if reason == "version_marker_conflict"));
21104        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21105        assert!(ctx.take_commands().unwrap().is_empty());
21106    }
21107
21108    #[test]
21109    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
21110        let mut state = WorkflowState::new(
21111            Vec::new(),
21112            "rust-workers".to_string(),
21113            DEFAULT_CODEC.to_string(),
21114            None,
21115        )
21116        .expect("workflow state");
21117        state.workflow_command_identity = "command-7".to_string();
21118        let context = WorkflowContext {
21119            state: Arc::new(Mutex::new(state)),
21120            cancellation_scope_id: "root".into(),
21121        };
21122        let item =
21123            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
21124
21125        context
21126            .append_workflow_stream("output", &[item], Some(10))
21127            .expect("append command");
21128        context
21129            .error_workflow_stream("output", "producer failed", None)
21130            .expect("error command");
21131        let commands = context.take_commands().expect("commands");
21132
21133        assert_eq!(commands[0]["type"], "record_side_effect");
21134        assert_eq!(
21135            commands[0]["workflow_stream"]["command_identity"],
21136            "command-7"
21137        );
21138        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
21139        assert_eq!(
21140            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
21141            "dw-stream:command-7:0:0"
21142        );
21143        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
21144
21145        let recorded = history_event(
21146            "SideEffectRecorded",
21147            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
21148        );
21149        let mut replay_state = WorkflowState::new(
21150            vec![recorded],
21151            "rust-workers".to_string(),
21152            DEFAULT_CODEC.to_string(),
21153            None,
21154        )
21155        .expect("replay state");
21156        replay_state.workflow_command_identity = "command-7".to_string();
21157        let replay_context = WorkflowContext {
21158            state: Arc::new(Mutex::new(replay_state)),
21159            cancellation_scope_id: "root".into(),
21160        };
21161        replay_context
21162            .append_workflow_stream(
21163                "output",
21164                &[WorkflowStreamAppendItem::from_reference(
21165                    "s3://bucket/item.avro",
21166                )],
21167                Some(10),
21168            )
21169            .expect("replayed append");
21170        assert!(replay_context
21171            .take_commands()
21172            .expect("replayed commands")
21173            .is_empty());
21174    }
21175
21176    #[test]
21177    fn workflow_stream_authoring_requires_server_durable_command_identity() {
21178        let context = workflow_context(Vec::new());
21179        let error = context
21180            .append_workflow_stream(
21181                "output",
21182                &[WorkflowStreamAppendItem::from_reference(
21183                    "s3://bucket/item.avro",
21184                )],
21185                None,
21186            )
21187            .expect_err("stream append without durable command identity must fail closed");
21188
21189        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
21190        assert!(context.take_commands().expect("commands").is_empty());
21191    }
21192
21193    #[test]
21194    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
21195        let client = Client::builder("http://localhost:8080").build().unwrap();
21196        let mut worker = Worker::new(client, "rust-workers");
21197        worker.register_workflow("streams.worker", |ctx, _| async move {
21198            ctx.append_workflow_stream(
21199                "output",
21200                &[WorkflowStreamAppendItem::new(json!("hello"))?],
21201                None,
21202            )?;
21203            ctx.close_workflow_stream("output", None)?;
21204            Ok(json!("done"))
21205        });
21206        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
21207            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
21208            task.workflow_command_id = command_id.clone();
21209            let expected_identity = command_id
21210                .as_deref()
21211                .filter(|id| !id.is_empty())
21212                .unwrap_or(&task.task_id)
21213                .to_string();
21214            let commands = worker
21215                .execute_workflow_task(task)
21216                .expect("ordinary worker stream output");
21217            assert_eq!(commands.len(), 3);
21218            assert_eq!(
21219                commands[0]["workflow_stream"]["command_identity"],
21220                expected_identity
21221            );
21222            assert_eq!(
21223                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
21224                format!("dw-stream:{expected_identity}:0:0")
21225            );
21226            assert_eq!(
21227                commands[1]["workflow_stream"]["command_identity"],
21228                expected_identity
21229            );
21230            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
21231            let history = commands[..2]
21232                .iter()
21233                .enumerate()
21234                .map(|(index, command)| {
21235                    history_event(
21236                        "SideEffectRecorded",
21237                        json!({"sequence":index + 1,"result":command["result"]}),
21238                    )
21239                })
21240                .collect();
21241            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
21242            replay.task_id = "replacement-task".to_string();
21243            let replayed = worker
21244                .execute_workflow_task(replay)
21245                .expect("replacement worker consumes recorded stream effects");
21246            assert_eq!(replayed.len(), 1);
21247            assert_eq!(replayed[0]["type"], "complete_workflow");
21248        }
21249        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
21250        missing.task_id.clear();
21251        assert!(matches!(
21252            worker.execute_workflow_task(missing),
21253            Err(Error::MissingWorkflowCommandIdentity)
21254        ));
21255    }
21256
21257    #[test]
21258    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
21259        fn worker(calls: Arc<AtomicUsize>) -> Worker {
21260            let client = Client::new("http://127.0.0.1:8080").expect("client");
21261            let mut worker = Worker::new(client, "rust-workers");
21262            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
21263                let calls = Arc::clone(&calls);
21264                async move {
21265                    let captured = ctx.side_effect(|| {
21266                        calls.fetch_add(1, Ordering::SeqCst);
21267                        "captured-once".to_string()
21268                    })?;
21269                    let version = ctx.get_version("cold-restart", 1, 2)?;
21270                    Ok(json!({"captured": captured, "version": version}))
21271                }
21272            });
21273            worker
21274        }
21275
21276        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
21277            WorkflowTask {
21278                task_id: "wft-side-effect-version".to_string(),
21279                observability_context: None,
21280                dispatch_observability_context: None,
21281                observability_links: None,
21282                workflow_command_id: None,
21283                workflow_id: Some("wf-side-effect-version".to_string()),
21284                run_id: Some("run-side-effect-version".to_string()),
21285                workflow_type: "rust.side-effect-version".to_string(),
21286                cancel_requested: false,
21287                payload_codec: DEFAULT_CODEC.to_string(),
21288                arguments: Some(
21289                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
21290                ),
21291                history_events,
21292                total_history_events: None,
21293                history_size_bytes: None,
21294                continue_as_new_recommended: None,
21295                history_budget_pressure: None,
21296                next_history_page_token: None,
21297                workflow_task_attempt: 1,
21298                workflow_signal_id: None,
21299                signal_name: None,
21300                signal_arguments: None,
21301                workflow_update_id: None,
21302                update_name: None,
21303                lease_owner: Some("rust-worker".to_string()),
21304            }
21305        }
21306
21307        let calls = Arc::new(AtomicUsize::new(0));
21308        let initial = worker(Arc::clone(&calls))
21309            .execute_workflow_task(task(Vec::new()))
21310            .expect("initial execution");
21311        assert_eq!(
21312            initial
21313                .iter()
21314                .map(|command| &command["type"])
21315                .collect::<Vec<_>>(),
21316            vec![
21317                "record_side_effect",
21318                "record_version_marker",
21319                "complete_workflow"
21320            ]
21321        );
21322        assert_eq!(calls.load(Ordering::SeqCst), 1);
21323
21324        let restarted = worker(Arc::clone(&calls));
21325        let replayed = restarted
21326            .execute_workflow_task(task(vec![
21327                history_event(
21328                    "SideEffectRecorded",
21329                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
21330                ),
21331                history_event(
21332                    "VersionMarkerRecorded",
21333                    json!({
21334                        "sequence": 2,
21335                        "change_id": "cold-restart",
21336                        "version": 2,
21337                        "min_supported": 1,
21338                        "max_supported": 2,
21339                    }),
21340                ),
21341            ]))
21342            .expect("cold replay");
21343        assert_eq!(replayed.len(), 1);
21344        assert_eq!(replayed[0]["type"], "complete_workflow");
21345        assert_eq!(calls.load(Ordering::SeqCst), 1);
21346    }
21347
21348    #[test]
21349    fn side_effect_replay_rejects_changed_rust_value_type() {
21350        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
21351        let ctx = workflow_context(vec![history_event(
21352            "SideEffectRecorded",
21353            json!({"sequence": 1, "result": result}),
21354        )]);
21355        let error = ctx
21356            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
21357            .expect_err("changed type must fail replay");
21358        assert!(matches!(
21359            error,
21360            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21361                if reason == "side_effect_type_mismatch"
21362        ));
21363    }
21364
21365    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
21366        vec![
21367            history_event(
21368                "ActivityScheduled",
21369                json!({
21370                    "sequence": 1,
21371                    "activity_type": "flaky",
21372                    "activity_execution_id": "act-1",
21373                    "activity": {
21374                        "id": "act-1",
21375                        "sequence": 1,
21376                        "type": "flaky",
21377                        "queue": "critical-activities",
21378                        "execution_mode": null,
21379                        "retry_policy": {
21380                            "snapshot_version": 1,
21381                            "max_attempts": 3,
21382                            "backoff_seconds": [2, 4],
21383                            "start_to_close_timeout": 30,
21384                            "schedule_to_start_timeout": 5,
21385                            "schedule_to_close_timeout": 90,
21386                            "heartbeat_timeout": 10,
21387                            "non_retryable_error_types": ["PermanentError"]
21388                        }
21389                    }
21390                }),
21391            ),
21392            history_event(
21393                "ActivityStarted",
21394                json!({
21395                    "sequence": 1,
21396                    "activity_type": "flaky",
21397                    "activity_execution_id": "act-1",
21398                    "activity_attempt_id": "attempt-1",
21399                    "attempt_number": 1
21400                }),
21401            ),
21402            history_event(
21403                "ActivityRetryScheduled",
21404                json!({
21405                    "sequence": 1,
21406                    "activity_type": "flaky",
21407                    "activity_execution_id": "act-1",
21408                    "activity_attempt_id": "attempt-1",
21409                    "attempt_number": 1,
21410                    "retry_after_attempt": 1,
21411                    "retry_backoff_seconds": 2,
21412                    "failure_category": "activity",
21413                    "exception_type": "TransientError"
21414                }),
21415            ),
21416            history_event(
21417                "ActivityStarted",
21418                json!({
21419                    "sequence": 1,
21420                    "activity_type": "flaky",
21421                    "activity_execution_id": "act-1",
21422                    "activity_attempt_id": "attempt-2",
21423                    "attempt_number": 2
21424                }),
21425            ),
21426            history_event(
21427                "ActivityCompleted",
21428                json!({
21429                    "sequence": 1,
21430                    "activity_type": "flaky",
21431                    "activity_execution_id": "act-1",
21432                    "activity_attempt_id": "attempt-2",
21433                    "attempt_number": 2,
21434                    "payload_codec": DEFAULT_CODEC,
21435                    "result": fixture_envelope(json!({"status":"recovered"}))
21436                }),
21437            ),
21438        ]
21439    }
21440
21441    fn retry_activity_options() -> ActivityOptions {
21442        ActivityOptions::new()
21443            .task_queue("critical-activities")
21444            .retry_policy(
21445                ActivityRetryPolicy::new(3)
21446                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
21447                    .non_retryable_error_type("PermanentError"),
21448            )
21449            .start_to_close_timeout(Duration::from_secs(30))
21450            .schedule_to_start_timeout(Duration::from_secs(5))
21451            .schedule_to_close_timeout(Duration::from_secs(90))
21452            .heartbeat_timeout(Duration::from_secs(10))
21453    }
21454
21455    #[test]
21456    fn fixed_avro_value_round_trips_json_values() {
21457        let value = json!({"greeting": "hello", "count": 3, "ok": true});
21458        let envelope = PayloadEnvelope::avro(&value).expect("encode");
21459        assert_eq!(envelope.codec, DEFAULT_CODEC);
21460        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
21461    }
21462
21463    #[tokio::test]
21464    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
21465        let client = Client::new("http://127.0.0.1:8080").expect("client");
21466        let mut worker = Worker::new(client, "rust-workers");
21467        worker.register_typed_workflow(
21468            "typed.contract.workflow",
21469            |_ctx, input: TypedContract| async move { Ok(input) },
21470        );
21471        worker.register_typed_activity(
21472            "typed.contract.activity",
21473            |_ctx, input: TypedContract| async move { Ok(input) },
21474        );
21475
21476        let expected = typed_contract();
21477        let arguments = AvroValue::Array(vec![
21478            AvroValue::from_serialize(&expected).expect("typed request")
21479        ]);
21480        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
21481        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
21482        workflow.arguments = Some(envelope.clone());
21483        let commands = worker
21484            .execute_workflow_task(workflow)
21485            .expect("typed workflow task");
21486        let workflow_result: TypedContract =
21487            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21488                .expect("workflow result envelope")
21489                .deserialize()
21490                .expect("workflow result type");
21491        assert_eq!(workflow_result, expected);
21492
21493        let activity = ActivityTask {
21494            task_id: "typed-contract-activity".to_string(),
21495            workflow_id: None,
21496            run_id: None,
21497            activity_execution_id: None,
21498            observability_context: None,
21499            dispatch_observability_context: None,
21500            observability_links: None,
21501            activity_attempt_id: Some("typed-contract-attempt".to_string()),
21502            attempt_id: None,
21503            activity_type: "typed.contract.activity".to_string(),
21504            payload_codec: DEFAULT_CODEC.to_string(),
21505            arguments: Some(envelope),
21506            attempt_number: 1,
21507            lease_owner: Some("rust-worker".to_string()),
21508        };
21509        let activity_result: TypedContract = worker
21510            .execute_activity_task(activity)
21511            .await
21512            .expect("typed activity task")
21513            .deserialize()
21514            .expect("activity result type");
21515        assert_eq!(activity_result, expected);
21516    }
21517
21518    #[test]
21519    fn typed_entry_mismatch_refuses_before_body_and_preserves_original_input() {
21520        let calls = Arc::new(AtomicUsize::new(0));
21521        let observed = Arc::clone(&calls);
21522        let client = Client::new("http://127.0.0.1:8080").expect("client");
21523        let mut worker = Worker::new(client.clone(), "rust-workers");
21524        worker.register_typed_workflow("entry.safe", move |_ctx, input: i64| {
21525            observed.fetch_add(1, Ordering::SeqCst);
21526            async move { Ok(input) }
21527        });
21528        let mut task = workflow_task("entry.safe", Vec::new(), DEFAULT_CODEC);
21529        task.arguments = Some(fixture_envelope(json!(["private-original-value"])));
21530        let original = task.clone();
21531        let error = worker
21532            .execute_workflow_task(task)
21533            .expect_err("incompatible entry must refuse the task, not fail the run");
21534        assert_eq!(calls.load(Ordering::SeqCst), 0);
21535        assert!(error
21536            .to_string()
21537            .contains("workflow_entry_arguments_mismatch:"));
21538        assert!(!error.to_string().contains("private-original-value"));
21539
21540        let mut compatible = Worker::new(client, "rust-workers");
21541        compatible
21542            .register_typed_workflow("entry.safe", |_ctx, input: String| async move { Ok(input) });
21543        let commands = compatible
21544            .execute_workflow_task(original)
21545            .expect("same recorded input");
21546        assert_eq!(commands[0]["type"], "complete_workflow");
21547        assert_eq!(
21548            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).unwrap(),
21549            json!("private-original-value")
21550        );
21551    }
21552
21553    #[test]
21554    fn typed_entry_replayed_mismatch_refuses_before_state_factory_and_body() {
21555        let factories = Arc::new(AtomicUsize::new(0));
21556        let observed = Arc::clone(&factories);
21557        let client = Client::new("http://127.0.0.1:8080").expect("client");
21558        let mut worker = Worker::new(client, "rust-workers");
21559        worker.register_typed_replayed_workflow(
21560            "entry.replayed",
21561            move || {
21562                observed.fetch_add(1, Ordering::SeqCst);
21563                ()
21564            },
21565            |_ctx, _input: i64, _state| async move {
21566                panic!("body must not start");
21567                #[allow(unreachable_code)]
21568                Ok(0_i64)
21569            },
21570        );
21571        let mut task = workflow_task("entry.replayed", Vec::new(), DEFAULT_CODEC);
21572        task.arguments = Some(fixture_envelope(json!(["private-replayed-value"])));
21573        let error = worker
21574            .execute_workflow_task(task)
21575            .expect_err("entry refusal");
21576        assert_eq!(factories.load(Ordering::SeqCst), 0);
21577        assert!(error
21578            .to_string()
21579            .contains("workflow_entry_arguments_mismatch:"));
21580        assert!(!error.to_string().contains("private-replayed-value"));
21581
21582        let replay = worker.workflows["entry.replayed"].replay.as_ref().unwrap();
21583        let Err(error) = replay(
21584            workflow_context(Vec::new()),
21585            AvroValue::Array(vec![AvroValue::String("private-replayed-value".into())]),
21586        ) else {
21587            panic!("query replay must refuse before creating application state");
21588        };
21589        assert_eq!(factories.load(Ordering::SeqCst), 0);
21590        assert!(!error.to_string().contains("private-replayed-value"));
21591    }
21592
21593    #[test]
21594    fn typed_entry_deserializes_once_before_entering_application_code() {
21595        static DECODES: AtomicUsize = AtomicUsize::new(0);
21596        struct Counted(i64);
21597        impl<'de> Deserialize<'de> for Counted {
21598            fn deserialize<D: Deserializer<'de>>(
21599                deserializer: D,
21600            ) -> std::result::Result<Self, D::Error> {
21601                DECODES.fetch_add(1, Ordering::SeqCst);
21602                i64::deserialize(deserializer).map(Self)
21603            }
21604        }
21605        DECODES.store(0, Ordering::SeqCst);
21606        let client = Client::new("http://127.0.0.1:8080").expect("client");
21607        let mut worker = Worker::new(client, "rust-workers");
21608        worker.register_typed_workflow(
21609            "entry.once",
21610            |_ctx, input: Counted| async move { Ok(input.0) },
21611        );
21612        let mut task = workflow_task("entry.once", Vec::new(), DEFAULT_CODEC);
21613        task.arguments = Some(fixture_envelope(json!([7])));
21614        let commands = worker.execute_workflow_task(task).expect("typed result");
21615        assert_eq!(commands[0]["type"], "complete_workflow");
21616        assert_eq!(DECODES.load(Ordering::SeqCst), 1);
21617    }
21618
21619    #[test]
21620    fn typed_entry_body_input_error_remains_a_business_failure() {
21621        let client = Client::new("http://127.0.0.1:8080").expect("client");
21622        let mut worker = Worker::new(client, "rust-workers");
21623        worker.register_typed_workflow("entry.body", |_ctx, _input: i64| async move {
21624            Err::<i64, _>(handler_type_error::<i64>(
21625                HandlerKind::Workflow,
21626                "entry.body",
21627                HandlerValueKind::Input,
21628                "deliberate body error",
21629            ))
21630        });
21631        let mut task = workflow_task("entry.body", Vec::new(), DEFAULT_CODEC);
21632        task.arguments = Some(fixture_envelope(json!([7])));
21633        let commands = worker
21634            .execute_workflow_task(task)
21635            .expect("business failure command");
21636        assert_eq!(commands[0]["type"], "fail_workflow");
21637        assert!(commands[0]["message"]
21638            .as_str()
21639            .unwrap()
21640            .contains("deliberate body error"));
21641    }
21642
21643    #[test]
21644    fn typed_entry_body_cannot_claim_the_adapter_refusal() {
21645        let client = Client::new("http://127.0.0.1:8080").expect("client");
21646        let mut worker = Worker::new(client, "rust-workers");
21647        worker.register_typed_workflow("entry.body.refusal", |_ctx, _input: i64| async move {
21648            Err::<i64, _>(handler_type_error::<i64>(
21649                HandlerKind::Workflow,
21650                "entry.body.refusal",
21651                HandlerValueKind::Input,
21652                "workflow_entry_arguments_mismatch: deliberate body error",
21653            ))
21654        });
21655        let mut task = workflow_task("entry.body.refusal", Vec::new(), DEFAULT_CODEC);
21656        task.arguments = Some(fixture_envelope(json!([7])));
21657        let commands = worker
21658            .execute_workflow_task(task)
21659            .expect("business failure");
21660        assert_eq!(commands[0]["type"], "fail_workflow");
21661    }
21662
21663    #[tokio::test]
21664    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
21665        let client = Client::new("http://127.0.0.1:8080").expect("client");
21666        let mut worker = Worker::new(client, "rust-workers");
21667        worker.register_typed_workflow(
21668            "typed.shape.workflow",
21669            |_ctx, input: TypedContract| async move { Ok(input) },
21670        );
21671        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
21672            Ok(f64::NAN)
21673        });
21674
21675        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
21676        workflow.arguments = Some(
21677            encode_typed_envelope(
21678                &AvroValue::Array(vec![
21679                    AvroValue::String("first".to_string()),
21680                    AvroValue::String("second".to_string()),
21681                ]),
21682                DEFAULT_CODEC,
21683            )
21684            .expect("malformed typed arguments"),
21685        );
21686        let error = worker
21687            .execute_workflow_task(workflow)
21688            .expect_err("entry shape mismatch refuses the task");
21689        let message = error.to_string();
21690        assert!(message.contains("workflow_entry_arguments_mismatch:"));
21691        assert!(message.contains("typed.shape.workflow"));
21692        assert!(message.contains(type_name::<TypedContract>()));
21693
21694        let activity = ActivityTask {
21695            task_id: "typed-unsupported-activity".to_string(),
21696            workflow_id: None,
21697            run_id: None,
21698            activity_execution_id: None,
21699            observability_context: None,
21700            dispatch_observability_context: None,
21701            observability_links: None,
21702            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
21703            attempt_id: None,
21704            activity_type: "typed.unsupported.activity".to_string(),
21705            payload_codec: DEFAULT_CODEC.to_string(),
21706            arguments: Some(
21707                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21708                    .expect("unit arguments"),
21709            ),
21710            attempt_number: 1,
21711            lease_owner: Some("rust-worker".to_string()),
21712        };
21713        let Error::HandlerType {
21714            handler_kind,
21715            handler_name,
21716            value_kind,
21717            rust_type,
21718            message,
21719        } = worker
21720            .execute_activity_task(activity)
21721            .await
21722            .expect_err("non-finite handler output must fail")
21723        else {
21724            panic!("expected contextual handler type failure");
21725        };
21726        assert_eq!(handler_kind, HandlerKind::Activity);
21727        assert_eq!(handler_name, "typed.unsupported.activity");
21728        assert_eq!(value_kind, HandlerValueKind::Result);
21729        assert_eq!(rust_type, type_name::<f64>());
21730        assert!(message.contains("non_finite_float"));
21731    }
21732
21733    #[tokio::test]
21734    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
21735        #[derive(Clone, Default)]
21736        struct State {
21737            observed: Option<TypedContract>,
21738        }
21739
21740        let client = Client::new("http://127.0.0.1:8080").expect("client");
21741        let mut worker = Worker::new(client, "rust-workers");
21742        worker.register_typed_replayed_workflow(
21743            "typed.contract.replayed",
21744            State::default,
21745            |ctx, input: TypedContract, state| async move {
21746                let result: TypedContract =
21747                    ctx.activity_typed("typed.contract.activity", input).await?;
21748                state.update(|current| current.observed = Some(result.clone()))?;
21749                Ok(result)
21750            },
21751        );
21752        worker.register_replayed_query::<State, _, _>(
21753            "typed.contract.replayed",
21754            "observed",
21755            |_ctx, state, _args| async move {
21756                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
21757            },
21758        );
21759
21760        let expected = typed_contract();
21761        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
21762        let workflow_arguments =
21763            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
21764                .expect("workflow arguments");
21765        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
21766        let task = QueryTask {
21767            query_task_id: "typed-replay-query".to_string(),
21768            observability_context: None,
21769            dispatch_observability_context: None,
21770            observability_links: None,
21771            query_task_attempt: 1,
21772            lease_owner: Some("rust-worker".to_string()),
21773            workflow_id: Some("typed-replay".to_string()),
21774            run_id: Some("typed-replay-run".to_string()),
21775            workflow_type: "typed.contract.replayed".to_string(),
21776            query_name: "observed".to_string(),
21777            payload_codec: DEFAULT_CODEC.to_string(),
21778            workflow_arguments: Some(workflow_arguments),
21779            query_arguments: Some(
21780                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21781                    .expect("query arguments"),
21782            ),
21783            history_events: vec![
21784                history_event(
21785                    "ActivityScheduled",
21786                    json!({
21787                        "sequence": 1,
21788                        "activity_type": "typed.contract.activity"
21789                    }),
21790                ),
21791                history_event(
21792                    "ActivityCompleted",
21793                    json!({
21794                        "sequence": 1,
21795                        "activity_type": "typed.contract.activity",
21796                        "payload_codec": DEFAULT_CODEC,
21797                        "result": result
21798                    }),
21799                ),
21800            ],
21801            history_export: None,
21802            run_status: Some("completed".to_string()),
21803        };
21804
21805        assert_eq!(
21806            worker
21807                .execute_query_task(task)
21808                .await
21809                .expect("typed replay query")
21810                .deserialize::<i64>()
21811                .expect("query result"),
21812            expected.signed
21813        );
21814    }
21815
21816    #[tokio::test]
21817    async fn update_context_preserves_workflow_input_and_committed_signals() {
21818        let client = Client::new("http://127.0.0.1:8080").expect("client");
21819        let mut worker = Worker::new(client, "rust-workers");
21820        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
21821        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
21822        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
21823        let expected_input = workflow_input.clone();
21824        let expected_signals = signal_arguments.clone();
21825        let handler = move |context: QueryContext, arguments: AvroValue| {
21826            let expected_input = expected_input.clone();
21827            let expected_signals = expected_signals.clone();
21828            async move {
21829                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
21830                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
21831                assert_eq!(context.workflow_input_avro_value(), &expected_input);
21832                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
21833                assert_eq!(
21834                    context.signals_avro_value("changed"),
21835                    vec![expected_signals.clone()]
21836                );
21837                assert_eq!(
21838                    context.signals("changed"),
21839                    vec![expected_signals
21840                        .into_iter()
21841                        .map(AvroValue::into_json)
21842                        .collect::<Result<Vec<_>>>()?]
21843                );
21844                assert_eq!(
21845                    context.signal_events()[0].id.as_deref(),
21846                    Some("signal-original")
21847                );
21848                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
21849                Ok(arguments)
21850            }
21851        };
21852        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
21853        worker.register_update_avro_value("snapshot", "inspect", handler);
21854        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
21855        let update_envelope =
21856            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
21857        let mut task = workflow_task(
21858            "snapshot",
21859            vec![
21860                history_event(
21861                    "SignalReceived",
21862                    json!({
21863                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
21864                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
21865                    }),
21866                ),
21867                history_event(
21868                    "UpdateAccepted",
21869                    json!({
21870                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
21871                    }),
21872                ),
21873            ],
21874            DEFAULT_CODEC,
21875        );
21876        task.arguments =
21877            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
21878        task.workflow_update_id = Some("update-original".into());
21879        task.update_name = Some("inspect".into());
21880        let query = QueryTask {
21881            query_task_id: "query-snapshot".into(),
21882            observability_context: None,
21883            dispatch_observability_context: None,
21884            observability_links: None,
21885            query_task_attempt: 1,
21886            lease_owner: None,
21887            workflow_id: task.workflow_id.clone(),
21888            run_id: task.run_id.clone(),
21889            workflow_type: task.workflow_type.clone(),
21890            query_name: "inspect".into(),
21891            payload_codec: DEFAULT_CODEC.into(),
21892            workflow_arguments: task.arguments.clone(),
21893            query_arguments: Some(update_envelope),
21894            history_events: task.history_events.clone(),
21895            history_export: None,
21896            run_status: Some("running".into()),
21897        };
21898        assert_eq!(
21899            worker
21900                .execute_query_task(query)
21901                .await
21902                .expect("query snapshot"),
21903            update_arguments
21904        );
21905        for _ in 0..2 {
21906            let commands = worker
21907                .execute_workflow_task(task.clone())
21908                .expect("cold update snapshot");
21909            assert_eq!(commands[0]["type"], "complete_update");
21910            assert_eq!(commands[0]["update_id"], "update-original");
21911            assert_eq!(
21912                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21913                    .expect("update result"),
21914                update_arguments
21915            );
21916        }
21917    }
21918
21919    #[test]
21920    fn committed_signal_snapshot_counts_identities_once() {
21921        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
21922        let received = history_event(
21923            "SignalReceived",
21924            json!({
21925                "signal_id": "signal-first", "workflow_command_id": "command-first",
21926                "signal_name": "changed", "arguments": arguments.clone(),
21927            }),
21928        );
21929        let applied = history_event(
21930            "SignalApplied",
21931            json!({
21932                "signal_id": "signal-first", "workflow_command_id": "command-first",
21933                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
21934            }),
21935        );
21936        let distinct = history_event(
21937            "SignalReceived",
21938            json!({
21939                "signal_id": "signal-second", "workflow_command_id": "command-second",
21940                "signal_name": "changed", "arguments": arguments,
21941            }),
21942        );
21943        let history = vec![received.clone(), applied.clone(), distinct];
21944        let signals =
21945            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
21946        assert_eq!(signals.len(), 2);
21947        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21948        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
21949        assert_eq!(signals[0].workflow_sequence, Some(1));
21950        assert_eq!(signals[0].arguments, signals[1].arguments);
21951        let mut command_only = received.clone();
21952        command_only
21953            .payload
21954            .as_object_mut()
21955            .expect("payload")
21956            .remove("signal_id");
21957        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
21958            .expect("command identity");
21959        assert_eq!(signals.len(), 1);
21960        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21961        let mut conflicting = applied;
21962        conflicting.payload["value"] =
21963            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
21964        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
21965    }
21966
21967    #[test]
21968    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
21969        for arguments in [
21970            vec![],
21971            vec![AvroValue::Array(vec![
21972                AvroValue::Long(1),
21973                AvroValue::Long(2),
21974            ])],
21975            vec![AvroValue::Bytes(vec![0, 255])],
21976            vec![AvroValue::Null],
21977            vec![AvroValue::Boolean(false)],
21978            vec![
21979                AvroValue::Long(1),
21980                AvroValue::Array(vec![AvroValue::Long(2)]),
21981            ],
21982        ] {
21983            let applied = match arguments.as_slice() {
21984                [] => AvroValue::Boolean(true),
21985                [value] => value.clone(),
21986                values => AvroValue::Array(values.to_vec()),
21987            };
21988            for applied in [applied, AvroValue::Array(arguments.clone())] {
21989                let events = vec![
21990                    history_event(
21991                        "SignalReceived",
21992                        json!({
21993                            "signal_id": "original", "signal_name": "changed",
21994                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
21995                        }),
21996                    ),
21997                    history_event(
21998                        "SignalApplied",
21999                        json!({
22000                            "signal_id": "original", "signal_name": "changed",
22001                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
22002                        }),
22003                    ),
22004                ];
22005                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
22006                    .expect("canonical signal snapshot");
22007                assert_eq!(signals.len(), 1);
22008                assert_eq!(signals[0].avro_arguments, arguments);
22009            }
22010        }
22011    }
22012
22013    #[tokio::test]
22014    async fn update_context_rejects_malformed_snapshot_before_handler() {
22015        let client = Client::new("http://127.0.0.1:8080").expect("client");
22016        let mut worker = Worker::new(client, "rust-workers");
22017        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
22018        let calls = Arc::new(AtomicUsize::new(0));
22019        let observed = Arc::clone(&calls);
22020        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
22021            observed.fetch_add(1, Ordering::SeqCst);
22022            async { Ok(Value::Null) }
22023        });
22024        let mut task = workflow_task(
22025            "snapshot",
22026            vec![history_event(
22027                "UpdateAccepted",
22028                json!({
22029                    "update_id": "update-original", "update_name": "inspect",
22030                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
22031                }),
22032            )],
22033            DEFAULT_CODEC,
22034        );
22035        task.workflow_update_id = Some("update-original".into());
22036        task.update_name = Some("inspect".into());
22037        let mut bad_input = task.clone();
22038        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
22039        assert!(worker.execute_workflow_task(bad_input).is_err());
22040        task.history_events.insert(0, history_event("SignalReceived", json!({
22041            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
22042        })));
22043        assert!(worker.execute_workflow_task(task).is_err());
22044        assert_eq!(calls.load(Ordering::SeqCst), 0);
22045    }
22046
22047    #[tokio::test]
22048    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
22049        let client = Client::new("http://127.0.0.1:8080").expect("client");
22050        let mut worker = Worker::new(client, "rust-workers");
22051        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
22052        worker
22053            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
22054        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
22055            Ok(input)
22056        });
22057        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
22058            Ok(input)
22059        });
22060        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
22061            Ok(AvroValue::Array(
22062                ctx.wait_signal_avro_value("changed").await?,
22063            ))
22064        });
22065
22066        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
22067        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
22068
22069        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
22070        workflow.arguments = Some(envelope.clone());
22071        let commands = worker
22072            .execute_workflow_task(workflow)
22073            .expect("typed workflow task");
22074        assert_eq!(commands[0]["type"], "complete_workflow");
22075        assert_eq!(
22076            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22077                .expect("typed workflow result"),
22078            arguments
22079        );
22080
22081        let activity = ActivityTask {
22082            task_id: "activity-typed".to_string(),
22083            workflow_id: None,
22084            run_id: None,
22085            activity_execution_id: None,
22086            observability_context: None,
22087            dispatch_observability_context: None,
22088            observability_links: None,
22089            activity_attempt_id: Some("attempt-typed".to_string()),
22090            attempt_id: None,
22091            activity_type: "typed.activity".to_string(),
22092            payload_codec: DEFAULT_CODEC.to_string(),
22093            arguments: Some(envelope.clone()),
22094            attempt_number: 1,
22095            lease_owner: Some("rust-worker".to_string()),
22096        };
22097        assert_eq!(
22098            worker
22099                .execute_activity_task(activity)
22100                .await
22101                .expect("typed activity result"),
22102            arguments
22103        );
22104
22105        let query = QueryTask {
22106            query_task_id: "query-typed".to_string(),
22107            observability_context: None,
22108            dispatch_observability_context: None,
22109            observability_links: None,
22110            query_task_attempt: 1,
22111            lease_owner: Some("rust-worker".to_string()),
22112            workflow_id: Some("typed-1".to_string()),
22113            run_id: Some("run-typed".to_string()),
22114            workflow_type: "typed.echo".to_string(),
22115            query_name: "inspect".to_string(),
22116            payload_codec: DEFAULT_CODEC.to_string(),
22117            workflow_arguments: Some(
22118                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
22119                    .expect("workflow input"),
22120            ),
22121            query_arguments: Some(envelope.clone()),
22122            history_events: Vec::new(),
22123            history_export: None,
22124            run_status: Some("running".to_string()),
22125        };
22126        assert_eq!(
22127            worker
22128                .execute_query_task(query)
22129                .await
22130                .expect("typed query result"),
22131            arguments
22132        );
22133
22134        let mut update = workflow_task(
22135            "typed.echo",
22136            vec![history_event(
22137                "UpdateAccepted",
22138                json!({
22139                    "update_id": "update-typed",
22140                    "update_name": "replace",
22141                    "arguments": envelope.clone(),
22142                }),
22143            )],
22144            DEFAULT_CODEC,
22145        );
22146        update.workflow_update_id = Some("update-typed".to_string());
22147        update.update_name = Some("replace".to_string());
22148        let commands = worker
22149            .execute_workflow_task(update)
22150            .expect("typed update task");
22151        assert_eq!(commands[0]["type"], "complete_update");
22152        assert_eq!(
22153            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22154                .expect("typed update result"),
22155            arguments
22156        );
22157
22158        let mut signal = workflow_task(
22159            "typed.signal",
22160            vec![history_event(
22161                "SignalReceived",
22162                json!({
22163                    "signal_id": "signal-typed",
22164                    "signal_name": "changed",
22165                    "arguments": envelope.clone(),
22166                }),
22167            )],
22168            DEFAULT_CODEC,
22169        );
22170        signal.workflow_signal_id = Some("signal-typed".to_string());
22171        signal.signal_name = Some("changed".to_string());
22172        signal.signal_arguments = Some(envelope);
22173        let commands = worker
22174            .execute_workflow_task(signal)
22175            .expect("typed signal resume");
22176        assert_eq!(
22177            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22178                .expect("typed signal result"),
22179            arguments
22180        );
22181    }
22182
22183    #[tokio::test]
22184    async fn typed_helpers_never_parse_json_inspection_projection() {
22185        let collision_values = projection_collision_probe();
22186        let expected = AvroValue::Array(collision_values.clone());
22187        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
22188
22189        let activity_context = workflow_context_with_codec(
22190            vec![history_event(
22191                "ActivityCompleted",
22192                json!({
22193                    "sequence": 1,
22194                    "activity_type": "collision.activity",
22195                    "payload_codec": DEFAULT_CODEC,
22196                    "result": envelope.clone(),
22197                }),
22198            )],
22199            DEFAULT_CODEC,
22200        );
22201        assert_eq!(
22202            activity_context
22203                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
22204                .await
22205                .expect("typed activity collision result"),
22206            expected
22207        );
22208
22209        let signal_context = workflow_context_with_codec(
22210            vec![
22211                history_event(
22212                    "SignalWaitOpened",
22213                    json!({"sequence": 1, "signal_name": "collision"}),
22214                ),
22215                history_event(
22216                    "SignalApplied",
22217                    json!({
22218                        "sequence": 1,
22219                        "signal_name": "collision",
22220                        "payload_codec": DEFAULT_CODEC,
22221                        "value": envelope.clone(),
22222                    }),
22223                ),
22224            ],
22225            DEFAULT_CODEC,
22226        );
22227        assert_eq!(
22228            signal_context
22229                .wait_signal_avro_value("collision")
22230                .await
22231                .expect("typed signal collision arguments"),
22232            collision_values
22233        );
22234
22235        let child_context = workflow_context_with_codec(
22236            vec![
22237                history_event(
22238                    "ChildWorkflowScheduled",
22239                    json!({
22240                        "sequence": 1,
22241                        "child_workflow_instance_id": "collision-child",
22242                        "child_workflow_run_id": "collision-run",
22243                        "child_workflow_type": "collision.child",
22244                    }),
22245                ),
22246                history_event(
22247                    "ChildRunCompleted",
22248                    json!({
22249                        "sequence": 1,
22250                        "child_workflow_instance_id": "collision-child",
22251                        "child_workflow_run_id": "collision-run",
22252                        "child_workflow_type": "collision.child",
22253                        "payload_codec": DEFAULT_CODEC,
22254                        "result": envelope,
22255                    }),
22256                ),
22257            ],
22258            DEFAULT_CODEC,
22259        );
22260        let child = child_context
22261            .start_child_workflow_avro_value(
22262                "collision.child",
22263                ChildWorkflowOptions::new("collision-workers"),
22264                AvroValue::Array(Vec::new()),
22265            )
22266            .await
22267            .expect("typed child collision result");
22268        assert_eq!(child.result, expected);
22269    }
22270
22271    #[tokio::test]
22272    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
22273        let client = Client::new("http://127.0.0.1:8080").expect("client");
22274        let mut worker = Worker::new(client, "rust-workers");
22275        worker.register_replayed_workflow_avro_value(
22276            "typed.replayed",
22277            || (),
22278            |_ctx, input, _state| async move { Ok(input) },
22279        );
22280        worker.register_replayed_query_avro_value::<(), _, _>(
22281            "typed.replayed",
22282            "inspect",
22283            |ctx, _state, args| async move {
22284                let mut signals = ctx.signals_avro_value("collision");
22285                let signal = signals
22286                    .pop()
22287                    .map(AvroValue::Array)
22288                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
22289                Ok(AvroValue::Array(vec![
22290                    ctx.workflow_input_avro_value().clone(),
22291                    signal,
22292                    args,
22293                ]))
22294            },
22295        );
22296        let arguments = AvroValue::Array(projection_collision_probe());
22297        let signal_arguments =
22298            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
22299        let task = QueryTask {
22300            query_task_id: "query-typed-replay".to_string(),
22301            observability_context: None,
22302            dispatch_observability_context: None,
22303            observability_links: None,
22304            query_task_attempt: 1,
22305            lease_owner: Some("rust-worker".to_string()),
22306            workflow_id: Some("typed-replay".to_string()),
22307            run_id: Some("run-typed-replay".to_string()),
22308            workflow_type: "typed.replayed".to_string(),
22309            query_name: "inspect".to_string(),
22310            payload_codec: DEFAULT_CODEC.to_string(),
22311            workflow_arguments: Some(
22312                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
22313            ),
22314            query_arguments: Some(
22315                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
22316            ),
22317            history_events: vec![history_event(
22318                "SignalReceived",
22319                json!({
22320                    "signal_id": "collision-signal",
22321                    "signal_name": "collision",
22322                    "workflow_sequence": 1,
22323                    "payload_codec": DEFAULT_CODEC,
22324                    "arguments": signal_arguments,
22325                }),
22326            )],
22327            history_export: None,
22328            run_status: Some("completed".to_string()),
22329        };
22330
22331        assert_eq!(
22332            worker
22333                .execute_query_task(task)
22334                .await
22335                .expect("typed replay query"),
22336            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
22337        );
22338    }
22339
22340    #[test]
22341    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
22342        let value = BTreeMap::from([(1_i32, "integer key")]);
22343        let error = PayloadEnvelope::avro(&value)
22344            .expect_err("integer map keys must fail")
22345            .to_string();
22346
22347        assert!(error.contains("invalid_map_key"));
22348    }
22349
22350    #[test]
22351    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
22352        let envelope = PayloadEnvelope {
22353            codec: "json".to_string(),
22354            blob: r#"{"greeting":"hello"}"#.to_string(),
22355        };
22356
22357        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
22358        let diagnostic = error.to_string();
22359        assert!(diagnostic.contains("unsupported_payload_codec"));
22360        assert!(diagnostic.contains("codec=\"avro\""));
22361        assert!(diagnostic.contains("HTTP document transport"));
22362    }
22363
22364    #[test]
22365    fn untagged_json_payload_value_fails_closed() {
22366        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
22367            .expect_err("untagged JSON payload values must fail");
22368        let diagnostic = error.to_string();
22369        assert!(diagnostic.contains("unsupported_payload_codec"));
22370        assert!(diagnostic.contains("untagged durable payload"));
22371        assert!(diagnostic.contains("HTTP document transport"));
22372    }
22373
22374    #[test]
22375    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
22376        let envelope = PayloadEnvelope {
22377            codec: DEFAULT_CODEC.to_string(),
22378            blob: BASE64.encode([0x01]),
22379        };
22380
22381        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
22382        assert!(error.to_string().contains("invalid_payload_framing"));
22383    }
22384
22385    #[tokio::test]
22386    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
22387        let server = MockWorkerServer::start();
22388        let client = Client::builder(server.base_url())
22389            .timeout(Duration::from_secs(2))
22390            .build()
22391            .expect("client");
22392        let invalid_commands = [
22393            json!({
22394                "type": "complete_workflow",
22395                "result": {"codec": "json", "blob": null}
22396            }),
22397            json!({
22398                "type": "schedule_activity",
22399                "arguments": {"codec": "yaml", "blob": "ignored"}
22400            }),
22401            json!({
22402                "type": "start_child_workflow",
22403                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
22404            }),
22405            json!({"type": "continue_as_new", "arguments": []}),
22406            json!({"type": "complete_update"}),
22407            json!({"type": "record_side_effect", "result": null}),
22408            json!({
22409                "type": "start_service_operation",
22410                "payload_codec": DEFAULT_CODEC,
22411                "request_payload": "raw-avro-bytes"
22412            }),
22413        ];
22414
22415        for command in invalid_commands {
22416            let error = client
22417                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
22418                .await
22419                .expect_err("invalid durable payload must fail locally");
22420            let diagnostic = error.to_string();
22421            assert!(
22422                diagnostic.contains("unsupported_payload_codec")
22423                    || diagnostic.contains("invalid_payload_envelope")
22424                    || diagnostic.contains("untagged durable payload"),
22425                "unexpected validation diagnostic: {diagnostic}"
22426            );
22427        }
22428
22429        assert_eq!(
22430            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
22431            0,
22432            "invalid command payloads must not reach HTTP transport"
22433        );
22434    }
22435
22436    #[test]
22437    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
22438        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
22439        let commands = [
22440            json!({"type": "complete_workflow", "result": envelope.clone()}),
22441            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
22442            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
22443            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
22444            json!({"type": "complete_update", "result": envelope.clone()}),
22445            json!({"type": "record_side_effect", "result": envelope.clone()}),
22446            json!({
22447                "type": "start_service_operation",
22448                "payload_codec": DEFAULT_CODEC,
22449                "request_payload": envelope.clone()
22450            }),
22451            json!({
22452                "type": "complete_workflow",
22453                "result": envelope,
22454                "metadata": {
22455                    "codec": "json",
22456                    "payload_codec": "customer-codec",
22457                    "result": {"codec": "yaml", "blob": null}
22458                }
22459            }),
22460        ];
22461
22462        validate_workflow_task_commands(&commands)
22463            .expect("customer metadata must not become a protocol codec declaration");
22464    }
22465
22466    #[test]
22467    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
22468        assert_eq!(
22469            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
22470            AvroValue::Array(Vec::new())
22471        );
22472        assert_eq!(
22473            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
22474            AvroValue::Array(Vec::new())
22475        );
22476
22477        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22478        signal.signal_name = Some("empty-signal".to_string());
22479        signal.signal_arguments = None;
22480        let decoded = decode_resume_signal(&signal)
22481            .expect("valid Avro signal")
22482            .expect("named signal resumes the workflow");
22483        assert!(decoded.arguments.is_empty());
22484    }
22485
22486    #[tokio::test]
22487    async fn malformed_task_level_codecs_become_pre_handler_failures() {
22488        let client = Client::new("http://127.0.0.1:8080").expect("client");
22489        let mut worker = Worker::new(client, "rust-workers");
22490        let handler_calls = Arc::new(AtomicUsize::new(0));
22491
22492        let calls = Arc::clone(&handler_calls);
22493        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22494            calls.fetch_add(1, Ordering::SeqCst);
22495            async move { Ok(Value::Null) }
22496        });
22497        let calls = Arc::clone(&handler_calls);
22498        worker.register_activity("codec.activity", move |_ctx, _args| {
22499            calls.fetch_add(1, Ordering::SeqCst);
22500            async move { Ok(Value::Null) }
22501        });
22502        let calls = Arc::clone(&handler_calls);
22503        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22504            calls.fetch_add(1, Ordering::SeqCst);
22505            async move { Ok(Value::Null) }
22506        });
22507
22508        let mut failures = Vec::new();
22509        for codec_case in [
22510            InvalidTaskPayloadCodec::Missing,
22511            InvalidTaskPayloadCodec::Null,
22512            InvalidTaskPayloadCodec::NonString,
22513        ] {
22514            let mut workflow = json!({
22515                "task_id": format!("workflow-{}", codec_case.label()),
22516                "workflow_type": "codec.workflow"
22517            });
22518            codec_case.apply(&mut workflow);
22519            match serde_json::from_value::<WorkflowTask>(workflow) {
22520                Ok(task) => match worker.execute_workflow_task(task) {
22521                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
22522                    outcome => failures.push(format!(
22523                        "workflow {} codec returned {outcome:?}",
22524                        codec_case.label()
22525                    )),
22526                },
22527                Err(error) => failures.push(format!(
22528                    "workflow {} codec failed transport deserialization: {error}",
22529                    codec_case.label()
22530                )),
22531            }
22532
22533            let mut activity = json!({
22534                "task_id": format!("activity-{}", codec_case.label()),
22535                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
22536                "activity_type": "codec.activity",
22537                "attempt_number": 1
22538            });
22539            codec_case.apply(&mut activity);
22540            match serde_json::from_value::<ActivityTask>(activity) {
22541                Ok(task) => match worker.execute_activity_task(task).await {
22542                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
22543                    outcome => failures.push(format!(
22544                        "activity {} codec returned {outcome:?}",
22545                        codec_case.label()
22546                    )),
22547                },
22548                Err(error) => failures.push(format!(
22549                    "activity {} codec failed transport deserialization: {error}",
22550                    codec_case.label()
22551                )),
22552            }
22553
22554            let mut query = json!({
22555                "query_task_id": format!("query-{}", codec_case.label()),
22556                "workflow_type": "codec.workflow",
22557                "query_name": "known"
22558            });
22559            codec_case.apply(&mut query);
22560            match serde_json::from_value::<QueryTask>(query) {
22561                Ok(task) => match worker.execute_query_task(task).await {
22562                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
22563                    outcome => failures.push(format!(
22564                        "query {} codec returned {outcome:?}",
22565                        codec_case.label()
22566                    )),
22567                },
22568                Err(error) => failures.push(format!(
22569                    "query {} codec failed transport deserialization: {error}",
22570                    codec_case.label()
22571                )),
22572            }
22573        }
22574
22575        assert!(failures.is_empty(), "{}", failures.join("\n"));
22576        assert_eq!(
22577            handler_calls.load(Ordering::SeqCst),
22578            0,
22579            "invalid task codecs must not invoke a handler"
22580        );
22581    }
22582
22583    #[tokio::test]
22584    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
22585        for codec_case in [
22586            InvalidTaskPayloadCodec::Missing,
22587            InvalidTaskPayloadCodec::Null,
22588            InvalidTaskPayloadCodec::NonString,
22589        ] {
22590            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
22591            let client = Client::builder(server.base_url())
22592                .timeout(Duration::from_secs(2))
22593                .build()
22594                .expect("client");
22595            let mut worker = Worker::new(client, "rust-workers")
22596                .worker_id("codec-worker")
22597                .poll_timeout(Duration::from_millis(10));
22598            let handler_calls = Arc::new(AtomicUsize::new(0));
22599
22600            let calls = Arc::clone(&handler_calls);
22601            worker.register_workflow("codec.workflow", move |_ctx, _args| {
22602                calls.fetch_add(1, Ordering::SeqCst);
22603                async move { Ok(Value::Null) }
22604            });
22605            let calls = Arc::clone(&handler_calls);
22606            worker.register_activity("codec.activity", move |_ctx, _args| {
22607                calls.fetch_add(1, Ordering::SeqCst);
22608                async move { Ok(Value::Null) }
22609            });
22610            let calls = Arc::clone(&handler_calls);
22611            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22612                calls.fetch_add(1, Ordering::SeqCst);
22613                async move { Ok(Value::Null) }
22614            });
22615
22616            assert_eq!(
22617                worker.run_once().await.expect("invalid tasks are settled"),
22618                3,
22619                "all {} codec tasks must be handled",
22620                codec_case.label()
22621            );
22622            assert_eq!(
22623                handler_calls.load(Ordering::SeqCst),
22624                0,
22625                "{} task codecs must fail before every handler",
22626                codec_case.label()
22627            );
22628
22629            for path in [
22630                "/api/worker/workflow-tasks/codec-workflow/fail",
22631                "/api/worker/activity-tasks/codec-activity/fail",
22632                "/api/worker/query-tasks/codec-query/fail",
22633            ] {
22634                let body = server.request_body(path);
22635                assert!(
22636                    body["failure"]["message"]
22637                        .as_str()
22638                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
22639                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
22640                    codec_case.label()
22641                );
22642            }
22643            assert_eq!(
22644                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
22645                    ["reason"],
22646                "query_payload_decode_failed"
22647            );
22648            for path in [
22649                "/api/worker/workflow-tasks/codec-workflow/complete",
22650                "/api/worker/activity-tasks/codec-activity/complete",
22651                "/api/worker/query-tasks/codec-query/complete",
22652            ] {
22653                assert_eq!(
22654                    server.request_count(path),
22655                    0,
22656                    "invalid {} codec task reached {path}",
22657                    codec_case.label()
22658                );
22659            }
22660        }
22661    }
22662
22663    #[tokio::test]
22664    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
22665        let client = Client::new("http://127.0.0.1:8080").expect("client");
22666        let mut worker = Worker::new(client, "rust-workers");
22667        let handler_calls = Arc::new(AtomicUsize::new(0));
22668
22669        let calls = Arc::clone(&handler_calls);
22670        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22671            calls.fetch_add(1, Ordering::SeqCst);
22672            async move { Ok(Value::Null) }
22673        });
22674        let calls = Arc::clone(&handler_calls);
22675        worker.register_activity("codec.activity", move |_ctx, _args| {
22676            calls.fetch_add(1, Ordering::SeqCst);
22677            async move { Ok(Value::Null) }
22678        });
22679        let calls = Arc::clone(&handler_calls);
22680        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
22681            calls.fetch_add(1, Ordering::SeqCst);
22682            async move { Ok(Value::Null) }
22683        });
22684        let calls = Arc::clone(&handler_calls);
22685        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22686            calls.fetch_add(1, Ordering::SeqCst);
22687            async move { Ok(Value::Null) }
22688        });
22689
22690        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22691        workflow.payload_codec = "json".to_string();
22692        workflow.arguments = None;
22693        let error = worker
22694            .execute_workflow_task(workflow)
22695            .expect_err("task codec must be checked before workflow invocation");
22696        assert!(error.to_string().contains("unsupported_payload_codec"));
22697
22698        let activity = ActivityTask {
22699            task_id: "activity-invalid-codec".to_string(),
22700            workflow_id: None,
22701            run_id: None,
22702            activity_execution_id: None,
22703            observability_context: None,
22704            dispatch_observability_context: None,
22705            observability_links: None,
22706            activity_attempt_id: None,
22707            attempt_id: None,
22708            activity_type: "codec.activity".to_string(),
22709            payload_codec: "unknown".to_string(),
22710            arguments: None,
22711            attempt_number: 1,
22712            lease_owner: None,
22713        };
22714        let error = worker
22715            .execute_activity_task(activity)
22716            .await
22717            .expect_err("task codec must be checked before activity invocation");
22718        assert!(error.to_string().contains("unsupported_payload_codec"));
22719
22720        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22721        update.workflow_update_id = Some("update-invalid-codec".to_string());
22722        update.update_name = Some("known".to_string());
22723        update.history_events.push(history_event(
22724            "UpdateAccepted",
22725            json!({
22726                "update_id": "update-invalid-codec",
22727                "update_name": "known",
22728                "arguments": {"codec": "json", "blob": null}
22729            }),
22730        ));
22731        let error = worker
22732            .execute_workflow_task(update)
22733            .expect_err("nested update codec must be checked before handler lookup");
22734        assert!(error.to_string().contains("unsupported_payload_codec"));
22735
22736        let query: QueryTask = serde_json::from_value(json!({
22737            "query_task_id": "query-invalid-codec",
22738            "workflow_type": "codec.workflow",
22739            "query_name": "known",
22740            "payload_codec": DEFAULT_CODEC,
22741            "workflow_arguments": null,
22742            "query_arguments": null,
22743            "history_export": {
22744                "payloads": {"codec": DEFAULT_CODEC},
22745                "signals": [{
22746                    "name": "empty",
22747                    "payload_codec": "json",
22748                    "arguments": null
22749                }]
22750            }
22751        }))
22752        .expect("query task");
22753        let failure = worker
22754            .execute_query_task(query)
22755            .await
22756            .expect_err("exported signal codec must be checked before query invocation");
22757        assert_eq!(failure.reason, "query_payload_decode_failed");
22758        assert!(failure.message.contains("unsupported_payload_codec"));
22759
22760        let exported_history: QueryTask = serde_json::from_value(json!({
22761            "query_task_id": "query-invalid-history-codec",
22762            "workflow_type": "codec.workflow",
22763            "query_name": "known",
22764            "payload_codec": DEFAULT_CODEC,
22765            "history_export": {
22766                "payloads": {"codec": DEFAULT_CODEC},
22767                "history_events": [{
22768                    "type": "ActivityCompleted",
22769                    "payload": {"payload_codec": "unknown", "result": null}
22770                }]
22771            }
22772        }))
22773        .expect("query task");
22774        let failure = worker
22775            .execute_query_task(exported_history)
22776            .await
22777            .expect_err("exported history codec must be checked before query invocation");
22778        assert_eq!(failure.reason, "query_payload_decode_failed");
22779        assert!(failure.message.contains("unsupported_payload_codec"));
22780        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
22781
22782        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22783        unknown_workflow.arguments = None;
22784        unknown_workflow.history_events.push(history_event(
22785            "SignalReceived",
22786            json!({
22787                "signal_name": "empty",
22788                "payload_codec": "json",
22789                "arguments": null
22790            }),
22791        ));
22792        let error = worker
22793            .execute_workflow_task(unknown_workflow)
22794            .expect_err("history codec must precede unknown workflow outcome");
22795        assert!(error.to_string().contains("unsupported_payload_codec"));
22796
22797        let unknown_activity = ActivityTask {
22798            task_id: "activity-unknown".to_string(),
22799            workflow_id: None,
22800            run_id: None,
22801            activity_execution_id: None,
22802            observability_context: None,
22803            dispatch_observability_context: None,
22804            observability_links: None,
22805            activity_attempt_id: None,
22806            attempt_id: None,
22807            activity_type: "missing".to_string(),
22808            payload_codec: "json".to_string(),
22809            arguments: None,
22810            attempt_number: 1,
22811            lease_owner: None,
22812        };
22813        let error = worker
22814            .execute_activity_task(unknown_activity)
22815            .await
22816            .expect_err("codec must precede unknown activity outcome");
22817        assert!(error.to_string().contains("unsupported_payload_codec"));
22818
22819        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22820        unknown_update.payload_codec = "json".to_string();
22821        unknown_update.arguments = None;
22822        unknown_update.workflow_update_id = Some("update-unknown".to_string());
22823        unknown_update.update_name = Some("missing".to_string());
22824        let error = worker
22825            .execute_workflow_task(unknown_update)
22826            .expect_err("codec must precede fail_update shortcut");
22827        assert!(error.to_string().contains("unsupported_payload_codec"));
22828
22829        let unknown_query: QueryTask = serde_json::from_value(json!({
22830            "query_task_id": "query-unknown",
22831            "workflow_type": "missing",
22832            "query_name": "missing",
22833            "payload_codec": "json",
22834            "workflow_arguments": null,
22835            "query_arguments": null
22836        }))
22837        .expect("query task");
22838        let failure = worker
22839            .execute_query_task(unknown_query)
22840            .await
22841            .expect_err("codec must precede unknown query outcome");
22842        assert_eq!(failure.reason, "query_payload_decode_failed");
22843        assert!(failure.message.contains("unsupported_payload_codec"));
22844    }
22845
22846    #[tokio::test]
22847    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
22848        let client = Client::new("http://127.0.0.1:8080").expect("client");
22849        let worker = Worker::new(client, "rust-workers");
22850
22851        for event_type in ["SignalReceived", "SignalApplied"] {
22852            for (payload_field, codec) in [
22853                ("value", "json"),
22854                ("input", "unknown"),
22855                ("arguments", "json"),
22856            ] {
22857                let payload = json!({
22858                    "signal_name": "empty",
22859                    payload_field: {"codec": codec, "blob": null}
22860                });
22861                let workflow = workflow_task(
22862                    "missing",
22863                    vec![history_event(event_type, payload.clone())],
22864                    DEFAULT_CODEC,
22865                );
22866                let error = worker
22867                    .execute_workflow_task(workflow)
22868                    .expect_err("signal payload codec must precede unknown workflow outcome");
22869                assert!(
22870                    error.to_string().contains("unsupported_payload_codec"),
22871                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
22872                );
22873
22874                let query: QueryTask = serde_json::from_value(json!({
22875                    "query_task_id": format!("query-{event_type}-{payload_field}"),
22876                    "workflow_type": "missing",
22877                    "query_name": "missing",
22878                    "payload_codec": DEFAULT_CODEC,
22879                    "workflow_arguments": null,
22880                    "query_arguments": null,
22881                    "history_events": [{
22882                        "event_type": event_type,
22883                        "payload": payload
22884                    }]
22885                }))
22886                .expect("query task");
22887                let failure = worker
22888                    .execute_query_task(query)
22889                    .await
22890                    .expect_err("signal payload codec must precede unknown query outcome");
22891                assert_eq!(
22892                    failure.reason, "query_payload_decode_failed",
22893                    "{event_type}.{payload_field} returned an unrelated query outcome"
22894                );
22895                assert!(
22896                    failure.message.contains("unsupported_payload_codec"),
22897                    "{event_type}.{payload_field} returned an unrelated query error: {}",
22898                    failure.message
22899                );
22900            }
22901        }
22902    }
22903
22904    #[test]
22905    fn workflow_context_schedules_activity_until_completion_is_in_history() {
22906        let ctx = WorkflowContext {
22907            cancellation_scope_id: "root".into(),
22908            state: Arc::new(Mutex::new(
22909                WorkflowState::new_with_identity(
22910                    Vec::new(),
22911                    Some("wf-parent".to_string()),
22912                    Some("run-parent".to_string()),
22913                    "rust-workers".to_string(),
22914                    DEFAULT_CODEC.to_string(),
22915                    None,
22916                )
22917                .expect("workflow state"),
22918            )),
22919        };
22920
22921        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
22922        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22923        assert!(matches!(
22924            call.as_mut().poll(&mut task_context),
22925            Poll::Pending
22926        ));
22927
22928        let commands = ctx.take_commands().expect("commands");
22929        assert_eq!(commands[0]["type"], "schedule_activity");
22930        assert_eq!(commands[0]["activity_type"], "hello.activity");
22931    }
22932
22933    #[test]
22934    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
22935        let ctx = workflow_context(Vec::new());
22936        let options = ActivityOptions::new()
22937            .task_queue("payments")
22938            .retry_policy(
22939                ActivityRetryPolicy::new(4)
22940                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
22941                    .non_retryable_error_type("ValidationError"),
22942            )
22943            .start_to_close_timeout(Duration::from_secs(120))
22944            .schedule_to_start_timeout(Duration::from_secs(10))
22945            .schedule_to_close_timeout(Duration::from_secs(300))
22946            .heartbeat_timeout(Duration::from_secs(15));
22947        let mut call = Box::pin(ctx.activity_with_options(
22948            "charge-card",
22949            options,
22950            json!([{"order_id": "o-1"}]),
22951        ));
22952        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22953
22954        assert!(matches!(
22955            call.as_mut().poll(&mut task_context),
22956            Poll::Pending
22957        ));
22958        assert!(matches!(
22959            call.as_mut().poll(&mut task_context),
22960            Poll::Pending
22961        ));
22962
22963        let commands = ctx.take_commands().expect("activity command");
22964        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
22965        assert_eq!(commands[0]["queue"], "payments");
22966        assert_eq!(
22967            commands[0]["retry_policy"],
22968            json!({
22969                "max_attempts": 4,
22970                "backoff_seconds": [1, 3, 9],
22971                "non_retryable_error_types": ["ValidationError"],
22972            })
22973        );
22974        assert_eq!(commands[0]["start_to_close_timeout"], 120);
22975        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
22976        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
22977        assert_eq!(commands[0]["heartbeat_timeout"], 15);
22978    }
22979
22980    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
22981        vec![
22982            history_event(
22983                "ActivityScheduled",
22984                json!({"sequence":1,"activity_type":"render",
22985                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
22986            ),
22987            history_event(
22988                "ActivityCompleted",
22989                json!({"sequence":1,"activity_type":"render",
22990                "payload_codec":DEFAULT_CODEC,
22991                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
22992            ),
22993        ]
22994    }
22995
22996    #[test]
22997    fn worker_session_activity_routes_to_session_queue_once() {
22998        let ctx = workflow_context(Vec::new());
22999        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23000        let mut call = Box::pin(
23001            ctx.activity("render", json!([]))
23002                .in_worker_session(session.clone()),
23003        );
23004        let mut cx = TaskContext::from_waker(noop_waker_ref());
23005        assert!(call.as_mut().poll(&mut cx).is_pending());
23006        assert!(call.as_mut().poll(&mut cx).is_pending());
23007        let commands = ctx.take_commands().unwrap();
23008        assert_eq!(commands.len(), 1);
23009        assert_eq!(commands[0]["queue"], "gpu-workers");
23010        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
23011    }
23012
23013    #[tokio::test]
23014    async fn worker_session_cold_replay_uses_recorded_avro_result() {
23015        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23016        for _replacement in 0..2 {
23017            let ctx = workflow_context(completed_worker_session_history(&session));
23018            let result: i64 = ctx
23019                .activity("render", json!([]))
23020                .in_worker_session(session.clone())
23021                .typed()
23022                .await
23023                .unwrap();
23024            assert_eq!(result, 42);
23025            assert!(ctx.take_commands().unwrap().is_empty());
23026        }
23027    }
23028
23029    #[test]
23030    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
23031        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23032        for changed in [
23033            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
23034            Some(original.clone().ttl_seconds(60)),
23035            Some(original.clone().requirements(["gpu:l4"])),
23036            None,
23037        ] {
23038            let ctx = workflow_context(completed_worker_session_history(&original));
23039            let mut call = ctx.activity_with_options(
23040                "render",
23041                ActivityOptions::new().task_queue("gpu-workers"),
23042                json!([]),
23043            );
23044            if let Some(changed) = changed {
23045                call = call.in_worker_session(changed);
23046            }
23047            let mut call = Box::pin(call);
23048            let mut cx = TaskContext::from_waker(noop_waker_ref());
23049            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23050                call.as_mut().poll(&mut cx)
23051            else {
23052                panic!("changed session must fail replay");
23053            };
23054            assert_eq!(failure.reason, "activity_worker_session_mismatch");
23055            assert!(ctx.take_commands().unwrap().is_empty());
23056        }
23057    }
23058
23059    #[test]
23060    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
23061        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23062        let ctx = workflow_context(Vec::new());
23063        let mut local = Box::pin(
23064            ctx.local_activity("render", json!([]))
23065                .in_worker_session(session.clone()),
23066        );
23067        let mut cx = TaskContext::from_waker(noop_waker_ref());
23068        assert!(matches!(
23069            local.as_mut().poll(&mut cx),
23070            Poll::Ready(Err(Error::WorkerLoop(_)))
23071        ));
23072        assert!(ctx.take_commands().unwrap().is_empty());
23073        let mut remote = Box::pin(
23074            ctx.activity_with_options(
23075                "render",
23076                ActivityOptions::new().task_queue("other"),
23077                json!([]),
23078            )
23079            .in_worker_session(session),
23080        );
23081        assert!(matches!(
23082            remote.as_mut().poll(&mut cx),
23083            Poll::Ready(Err(Error::WorkerLoop(_)))
23084        ));
23085        assert!(ctx.take_commands().unwrap().is_empty());
23086    }
23087
23088    #[test]
23089    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
23090        let ctx = workflow_context(Vec::new());
23091        let options = ActivityOptions::new().retry_policy(
23092            ActivityRetryPolicy::new(3)
23093                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
23094        );
23095        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23096        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23097
23098        assert!(matches!(
23099            call.as_mut().poll(&mut task_context),
23100            Poll::Pending
23101        ));
23102        assert_eq!(
23103            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
23104            json!([1, 2])
23105        );
23106    }
23107
23108    #[test]
23109    fn activity_options_preserve_unused_explicit_backoff_entries() {
23110        for max_attempts in [1, 2, 10] {
23111            let ctx = workflow_context(Vec::new());
23112            let options =
23113                ActivityOptions::new()
23114                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
23115                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
23116                    ));
23117            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23118            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23119            assert!(matches!(
23120                call.as_mut().poll(&mut task_context),
23121                Poll::Pending
23122            ));
23123            let commands = ctx.take_commands().expect("command");
23124            assert_eq!(commands.len(), 1);
23125            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
23126            assert_eq!(
23127                commands[0]["retry_policy"]["backoff_seconds"],
23128                json!([1, 2, 5, 10, 15, 30, 60, 120])
23129            );
23130        }
23131        let default_options = ActivityOptions::new().validate().expect("default options");
23132        let default_policy = current_activity_retry_snapshot(&default_options);
23133        assert_eq!(
23134            default_policy.max_attempts,
23135            RecordedSnapshotValue::Known(Some(1))
23136        );
23137        assert_eq!(
23138            default_policy.backoff_seconds,
23139            RecordedSnapshotValue::Known(Vec::new())
23140        );
23141    }
23142
23143    #[test]
23144    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
23145        let fixture: Value = serde_json::from_str(include_str!(
23146            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
23147        ))
23148        .expect("published PHP fixture");
23149        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
23150            .expect("unchanged published history");
23151        let matching = ActivityOptions::new().task_queue("default").retry_policy(
23152            ActivityRetryPolicy::new(1)
23153                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
23154        );
23155        let mut changed_tail = matching.clone();
23156        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
23157            [1, 2, 5, 10, 15, 30, 60, 121]
23158                .map(Duration::from_secs)
23159                .to_vec(),
23160        ));
23161        let mut changed_first = matching.clone();
23162        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
23163            [2, 2, 5, 10, 15, 30, 60, 120]
23164                .map(Duration::from_secs)
23165                .to_vec(),
23166        ));
23167        let mut changed_attempts = matching.clone();
23168        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
23169        let mut changed_types = matching.clone();
23170        changed_types
23171            .retry_policy
23172            .as_mut()
23173            .unwrap()
23174            .non_retryable_error_types = vec!["ChangedError".into()];
23175        let mut changed_start = matching.clone();
23176        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
23177        let mut changed_schedule_start = matching.clone();
23178        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
23179        let mut changed_schedule_close = matching.clone();
23180        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
23181        let mut changed_heartbeat = matching;
23182        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
23183        let unchanged_defaults = ActivityOptions::new().task_queue("default");
23184        for options in [
23185            changed_tail,
23186            changed_first,
23187            changed_attempts,
23188            changed_types,
23189            changed_start,
23190            changed_schedule_start,
23191            changed_schedule_close,
23192            changed_heartbeat,
23193            unchanged_defaults,
23194        ] {
23195            let ctx = workflow_context(history.clone());
23196            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
23197            assert!(!ctx.patched("frozen-zero").unwrap());
23198            ctx.deprecate_patch("frozen-zero").unwrap();
23199            let mut call =
23200                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
23201            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23202            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23203                call.as_mut().poll(&mut task_context)
23204            else {
23205                panic!("changed explicit policy must fail replay")
23206            };
23207            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
23208            assert_eq!(failure.sequence, Some(2));
23209            assert!(ctx.take_commands().unwrap().is_empty());
23210        }
23211    }
23212
23213    #[test]
23214    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
23215        let cases = [
23216            (
23217                ActivityOptions::new().task_queue("  "),
23218                ActivityOptionsErrorKind::EmptyTaskQueue,
23219            ),
23220            (
23221                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
23222                ActivityOptionsErrorKind::EmptyRetryPolicy,
23223            ),
23224            (
23225                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
23226                ActivityOptionsErrorKind::InvalidMaxAttempts,
23227            ),
23228            (
23229                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
23230                    max_attempts: None,
23231                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
23232                    non_retryable_error_types: Vec::new(),
23233                }),
23234                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
23235            ),
23236            (
23237                ActivityOptions::new().retry_policy(
23238                    ActivityRetryPolicy::new(2).exponential_backoff(
23239                        Duration::from_secs(1),
23240                        0,
23241                        None,
23242                    ),
23243                ),
23244                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
23245            ),
23246            (
23247                ActivityOptions::new()
23248                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
23249                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
23250            ),
23251            (
23252                ActivityOptions::new().retry_policy(
23253                    ActivityRetryPolicy::new(10_002).exponential_backoff(
23254                        Duration::from_secs(1),
23255                        1,
23256                        None,
23257                    ),
23258                ),
23259                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
23260            ),
23261            (
23262                ActivityOptions::new().retry_policy(
23263                    ActivityRetryPolicy::new(2)
23264                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
23265                ),
23266                ActivityOptionsErrorKind::BackoffOverflow,
23267            ),
23268        ];
23269
23270        for (options, expected_kind) in cases {
23271            let ctx = workflow_context(Vec::new());
23272            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23273            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23274            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
23275                call.as_mut().poll(&mut task_context)
23276            else {
23277                panic!("expected typed activity validation error");
23278            };
23279            assert_eq!(error.kind, expected_kind);
23280            assert!(ctx.take_commands().expect("commands").is_empty());
23281        }
23282    }
23283
23284    #[test]
23285    fn activity_options_validate_positive_and_ordered_timeouts() {
23286        let zero_timeout_cases = [
23287            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
23288            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
23289            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
23290            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
23291        ];
23292        for options in zero_timeout_cases {
23293            assert_eq!(
23294                options.validate().expect_err("zero timeout").kind,
23295                ActivityOptionsErrorKind::TimeoutNotPositive
23296            );
23297        }
23298
23299        let ordering_cases = [
23300            ActivityOptions::new()
23301                .heartbeat_timeout(Duration::from_secs(11))
23302                .start_to_close_timeout(Duration::from_secs(10)),
23303            ActivityOptions::new()
23304                .start_to_close_timeout(Duration::from_secs(31))
23305                .schedule_to_close_timeout(Duration::from_secs(30)),
23306            ActivityOptions::new()
23307                .schedule_to_start_timeout(Duration::from_secs(31))
23308                .schedule_to_close_timeout(Duration::from_secs(30)),
23309        ];
23310        for options in ordering_cases {
23311            assert_eq!(
23312                options.validate().expect_err("timeout order").kind,
23313                ActivityOptionsErrorKind::TimeoutOrder
23314            );
23315        }
23316
23317        assert_eq!(
23318            ActivityOptions::new()
23319                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
23320                .validate()
23321                .expect_err("protocol integer overflow")
23322                .kind,
23323            ActivityOptionsErrorKind::TimeoutOverflow
23324        );
23325    }
23326
23327    #[test]
23328    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
23329        let ctx = workflow_context(completed_retry_activity_history());
23330        let mut call =
23331            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23332        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23333
23334        assert!(matches!(
23335            call.as_mut().poll(&mut task_context),
23336            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23337        ));
23338        assert!(ctx.take_commands().expect("commands").is_empty());
23339        ctx.ensure_history_consumed().expect("history consumed");
23340    }
23341
23342    #[test]
23343    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
23344        let mut options = retry_activity_options();
23345        options
23346            .retry_policy
23347            .as_mut()
23348            .expect("retry policy")
23349            .non_retryable_error_types
23350            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
23351
23352        let new_ctx = workflow_context(Vec::new());
23353        let mut new_call =
23354            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
23355        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23356        assert!(matches!(
23357            new_call.as_mut().poll(&mut task_context),
23358            Poll::Pending
23359        ));
23360        let commands = new_ctx.take_commands().expect("commands");
23361        assert_eq!(commands.len(), 1);
23362        assert_eq!(
23363            commands[0]["retry_policy"]["non_retryable_error_types"],
23364            json!(["PermanentError"])
23365        );
23366
23367        let replay_ctx = workflow_context(completed_retry_activity_history());
23368        let mut replay_call =
23369            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
23370        assert!(matches!(
23371            replay_call.as_mut().poll(&mut task_context),
23372            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23373        ));
23374        assert!(replay_ctx.take_commands().expect("commands").is_empty());
23375        replay_ctx
23376            .ensure_history_consumed()
23377            .expect("history consumed");
23378    }
23379
23380    #[test]
23381    fn replayed_intermediate_retry_remains_pending_across_restarts() {
23382        let history = completed_retry_activity_history()
23383            .into_iter()
23384            .take(3)
23385            .collect::<Vec<_>>();
23386
23387        for _restart in 0..2 {
23388            let ctx = workflow_context(history.clone());
23389            let mut call =
23390                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23391            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23392            assert!(matches!(
23393                call.as_mut().poll(&mut task_context),
23394                Poll::Pending
23395            ));
23396            assert!(ctx.take_commands().expect("commands").is_empty());
23397        }
23398    }
23399
23400    #[test]
23401    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
23402        let mut changed_queue = retry_activity_options();
23403        changed_queue.task_queue = Some("different-queue".to_string());
23404
23405        let mut changed_max_attempts = retry_activity_options();
23406        let retry_policy = changed_max_attempts
23407            .retry_policy
23408            .as_mut()
23409            .expect("retry policy");
23410        retry_policy.max_attempts = Some(4);
23411
23412        let mut changed_backoff = retry_activity_options();
23413        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
23414        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
23415            Duration::from_secs(3),
23416            Duration::from_secs(4),
23417        ]));
23418
23419        let mut changed_non_retryable_types = retry_activity_options();
23420        let retry_policy = changed_non_retryable_types
23421            .retry_policy
23422            .as_mut()
23423            .expect("retry policy");
23424        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
23425
23426        let mut changed_start_to_close = retry_activity_options();
23427        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
23428        let mut changed_schedule_to_start = retry_activity_options();
23429        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
23430        let mut changed_schedule_to_close = retry_activity_options();
23431        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
23432        let mut changed_heartbeat = retry_activity_options();
23433        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
23434
23435        let cases = [
23436            (changed_queue, "activity_task_queue_mismatch"),
23437            (changed_max_attempts, "activity_retry_policy_mismatch"),
23438            (changed_backoff, "activity_retry_policy_mismatch"),
23439            (
23440                changed_non_retryable_types,
23441                "activity_retry_policy_mismatch",
23442            ),
23443            (changed_start_to_close, "activity_retry_policy_mismatch"),
23444            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
23445            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
23446            (changed_heartbeat, "activity_retry_policy_mismatch"),
23447        ];
23448
23449        for (options, expected_reason) in cases {
23450            let ctx = workflow_context(completed_retry_activity_history());
23451            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
23452            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23453            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23454                call.as_mut().poll(&mut task_context)
23455            else {
23456                panic!("changed activity options must fail replay");
23457            };
23458            assert_eq!(failure.reason, expected_reason);
23459            assert_eq!(failure.sequence, Some(1));
23460            assert!(ctx.take_commands().expect("commands").is_empty());
23461        }
23462    }
23463
23464    #[test]
23465    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
23466        let cases = [
23467            (
23468                "execution_mode",
23469                json!("local"),
23470                "activity_execution_mode_mismatch",
23471            ),
23472            (
23473                "snapshot_version",
23474                json!(2),
23475                "activity_retry_policy_mismatch",
23476            ),
23477        ];
23478
23479        for (field, value, expected_reason) in cases {
23480            let mut history = completed_retry_activity_history();
23481            let activity = history[0].payload["activity"]
23482                .as_object_mut()
23483                .expect("activity snapshot");
23484            if field == "execution_mode" {
23485                activity.insert(field.to_string(), value);
23486            } else {
23487                activity["retry_policy"]
23488                    .as_object_mut()
23489                    .expect("retry snapshot")
23490                    .insert(field.to_string(), value);
23491            }
23492
23493            let ctx = workflow_context(history);
23494            let mut call =
23495                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23496            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23497            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23498                call.as_mut().poll(&mut task_context)
23499            else {
23500                panic!("changed {field} must fail replay");
23501            };
23502            assert_eq!(failure.reason, expected_reason);
23503            assert_eq!(failure.sequence, Some(1));
23504            assert!(ctx.take_commands().expect("commands").is_empty());
23505        }
23506    }
23507
23508    #[test]
23509    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
23510        for (nested, field, value, terminal_only) in [
23511            (false, "execution_mode", json!("local"), false),
23512            (false, "local_activity", json!(true), false),
23513            (true, "local_activity", json!(true), false),
23514            (false, "local_activity", json!(true), true),
23515        ] {
23516            let mut history = completed_retry_activity_history();
23517            history[0]
23518                .payload
23519                .as_object_mut()
23520                .unwrap()
23521                .remove("activity");
23522            let event = if terminal_only {
23523                history.last_mut().unwrap()
23524            } else {
23525                &mut history[0]
23526            };
23527            if nested {
23528                event.payload["activity"] = json!({(field): value});
23529            } else {
23530                event.payload[field] = value;
23531            }
23532            let ctx = workflow_context(history);
23533            let mut call =
23534                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23535            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23536            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23537                call.as_mut().poll(&mut task_context)
23538            else {
23539                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
23540            };
23541            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
23542            assert_eq!(failure.sequence, Some(1));
23543            assert!(ctx.take_commands().expect("commands").is_empty());
23544        }
23545    }
23546
23547    #[test]
23548    fn activity_history_rejects_conflicting_local_execution_markers() {
23549        let mut history = completed_retry_activity_history();
23550        history.last_mut().unwrap().payload["local_activity"] = json!(true);
23551        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
23552            .expect_err("remote schedule cannot become a local completion");
23553        assert!(
23554            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
23555            if reason == "activity_execution_mode_conflict")
23556        );
23557    }
23558
23559    #[test]
23560    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
23561        let mut history = completed_retry_activity_history();
23562        let activity = history[0].payload["activity"]
23563            .as_object_mut()
23564            .expect("activity snapshot");
23565        activity.remove("execution_mode");
23566        activity.remove("retry_policy");
23567
23568        let mut current = retry_activity_options();
23569        current.start_to_close_timeout = Some(Duration::from_secs(45));
23570        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
23571        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
23572        current.heartbeat_timeout = Some(Duration::from_secs(12));
23573
23574        let ctx = workflow_context(history);
23575        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
23576        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23577        assert!(matches!(
23578            call.as_mut().poll(&mut task_context),
23579            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23580        ));
23581        assert!(ctx.take_commands().expect("commands").is_empty());
23582        ctx.ensure_history_consumed().expect("history consumed");
23583    }
23584
23585    #[test]
23586    fn terminal_activity_failed_after_start_returns_typed_failure() {
23587        let history = vec![
23588            history_event(
23589                "ActivityScheduled",
23590                json!({
23591                    "sequence": 1,
23592                    "activity_type": "flaky",
23593                    "activity_execution_id": "act-terminal",
23594                    "activity": {
23595                        "id": "act-terminal",
23596                        "sequence": 1,
23597                        "type": "flaky",
23598                        "queue": "critical-activities",
23599                        "retry_policy": {
23600                            "snapshot_version": 1,
23601                            "max_attempts": 3,
23602                            "backoff_seconds": [2, 4],
23603                            "non_retryable_error_types": ["PermanentError"]
23604                        }
23605                    }
23606                }),
23607            ),
23608            history_event(
23609                "ActivityStarted",
23610                json!({
23611                    "sequence": 1,
23612                    "activity_type": "flaky",
23613                    "activity_execution_id": "act-terminal",
23614                    "activity_attempt_id": "attempt-1",
23615                    "attempt_number": 1
23616                }),
23617            ),
23618            history_event(
23619                "ActivityFailed",
23620                json!({
23621                    "sequence": 1,
23622                    "activity_type": "flaky",
23623                    "activity_execution_id": "act-terminal",
23624                    "activity_attempt_id": "attempt-1",
23625                    "attempt_number": 1,
23626                    "failure_id": "failure-terminal",
23627                    "failure_category": "activity",
23628                    "exception_type": "PermanentError",
23629                    "message": "cannot retry",
23630                    "non_retryable": true
23631                }),
23632            ),
23633        ];
23634        let ctx = workflow_context(history);
23635        let mut call =
23636            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23637        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23638
23639        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23640            call.as_mut().poll(&mut task_context)
23641        else {
23642            panic!("terminal ActivityFailed must settle the activity future");
23643        };
23644        assert_eq!(failure.kind, ActivityFailureKind::Failed);
23645        assert_eq!(
23646            failure.activity_execution_id.as_deref(),
23647            Some("act-terminal")
23648        );
23649        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
23650        assert!(failure.non_retryable);
23651        assert!(ctx.take_commands().expect("commands").is_empty());
23652        ctx.ensure_history_consumed().expect("history consumed");
23653    }
23654
23655    #[test]
23656    fn activity_terminal_events_return_machine_readable_failures() {
23657        let cases = [
23658            (
23659                "ActivityFailed",
23660                json!({
23661                    "sequence": 1,
23662                    "activity_type": "charge-card",
23663                    "activity_execution_id": "act-1",
23664                    "activity_attempt_id": "attempt-2",
23665                    "attempt_number": 2,
23666                    "failure_id": "failure-1",
23667                    "failure_category": "activity",
23668                    "exception_type": "PaymentDeclined",
23669                    "exception_class": "payments.PaymentDeclined",
23670                    "message": "card declined",
23671                    "non_retryable": true
23672                }),
23673                ActivityFailureKind::Failed,
23674                "activity",
23675            ),
23676            (
23677                "ActivityCancelled",
23678                json!({
23679                    "sequence": 1,
23680                    "activity_type": "charge-card",
23681                    "activity_execution_id": "act-1",
23682                    "activity_attempt_id": "attempt-1"
23683                }),
23684                ActivityFailureKind::Cancelled,
23685                "cancelled",
23686            ),
23687        ];
23688
23689        for (event_type, payload, expected_kind, expected_reason) in cases {
23690            let ctx = workflow_context(vec![history_event(event_type, payload)]);
23691            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
23692            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23693            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23694                call.as_mut().poll(&mut task_context)
23695            else {
23696                panic!("expected terminal activity failure");
23697            };
23698            assert_eq!(failure.kind, expected_kind);
23699            assert_eq!(failure.reason, expected_reason);
23700            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
23701            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
23702        }
23703    }
23704
23705    #[test]
23706    fn every_activity_timeout_class_is_typed() {
23707        for timeout_kind in [
23708            "start_to_close",
23709            "schedule_to_start",
23710            "schedule_to_close",
23711            "heartbeat",
23712        ] {
23713            let ctx = workflow_context(vec![history_event(
23714                "ActivityTimedOut",
23715                json!({
23716                    "sequence": 1,
23717                    "activity_type": "slow",
23718                    "activity_execution_id": "act-timeout",
23719                    "activity_attempt_id": "attempt-timeout",
23720                    "failure_category": "timeout",
23721                    "timeout_kind": timeout_kind,
23722                    "message": "deadline expired"
23723                }),
23724            )]);
23725            let mut call = Box::pin(ctx.activity("slow", json!([])));
23726            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23727            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23728                call.as_mut().poll(&mut task_context)
23729            else {
23730                panic!("expected timeout failure");
23731            };
23732            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
23733            assert_eq!(failure.reason, timeout_kind);
23734            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
23735            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
23736        }
23737    }
23738
23739    #[test]
23740    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
23741        let ctx = workflow_context(Vec::new());
23742        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
23743        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23744
23745        assert!(matches!(
23746            sleep.as_mut().poll(&mut task_context),
23747            Poll::Pending
23748        ));
23749        assert!(matches!(
23750            sleep.as_mut().poll(&mut task_context),
23751            Poll::Pending
23752        ));
23753
23754        let commands = ctx.take_commands().expect("timer command");
23755        assert_eq!(
23756            commands,
23757            vec![json!({
23758                "type": "start_timer",
23759                "delay_seconds": 2,
23760            })]
23761        );
23762    }
23763
23764    #[test]
23765    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
23766        let history = vec![
23767            history_event(
23768                "TimerScheduled",
23769                json!({
23770                    "sequence": 1,
23771                    "timer_id": "timer-1",
23772                    "delay_seconds": 5,
23773                    "fire_at": "2026-07-11T12:00:05Z",
23774                }),
23775            ),
23776            history_event(
23777                "TimerFired",
23778                json!({
23779                    "sequence": 1,
23780                    "timer_id": "timer-1",
23781                    "delay_seconds": 5,
23782                    "fire_at": "2026-07-11T12:00:05Z",
23783                    "fired_at": "2026-07-11T12:00:05Z",
23784                }),
23785            ),
23786        ];
23787
23788        for _restart in 0..2 {
23789            let ctx = workflow_context(history.clone());
23790            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
23791            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23792            assert!(matches!(
23793                sleep.as_mut().poll(&mut task_context),
23794                Poll::Ready(Ok(()))
23795            ));
23796            assert!(ctx.take_commands().expect("commands").is_empty());
23797            ctx.ensure_history_consumed().expect("history consumed");
23798        }
23799    }
23800
23801    #[test]
23802    fn workflow_sleep_rejects_changed_delay_during_replay() {
23803        let ctx = workflow_context(vec![
23804            history_event(
23805                "TimerScheduled",
23806                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23807            ),
23808            history_event(
23809                "TimerFired",
23810                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23811            ),
23812        ]);
23813        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
23814        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23815
23816        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23817            sleep.as_mut().poll(&mut task_context)
23818        else {
23819            panic!("changed timer delay must be rejected");
23820        };
23821        assert_eq!(failure.reason, "timer_delay_mismatch");
23822        assert_eq!(failure.sequence, Some(1));
23823    }
23824
23825    #[test]
23826    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
23827        let ctx = workflow_context(Vec::new());
23828        let mut wait = Box::pin(
23829            ctx.wait_condition(
23830                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
23831                    .timeout(Duration::from_millis(60_001)),
23832                || Ok(false),
23833            ),
23834        );
23835        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23836
23837        assert!(matches!(
23838            wait.as_mut().poll(&mut task_context),
23839            Poll::Pending
23840        ));
23841        assert!(matches!(
23842            wait.as_mut().poll(&mut task_context),
23843            Poll::Pending
23844        ));
23845        assert_eq!(
23846            ctx.take_commands().expect("condition command"),
23847            vec![json!({
23848                "type": "open_condition_wait",
23849                "condition_wait_occurrence_id": "rust:condition-wait:0",
23850                "condition_key": "approval.ready",
23851                "condition_definition_fingerprint": "sha256:approval-v1",
23852                "timeout_seconds": 61,
23853            })]
23854        );
23855    }
23856
23857    #[test]
23858    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
23859        let ctx = workflow_context(Vec::new());
23860        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
23861        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23862        assert!(matches!(
23863            satisfied.as_mut().poll(&mut task_context),
23864            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23865        ));
23866
23867        let mut timed_out = Box::pin(wait_condition!(
23868            ctx,
23869            "no-wait",
23870            timeout: Duration::ZERO,
23871            || Ok(false),
23872        ));
23873        assert!(matches!(
23874            timed_out.as_mut().poll(&mut task_context),
23875            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
23876        ));
23877        assert!(ctx.take_commands().expect("commands").is_empty());
23878    }
23879
23880    #[test]
23881    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
23882        let signal_history = vec![
23883            history_event(
23884                "ConditionWaitOpened",
23885                json!({
23886                    "sequence": 4,
23887                    "condition_wait_id": "condition:4",
23888                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23889                    "condition_key": "approval",
23890                    "condition_definition_fingerprint": "sha256:approval-v1",
23891                    "timeout_seconds": 30,
23892                }),
23893            ),
23894            history_event(
23895                "SignalReceived",
23896                json!({
23897                    "workflow_sequence": 4,
23898                    "signal_name": "approve",
23899                    "arguments": fixture_envelope(json!(["Ada"])),
23900                }),
23901            ),
23902        ];
23903        for _worker_before_or_after_restart in 0..2 {
23904            let ctx = workflow_context(signal_history.clone());
23905            let predicate_ctx = ctx.clone();
23906            let mut wait = Box::pin(
23907                ctx.wait_condition(
23908                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
23909                        .timeout(Duration::from_secs(30)),
23910                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
23911                ),
23912            );
23913            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23914            assert!(matches!(
23915                wait.as_mut().poll(&mut task_context),
23916                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23917            ));
23918            assert!(ctx.take_commands().expect("commands").is_empty());
23919            ctx.ensure_history_consumed().expect("condition consumed");
23920        }
23921
23922        let update_history = vec![
23923            history_event(
23924                "ConditionWaitOpened",
23925                json!({
23926                    "sequence": 7,
23927                    "condition_wait_id": "condition:7",
23928                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23929                    "condition_key": "update-approval",
23930                    "condition_definition_fingerprint": "sha256:update-approval-v1",
23931                }),
23932            ),
23933            history_event(
23934                "UpdateApplied",
23935                json!({
23936                    "sequence": 7,
23937                    "update_id": "update-1",
23938                    "update_name": "approve",
23939                    "arguments": fixture_envelope(json!([true])),
23940                }),
23941            ),
23942        ];
23943        let ctx = workflow_context(update_history);
23944        let predicate_ctx = ctx.clone();
23945        let mut wait = Box::pin(ctx.wait_condition(
23946            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
23947            move || {
23948                Ok(predicate_ctx
23949                    .updates("approve")?
23950                    .first()
23951                    .and_then(|arguments| arguments.first())
23952                    .and_then(Value::as_bool)
23953                    == Some(true))
23954            },
23955        ));
23956        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23957        assert!(matches!(
23958            wait.as_mut().poll(&mut task_context),
23959            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23960        ));
23961        assert!(ctx.take_commands().expect("commands").is_empty());
23962        ctx.ensure_history_consumed().expect("condition consumed");
23963    }
23964
23965    #[test]
23966    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
23967        let open_history = vec![
23968            history_event(
23969                "ConditionWaitOpened",
23970                json!({
23971                    "sequence": 3,
23972                    "condition_wait_id": "condition:3",
23973                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23974                    "condition_key": "two-votes",
23975                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23976                    "timeout_seconds": 120,
23977                }),
23978            ),
23979            history_event(
23980                "SignalReceived",
23981                json!({
23982                    "workflow_sequence": 3,
23983                    "signal_name": "vote",
23984                    "arguments": fixture_envelope(json!(["first"])),
23985                }),
23986            ),
23987        ];
23988        for _worker_before_or_after_restart in 0..2 {
23989            let ctx = workflow_context(open_history.clone());
23990            let predicate_ctx = ctx.clone();
23991            let mut wait = Box::pin(
23992                ctx.wait_condition(
23993                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
23994                        .timeout(Duration::from_secs(120)),
23995                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
23996                ),
23997            );
23998            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23999            assert!(matches!(
24000                wait.as_mut().poll(&mut task_context),
24001                Poll::Pending
24002            ));
24003            assert_eq!(
24004                ctx.take_commands().expect("reopened condition"),
24005                vec![json!({
24006                    "type": "open_condition_wait",
24007                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24008                    "condition_key": "two-votes",
24009                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24010                    "timeout_seconds": 120,
24011                })]
24012            );
24013        }
24014
24015        let satisfied_ctx = workflow_context(vec![
24016            history_event(
24017                "ConditionWaitOpened",
24018                json!({
24019                    "sequence": 5,
24020                    "condition_wait_id": "condition:5",
24021                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24022                    "condition_key": "approval",
24023                    "condition_definition_fingerprint": "sha256:approval-v1",
24024                }),
24025            ),
24026            history_event(
24027                "ConditionWaitSatisfied",
24028                json!({
24029                    "sequence": 5,
24030                    "condition_wait_id": "condition:5",
24031                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24032                    "condition_key": "approval",
24033                    "condition_definition_fingerprint": "sha256:approval-v1",
24034                }),
24035            ),
24036        ]);
24037        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
24038            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
24039            || Ok(false),
24040        ));
24041        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24042        assert!(matches!(
24043            satisfied.as_mut().poll(&mut task_context),
24044            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24045        ));
24046
24047        let timed_out_ctx = workflow_context(vec![
24048            history_event(
24049                "ConditionWaitOpened",
24050                json!({
24051                    "sequence": 8,
24052                    "condition_wait_id": "condition:8",
24053                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24054                    "condition_key": "approval-timeout",
24055                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
24056                    "timeout_seconds": 5,
24057                }),
24058            ),
24059            history_event(
24060                "TimerScheduled",
24061                json!({
24062                    "sequence": 9,
24063                    "timer_id": "condition-timer:9",
24064                    "timer_kind": "condition_timeout",
24065                    "condition_wait_id": "condition:8",
24066                    "delay_seconds": 5,
24067                }),
24068            ),
24069            history_event(
24070                "TimerFired",
24071                json!({
24072                    "sequence": 9,
24073                    "timer_id": "condition-timer:9",
24074                    "timer_kind": "condition_timeout",
24075                    "condition_wait_id": "condition:8",
24076                    "delay_seconds": 5,
24077                }),
24078            ),
24079        ]);
24080        let mut timed_out = Box::pin(
24081            timed_out_ctx.wait_condition(
24082                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
24083                    .timeout(Duration::from_secs(5)),
24084                || Ok(true),
24085            ),
24086        );
24087        assert!(matches!(
24088            timed_out.as_mut().poll(&mut task_context),
24089            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
24090        ));
24091    }
24092
24093    #[test]
24094    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
24095        let ctx = workflow_context(reopened_selection_condition_history());
24096        {
24097            let state = ctx.state.lock().unwrap();
24098            assert!(matches!(
24099                selection_member_recorded_command(&state, 2),
24100                Some(RecordedCommand::ConditionWait {
24101                    sequence: 3,
24102                    result: None,
24103                    ..
24104                })
24105            ));
24106        }
24107        let mut selected = Box::pin(ctx.select_keyed(vec![
24108            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
24109            (
24110                "votes",
24111                ParallelOperation::condition(
24112                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
24113                    || Ok(true),
24114                ),
24115            ),
24116        ]));
24117        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24118        assert!(selected.as_mut().poll(&mut task_context).is_pending());
24119        assert!(
24120            ctx.take_commands().unwrap().is_empty(),
24121            "true predicate must not reopen the recorded wait"
24122        );
24123        ctx.ensure_history_consumed()
24124            .expect("physical reopens are consumed while canonical selection is pending");
24125    }
24126
24127    #[test]
24128    fn reopened_selection_condition_replays_its_latest_physical_winner() {
24129        for (terminal_type, acknowledge_timeout) in [
24130            ("ConditionWaitSatisfied", false),
24131            ("ConditionWaitTimedOut", false),
24132            ("TimerFired", false),
24133            ("TimerFired", true),
24134        ] {
24135            let mut history = reopened_selection_condition_history();
24136            let original_identity = history[1].payload["condition_wait_id"].clone();
24137            let uses_timer = terminal_type == "TimerFired";
24138            let mut resolution_payload = history[3].payload.clone();
24139            if uses_timer {
24140                for event in &mut history[1..] {
24141                    event.payload["timeout_seconds"] = json!(3);
24142                }
24143                resolution_payload = history[3].payload.clone();
24144                resolution_payload["timer_kind"] = json!("condition_timeout");
24145                resolution_payload["timer_id"] = json!("condition-timeout-3");
24146                resolution_payload["delay_seconds"] = json!(3);
24147                history.push(history_event("TimerScheduled", resolution_payload.clone()));
24148            }
24149            let mut resolution = history_event(terminal_type, resolution_payload.clone());
24150            resolution
24151                .raw
24152                .insert("id".into(), json!("latest-condition-resolution"));
24153            history.push(resolution);
24154            history.push(history_event(
24155                "SelectionResolved",
24156                json!({
24157                    "selection_group_id": "select-calls:1:2",
24158                    "selection_group_base_sequence": 1,
24159                    "selection_group_size": 2,
24160                    "member_key": "votes",
24161                    "member_index": 1,
24162                    "member_base_sequence": 2,
24163                    "member_size": 1,
24164                    "operation_kind": "condition",
24165                    "operation_identity": original_identity,
24166                    "outcome": "completed",
24167                    "resolution_event_id": "latest-condition-resolution",
24168                    "resolution_event_type": terminal_type,
24169                }),
24170            ));
24171            if acknowledge_timeout {
24172                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
24173            }
24174            let ctx = workflow_context(history);
24175            let mut selected = Box::pin(ctx.select_keyed(vec![
24176                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
24177                (
24178                    "votes",
24179                    ParallelOperation::condition(
24180                        if uses_timer {
24181                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24182                                .timeout(Duration::from_secs(3))
24183                        } else {
24184                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24185                        },
24186                        || Ok(true),
24187                    ),
24188                ),
24189            ]));
24190            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24191            match selected.as_mut().poll(&mut task_context) {
24192                Poll::Ready(Ok(result)) => {
24193                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
24194                    let expected = if terminal_type == "ConditionWaitSatisfied" {
24195                        ConditionWaitResult::Satisfied
24196                    } else {
24197                        ConditionWaitResult::TimedOut
24198                    };
24199                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
24200                }
24201                other => panic!("latest physical winner must replay: {other:?}"),
24202            }
24203            assert!(ctx.take_commands().unwrap().is_empty());
24204            ctx.ensure_history_consumed()
24205                .expect("winner history consumed");
24206        }
24207    }
24208
24209    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
24210        let fixture: Value = serde_json::from_str(include_str!(
24211            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
24212        ))
24213        .expect("grouped condition fixture");
24214        fixture["history"]
24215            .as_array()
24216            .unwrap()
24217            .iter()
24218            .map(|event| {
24219                let mut payload = event["payload"].clone();
24220                let index = payload["parallel_group_index"].as_u64().unwrap();
24221                payload["parallel_group_id"] = json!("select-calls:1:2");
24222                payload["parallel_group_mode"] = json!("select");
24223                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
24224                payload["selection_member_index"] = json!(index);
24225                payload["selection_member_base_sequence"] = json!(index + 1);
24226                payload["selection_member_size"] = json!(1);
24227                payload["selection_member_kind"] =
24228                    json!(if index == 0 { "timer" } else { "condition" });
24229                history_event(event["event_type"].as_str().unwrap(), payload)
24230            })
24231            .collect()
24232    }
24233
24234    #[test]
24235    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
24236        let fixture: Value = serde_json::from_str(include_str!(
24237            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
24238        ))
24239        .expect("grouped condition fixture");
24240        let original = fixture["history"].as_array().expect("fixture history");
24241        let decode = |events: &[Value]| {
24242            let history = events
24243                .iter()
24244                .map(|event| {
24245                    history_event(
24246                        event["event_type"].as_str().unwrap(),
24247                        event["payload"].clone(),
24248                    )
24249                })
24250                .collect::<Vec<_>>();
24251            recorded_commands(
24252                &history,
24253                DEFAULT_CODEC,
24254                WorkflowIdentity {
24255                    workflow_id: None,
24256                    run_id: None,
24257                },
24258            )
24259        };
24260        assert!(decode(original).is_ok());
24261        for field in [
24262            "condition_wait_occurrence_id",
24263            "condition_key",
24264            "condition_definition_fingerprint",
24265            "timeout_seconds",
24266            "parallel_group_id",
24267            "parallel_group_size",
24268            "parallel_group_index",
24269        ] {
24270            let mut changed = original.clone();
24271            changed[3]["payload"][field] = match field {
24272                "timeout_seconds" | "parallel_group_size" => json!(30),
24273                "parallel_group_index" => json!(0),
24274                _ => json!("changed"),
24275            };
24276            assert!(
24277                decode(&changed).is_err(),
24278                "reopen must reject changed {field}"
24279            );
24280        }
24281        let mut unsettled = original.clone();
24282        unsettled.remove(2);
24283        assert!(
24284            decode(&unsettled).is_err(),
24285            "physical predecessor must be resolved"
24286        );
24287        let mut timed_out = original.clone();
24288        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
24289        assert!(decode(&timed_out).is_err(), "timeout is terminal");
24290        let mut late_resolution = original.clone();
24291        late_resolution.swap(2, 3);
24292        assert!(
24293            decode(&late_resolution).is_err(),
24294            "later history cannot authorize a reopen"
24295        );
24296    }
24297
24298    #[test]
24299    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
24300        let history = vec![
24301            history_event(
24302                "ConditionWaitOpened",
24303                json!({
24304                    "sequence": 3,
24305                    "condition_wait_id": "condition:3",
24306                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24307                    "condition_key": "two-votes",
24308                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24309                }),
24310            ),
24311            history_event(
24312                "SignalReceived",
24313                json!({
24314                    "workflow_sequence": 3,
24315                    "signal_name": "vote",
24316                    "arguments": fixture_envelope(json!(["first"])),
24317                }),
24318            ),
24319            history_event(
24320                "ConditionWaitSatisfied",
24321                json!({
24322                    "sequence": 3,
24323                    "condition_wait_id": "condition:3",
24324                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24325                    "condition_key": "two-votes",
24326                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24327                }),
24328            ),
24329            history_event(
24330                "ConditionWaitOpened",
24331                json!({
24332                    "sequence": 5,
24333                    "condition_wait_id": "condition:5",
24334                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24335                    "condition_key": "two-votes",
24336                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24337                }),
24338            ),
24339            history_event(
24340                "SignalReceived",
24341                json!({
24342                    "workflow_sequence": 5,
24343                    "signal_name": "vote",
24344                    "arguments": fixture_envelope(json!(["second"])),
24345                }),
24346            ),
24347            history_event(
24348                "ConditionWaitSatisfied",
24349                json!({
24350                    "sequence": 5,
24351                    "condition_wait_id": "condition:5",
24352                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24353                    "condition_key": "two-votes",
24354                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24355                }),
24356            ),
24357        ];
24358        for _cold_worker_or_restart in 0..2 {
24359            let ctx = workflow_context(history.clone());
24360            let predicate_ctx = ctx.clone();
24361            let mut wait = Box::pin(ctx.wait_condition(
24362                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
24363                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
24364            ));
24365            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24366
24367            assert!(matches!(
24368                wait.as_mut().poll(&mut task_context),
24369                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24370            ));
24371            assert!(ctx.take_commands().expect("commands").is_empty());
24372            ctx.ensure_history_consumed()
24373                .expect("every physical wait-open is consumed");
24374        }
24375    }
24376
24377    #[test]
24378    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
24379        let history = vec![
24380            history_event(
24381                "ConditionWaitOpened",
24382                json!({
24383                    "sequence": 3,
24384                    "condition_wait_id": "condition:3",
24385                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24386                    "condition_key": "approved",
24387                    "condition_definition_fingerprint": "sha256:approved-v1",
24388                }),
24389            ),
24390            history_event(
24391                "UpdateApplied",
24392                json!({
24393                    "sequence": 3,
24394                    "update_id": "update-1",
24395                    "update_name": "approve",
24396                    "arguments": fixture_envelope(json!([false])),
24397                }),
24398            ),
24399            history_event(
24400                "ConditionWaitOpened",
24401                json!({
24402                    "sequence": 5,
24403                    "condition_wait_id": "condition:5",
24404                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24405                    "condition_key": "approved",
24406                    "condition_definition_fingerprint": "sha256:approved-v1",
24407                }),
24408            ),
24409            history_event(
24410                "UpdateApplied",
24411                json!({
24412                    "sequence": 5,
24413                    "update_id": "update-2",
24414                    "update_name": "approve",
24415                    "arguments": fixture_envelope(json!([true])),
24416                }),
24417            ),
24418        ];
24419
24420        for _cold_worker_or_restart in 0..2 {
24421            let ctx = workflow_context(history.clone());
24422            let predicate_ctx = ctx.clone();
24423            let mut wait = Box::pin(ctx.wait_condition(
24424                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
24425                move || {
24426                    Ok(predicate_ctx
24427                        .updates("approve")?
24428                        .last()
24429                        .and_then(|arguments| arguments.first())
24430                        .and_then(Value::as_bool)
24431                        == Some(true))
24432                },
24433            ));
24434            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24435
24436            assert!(matches!(
24437                wait.as_mut().poll(&mut task_context),
24438                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24439            ));
24440            assert!(ctx.take_commands().expect("commands").is_empty());
24441            ctx.ensure_history_consumed()
24442                .expect("every update-driven reopen is consumed");
24443        }
24444    }
24445
24446    #[test]
24447    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
24448        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
24449            ("shared", "sha256:first", "shared", "sha256:second"),
24450            ("first", "sha256:shared", "second", "sha256:shared"),
24451            ("shared", "sha256:shared", "shared", "sha256:shared"),
24452            ("first", "sha256:first", "second", "sha256:second"),
24453        ] {
24454            let history = vec![
24455                history_event(
24456                    "ConditionWaitOpened",
24457                    json!({
24458                        "sequence": 3,
24459                        "condition_wait_id": "condition:3",
24460                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24461                        "condition_key": first_key,
24462                        "condition_definition_fingerprint": first_fingerprint,
24463                    }),
24464                ),
24465                history_event(
24466                    "ConditionWaitSatisfied",
24467                    json!({
24468                        "sequence": 3,
24469                        "condition_wait_id": "condition:3",
24470                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24471                        "condition_key": first_key,
24472                        "condition_definition_fingerprint": first_fingerprint,
24473                    }),
24474                ),
24475                history_event(
24476                    "ConditionWaitOpened",
24477                    json!({
24478                        "sequence": 4,
24479                        "condition_wait_id": "condition:4",
24480                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24481                        "condition_key": second_key,
24482                        "condition_definition_fingerprint": second_fingerprint,
24483                    }),
24484                ),
24485                history_event(
24486                    "ConditionWaitSatisfied",
24487                    json!({
24488                        "sequence": 4,
24489                        "condition_wait_id": "condition:4",
24490                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24491                        "condition_key": second_key,
24492                        "condition_definition_fingerprint": second_fingerprint,
24493                    }),
24494                ),
24495            ];
24496            for _cold_worker_or_restart in 0..2 {
24497                let ctx = workflow_context(history.clone());
24498                let mut task_context = TaskContext::from_waker(noop_waker_ref());
24499                let mut first = Box::pin(ctx.wait_condition(
24500                    ConditionWaitOptions::new(first_key, first_fingerprint),
24501                    || Ok(false),
24502                ));
24503                assert!(matches!(
24504                    first.as_mut().poll(&mut task_context),
24505                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24506                ));
24507
24508                let mut second = Box::pin(ctx.wait_condition(
24509                    ConditionWaitOptions::new(second_key, second_fingerprint),
24510                    || Ok(false),
24511                ));
24512                assert!(matches!(
24513                    second.as_mut().poll(&mut task_context),
24514                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24515                ));
24516                assert!(ctx.take_commands().expect("commands").is_empty());
24517                ctx.ensure_history_consumed()
24518                    .expect("each authored wait consumes one occurrence");
24519            }
24520        }
24521    }
24522
24523    #[test]
24524    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
24525        fn worker() -> Worker {
24526            let client = Client::new("http://127.0.0.1:8080").expect("client");
24527            let mut worker = Worker::new(client, "rust-workers");
24528            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
24529                let mut outcomes = Vec::new();
24530                for _ in 0..2 {
24531                    outcomes.push(
24532                        ctx.wait_condition(
24533                            ConditionWaitOptions::new("shared", "sha256:shared"),
24534                            || Ok(false),
24535                        )
24536                        .await?,
24537                    );
24538                }
24539                Ok(json!(outcomes))
24540            });
24541            worker
24542        }
24543
24544        let task = workflow_task(
24545            "rust.condition-loop",
24546            vec![
24547                history_event(
24548                    "ConditionWaitOpened",
24549                    json!({
24550                        "sequence": 1,
24551                        "condition_wait_id": "condition:1",
24552                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24553                        "condition_key": "shared",
24554                        "condition_definition_fingerprint": "sha256:shared",
24555                    }),
24556                ),
24557                history_event(
24558                    "ConditionWaitSatisfied",
24559                    json!({
24560                        "sequence": 1,
24561                        "condition_wait_id": "condition:1",
24562                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24563                        "condition_key": "shared",
24564                        "condition_definition_fingerprint": "sha256:shared",
24565                    }),
24566                ),
24567                history_event(
24568                    "ConditionWaitOpened",
24569                    json!({
24570                        "sequence": 2,
24571                        "condition_wait_id": "condition:2",
24572                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24573                        "condition_key": "shared",
24574                        "condition_definition_fingerprint": "sha256:shared",
24575                    }),
24576                ),
24577                history_event(
24578                    "ConditionWaitSatisfied",
24579                    json!({
24580                        "sequence": 2,
24581                        "condition_wait_id": "condition:2",
24582                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24583                        "condition_key": "shared",
24584                        "condition_definition_fingerprint": "sha256:shared",
24585                    }),
24586                ),
24587            ],
24588            DEFAULT_CODEC,
24589        );
24590
24591        for _cold_worker_or_restart in 0..2 {
24592            let commands = worker()
24593                .execute_workflow_task(task.clone())
24594                .expect("adjacent loop waits replay deterministically");
24595            assert_eq!(commands.len(), 1);
24596            assert_eq!(commands[0]["type"], "complete_workflow");
24597            assert_eq!(
24598                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24599                json!(["satisfied", "satisfied"])
24600            );
24601        }
24602    }
24603
24604    #[test]
24605    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
24606        let history = vec![history_event(
24607            "ConditionWaitOpened",
24608            json!({
24609                "sequence": 12,
24610                "condition_wait_id": "condition:12",
24611                "condition_wait_occurrence_id": "rust:condition-wait:0",
24612                "condition_key": "approval",
24613                "condition_definition_fingerprint": "sha256:approval-v1",
24614                "timeout_seconds": 30,
24615            }),
24616        )];
24617        for (options, expected_reason) in [
24618            (
24619                ConditionWaitOptions::new("changed", "sha256:approval-v1")
24620                    .timeout(Duration::from_secs(30)),
24621                "condition_wait_key_mismatch",
24622            ),
24623            (
24624                ConditionWaitOptions::new("approval", "sha256:approval-v2")
24625                    .timeout(Duration::from_secs(30)),
24626                "condition_wait_predicate_mismatch",
24627            ),
24628            (
24629                ConditionWaitOptions::new("approval", "sha256:approval-v1")
24630                    .timeout(Duration::from_secs(29)),
24631                "condition_wait_timeout_mismatch",
24632            ),
24633        ] {
24634            let ctx = workflow_context(history.clone());
24635            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
24636            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24637            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24638                wait.as_mut().poll(&mut task_context)
24639            else {
24640                panic!("changed condition definition must fail replay");
24641            };
24642            assert_eq!(failure.reason, expected_reason);
24643            assert_eq!(failure.sequence, Some(12));
24644        }
24645    }
24646
24647    #[test]
24648    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
24649        let error = WorkflowState::new(
24650            vec![history_event(
24651                "ConditionWaitOpened",
24652                json!({
24653                    "sequence": 12,
24654                    "condition_wait_id": "condition:12",
24655                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24656                    "condition_key": "approval",
24657                }),
24658            )],
24659            "rust-workers".to_string(),
24660            DEFAULT_CODEC.to_string(),
24661            None,
24662        )
24663        .expect_err("condition history without a predicate fingerprint must fail");
24664
24665        assert!(matches!(
24666            error,
24667            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24668                if reason == "condition_wait_predicate_fingerprint_missing"
24669        ));
24670    }
24671
24672    #[test]
24673    fn condition_wait_history_requires_authored_occurrence_identity() {
24674        let error = WorkflowState::new(
24675            vec![history_event(
24676                "ConditionWaitOpened",
24677                json!({
24678                    "sequence": 12,
24679                    "condition_wait_id": "condition:12",
24680                    "condition_key": "approval",
24681                    "condition_definition_fingerprint": "sha256:approval-v1",
24682                }),
24683            )],
24684            "rust-workers".to_string(),
24685            DEFAULT_CODEC.to_string(),
24686            None,
24687        )
24688        .expect_err("condition history without occurrence identity must fail");
24689
24690        assert!(matches!(
24691            error,
24692            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24693                if reason == "condition_wait_occurrence_id_missing"
24694        ));
24695    }
24696
24697    #[test]
24698    fn typed_search_attribute_updates_validate_emit_and_replay() {
24699        let update = SearchAttributeUpdate::new()
24700            .keyword("OrderStatus", " waiting ")
24701            .expect("keyword")
24702            .int("Attempt", 3)
24703            .expect("int")
24704            .bool("Escalated", false)
24705            .expect("bool")
24706            .keyword_list("Regions", ["us-east", "eu-west"])
24707            .expect("list")
24708            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
24709            .expect("datetime")
24710            .delete("LegacyStatus")
24711            .expect("delete");
24712        let ctx = workflow_context(Vec::new());
24713        ctx.upsert_search_attributes(update.clone())
24714            .expect("typed update");
24715        assert_eq!(
24716            ctx.take_commands().expect("search-attribute command"),
24717            vec![json!({
24718                "type": "upsert_search_attributes",
24719                "attributes": {
24720                    "Attempt": 3,
24721                    "Escalated": false,
24722                    "LegacyStatus": null,
24723                    "OrderStatus": "waiting",
24724                    "Regions": ["us-east", "eu-west"],
24725                    "UpdatedAt": "2026-08-22T04:00:00Z",
24726                },
24727                "attribute_types": {
24728                    "Attempt": "int",
24729                    "Escalated": "bool",
24730                    "OrderStatus": "keyword",
24731                    "Regions": "keyword_list",
24732                    "UpdatedAt": "datetime",
24733                },
24734            })]
24735        );
24736
24737        let replay = workflow_context(vec![history_event(
24738            "SearchAttributesUpserted",
24739            json!({
24740                "sequence": 6,
24741                "attributes": {
24742                    "Attempt": 3,
24743                    "Escalated": false,
24744                    "LegacyStatus": null,
24745                    "OrderStatus": "waiting",
24746                    "Regions": ["us-east", "eu-west"],
24747                    "UpdatedAt": "2026-08-22T04:00:00Z",
24748                },
24749                "attribute_types": {
24750                    "Attempt": "int",
24751                    "Escalated": "bool",
24752                    "OrderStatus": "keyword",
24753                    "Regions": "keyword_list",
24754                    "UpdatedAt": "datetime",
24755                },
24756                "merged": {},
24757            }),
24758        )]);
24759        replay
24760            .upsert_search_attributes(update)
24761            .expect("matching update replays");
24762        assert!(replay.take_commands().expect("commands").is_empty());
24763        replay.ensure_history_consumed().expect("history consumed");
24764
24765        let type_drift = workflow_context(vec![history_event(
24766            "SearchAttributesUpserted",
24767            json!({
24768                "sequence": 7,
24769                "attributes": {"OrderStatus": "waiting"},
24770                "attribute_types": {"OrderStatus": "keyword"},
24771                "merged": {"OrderStatus": "waiting"},
24772            }),
24773        )]);
24774        let error = type_drift
24775            .upsert_search_attributes(
24776                SearchAttributeUpdate::new()
24777                    .string("OrderStatus", "waiting")
24778                    .expect("string update"),
24779            )
24780            .expect_err("same JSON value with a changed type must fail replay");
24781        assert!(matches!(
24782            error,
24783            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24784                if reason == "search_attribute_type_mismatch"
24785        ));
24786
24787        let malformed_types = WorkflowState::new(
24788            vec![history_event(
24789                "SearchAttributesUpserted",
24790                json!({
24791                    "sequence": 8,
24792                    "attributes": {"OrderStatus": "waiting"},
24793                    "attribute_types": {"OrderStatus": "unsupported"},
24794                    "merged": {"OrderStatus": "waiting"},
24795                }),
24796            )],
24797            "rust-workers".to_string(),
24798            DEFAULT_CODEC.to_string(),
24799            None,
24800        )
24801        .expect_err("unsupported search-attribute type metadata must fail");
24802        assert!(matches!(
24803            malformed_types,
24804            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24805                if reason == "search_attribute_types_malformed"
24806        ));
24807
24808        assert!(matches!(
24809            SearchAttributeUpdate::new().keyword("bad key", "value"),
24810            Err(SearchAttributeUpdateError::InvalidKey(_))
24811        ));
24812        assert!(matches!(
24813            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
24814            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
24815        ));
24816        assert!(matches!(
24817            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
24818            Err(SearchAttributeUpdateError::ValueTooLong { .. })
24819        ));
24820        assert!(matches!(
24821            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
24822            Err(SearchAttributeUpdateError::InvalidDateTime(_))
24823        ));
24824        assert!(matches!(
24825            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
24826            Err(Error::InvalidSearchAttributeUpdate(
24827                SearchAttributeUpdateError::Empty
24828            ))
24829        ));
24830    }
24831
24832    #[test]
24833    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
24834        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
24835        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
24836
24837        assert!(SearchAttributeUpdate::new()
24838            .string("AsciiDescription", ascii)
24839            .is_ok());
24840        assert!(SearchAttributeUpdate::new()
24841            .string("Utf8Description", utf8)
24842            .is_ok());
24843        assert!(matches!(
24844            SearchAttributeUpdate::new().string(
24845                "TooLongDescription",
24846                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
24847            ),
24848            Err(SearchAttributeUpdateError::ValueTooLong {
24849                kind: "string",
24850                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
24851                ..
24852            })
24853        ));
24854    }
24855
24856    #[test]
24857    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
24858        let lone_fire = WorkflowState::new(
24859            vec![history_event(
24860                "TimerFired",
24861                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24862            )],
24863            "rust-workers".to_string(),
24864            DEFAULT_CODEC.to_string(),
24865            None,
24866        )
24867        .expect_err("TimerFired requires TimerScheduled");
24868        assert!(matches!(
24869            lone_fire,
24870            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24871                if reason == "timer_schedule_missing_or_duplicate"
24872        ));
24873
24874        let wrong_identity = WorkflowState::new(
24875            vec![
24876                history_event(
24877                    "TimerScheduled",
24878                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24879                ),
24880                history_event(
24881                    "TimerFired",
24882                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24883                ),
24884            ],
24885            "rust-workers".to_string(),
24886            DEFAULT_CODEC.to_string(),
24887            None,
24888        )
24889        .expect_err("fire must match scheduled timer identity");
24890        assert!(matches!(
24891            wrong_identity,
24892            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24893                if reason == "timer_identity_mismatch"
24894        ));
24895
24896        let duplicate_fire = WorkflowState::new(
24897            vec![
24898                history_event(
24899                    "TimerScheduled",
24900                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24901                ),
24902                history_event(
24903                    "TimerFired",
24904                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24905                ),
24906                history_event(
24907                    "TimerFired",
24908                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24909                ),
24910            ],
24911            "rust-workers".to_string(),
24912            DEFAULT_CODEC.to_string(),
24913            None,
24914        )
24915        .expect_err("a durable timer cannot fire twice");
24916        assert!(matches!(
24917            duplicate_fire,
24918            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24919                if reason == "duplicate_timer_fire"
24920        ));
24921
24922        let wrong_fired_delay = WorkflowState::new(
24923            vec![
24924                history_event(
24925                    "TimerScheduled",
24926                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24927                ),
24928                history_event(
24929                    "TimerFired",
24930                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
24931                ),
24932            ],
24933            "rust-workers".to_string(),
24934            DEFAULT_CODEC.to_string(),
24935            None,
24936        )
24937        .expect_err("timer schedule and fire delays must agree");
24938        assert!(matches!(
24939            wrong_fired_delay,
24940            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24941                if reason == "timer_history_delay_mismatch"
24942        ));
24943    }
24944
24945    #[test]
24946    fn replay_rejects_activity_moved_before_recorded_timer() {
24947        let ctx = workflow_context(vec![
24948            history_event(
24949                "TimerScheduled",
24950                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24951            ),
24952            history_event(
24953                "TimerFired",
24954                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24955            ),
24956            history_event(
24957                "ActivityCompleted",
24958                json!({
24959                    "sequence": 2,
24960                    "activity_type": "after-timer",
24961                    "payload_codec": DEFAULT_CODEC,
24962                    "result": fixture_envelope(json!("done")),
24963                }),
24964            ),
24965        ]);
24966        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
24967        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24968
24969        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24970            activity.as_mut().poll(&mut task_context)
24971        else {
24972            panic!("reordered durable command must be rejected");
24973        };
24974        assert_eq!(failure.reason, "recorded_command_mismatch");
24975        assert_eq!(failure.sequence, Some(1));
24976        assert_eq!(failure.expected.as_deref(), Some("timer"));
24977        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
24978    }
24979
24980    #[test]
24981    fn workflow_context_emits_a_typed_named_signal_wait() {
24982        let ctx = workflow_context(Vec::new());
24983        let mut signal = Box::pin(ctx.wait_signal("finish"));
24984        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24985
24986        assert!(matches!(
24987            signal.as_mut().poll(&mut task_context),
24988            Poll::Pending
24989        ));
24990        assert_eq!(
24991            ctx.take_commands().expect("signal-wait command"),
24992            vec![json!({
24993                "type": "open_signal_wait",
24994                "signal_name": "finish",
24995            })]
24996        );
24997    }
24998
24999    #[test]
25000    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
25001        let ctx = workflow_context(Vec::new());
25002        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
25003        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25004
25005        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
25006        else {
25007            panic!("runtime-reserved signal should be rejected");
25008        };
25009        assert!(message.contains("reserved by the workflow runtime"));
25010        assert!(ctx.take_commands().expect("commands").is_empty());
25011    }
25012
25013    #[tokio::test]
25014    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
25015        let client = Client::builder("http://127.0.0.1:9")
25016            .build()
25017            .expect("client");
25018        let error = client
25019            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
25020            .await
25021            .expect_err("runtime-reserved signal should be rejected before transport");
25022
25023        assert!(
25024            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
25025        );
25026    }
25027
25028    #[test]
25029    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
25030        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25031            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25032                value.to_string(),
25033            )]))
25034            .expect("message payload");
25035            json!({
25036                "schema": MESSAGE_STREAM_SCHEMA,
25037                "stream_name": "orders",
25038                "message_id": message_id,
25039                "position": position,
25040                "payload_envelope": payload,
25041            })
25042        }
25043
25044        fn opened(sequence: u64) -> HistoryEvent {
25045            history_event(
25046                "SignalWaitOpened",
25047                json!({
25048                    "sequence": sequence,
25049                    "signal_name": MESSAGE_STREAM_SIGNAL,
25050                }),
25051            )
25052        }
25053
25054        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25055            history_event(
25056                "SignalApplied",
25057                json!({
25058                    "sequence": sequence,
25059                    "signal_name": MESSAGE_STREAM_SIGNAL,
25060                    "value": fixture_envelope(json!([delivery])),
25061                }),
25062            )
25063        }
25064
25065        fn received(delivery: Value) -> HistoryEvent {
25066            history_event(
25067                "SignalReceived",
25068                json!({
25069                    "signal_name": MESSAGE_STREAM_SIGNAL,
25070                    "arguments": fixture_envelope(json!([delivery])),
25071                    "payload_codec": DEFAULT_CODEC,
25072                }),
25073            )
25074        }
25075
25076        let client = Client::new("http://127.0.0.1:8080").expect("client");
25077        let mut worker = Worker::new(client, "rust-workers");
25078        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
25079            let messages = ctx.message_stream("orders")?.receive(2).await?;
25080            Ok(json!(messages
25081                .into_iter()
25082                .map(|message| message.message_id)
25083                .collect::<Vec<_>>()))
25084        });
25085
25086        let first = delivery("message-1", 1, "one");
25087        let second = delivery("message-2", 2, "two");
25088        let batch = worker
25089            .execute_workflow_task_decision(workflow_task(
25090                "rust.message-stream-batch",
25091                vec![
25092                    opened(1),
25093                    received(first.clone()),
25094                    applied(1, first.clone()),
25095                    received(first.clone()),
25096                    received(second),
25097                ],
25098                DEFAULT_CODEC,
25099            ))
25100            .expect("worker task consumes the available batch");
25101
25102        assert_eq!(batch.commands.len(), 1);
25103        assert_eq!(batch.commands[0]["type"], "complete_workflow");
25104        assert_eq!(
25105            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
25106                .expect("workflow result"),
25107            json!(["message-1", "message-2"])
25108        );
25109        assert_eq!(
25110            batch.message_stream_cursors,
25111            vec![json!({"stream_name": "orders", "through_position": 2})]
25112        );
25113        assert!(batch.message_stream_waits.is_empty());
25114
25115        let partial = worker
25116            .execute_workflow_task_decision(workflow_task(
25117                "rust.message-stream-batch",
25118                vec![opened(1), received(first.clone()), applied(1, first)],
25119                DEFAULT_CODEC,
25120            ))
25121            .expect("worker task returns without waiting for a missing second item");
25122        assert_eq!(partial.commands.len(), 1);
25123        assert_eq!(partial.commands[0]["type"], "complete_workflow");
25124        assert_eq!(
25125            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
25126                .expect("workflow result"),
25127            json!(["message-1"])
25128        );
25129        assert_eq!(
25130            partial.message_stream_cursors,
25131            vec![json!({"stream_name": "orders", "through_position": 1})]
25132        );
25133        assert!(partial.message_stream_waits.is_empty());
25134    }
25135
25136    #[test]
25137    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
25138        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25139            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25140                value.to_string(),
25141            )]))
25142            .expect("message payload");
25143            json!({
25144                "schema": MESSAGE_STREAM_SCHEMA,
25145                "stream_name": "orders",
25146                "message_id": message_id,
25147                "position": position,
25148                "payload_envelope": payload,
25149            })
25150        }
25151
25152        fn opened(sequence: u64) -> HistoryEvent {
25153            history_event(
25154                "SignalWaitOpened",
25155                json!({
25156                    "sequence": sequence,
25157                    "signal_name": MESSAGE_STREAM_SIGNAL,
25158                }),
25159            )
25160        }
25161
25162        fn received(delivery: Value) -> HistoryEvent {
25163            history_event(
25164                "SignalReceived",
25165                json!({
25166                    "signal_name": MESSAGE_STREAM_SIGNAL,
25167                    "arguments": fixture_envelope(json!([delivery])),
25168                    "payload_codec": DEFAULT_CODEC,
25169                }),
25170            )
25171        }
25172
25173        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25174            history_event(
25175                "SignalApplied",
25176                json!({
25177                    "sequence": sequence,
25178                    "signal_name": MESSAGE_STREAM_SIGNAL,
25179                    "value": fixture_envelope(json!([delivery])),
25180                }),
25181            )
25182        }
25183
25184        let client = Client::new("http://127.0.0.1:8080").expect("client");
25185        let mut worker = Worker::new(client, "rust-workers");
25186        worker.register_workflow(
25187            "rust.message-stream-partial-batches",
25188            |ctx, _input| async move {
25189                let stream = ctx.message_stream("orders")?;
25190                let first = stream.receive(10).await?;
25191                let second = stream.receive(10).await?;
25192                Ok(json!([
25193                    first
25194                        .into_iter()
25195                        .map(|message| message.message_id)
25196                        .collect::<Vec<_>>(),
25197                    second
25198                        .into_iter()
25199                        .map(|message| message.message_id)
25200                        .collect::<Vec<_>>(),
25201                ]))
25202            },
25203        );
25204
25205        let first = delivery("message-1", 1, "one");
25206        let second = delivery("message-2", 2, "two");
25207        let decision = worker
25208            .execute_workflow_task_decision(workflow_task(
25209                "rust.message-stream-partial-batches",
25210                vec![
25211                    opened(1),
25212                    received(first.clone()),
25213                    applied(1, first),
25214                    opened(2),
25215                    received(second.clone()),
25216                    applied(2, second),
25217                ],
25218                DEFAULT_CODEC,
25219            ))
25220            .expect("cold replay preserves both authored receive boundaries");
25221
25222        assert_eq!(decision.commands.len(), 1);
25223        assert_eq!(decision.commands[0]["type"], "complete_workflow");
25224        assert_eq!(
25225            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
25226                .expect("workflow result"),
25227            json!([["message-1"], ["message-2"]])
25228        );
25229        assert_eq!(
25230            decision.message_stream_cursors,
25231            vec![json!({"stream_name": "orders", "through_position": 2})]
25232        );
25233        assert!(decision.message_stream_waits.is_empty());
25234    }
25235
25236    #[test]
25237    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
25238        let ctx = workflow_context(Vec::new());
25239        let stream = ctx.message_stream("orders").expect("message stream");
25240        let mut receive = Box::pin(stream.receive(10));
25241        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25242
25243        assert!(matches!(
25244            receive.as_mut().poll(&mut task_context),
25245            Poll::Pending
25246        ));
25247        assert_eq!(
25248            ctx.take_commands().expect("message-stream wait command"),
25249            vec![json!({
25250                "type": "open_signal_wait",
25251                "signal_name": MESSAGE_STREAM_SIGNAL,
25252            })]
25253        );
25254        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
25255        assert!(cursors.is_empty());
25256        assert_eq!(
25257            waits,
25258            vec![json!({"stream_name": "orders", "after_position": 0})]
25259        );
25260    }
25261
25262    #[test]
25263    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
25264        let ctx = workflow_context(vec![history_event(
25265            "SignalReceived",
25266            json!({
25267                "signal_name": MESSAGE_STREAM_SIGNAL,
25268                "arguments": fixture_envelope(json!([{
25269                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
25270                    "stream_name": "orders",
25271                    "through_position": 2,
25272                }])),
25273                "payload_codec": DEFAULT_CODEC,
25274            }),
25275        )]);
25276        let stream = ctx.message_stream("orders").expect("message stream");
25277        let mut receive = Box::pin(stream.receive(10));
25278        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25279
25280        assert!(matches!(
25281            receive.as_mut().poll(&mut task_context),
25282            Poll::Pending
25283        ));
25284        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
25285        assert_eq!(
25286            cursors,
25287            vec![json!({"stream_name": "orders", "through_position": 2})]
25288        );
25289        assert_eq!(
25290            waits,
25291            vec![json!({"stream_name": "orders", "after_position": 2})]
25292        );
25293    }
25294
25295    #[test]
25296    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
25297        let mut empty_map = BTreeMap::new();
25298        let mut nested = BTreeMap::new();
25299        nested.insert(
25300            "value".to_string(),
25301            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
25302        );
25303        let values = vec![
25304            AvroValue::Bytes(vec![0, 255]),
25305            AvroValue::Long(1),
25306            AvroValue::Double(1.0),
25307            AvroValue::Array(Vec::new()),
25308            AvroValue::Map(std::mem::take(&mut empty_map)),
25309            AvroValue::Map(nested),
25310        ];
25311        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
25312        let transport = vec![json!({
25313            "schema": MESSAGE_STREAM_SCHEMA,
25314            "stream_name": "orders",
25315            "message_id": "message-1",
25316            "position": 1,
25317            "payload_envelope": payload,
25318        })];
25319
25320        for _ in 0..2 {
25321            let Some(MessageStreamDelivery::Message(message)) =
25322                decode_message_stream_delivery(transport.clone()).expect("delivery")
25323            else {
25324                panic!("message delivery expected");
25325            };
25326            assert_eq!(message.arguments, values);
25327            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
25328            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
25329        }
25330    }
25331
25332    #[test]
25333    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
25334        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25335            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25336                value.to_string(),
25337            )]))
25338            .expect("message payload");
25339            json!({
25340                "schema": MESSAGE_STREAM_SCHEMA,
25341                "stream_name": "orders",
25342                "message_id": message_id,
25343                "position": position,
25344                "payload_envelope": payload,
25345            })
25346        }
25347
25348        fn opened(sequence: u64) -> HistoryEvent {
25349            history_event(
25350                "SignalWaitOpened",
25351                json!({
25352                    "sequence": sequence,
25353                    "signal_name": MESSAGE_STREAM_SIGNAL,
25354                }),
25355            )
25356        }
25357
25358        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25359            history_event(
25360                "SignalApplied",
25361                json!({
25362                    "sequence": sequence,
25363                    "signal_name": MESSAGE_STREAM_SIGNAL,
25364                    "value": fixture_envelope(json!([delivery])),
25365                }),
25366            )
25367        }
25368
25369        fn worker() -> Worker {
25370            let client = Client::new("http://127.0.0.1:8080").expect("client");
25371            let mut worker = Worker::new(client, "rust-workers");
25372            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
25373                let stream = ctx.message_stream("orders")?;
25374                let first = stream.receive_one().await?;
25375                let second = stream.receive_one().await?;
25376                Ok(json!([first.message_id, second.message_id]))
25377            });
25378            worker
25379        }
25380
25381        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
25382            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
25383            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
25384            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
25385            task
25386        }
25387
25388        let waiting = worker()
25389            .execute_workflow_task_decision(workflow_task(
25390                "rust.message-stream",
25391                Vec::new(),
25392                DEFAULT_CODEC,
25393            ))
25394            .expect("first worker opens the stream wait");
25395        assert_eq!(
25396            waiting.commands,
25397            vec![json!({
25398                "type": "open_signal_wait",
25399                "signal_name": MESSAGE_STREAM_SIGNAL,
25400            })]
25401        );
25402        assert!(waiting.message_stream_cursors.is_empty());
25403        assert_eq!(
25404            waiting.message_stream_waits,
25405            vec![json!({"stream_name": "orders", "after_position": 0})]
25406        );
25407
25408        let first_delivery = delivery("message-1", 1, "one");
25409        let first_arrival = worker()
25410            .execute_workflow_task_decision(task_with_resume(
25411                vec![opened(1)],
25412                first_delivery.clone(),
25413            ))
25414            .expect("replacement worker consumes the first arrival");
25415        assert_eq!(
25416            first_arrival.commands,
25417            vec![json!({
25418                "type": "open_signal_wait",
25419                "signal_name": MESSAGE_STREAM_SIGNAL,
25420            })]
25421        );
25422        assert_eq!(
25423            first_arrival.message_stream_cursors,
25424            vec![json!({"stream_name": "orders", "through_position": 1})]
25425        );
25426        assert_eq!(
25427            first_arrival.message_stream_waits,
25428            vec![json!({"stream_name": "orders", "after_position": 1})]
25429        );
25430
25431        let second_delivery = delivery("message-2", 2, "two");
25432        let first_applied = applied(1, first_delivery);
25433        let completed = worker()
25434            .execute_workflow_task_decision(task_with_resume(
25435                vec![opened(1), first_applied.clone(), opened(2)],
25436                second_delivery.clone(),
25437            ))
25438            .expect("next replacement worker consumes the second arrival");
25439        assert_eq!(completed.commands.len(), 1);
25440        assert_eq!(completed.commands[0]["type"], "complete_workflow");
25441        assert_eq!(
25442            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
25443                .expect("workflow result"),
25444            json!(["message-1", "message-2"])
25445        );
25446        assert_eq!(
25447            completed.message_stream_cursors,
25448            vec![json!({"stream_name": "orders", "through_position": 2})]
25449        );
25450        assert!(completed.message_stream_waits.is_empty());
25451
25452        let replay_history = vec![
25453            opened(1),
25454            first_applied,
25455            opened(2),
25456            applied(2, second_delivery),
25457        ];
25458        for _cold_worker_or_restart in 0..2 {
25459            let replayed = worker()
25460                .execute_workflow_task_decision(workflow_task(
25461                    "rust.message-stream",
25462                    replay_history.clone(),
25463                    DEFAULT_CODEC,
25464                ))
25465                .expect("cold worker replays each logical message exactly once");
25466            assert_eq!(replayed.commands.len(), 1);
25467            assert_eq!(
25468                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
25469                    .expect("replayed workflow result"),
25470                json!(["message-1", "message-2"])
25471            );
25472            assert_eq!(
25473                replayed.message_stream_cursors,
25474                vec![json!({"stream_name": "orders", "through_position": 2})]
25475            );
25476            assert!(replayed.message_stream_waits.is_empty());
25477        }
25478    }
25479
25480    #[test]
25481    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
25482        assert!(!worker_protocol_supports_message_streams("1.14"));
25483        assert!(worker_protocol_supports_message_streams("1.15"));
25484        assert!(worker_protocol_supports_message_streams("1.16"));
25485        assert!(worker_protocol_supports_message_streams(
25486            WORKER_PROTOCOL_VERSION
25487        ));
25488        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
25489    }
25490
25491    #[test]
25492    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
25493        let ctx = workflow_context(vec![
25494            history_event(
25495                "ConditionWaitOpened",
25496                json!({
25497                    "sequence": 1,
25498                    "condition_wait_id": "condition:1",
25499                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25500                    "condition_key": "signal:finish",
25501                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
25502                }),
25503            ),
25504            history_event(
25505                "ConditionWaitSatisfied",
25506                json!({
25507                    "sequence": 1,
25508                    "condition_wait_id": "condition:1",
25509                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25510                    "condition_key": "signal:finish",
25511                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
25512                }),
25513            ),
25514            history_event(
25515                "SignalReceived",
25516                json!({"signal_name": "finish", "arguments": []}),
25517            ),
25518        ]);
25519        let mut signal = Box::pin(ctx.wait_signal("finish"));
25520        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25521
25522        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25523            signal.as_mut().poll(&mut task_context)
25524        else {
25525            panic!("condition history must not resolve as a typed signal wait");
25526        };
25527        assert_eq!(failure.reason, "recorded_command_mismatch");
25528        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
25529    }
25530
25531    #[test]
25532    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
25533        let signal_then_timer = vec![
25534            history_event(
25535                "SignalWaitOpened",
25536                json!({"sequence": 1, "signal_name": "go"}),
25537            ),
25538            history_event(
25539                "SignalApplied",
25540                json!({
25541                    "sequence": 1,
25542                    "signal_name": "go",
25543                    "value": fixture_envelope(json!(["now"])),
25544                }),
25545            ),
25546            history_event(
25547                "TimerScheduled",
25548                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
25549            ),
25550            history_event(
25551                "TimerFired",
25552                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
25553            ),
25554        ];
25555
25556        let ctx = workflow_context(signal_then_timer.clone());
25557        let mut signal = Box::pin(ctx.wait_signal("go"));
25558        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25559        assert!(matches!(
25560            signal.as_mut().poll(&mut task_context),
25561            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
25562        ));
25563        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
25564        assert!(matches!(
25565            timer.as_mut().poll(&mut task_context),
25566            Poll::Ready(Ok(()))
25567        ));
25568        ctx.ensure_history_consumed()
25569            .expect("signal and timer history consumed in order");
25570
25571        let reordered = workflow_context(signal_then_timer);
25572        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
25573        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25574            timer_first.as_mut().poll(&mut task_context)
25575        else {
25576            panic!("timer cannot consume signal-wait-first history");
25577        };
25578        assert_eq!(failure.reason, "recorded_command_mismatch");
25579        assert_eq!(failure.sequence, Some(1));
25580        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
25581
25582        let timer_then_signal = vec![
25583            history_event(
25584                "TimerScheduled",
25585                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25586            ),
25587            history_event(
25588                "TimerFired",
25589                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25590            ),
25591            history_event(
25592                "SignalWaitOpened",
25593                json!({"sequence": 2, "signal_name": "go"}),
25594            ),
25595            history_event(
25596                "SignalApplied",
25597                json!({
25598                    "sequence": 2,
25599                    "signal_name": "go",
25600                    "value": fixture_envelope(json!([])),
25601                }),
25602            ),
25603        ];
25604        let reordered = workflow_context(timer_then_signal);
25605        let mut signal_first = Box::pin(reordered.wait_signal("go"));
25606        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25607            signal_first.as_mut().poll(&mut task_context)
25608        else {
25609            panic!("signal wait cannot consume timer-first history");
25610        };
25611        assert_eq!(failure.reason, "recorded_command_mismatch");
25612        assert_eq!(failure.sequence, Some(1));
25613        assert_eq!(failure.expected.as_deref(), Some("timer"));
25614    }
25615
25616    #[test]
25617    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
25618        let duplicate_timer = WorkflowState::new(
25619            vec![
25620                history_event(
25621                    "TimerScheduled",
25622                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25623                ),
25624                history_event(
25625                    "TimerScheduled",
25626                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
25627                ),
25628            ],
25629            "rust-workers".to_string(),
25630            DEFAULT_CODEC.to_string(),
25631            None,
25632        )
25633        .expect_err("one workflow sequence cannot schedule two timers");
25634        assert!(matches!(
25635            duplicate_timer,
25636            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25637                if reason == "timer_schedule_missing_or_duplicate"
25638        ));
25639
25640        let colliding_kinds = WorkflowState::new(
25641            vec![
25642                history_event(
25643                    "TimerScheduled",
25644                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25645                ),
25646                history_event(
25647                    "ActivityCompleted",
25648                    json!({"sequence": 1, "activity_type": "same-sequence"}),
25649                ),
25650            ],
25651            "rust-workers".to_string(),
25652            DEFAULT_CODEC.to_string(),
25653            None,
25654        )
25655        .expect_err("one workflow sequence cannot identify two command kinds");
25656        assert!(matches!(
25657            colliding_kinds,
25658            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25659                if reason == "durable_command_sequence_collision"
25660        ));
25661
25662        let duplicate_signal_wait = WorkflowState::new(
25663            vec![
25664                history_event(
25665                    "SignalWaitOpened",
25666                    json!({"sequence": 1, "signal_name": "go"}),
25667                ),
25668                history_event(
25669                    "SignalWaitOpened",
25670                    json!({"sequence": 1, "signal_name": "go"}),
25671                ),
25672            ],
25673            "rust-workers".to_string(),
25674            DEFAULT_CODEC.to_string(),
25675            None,
25676        )
25677        .expect_err("one workflow sequence cannot open two signal waits");
25678        assert!(matches!(
25679            duplicate_signal_wait,
25680            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25681                if reason == "signal_wait_open_missing_or_duplicate"
25682        ));
25683    }
25684
25685    #[test]
25686    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
25687        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
25688            .expect("side-effect result");
25689        let ctx = workflow_context(vec![history_event(
25690            "SideEffectRecorded",
25691            json!({"sequence": 99, "result": result}),
25692        )]);
25693
25694        let replayed: Value = ctx
25695            .side_effect(|| panic!("recorded side effect must not run"))
25696            .expect("positive global workflow sequence is valid");
25697        assert_eq!(replayed, json!({"captured": true}));
25698        ctx.ensure_history_consumed().expect("history consumed");
25699    }
25700
25701    #[test]
25702    fn workflow_history_rejects_zero_and_descending_command_sequences() {
25703        let result =
25704            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
25705        let zero = WorkflowState::new(
25706            vec![history_event(
25707                "SideEffectRecorded",
25708                json!({"sequence": 0, "result": result.clone()}),
25709            )],
25710            "rust-workers".to_string(),
25711            DEFAULT_CODEC.to_string(),
25712            None,
25713        )
25714        .expect_err("durable command sequences must be positive");
25715        assert!(matches!(
25716            zero,
25717            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25718                if reason == "durable_command_sequence_invalid"
25719        ));
25720
25721        let descending = WorkflowState::new(
25722            vec![
25723                history_event(
25724                    "SideEffectRecorded",
25725                    json!({"sequence": 3, "result": result}),
25726                ),
25727                history_event(
25728                    "VersionMarkerRecorded",
25729                    json!({
25730                        "sequence": 2,
25731                        "change_id": "descending-marker",
25732                        "version": 1,
25733                        "min_supported": 1,
25734                        "max_supported": 1,
25735                    }),
25736                ),
25737            ],
25738            "rust-workers".to_string(),
25739            DEFAULT_CODEC.to_string(),
25740            None,
25741        )
25742        .expect_err("new durable commands must remain strictly ordered");
25743        let Error::NonDeterministicReplay(failure) = descending else {
25744            panic!("expected typed replay failure");
25745        };
25746        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
25747        assert_eq!(failure.sequence, Some(2));
25748        assert_eq!(
25749            failure.expected.as_deref(),
25750            Some("workflow sequence greater than 3")
25751        );
25752        assert_eq!(failure.actual.as_deref(), Some("2"));
25753    }
25754
25755    #[test]
25756    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
25757        fn worker() -> Worker {
25758            let client = Client::new("http://127.0.0.1:8080").expect("client");
25759            let mut worker = Worker::new(client, "rust-workers");
25760            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
25761                ctx.wait_signal("finish").await?;
25762                let marker: String =
25763                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
25764                assert_eq!(marker, "after-finish");
25765                Ok(json!("finished"))
25766            });
25767            worker
25768        }
25769
25770        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
25771            .expect("side-effect result");
25772        let task = workflow_task(
25773            "rust.finish-after-gaps",
25774            vec![
25775                history_event(
25776                    "SignalWaitOpened",
25777                    json!({"sequence": 1, "signal_name": "finish"}),
25778                ),
25779                history_event(
25780                    "SignalReceived",
25781                    json!({
25782                        "signal_id": "increment-3",
25783                        "signal_name": "increment",
25784                        "workflow_sequence": 2,
25785                        "payload_codec": DEFAULT_CODEC,
25786                        "arguments": fixture_envelope(json!([3])),
25787                    }),
25788                ),
25789                history_event(
25790                    "SignalReceived",
25791                    json!({
25792                        "signal_id": "increment-5",
25793                        "signal_name": "increment",
25794                        "workflow_sequence": 3,
25795                        "payload_codec": DEFAULT_CODEC,
25796                        "arguments": fixture_envelope(json!([5])),
25797                    }),
25798                ),
25799                history_event(
25800                    "SignalReceived",
25801                    json!({
25802                        "signal_id": "finish",
25803                        "signal_name": "finish",
25804                        "workflow_sequence": 4,
25805                        "payload_codec": DEFAULT_CODEC,
25806                        "arguments": fixture_envelope(json!([])),
25807                    }),
25808                ),
25809                history_event(
25810                    "SignalApplied",
25811                    json!({
25812                        "sequence": 1,
25813                        "signal_id": "finish",
25814                        "signal_name": "finish",
25815                        "payload_codec": DEFAULT_CODEC,
25816                        "value": fixture_envelope(json!([])),
25817                    }),
25818                ),
25819                history_event(
25820                    "SideEffectRecorded",
25821                    json!({"sequence": 5, "result": marker}),
25822                ),
25823            ],
25824            DEFAULT_CODEC,
25825        );
25826
25827        for _original_or_cold_worker in 0..2 {
25828            let commands = worker()
25829                .execute_workflow_task(task.clone())
25830                .expect("signal gaps preserve deterministic replay");
25831            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
25832            assert_eq!(commands[0]["type"], "complete_workflow");
25833            assert_eq!(
25834                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
25835                json!("finished")
25836            );
25837        }
25838    }
25839
25840    #[test]
25841    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
25842        let ctx = workflow_context(Vec::new());
25843        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
25844        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25845        assert!(matches!(
25846            sleep.as_mut().poll(&mut task_context),
25847            Poll::Ready(Err(Error::TimerDurationOverflow))
25848        ));
25849        assert!(ctx.take_commands().expect("commands").is_empty());
25850    }
25851
25852    #[test]
25853    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
25854        let entries = AvroValue::Map(BTreeMap::from([
25855            ("text".to_string(), AvroValue::String("same".to_string())),
25856            (
25857                "nested".to_string(),
25858                AvroValue::Map(BTreeMap::from([
25859                    ("beta".to_string(), AvroValue::Long(2)),
25860                    ("alpha".to_string(), AvroValue::Long(1)),
25861                ])),
25862            ),
25863            ("long".to_string(), AvroValue::Long(7)),
25864            ("double".to_string(), AvroValue::Double(7.0)),
25865            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
25866        ]));
25867        let ctx = workflow_context(Vec::new());
25868        ctx.upsert_memo(entries.clone()).expect("valid memo update");
25869        let commands = ctx.take_commands().expect("commands");
25870
25871        assert_eq!(commands.len(), 1);
25872        assert_eq!(commands[0]["type"], "upsert_memo");
25873        let server_entries = json!({
25874            "codec": "avro",
25875            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
25876        });
25877        assert_eq!(
25878            commands[0]["entries"]
25879                .as_object()
25880                .expect("entries envelope")
25881                .keys()
25882                .collect::<Vec<_>>(),
25883            vec!["blob", "codec"]
25884        );
25885        assert_eq!(commands[0]["entries"], server_entries);
25886        let wire_entries =
25887            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
25888        assert_eq!(wire_entries, entries);
25889
25890        let history = vec![history_event(
25891            "MemoUpserted",
25892            json!({
25893                "sequence": 1,
25894                "entries": server_entries.clone(),
25895                "merged": server_entries,
25896            }),
25897        )];
25898        let replay = workflow_context(history.clone());
25899        replay
25900            .upsert_memo(entries.clone())
25901            .expect("matching replay identity");
25902        assert!(replay.take_commands().expect("replay commands").is_empty());
25903
25904        let changed_types = AvroValue::Map(BTreeMap::from([
25905            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
25906            (
25907                "nested".to_string(),
25908                AvroValue::Map(BTreeMap::from([
25909                    ("alpha".to_string(), AvroValue::Long(1)),
25910                    ("beta".to_string(), AvroValue::Long(2)),
25911                ])),
25912            ),
25913            ("long".to_string(), AvroValue::Double(7.0)),
25914            ("double".to_string(), AvroValue::Long(7)),
25915            ("binary".to_string(), AvroValue::String("same".to_string())),
25916        ]));
25917        let error = workflow_context(history)
25918            .upsert_memo(changed_types)
25919            .expect_err("memo replay identity must preserve Avro value types");
25920        assert!(matches!(
25921            error,
25922            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25923        ));
25924    }
25925
25926    #[test]
25927    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
25928        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
25929            .expect("memo envelope");
25930        let replay = workflow_context(vec![history_event(
25931            "MemoUpserted",
25932            json!({
25933                "sequence": 1,
25934                "entries": original.clone(),
25935                "merged": original
25936            }),
25937        )]);
25938        let error = replay
25939            .upsert_memo(json!({"stage": "changed"}))
25940            .expect_err("changed memo update must fail replay");
25941        assert!(matches!(
25942            error,
25943            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25944        ));
25945
25946        let invalid = workflow_context(Vec::new())
25947            .upsert_memo(
25948                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
25949            )
25950            .expect_err("oversized key");
25951        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
25952    }
25953
25954    #[test]
25955    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
25956        let negative_zero = AvroValue::Map(BTreeMap::from([(
25957            "reading".to_string(),
25958            AvroValue::Double(-0.0),
25959        )]));
25960        let negative_zero_envelope =
25961            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
25962        let history = vec![history_event(
25963            "MemoUpserted",
25964            json!({
25965                "sequence": 1,
25966                "entries": negative_zero_envelope.clone(),
25967                "merged": negative_zero_envelope,
25968            }),
25969        )];
25970
25971        workflow_context(history.clone())
25972            .upsert_memo(negative_zero)
25973            .expect("matching negative-zero history identity");
25974
25975        let error = workflow_context(history)
25976            .upsert_memo(AvroValue::Map(BTreeMap::from([(
25977                "reading".to_string(),
25978                AvroValue::Double(0.0),
25979            )])))
25980            .expect_err("positive zero must not consume negative-zero memo history");
25981        assert!(matches!(
25982            error,
25983            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25984        ));
25985    }
25986
25987    #[test]
25988    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
25989        let supported = json!({
25990            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
25991            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
25992        });
25993        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
25994        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
25995            "workflow_memo_updates": {"supported": false},
25996            "supported_workflow_task_commands": ["upsert_memo"]
25997        }))));
25998        assert!(commands_use_workflow_memo_updates(&[json!({
25999            "type": "upsert_memo",
26000            "entries": {"stage": "processing"}
26001        })]));
26002    }
26003
26004    #[test]
26005    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
26006        let client = Client::new("http://127.0.0.1:8080").expect("client");
26007        let mut worker = Worker::new(client, "rust-workers");
26008        worker.register_workflow("rust.timer", |ctx, _input| async move {
26009            ctx.sleep(Duration::from_secs(5)).await?;
26010            ctx.activity("after-timer", json!([])).await
26011        });
26012
26013        let task = |history_events| WorkflowTask {
26014            task_id: "wft-rust-timer-1".to_string(),
26015            observability_context: None,
26016            dispatch_observability_context: None,
26017            observability_links: None,
26018            workflow_command_id: None,
26019            workflow_id: Some("wf-rust-timer".to_string()),
26020            run_id: Some("run-rust-timer".to_string()),
26021            workflow_type: "rust.timer".to_string(),
26022            cancel_requested: false,
26023            payload_codec: DEFAULT_CODEC.to_string(),
26024            arguments: Some(
26025                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26026            ),
26027            history_events,
26028            total_history_events: None,
26029            history_size_bytes: None,
26030            continue_as_new_recommended: None,
26031            history_budget_pressure: None,
26032            next_history_page_token: None,
26033            workflow_task_attempt: 1,
26034            workflow_signal_id: None,
26035            signal_name: None,
26036            signal_arguments: None,
26037            workflow_update_id: None,
26038            update_name: None,
26039            lease_owner: Some("rust-worker".to_string()),
26040        };
26041
26042        let initial = worker
26043            .execute_workflow_task(task(Vec::new()))
26044            .expect("initial timer task");
26045        assert_eq!(
26046            initial,
26047            vec![json!({"type": "start_timer", "delay_seconds": 5})]
26048        );
26049
26050        let activity_result =
26051            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
26052        let replayed = worker
26053            .execute_workflow_task(task(vec![
26054                history_event(
26055                    "TimerScheduled",
26056                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26057                ),
26058                history_event(
26059                    "TimerFired",
26060                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26061                ),
26062                history_event(
26063                    "ActivityCompleted",
26064                    json!({
26065                        "sequence": 2,
26066                        "activity_type": "after-timer",
26067                        "payload_codec": DEFAULT_CODEC,
26068                        "result": activity_result,
26069                    }),
26070                ),
26071            ]))
26072            .expect("replayed workflow task");
26073        assert_eq!(replayed.len(), 1);
26074        assert_eq!(replayed[0]["type"], "complete_workflow");
26075        assert_eq!(
26076            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
26077            json!("done")
26078        );
26079    }
26080
26081    #[test]
26082    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
26083        let client = Client::new("http://127.0.0.1:8080").expect("client");
26084        let mut worker = Worker::new(client, "rust-workers");
26085        worker.register_workflow("rust.continue", |ctx, _input| async move {
26086            ctx.continue_as_new_with_options(
26087                ContinueAsNewOptions::new()
26088                    .workflow_type("rust.next")
26089                    .task_queue("next-workers"),
26090                json!([2, {"cursor": "next"}]),
26091            )
26092        });
26093
26094        let commands = worker
26095            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
26096            .expect("continue-as-new command");
26097
26098        assert_eq!(commands.len(), 1);
26099        assert_eq!(commands[0]["type"], "continue_as_new");
26100        assert_eq!(commands[0]["workflow_type"], "rust.next");
26101        assert_eq!(commands[0]["queue"], "next-workers");
26102        assert_eq!(
26103            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
26104                .expect("continue-as-new arguments"),
26105            json!([2, {"cursor": "next"}])
26106        );
26107    }
26108
26109    #[test]
26110    fn continue_as_new_preserves_typed_arguments() {
26111        let client = Client::new("http://127.0.0.1:8080").expect("client");
26112        let mut worker = Worker::new(client, "rust-workers");
26113        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
26114            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
26115            unreachable!("continue-as-new returns a control-flow error")
26116        });
26117
26118        let commands = worker
26119            .execute_workflow_task(workflow_task(
26120                "rust.typed-continue",
26121                Vec::new(),
26122                DEFAULT_CODEC,
26123            ))
26124            .expect("typed continue-as-new command");
26125
26126        assert_eq!(commands[0]["type"], "continue_as_new");
26127        assert_eq!(
26128            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
26129                .expect("typed continue arguments"),
26130            AvroValue::Array(vec![typed_fidelity_probe()])
26131        );
26132    }
26133
26134    #[test]
26135    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
26136        let client = Client::new("http://127.0.0.1:8080").expect("client");
26137        let mut worker = Worker::new(client, "rust-workers");
26138        worker.register_workflow("rust.continue", |ctx, _input| async move {
26139            ctx.continue_as_new(json!([2]))
26140        });
26141        let task = workflow_task(
26142            "rust.continue",
26143            vec![history_event(
26144                "WorkflowContinuedAsNew",
26145                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
26146            )],
26147            DEFAULT_CODEC,
26148        );
26149
26150        for _worker_restart_or_redelivery in 0..2 {
26151            let commands = worker
26152                .execute_workflow_task(task.clone())
26153                .expect("recorded transition replays");
26154            assert!(
26155                commands.is_empty(),
26156                "replay must not emit another successor"
26157            );
26158        }
26159    }
26160
26161    #[test]
26162    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
26163        let ctx = workflow_context(Vec::new());
26164        let error = ctx
26165            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
26166            .expect_err("blank queue must be rejected");
26167
26168        let Error::InvalidContinueAsNewOptions(error) = error else {
26169            panic!("expected typed continue-as-new validation error");
26170        };
26171        assert_eq!(error.field, "task_queue");
26172        assert!(ctx.take_commands().expect("commands").is_empty());
26173    }
26174
26175    #[test]
26176    fn workflow_context_exposes_server_history_budget() {
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.history-budget", |ctx, _input| async move {
26180            let budget = ctx.history_budget()?;
26181            Ok(json!({
26182                "events": budget.event_count,
26183                "bytes": budget.size_bytes,
26184                "recommended": budget.continue_as_new_recommended,
26185                "pressure": budget.pressure,
26186            }))
26187        });
26188        let task: WorkflowTask = serde_json::from_value(json!({
26189            "task_id": "task-history-budget",
26190            "workflow_type": "rust.history-budget",
26191            "payload_codec": DEFAULT_CODEC,
26192            "history_events": [],
26193            "total_history_events": 480,
26194            "history_size_bytes": 1_048_576,
26195            "continue_as_new_recommended": true,
26196            "history_budget_pressure": "continue_as_new_recommended",
26197        }))
26198        .expect("published workflow task");
26199
26200        let commands = worker
26201            .execute_workflow_task(task)
26202            .expect("history-budget workflow");
26203        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
26204        assert_eq!(result["events"], 480);
26205        assert_eq!(result["bytes"], 1_048_576);
26206        assert_eq!(result["recommended"], true);
26207        assert_eq!(result["pressure"], "continue_as_new_recommended");
26208    }
26209
26210    #[test]
26211    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
26212        let client = Client::new("http://127.0.0.1:8080").expect("client");
26213        let mut worker = Worker::new(client, "rust-workers");
26214        worker.register_workflow("rust.failing", |_ctx, _input| async move {
26215            Err(Error::Codec("rust_conformance_failure".to_string()))
26216        });
26217        let task = WorkflowTask {
26218            task_id: "wft-rust-failing-1".to_string(),
26219            observability_context: None,
26220            dispatch_observability_context: None,
26221            observability_links: None,
26222            workflow_command_id: None,
26223            workflow_id: Some("wf-rust-failing".to_string()),
26224            run_id: Some("run-rust-failing".to_string()),
26225            workflow_type: "rust.failing".to_string(),
26226            cancel_requested: false,
26227            payload_codec: DEFAULT_CODEC.to_string(),
26228            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26229            history_events: Vec::new(),
26230            total_history_events: Some(0),
26231            history_size_bytes: None,
26232            continue_as_new_recommended: None,
26233            history_budget_pressure: None,
26234            next_history_page_token: None,
26235            workflow_task_attempt: 1,
26236            workflow_signal_id: None,
26237            signal_name: None,
26238            signal_arguments: None,
26239            workflow_update_id: None,
26240            update_name: None,
26241            lease_owner: Some("rust-worker".to_string()),
26242        };
26243
26244        let commands = worker
26245            .execute_workflow_task(task)
26246            .expect("handler failure becomes a workflow command");
26247
26248        assert_eq!(commands.len(), 1);
26249        assert_eq!(commands[0]["type"], "fail_workflow");
26250        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
26251        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
26252        assert_eq!(commands[0]["non_retryable"], false);
26253        assert_eq!(
26254            commands[0]["message"],
26255            "codec error: rust_conformance_failure"
26256        );
26257        assert_eq!(
26258            commands[0]["exception"]["message"],
26259            "codec error: rust_conformance_failure"
26260        );
26261    }
26262
26263    #[test]
26264    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
26265        let client = Client::new("http://127.0.0.1:8080").expect("client");
26266        let mut worker = Worker::new(client, "rust-workers");
26267        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
26268            let _: String = ctx.side_effect(|| "captured".to_string())?;
26269            Err(Error::WorkerLoop("application failure".to_string()))
26270        });
26271
26272        let commands = worker
26273            .execute_workflow_task(workflow_task(
26274                "rust.failing-after-side-effect",
26275                Vec::new(),
26276                DEFAULT_CODEC,
26277            ))
26278            .expect("ordinary failure remains a workflow decision");
26279
26280        assert_eq!(commands.len(), 2);
26281        assert_eq!(commands[0]["type"], "record_side_effect");
26282        assert_eq!(commands[1]["type"], "fail_workflow");
26283    }
26284
26285    #[test]
26286    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
26287        let client = Client::new("http://127.0.0.1:8080").expect("client");
26288        let mut worker = Worker::new(client, "rust-workers");
26289        worker.register_workflow("rust.redrive", |ctx, _input| async move {
26290            ctx.activity("greet", json!([])).await?;
26291            Ok(Value::Null)
26292        });
26293        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
26294            match ctx.activity("greet", json!([])).await {
26295                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
26296                result => result,
26297            }
26298        });
26299
26300        let failed = history_event(
26301            "ActivityFailed",
26302            json!({
26303                "sequence": 1,
26304                "activity_type": "greet",
26305                "activity_execution_id": "activity-1",
26306                "message": "failed"
26307            }),
26308        );
26309        let commands = worker
26310            .execute_workflow_task(workflow_task(
26311                "rust.redrive",
26312                vec![failed.clone()],
26313                DEFAULT_CODEC,
26314            ))
26315            .expect("recorded failure becomes a workflow command");
26316        assert_eq!(commands[0]["type"], "fail_workflow");
26317        assert_eq!(commands[0]["failed_step_sequence"], 1);
26318        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
26319
26320        let translated = worker
26321            .execute_workflow_task(workflow_task(
26322                "rust.redrive-translated",
26323                vec![failed],
26324                DEFAULT_CODEC,
26325            ))
26326            .expect("translated failure becomes a workflow command");
26327        assert_eq!(translated[0]["type"], "fail_workflow");
26328        assert!(translated[0].get("failed_step_sequence").is_none());
26329        assert!(translated[0].get("failed_activity_execution_id").is_none());
26330
26331        let without_identity = worker
26332            .execute_workflow_task(workflow_task(
26333                "rust.redrive",
26334                vec![history_event(
26335                    "ActivityFailed",
26336                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
26337                )],
26338                DEFAULT_CODEC,
26339            ))
26340            .expect("incomplete identity still fails the workflow");
26341        assert!(without_identity[0].get("failed_step_sequence").is_none());
26342
26343        let timed_out = worker
26344            .execute_workflow_task(workflow_task(
26345                "rust.redrive",
26346                vec![history_event(
26347                    "ActivityTimedOut",
26348                    json!({
26349                        "sequence": 1,
26350                        "activity_type": "greet",
26351                        "activity_execution_id": "activity-timeout",
26352                    }),
26353                )],
26354                DEFAULT_CODEC,
26355            ))
26356            .expect("timeout still fails the workflow");
26357        assert!(timed_out[0].get("failed_step_sequence").is_none());
26358    }
26359
26360    #[test]
26361    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
26362        let client = Client::new("http://127.0.0.1:8080").expect("client");
26363        let mut worker = Worker::new(client, "rust-workers");
26364        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
26365            let first = ctx.activity("first", json!([])).await?;
26366            let second = ctx.activity("second", json!([first.clone()])).await?;
26367            Ok(json!({"first": first, "second": second}))
26368        });
26369        let first = history_event(
26370            "ActivityCompleted",
26371            json!({
26372                "sequence": 1,
26373                "activity_type": "first",
26374                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
26375                "payload_codec": DEFAULT_CODEC,
26376                "reused_from_run_id": "failed-run",
26377                "reused_activity_execution_id": "original-first",
26378            }),
26379        );
26380
26381        let retry = worker
26382            .execute_workflow_task(workflow_task(
26383                "rust.redrive-successor",
26384                vec![first.clone()],
26385                DEFAULT_CODEC,
26386            ))
26387            .expect("reused result replays before failed step");
26388        assert_eq!(retry.len(), 1);
26389        assert_eq!(retry[0]["type"], "schedule_activity");
26390        assert_eq!(retry[0]["activity_type"], "second");
26391        assert_eq!(
26392            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
26393            json!(["recorded"]),
26394        );
26395
26396        let second = history_event(
26397            "ActivityCompleted",
26398            json!({
26399                "sequence": 2,
26400                "activity_type": "second",
26401                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
26402                "payload_codec": DEFAULT_CODEC,
26403            }),
26404        );
26405        let completed = worker
26406            .execute_workflow_task(workflow_task(
26407                "rust.redrive-successor",
26408                vec![first, second],
26409                DEFAULT_CODEC,
26410            ))
26411            .expect("retried step completes the successor");
26412        assert_eq!(completed.len(), 1);
26413        assert_eq!(completed[0]["type"], "complete_workflow");
26414        assert_eq!(
26415            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
26416            json!({"first": "recorded", "second": "retried"}),
26417        );
26418    }
26419
26420    #[test]
26421    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
26422        let client = Client::new("http://127.0.0.1:8080").expect("client");
26423        let mut worker = Worker::new(client, "rust-workers");
26424        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
26425            Err(Error::WorkerLoop("application failure".to_string()))
26426        });
26427        let result =
26428            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
26429
26430        let error = worker
26431            .execute_workflow_task(workflow_task(
26432                "rust.removed-side-effect",
26433                vec![history_event(
26434                    "SideEffectRecorded",
26435                    json!({"sequence": 1, "result": result}),
26436                )],
26437                DEFAULT_CODEC,
26438            ))
26439            .expect_err("removed committed history must not become fail_workflow");
26440
26441        let Error::NonDeterministicReplay(failure) = error else {
26442            panic!("expected typed replay failure");
26443        };
26444        assert_eq!(failure.reason, "recorded_commands_unconsumed");
26445        assert_eq!(failure.sequence, Some(1));
26446        assert_eq!(failure.expected.as_deref(), Some("side effect"));
26447    }
26448
26449    #[test]
26450    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
26451        let client = Client::new("http://127.0.0.1:8080").expect("client");
26452        let mut worker = Worker::new(client, "rust-workers");
26453        worker.register_workflow(
26454            "rust.side-effect-before-marker-error",
26455            |ctx, _input| async move {
26456                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
26457                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
26458                ctx.get_version("restart-safe", 2, 2)?;
26459                Ok(Value::Null)
26460            },
26461        );
26462
26463        let error = worker
26464            .execute_workflow_task(workflow_task(
26465                "rust.side-effect-before-marker-error",
26466                vec![history_event(
26467                    "VersionMarkerRecorded",
26468                    json!({
26469                        "sequence": 1,
26470                        "change_id": "restart-safe",
26471                        "version": 1,
26472                        "min_supported": 1,
26473                        "max_supported": 1,
26474                    }),
26475                )],
26476                DEFAULT_CODEC,
26477            ))
26478            .expect_err("replay error must return no queued workflow commands");
26479
26480        let Error::NonDeterministicReplay(failure) = error else {
26481            panic!("expected typed replay failure");
26482        };
26483        assert_eq!(failure.reason, "version_marker_incompatible_range");
26484        assert_eq!(failure.sequence, Some(1));
26485    }
26486
26487    #[test]
26488    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
26489        let client = Client::new("http://127.0.0.1:8080").expect("client");
26490        let mut worker = Worker::new(client, "rust-workers");
26491        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
26492            ctx.sleep(Duration::from_secs(5)).await?;
26493            Ok(json!({"status": "timer fired"}))
26494        });
26495
26496        let task = WorkflowTask {
26497            task_id: "wft-rust-timer-pending".to_string(),
26498            observability_context: None,
26499            dispatch_observability_context: None,
26500            observability_links: None,
26501            workflow_command_id: None,
26502            workflow_id: Some("wf-rust-timer".to_string()),
26503            run_id: Some("run-rust-timer".to_string()),
26504            workflow_type: "rust.timer.pending".to_string(),
26505            cancel_requested: false,
26506            payload_codec: DEFAULT_CODEC.to_string(),
26507            arguments: Some(
26508                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26509            ),
26510            history_events: vec![history_event(
26511                "TimerScheduled",
26512                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26513            )],
26514            total_history_events: Some(1),
26515            history_size_bytes: None,
26516            continue_as_new_recommended: None,
26517            history_budget_pressure: None,
26518            next_history_page_token: None,
26519            workflow_task_attempt: 1,
26520            workflow_signal_id: None,
26521            signal_name: None,
26522            signal_arguments: None,
26523            workflow_update_id: None,
26524            update_name: None,
26525            lease_owner: Some("rust-worker".to_string()),
26526        };
26527
26528        for _redelivery_or_restart in 0..2 {
26529            let commands = worker
26530                .execute_workflow_task(task.clone())
26531                .expect("recorded timer remains pending");
26532            assert!(
26533                commands.is_empty(),
26534                "recorded timer must not be rescheduled"
26535            );
26536        }
26537    }
26538
26539    #[test]
26540    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
26541        let client = Client::new("http://127.0.0.1:8080").expect("client");
26542        let mut worker = Worker::new(client, "rust-workers");
26543        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
26544            Ok(json!({"status": "completed"}))
26545        });
26546        let task = WorkflowTask {
26547            task_id: "wft-rust-timer-removed".to_string(),
26548            observability_context: None,
26549            dispatch_observability_context: None,
26550            observability_links: None,
26551            workflow_command_id: None,
26552            workflow_id: Some("wf-rust-timer".to_string()),
26553            run_id: Some("run-rust-timer".to_string()),
26554            workflow_type: "rust.timer.removed".to_string(),
26555            cancel_requested: false,
26556            payload_codec: DEFAULT_CODEC.to_string(),
26557            arguments: Some(
26558                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26559            ),
26560            history_events: vec![
26561                history_event(
26562                    "TimerScheduled",
26563                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26564                ),
26565                history_event(
26566                    "TimerFired",
26567                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26568                ),
26569            ],
26570            total_history_events: Some(2),
26571            history_size_bytes: None,
26572            continue_as_new_recommended: None,
26573            history_budget_pressure: None,
26574            next_history_page_token: None,
26575            workflow_task_attempt: 1,
26576            workflow_signal_id: None,
26577            signal_name: None,
26578            signal_arguments: None,
26579            workflow_update_id: None,
26580            update_name: None,
26581            lease_owner: Some("rust-worker".to_string()),
26582        };
26583
26584        let Error::NonDeterministicReplay(failure) = worker
26585            .execute_workflow_task(task)
26586            .expect_err("removed timer must fail replay")
26587        else {
26588            panic!("expected typed replay failure");
26589        };
26590        assert_eq!(failure.reason, "recorded_commands_unconsumed");
26591        assert_eq!(failure.sequence, Some(1));
26592    }
26593
26594    #[test]
26595    fn workflow_context_emits_explicit_child_workflow_contract() {
26596        let ctx = WorkflowContext {
26597            cancellation_scope_id: "root".into(),
26598            state: Arc::new(Mutex::new(
26599                WorkflowState::new_with_identity(
26600                    Vec::new(),
26601                    Some("wf-parent".to_string()),
26602                    Some("run-parent".to_string()),
26603                    "parent-workers".to_string(),
26604                    DEFAULT_CODEC.to_string(),
26605                    None,
26606                )
26607                .expect("workflow state"),
26608            )),
26609        };
26610        let options = ChildWorkflowOptions::new("python-workers")
26611            .parent_close_policy(ParentClosePolicy::RequestCancel)
26612            .retry_policy(ChildWorkflowRetryPolicy {
26613                max_attempts: Some(3),
26614                backoff_seconds: vec![1, 5],
26615                non_retryable_error_types: vec!["ValidationError".to_string()],
26616            })
26617            .execution_timeout_seconds(600)
26618            .run_timeout_seconds(120);
26619        let mut call = Box::pin(ctx.start_child_workflow(
26620            "python.fulfil-order",
26621            options,
26622            json!([{"order_id": "order-42"}]),
26623        ));
26624        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26625
26626        assert!(matches!(
26627            call.as_mut().poll(&mut task_context),
26628            Poll::Pending
26629        ));
26630        let commands = ctx.take_commands().expect("commands");
26631        assert_eq!(commands.len(), 1);
26632        let command = &commands[0];
26633        assert_eq!(command["type"], "start_child_workflow");
26634        assert_eq!(command["workflow_type"], "python.fulfil-order");
26635        assert_eq!(command["queue"], "python-workers");
26636        assert_eq!(command["parent_close_policy"], "request_cancel");
26637        assert_eq!(command["retry_policy"]["max_attempts"], 3);
26638        assert_eq!(command["execution_timeout_seconds"], 600);
26639        assert_eq!(command["run_timeout_seconds"], 120);
26640        assert_eq!(
26641            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
26642            json!([{"order_id": "order-42"}])
26643        );
26644    }
26645
26646    fn child_parent_worker() -> Worker {
26647        let client = Client::new("http://127.0.0.1:8080").expect("client");
26648        let mut worker = Worker::new(client, "rust-parent-workers");
26649        worker.register_workflow("rust.parent", |ctx, _input| async move {
26650            let child = ctx
26651                .start_child_workflow(
26652                    "python.child",
26653                    ChildWorkflowOptions::new("python-child-workers")
26654                        .parent_close_policy(ParentClosePolicy::Terminate),
26655                    json!([{"codec_probe": [1, true, "rust"]}]),
26656                )
26657                .await?;
26658            Ok(json!({
26659                "parent_workflow_id": child.parent.workflow_id,
26660                "parent_run_id": child.parent.run_id,
26661                "child_workflow_id": child.child.workflow_id,
26662                "child_run_id": child.child.run_id,
26663                "child_workflow_type": child.child_workflow_type,
26664                "result": child.result,
26665            }))
26666        });
26667        worker
26668    }
26669
26670    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
26671        WorkflowTask {
26672            task_id: "wft-child-parent".to_string(),
26673            observability_context: None,
26674            dispatch_observability_context: None,
26675            observability_links: None,
26676            workflow_command_id: None,
26677            workflow_id: Some("wf-parent".to_string()),
26678            run_id: Some("run-parent".to_string()),
26679            workflow_type: "rust.parent".to_string(),
26680            cancel_requested: false,
26681            payload_codec: DEFAULT_CODEC.to_string(),
26682            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26683            history_events: vec![
26684                HistoryEvent {
26685                    event_type: "ChildWorkflowScheduled".to_string(),
26686                    payload: json!({
26687                        "sequence": 1,
26688                        "child_call_id": "call-child",
26689                        "child_workflow_instance_id": "wf-child",
26690                        "child_workflow_run_id": "run-child",
26691                        "child_workflow_type": "python.child",
26692                        "parent_close_policy": "terminate",
26693                    }),
26694                    raw: HashMap::new(),
26695                },
26696                HistoryEvent {
26697                    event_type: event_type.to_string(),
26698                    payload,
26699                    raw: HashMap::new(),
26700                },
26701            ],
26702            total_history_events: Some(2),
26703            history_size_bytes: None,
26704            continue_as_new_recommended: None,
26705            history_budget_pressure: None,
26706            next_history_page_token: None,
26707            workflow_task_attempt: 1,
26708            workflow_signal_id: None,
26709            signal_name: None,
26710            signal_arguments: None,
26711            workflow_update_id: None,
26712            update_name: None,
26713            lease_owner: Some("rust-worker".to_string()),
26714        }
26715    }
26716
26717    #[test]
26718    fn committed_child_result_replays_without_starting_a_duplicate() {
26719        let worker = child_parent_worker();
26720        let task = child_parent_task(
26721            "ChildRunCompleted",
26722            json!({
26723                "sequence": 1,
26724                "child_call_id": "call-child",
26725                "child_workflow_instance_id": "wf-child",
26726                "child_workflow_run_id": "run-child",
26727                "child_workflow_type": "python.child",
26728                "payload_codec": DEFAULT_CODEC,
26729                "result": fixture_envelope(json!({"from":"python","ok":true})),
26730            }),
26731        );
26732
26733        for _restart in 0..2 {
26734            let commands = worker
26735                .execute_workflow_task(task.clone())
26736                .expect("replayed parent task");
26737            assert_eq!(commands.len(), 1);
26738            assert_eq!(commands[0]["type"], "complete_workflow");
26739            assert!(!commands
26740                .iter()
26741                .any(|command| command["type"] == "start_child_workflow"));
26742            let output =
26743                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26744            assert_eq!(output["parent_workflow_id"], "wf-parent");
26745            assert_eq!(output["parent_run_id"], "run-parent");
26746            assert_eq!(output["child_workflow_id"], "wf-child");
26747            assert_eq!(output["child_run_id"], "run-child");
26748            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
26749        }
26750    }
26751
26752    #[test]
26753    fn typed_child_arguments_and_results_survive_replay() {
26754        let client = Client::new("http://127.0.0.1:8080").expect("client");
26755        let mut worker = Worker::new(client, "rust-parent-workers");
26756        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
26757            let child = ctx
26758                .start_child_workflow_avro_value(
26759                    "python.typed-child",
26760                    ChildWorkflowOptions::new("python-workers"),
26761                    AvroValue::Array(vec![typed_fidelity_probe()]),
26762                )
26763                .await?;
26764            Ok(child.result)
26765        });
26766
26767        let initial = worker
26768            .execute_workflow_task(workflow_task(
26769                "rust.typed-parent",
26770                Vec::new(),
26771                DEFAULT_CODEC,
26772            ))
26773            .expect("typed child start");
26774        assert_eq!(initial[0]["type"], "start_child_workflow");
26775        assert_eq!(
26776            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
26777                .expect("typed child arguments"),
26778            AvroValue::Array(vec![typed_fidelity_probe()])
26779        );
26780
26781        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
26782            .expect("typed child result");
26783        let task = workflow_task(
26784            "rust.typed-parent",
26785            vec![
26786                history_event(
26787                    "ChildWorkflowScheduled",
26788                    json!({
26789                        "sequence": 1,
26790                        "child_call_id": "call-typed",
26791                        "child_workflow_instance_id": "wf-child",
26792                        "child_workflow_run_id": "run-child",
26793                        "child_workflow_type": "python.typed-child",
26794                    }),
26795                ),
26796                history_event(
26797                    "ChildRunCompleted",
26798                    json!({
26799                        "sequence": 1,
26800                        "child_call_id": "call-typed",
26801                        "child_workflow_instance_id": "wf-child",
26802                        "child_workflow_run_id": "run-child",
26803                        "child_workflow_type": "python.typed-child",
26804                        "payload_codec": DEFAULT_CODEC,
26805                        "result": result,
26806                    }),
26807                ),
26808            ],
26809            DEFAULT_CODEC,
26810        );
26811
26812        let commands = worker
26813            .execute_workflow_task(task)
26814            .expect("typed child replay");
26815        assert_eq!(commands[0]["type"], "complete_workflow");
26816        assert_eq!(
26817            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
26818                .expect("typed parent result"),
26819            typed_fidelity_probe()
26820        );
26821    }
26822
26823    #[test]
26824    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
26825        let worker = child_parent_worker();
26826        let mut task = child_parent_task("unused", Value::Null);
26827        task.history_events.truncate(1);
26828        task.total_history_events = Some(1);
26829
26830        for _redelivery_or_restart in 0..2 {
26831            let commands = worker
26832                .execute_workflow_task(task.clone())
26833                .expect("recorded child remains pending");
26834            assert!(
26835                commands.is_empty(),
26836                "recorded pending child must not be started again"
26837            );
26838        }
26839    }
26840
26841    #[test]
26842    fn child_cancellation_becomes_stable_parent_failure_command() {
26843        let worker = child_parent_worker();
26844        let task = child_parent_task(
26845            "ChildRunCancelled",
26846            json!({
26847                "sequence": 1,
26848                "child_workflow_instance_id": "wf-child",
26849                "child_workflow_run_id": "run-child",
26850                "child_workflow_type": "python.child",
26851                "failure_id": "failure-child",
26852                "failure_category": "cancelled",
26853                "message": "cancelled by parent-close policy",
26854            }),
26855        );
26856
26857        let commands = worker
26858            .execute_workflow_task(task)
26859            .expect("parent settlement");
26860        assert_eq!(commands.len(), 1);
26861        assert_eq!(commands[0]["type"], "fail_workflow");
26862        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
26863        assert_eq!(
26864            commands[0]["exception"]["properties"]["reason"],
26865            "cancelled"
26866        );
26867        assert_eq!(
26868            commands[0]["exception"]["properties"]["child_workflow_run_id"],
26869            "run-child"
26870        );
26871    }
26872
26873    #[test]
26874    fn workflow_can_handle_typed_child_failure() {
26875        let client = Client::new("http://127.0.0.1:8080").expect("client");
26876        let mut worker = Worker::new(client, "rust-parent-workers");
26877        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
26878            match ctx
26879                .start_child_workflow(
26880                    "python.child",
26881                    ChildWorkflowOptions::new("python-child-workers"),
26882                    json!([]),
26883                )
26884                .await
26885            {
26886                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
26887                    "reason": failure.reason,
26888                    "failure_id": failure.failure_id,
26889                    "exception_class": failure.exception_class,
26890                    "child_run_id": failure.child_workflow_run_id,
26891                })),
26892                Err(error) => Err(error),
26893                Ok(_) => Err(Error::WorkerLoop(
26894                    "child unexpectedly succeeded".to_string(),
26895                )),
26896            }
26897        });
26898        let mut task = child_parent_task(
26899            "ChildRunFailed",
26900            json!({
26901                "sequence": 1,
26902                "child_workflow_instance_id": "wf-child",
26903                "child_workflow_run_id": "run-child",
26904                "child_workflow_type": "python.child",
26905                "failure_id": "failure-child",
26906                "failure_category": "child_workflow",
26907                "message": "payment rejected",
26908                "exception": {
26909                    "type": "PaymentRejected",
26910                    "class": "payments.PaymentRejected",
26911                    "message": "payment rejected"
26912                }
26913            }),
26914        );
26915        task.workflow_type = "rust.handled-parent".to_string();
26916        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
26917
26918        let commands = worker.execute_workflow_task(task).expect("handled failure");
26919        assert_eq!(commands[0]["type"], "complete_workflow");
26920        let output =
26921            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26922        assert_eq!(output["reason"], "child_workflow");
26923        assert_eq!(output["failure_id"], "failure-child");
26924        assert_eq!(output["exception_class"], "payments.PaymentRejected");
26925        assert_eq!(output["child_run_id"], "run-child");
26926    }
26927
26928    #[test]
26929    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
26930        let client = Client::new("http://127.0.0.1:8080").expect("client");
26931        let mut worker = Worker::new(client, "rust-workers");
26932
26933        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
26934            let signal = ctx.wait_signal("start").await?;
26935            let name = signal
26936                .first()
26937                .and_then(|value| value.as_str())
26938                .unwrap_or("world");
26939            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
26940            Ok(json!({
26941                "greeting": greeting,
26942                "language": "rust"
26943            }))
26944        });
26945
26946        let signal_arguments =
26947            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
26948        let task = WorkflowTask {
26949            task_id: "wft-rust-signal-1".to_string(),
26950            observability_context: None,
26951            dispatch_observability_context: None,
26952            observability_links: None,
26953            workflow_command_id: None,
26954            workflow_id: Some("wf-rust-hello".to_string()),
26955            run_id: Some("run-rust-hello".to_string()),
26956            workflow_type: "rust.hello_workflow".to_string(),
26957            cancel_requested: false,
26958            payload_codec: DEFAULT_CODEC.to_string(),
26959            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26960            history_events: vec![HistoryEvent {
26961                event_type: "SignalReceived".to_string(),
26962                payload: json!({
26963                    "signal_id": "sig-rust-1",
26964                    "signal_name": "start"
26965                }),
26966                raw: HashMap::new(),
26967            }],
26968            total_history_events: Some(1),
26969            history_size_bytes: None,
26970            continue_as_new_recommended: None,
26971            history_budget_pressure: None,
26972            next_history_page_token: None,
26973            workflow_task_attempt: 1,
26974            workflow_signal_id: Some("sig-rust-1".to_string()),
26975            signal_name: Some("start".to_string()),
26976            signal_arguments: Some(signal_arguments),
26977            workflow_update_id: None,
26978            update_name: None,
26979            lease_owner: Some("rust-worker".to_string()),
26980        };
26981
26982        let commands = worker.execute_workflow_task(task).expect("workflow task");
26983
26984        assert_eq!(commands.len(), 1);
26985        assert_eq!(commands[0]["type"], "schedule_activity");
26986        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
26987        assert_eq!(
26988            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
26989            json!(["Rust"])
26990        );
26991    }
26992
26993    #[test]
26994    fn workflow_task_appends_paginated_history_events() {
26995        let mut task = WorkflowTask {
26996            task_id: "wft-rust-pages-1".to_string(),
26997            observability_context: None,
26998            dispatch_observability_context: None,
26999            observability_links: None,
27000            workflow_command_id: None,
27001            workflow_id: Some("wf-rust-pages".to_string()),
27002            run_id: Some("run-rust-pages".to_string()),
27003            workflow_type: "rust.hello_workflow".to_string(),
27004            cancel_requested: false,
27005            payload_codec: DEFAULT_CODEC.to_string(),
27006            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
27007            history_events: vec![HistoryEvent {
27008                event_type: "WorkflowStarted".to_string(),
27009                payload: json!({}),
27010                raw: HashMap::new(),
27011            }],
27012            total_history_events: Some(3),
27013            history_size_bytes: None,
27014            continue_as_new_recommended: None,
27015            history_budget_pressure: None,
27016            next_history_page_token: Some("MQ==".to_string()),
27017            workflow_task_attempt: 1,
27018            workflow_signal_id: None,
27019            signal_name: None,
27020            signal_arguments: None,
27021            workflow_update_id: None,
27022            update_name: None,
27023            lease_owner: Some("rust-worker".to_string()),
27024        };
27025
27026        task.append_history_page(WorkflowTaskHistoryPage {
27027            history_events: vec![
27028                HistoryEvent {
27029                    event_type: "SignalReceived".to_string(),
27030                    payload: json!({
27031                        "signal_id": "sig-rust-1",
27032                        "signal_name": "start",
27033                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
27034                            .expect("signal arguments")
27035                    }),
27036                    raw: HashMap::new(),
27037                },
27038                HistoryEvent {
27039                    event_type: "MarkerRecorded".to_string(),
27040                    payload: json!({"sequence": 3}),
27041                    raw: HashMap::new(),
27042                },
27043            ],
27044            total_history_events: Some(3),
27045            next_history_page_token: None,
27046        });
27047
27048        assert_eq!(task.history_events.len(), 3);
27049        assert_eq!(task.total_history_events, Some(3));
27050        assert_eq!(task.next_history_page_token, None);
27051
27052        let signal = task
27053            .history_events
27054            .iter()
27055            .find(|event| event.event_type == "SignalReceived")
27056            .expect("signal event");
27057        assert_eq!(
27058            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
27059            vec![AvroValue::String("Rust".to_string())]
27060        );
27061    }
27062
27063    #[tokio::test]
27064    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
27065        let client = Client::new("http://127.0.0.1:8080").expect("client");
27066        let mut worker = Worker::new(client, "rust-workers");
27067        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27068        worker.register_query("counter", "current", |ctx, _args| async move {
27069            let mut count = 0_i64;
27070            for signal in ctx.signal_events() {
27071                let value = signal
27072                    .arguments
27073                    .first()
27074                    .and_then(Value::as_i64)
27075                    .unwrap_or_default();
27076                match signal.name.as_str() {
27077                    "increment" => count += value,
27078                    "set" => count = value,
27079                    _ => {}
27080                }
27081            }
27082            Ok(json!(count))
27083        });
27084
27085        let task = QueryTask {
27086            query_task_id: "query-rust-counter".to_string(),
27087            observability_context: None,
27088            dispatch_observability_context: None,
27089            observability_links: None,
27090            query_task_attempt: 1,
27091            lease_owner: Some("rust-worker".to_string()),
27092            workflow_id: Some("counter-1".to_string()),
27093            run_id: Some("run-counter-1".to_string()),
27094            workflow_type: "counter".to_string(),
27095            query_name: "current".to_string(),
27096            payload_codec: DEFAULT_CODEC.to_string(),
27097            workflow_arguments: Some(
27098                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
27099            ),
27100            query_arguments: Some(
27101                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
27102            ),
27103            history_events: vec![
27104                HistoryEvent {
27105                    event_type: "SignalReceived".to_string(),
27106                    payload: json!({
27107                        "signal_id": "php-signal-1",
27108                        "signal_name": "increment",
27109                        "workflow_sequence": 1,
27110                        "payload_codec": DEFAULT_CODEC,
27111                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
27112                    }),
27113                    raw: HashMap::new(),
27114                },
27115                HistoryEvent {
27116                    event_type: "SignalReceived".to_string(),
27117                    payload: json!({
27118                        "signal_id": "python-signal-2",
27119                        "signal_name": "increment",
27120                        "workflow_sequence": 2,
27121                        "payload_codec": DEFAULT_CODEC,
27122                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
27123                    }),
27124                    raw: HashMap::new(),
27125                },
27126                HistoryEvent {
27127                    event_type: "SignalReceived".to_string(),
27128                    payload: json!({
27129                        "signal_id": "rust-signal-3",
27130                        "signal_name": "set",
27131                        "workflow_sequence": 3,
27132                        "payload_codec": DEFAULT_CODEC,
27133                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
27134                    }),
27135                    raw: HashMap::new(),
27136                },
27137            ],
27138            history_export: None,
27139            run_status: Some("completed".to_string()),
27140        };
27141
27142        let result = worker.execute_query_task(task).await.expect("query result");
27143        assert_eq!(result.into_json().expect("query projection"), json!(0));
27144    }
27145
27146    #[tokio::test]
27147    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
27148        let worker = replay_counter_worker();
27149        let running_history = json!([
27150            {
27151                "type": "ActivityCompleted",
27152                "payload": {
27153                    "sequence": 1,
27154                    "activity_type": "load-counter",
27155                    "payload_codec": DEFAULT_CODEC,
27156                    "result": fixture_envelope(json!("loaded"))
27157                }
27158            },
27159            {
27160                "type": "SignalWaitOpened",
27161                "payload": {
27162                    "sequence": 3,
27163                    "signal_name": "increment"
27164                }
27165            },
27166            {
27167                "type": "SignalReceived",
27168                "payload": {
27169                    "signal_id": "signal-3",
27170                    "signal_name": "increment",
27171                    "workflow_sequence": 2,
27172                    "payload_codec": DEFAULT_CODEC,
27173                    "arguments": fixture_envelope(json!([3]))
27174                }
27175            },
27176            {
27177                "type": "SignalApplied",
27178                "payload": {
27179                    "sequence": 3,
27180                    "signal_id": "signal-3",
27181                    "signal_name": "increment",
27182                    "payload_codec": DEFAULT_CODEC,
27183                    "value": fixture_envelope(json!([3]))
27184                }
27185            }
27186        ]);
27187
27188        let running = worker
27189            .execute_query_task(replay_counter_query(
27190                "current",
27191                running_history.clone(),
27192                "running",
27193            ))
27194            .await
27195            .expect("running replay query");
27196        assert_eq!(
27197            running.clone().into_json().expect("query projection"),
27198            json!({"loaded": "loaded", "count": 3, "finished": false})
27199        );
27200
27201        let detached = worker
27202            .execute_query_task(replay_counter_query(
27203                "detached-mutation",
27204                running_history.clone(),
27205                "running",
27206            ))
27207            .await
27208            .expect("query mutates only its detached state clone");
27209        assert_eq!(detached.into_json().expect("query projection"), json!(999));
27210        let failed = worker
27211            .execute_query_task(replay_counter_query(
27212                "failed-mutation",
27213                running_history.clone(),
27214                "running",
27215            ))
27216            .await
27217            .expect_err("failed query");
27218        assert_eq!(failed.reason, "query_rejected");
27219        let unchanged = worker
27220            .execute_query_task(replay_counter_query("current", running_history, "running"))
27221            .await
27222            .expect("later query reconstructs unchanged state");
27223        assert_eq!(unchanged, running);
27224
27225        let restarted_worker = replay_counter_worker();
27226        let empty_arguments = fixture_envelope(json!([]));
27227        let loaded_result = fixture_envelope(json!("loaded"));
27228        let signal_three = fixture_blob(json!([3]));
27229        let signal_five = fixture_blob(json!([5]));
27230        let restarted_task: QueryTask = serde_json::from_value(json!({
27231            "query_task_id": "query-after-restart",
27232            "workflow_id": "counter-1",
27233            "run_id": "run-counter-1",
27234            "workflow_type": "replay-counter",
27235            "query_name": "current",
27236            "payload_codec": DEFAULT_CODEC,
27237            "workflow_arguments": empty_arguments.clone(),
27238            "query_arguments": empty_arguments,
27239            "history_events": [],
27240            "history_export": {
27241                "payloads": {"codec": DEFAULT_CODEC},
27242                "history_events": [
27243                    {
27244                        "type": "ActivityCompleted",
27245                        "payload": {
27246                            "sequence": 1,
27247                            "activity_type": "load-counter",
27248                            "payload_codec": DEFAULT_CODEC,
27249                            "result": null
27250                        }
27251                    },
27252                    {
27253                        "type": "SignalWaitOpened",
27254                        "payload": {
27255                            "sequence": 3,
27256                            "signal_name": "increment"
27257                        }
27258                    },
27259                    {
27260                        "type": "SignalReceived",
27261                        "payload": {
27262                            "signal_id": "signal-3",
27263                            "signal_name": "increment",
27264                            "workflow_sequence": 2
27265                        }
27266                    },
27267                    {
27268                        "type": "SignalApplied",
27269                        "payload": {
27270                            "sequence": 3,
27271                            "signal_id": "signal-3",
27272                            "signal_name": "increment"
27273                        }
27274                    },
27275                    {
27276                        "type": "SignalWaitOpened",
27277                        "payload": {
27278                            "sequence": 5,
27279                            "signal_name": "increment"
27280                        }
27281                    },
27282                    {
27283                        "type": "SignalReceived",
27284                        "payload": {
27285                            "signal_id": "signal-5",
27286                            "signal_name": "increment",
27287                            "workflow_sequence": 4
27288                        }
27289                    },
27290                    {
27291                        "type": "SignalApplied",
27292                        "payload": {
27293                            "sequence": 5,
27294                            "signal_id": "signal-5",
27295                            "signal_name": "increment"
27296                        }
27297                    }
27298                ],
27299                "activities": [{
27300                    "sequence": 1,
27301                    "activity_type": "load-counter",
27302                    "payload_codec": DEFAULT_CODEC,
27303                    "result": loaded_result
27304                }],
27305                "signals": [
27306                    {
27307                        "id": "signal-3",
27308                        "name": "increment",
27309                        "workflow_sequence": 2,
27310                        "payload_codec": DEFAULT_CODEC,
27311                        "arguments": signal_three
27312                    },
27313                    {
27314                        "id": "signal-5",
27315                        "name": "increment",
27316                        "workflow_sequence": 4,
27317                        "payload_codec": DEFAULT_CODEC,
27318                        "arguments": signal_five
27319                    }
27320                ]
27321            },
27322            "run_status": "completed"
27323        }))
27324        .expect("cold replay query task");
27325        let completed = restarted_worker
27326            .execute_query_task(restarted_task)
27327            .await
27328            .expect("completed cold replay query");
27329        assert_eq!(
27330            completed.into_json().expect("query projection"),
27331            json!({"loaded": "loaded", "count": 8, "finished": true})
27332        );
27333    }
27334
27335    #[tokio::test]
27336    async fn replayed_query_replay_failures_are_machine_readable() {
27337        let worker = replay_counter_worker();
27338        let task = replay_counter_query(
27339            "current",
27340            json!([{
27341                "type": "ActivityCompleted",
27342                "payload": {
27343                    "sequence": 1,
27344                    "payload_codec": DEFAULT_CODEC,
27345                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
27346                }
27347            }]),
27348            "running",
27349        );
27350        let failure = worker
27351            .execute_query_task(task)
27352            .await
27353            .expect_err("invalid replay history payload");
27354        assert_eq!(failure.reason, "query_payload_decode_failed");
27355        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
27356        assert!(failure.message.contains("invalid_payload_framing"));
27357    }
27358
27359    #[tokio::test]
27360    async fn query_task_restores_compact_history_from_export() {
27361        let client = Client::new("http://127.0.0.1:8080").expect("client");
27362        let mut worker = Worker::new(client, "rust-workers");
27363        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27364        worker.register_query("counter", "current", |ctx, _args| async move {
27365            Ok(json!(ctx.signals("increment")[0][0]))
27366        });
27367        let empty_arguments = fixture_envelope(json!([]));
27368        let exported_signal = fixture_blob(json!([9]));
27369        let task: QueryTask = serde_json::from_value(json!({
27370            "query_task_id": "query-export",
27371            "workflow_type": "counter",
27372            "query_name": "current",
27373            "payload_codec": DEFAULT_CODEC,
27374            "workflow_arguments": empty_arguments.clone(),
27375            "query_arguments": empty_arguments,
27376            "history_events": [],
27377            "history_export": {
27378                "payloads": {"codec": DEFAULT_CODEC},
27379                "history_events": [{
27380                    "type": "SignalReceived",
27381                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
27382                }],
27383                "signals": [{
27384                    "id": "signal-export",
27385                    "name": "increment",
27386                    "status": "applied",
27387                    "workflow_sequence": 1,
27388                    "payload_codec": DEFAULT_CODEC,
27389                    "arguments": exported_signal
27390                }]
27391            }
27392        }))
27393        .expect("query task");
27394
27395        let result = worker.execute_query_task(task).await.expect("query result");
27396        assert_eq!(result.into_json().expect("query projection"), json!(9));
27397    }
27398
27399    #[tokio::test]
27400    async fn query_task_failures_have_stable_reasons() {
27401        let client = Client::new("http://127.0.0.1:8080").expect("client");
27402        let mut worker = Worker::new(client, "rust-workers");
27403        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27404        worker.register_query(
27405            "counter",
27406            "current",
27407            |_ctx, _args| async move { Ok(json!(0)) },
27408        );
27409
27410        let base_task = QueryTask {
27411            query_task_id: "query-errors".to_string(),
27412            observability_context: None,
27413            dispatch_observability_context: None,
27414            observability_links: None,
27415            query_task_attempt: 1,
27416            lease_owner: None,
27417            workflow_id: Some("counter-errors".to_string()),
27418            run_id: Some("run-errors".to_string()),
27419            workflow_type: "counter".to_string(),
27420            query_name: "missing".to_string(),
27421            payload_codec: DEFAULT_CODEC.to_string(),
27422            workflow_arguments: Some(fixture_envelope(json!([]))),
27423            query_arguments: Some(fixture_envelope(json!([]))),
27424            history_events: Vec::new(),
27425            history_export: None,
27426            run_status: Some("running".to_string()),
27427        };
27428
27429        let unknown = worker
27430            .execute_query_task(base_task.clone())
27431            .await
27432            .expect_err("unknown query");
27433        assert_eq!(unknown.reason, "rejected_unknown_query");
27434
27435        let mut malformed = base_task;
27436        malformed.query_name = "current".to_string();
27437        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
27438        let malformed = worker
27439            .execute_query_task(malformed)
27440            .await
27441            .expect_err("malformed payload");
27442        assert_eq!(malformed.reason, "query_payload_decode_failed");
27443
27444        let client = Client::new("http://127.0.0.1:8080").expect("client");
27445        let mut unavailable_worker = Worker::new(client, "rust-workers");
27446        unavailable_worker
27447            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27448        let empty_arguments = fixture_envelope(json!([]));
27449        let unavailable_task: QueryTask = serde_json::from_value(json!({
27450            "query_task_id": "query-unavailable",
27451            "workflow_type": "counter",
27452            "query_name": "current",
27453            "payload_codec": DEFAULT_CODEC,
27454            "workflow_arguments": empty_arguments.clone(),
27455            "query_arguments": empty_arguments
27456        }))
27457        .expect("query task");
27458        let unavailable = unavailable_worker
27459            .execute_query_task(unavailable_task)
27460            .await
27461            .expect_err("query handler unavailable");
27462        assert_eq!(unavailable.reason, "query_handler_unavailable");
27463    }
27464
27465    #[tokio::test]
27466    async fn client_query_decodes_result_and_typed_failure() {
27467        let server = MockWorkerServer::start();
27468        let client = Client::builder(server.base_url())
27469            .timeout(Duration::from_secs(2))
27470            .build()
27471            .expect("client");
27472
27473        let result = client
27474            .query_workflow("counter-1", "current", json!([]))
27475            .await
27476            .expect("query result");
27477        assert_eq!(result, json!({"count": 8}));
27478
27479        let error = client
27480            .query_workflow("counter-1", "missing", json!([]))
27481            .await
27482            .expect_err("unknown query");
27483        let Error::QueryFailed(failure) = error else {
27484            panic!("expected typed query failure");
27485        };
27486        assert_eq!(failure.status, 404);
27487        assert_eq!(failure.reason, "rejected_unknown_query");
27488    }
27489
27490    const KEYED_SIGNAL_PATH: &str = "/api/workflows/keyed-1/signal/approve";
27491    const KEYED_RUN_SIGNAL_PATH: &str = "/api/workflows/keyed-1/runs/run-keyed-1/signal/approve";
27492    const KEYED_UPDATE_PATH: &str = "/api/workflows/keyed-1/update/adjust";
27493
27494    #[cfg(feature = "telemetry")]
27495    #[tokio::test]
27496    async fn optional_observability_client_uses_actual_discovery_and_preserves_business_intent() {
27497        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
27498        static PHASE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
27499        PHASE.store(0, Ordering::SeqCst);
27500        use opentelemetry::{
27501            propagation::TextMapPropagator,
27502            trace::{FutureExt, TracerProvider},
27503        };
27504        use opentelemetry_sdk::propagation::TraceContextPropagator;
27505        struct Restore;
27506        impl Drop for Restore {
27507            fn drop(&mut self) {
27508                opentelemetry::global::set_text_map_propagator(
27509                    opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
27510                );
27511            }
27512        }
27513        let _restore = Restore;
27514        opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());
27515        let headers = HashMap::from([(
27516            "traceparent".to_string(),
27517            "00-12345678901234567890123456789012-1234567890123456-01".to_string(),
27518        )]);
27519        let parent = TraceContextPropagator::new().extract(&headers);
27520        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27521            request_override: Some(|path, body, _number| {
27522                if path == "/api/cluster/info" {
27523                    return Some(if PHASE.load(Ordering::SeqCst) == 2 {
27524                        ("503 Service Unavailable", "{}".into())
27525                    } else {
27526                        ("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
27527                            "supported": true, "schema": "durable-workflow.trace-context", "version": if PHASE.load(Ordering::SeqCst) == 0 {1} else {99},
27528                            "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
27529                            "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
27530                        }}}}).to_string())
27531                    });
27532                }
27533                let body: Value = serde_json::from_str(body).ok()?;
27534                Some(("200 OK", json!({"workflow_id": "order", "run_id": "run", "workflow_type": "orders",
27535                    "outcome": "accepted", "command_id": "command", "request_id": body["request_id"],
27536                    "result": "original"}).to_string()))
27537            }),
27538            ..MockWorkerBehavior::default()
27539        });
27540        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder().build();
27541        let client = Client::new(server.base_url()).unwrap().with_telemetry(
27542            telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test")),
27543        );
27544        let input = json!([{"observability_context": {"business": "preserved"}}]);
27545        async {
27546            client
27547                .start_workflow("orders", "orders", "order", &input)
27548                .await
27549                .unwrap();
27550            assert!(server
27551                .request_body("/api/workflows")
27552                .get("observability_context")
27553                .is_none());
27554            client.cluster_info().await.unwrap();
27555            client
27556                .start_workflow("orders", "orders", "order", &input)
27557                .await
27558                .unwrap();
27559            client
27560                .signal_workflow_with_request_id("order", "ready", &input, "signal-original")
27561                .await
27562                .unwrap();
27563            client
27564                .update_workflow("order", "status", &input, Some("update-original"))
27565                .await
27566                .unwrap();
27567            client
27568                .cancel_workflow("order", WorkflowCommandOptions::default())
27569                .await
27570                .unwrap();
27571            for path in [
27572                "/api/workflows",
27573                "/api/workflows/order/signal/ready",
27574                "/api/workflows/order/update/status",
27575                "/api/workflows/order/cancel",
27576            ] {
27577                let bodies = server.request_bodies(path);
27578                let body = bodies.last().unwrap();
27579                assert_eq!(
27580                    body["observability_context"]["carrier"]["traceparent"],
27581                    headers["traceparent"]
27582                );
27583                assert!(body["observability_context"]["carrier"]
27584                    .get("baggage")
27585                    .is_none());
27586            }
27587            let starts = server.request_bodies("/api/workflows");
27588            assert_eq!(
27589                decode_wire_value(&starts[1]["input"], DEFAULT_CODEC).unwrap(),
27590                input
27591            );
27592            assert_eq!(
27593                server.request_body("/api/workflows/order/signal/ready")["request_id"],
27594                "signal-original"
27595            );
27596            assert_eq!(
27597                server.request_body("/api/workflows/order/update/status")["request_id"],
27598                "update-original"
27599            );
27600            PHASE.store(1, Ordering::SeqCst);
27601            client.cluster_info().await.unwrap();
27602            client
27603                .start_workflow("orders", "orders", "order", &input)
27604                .await
27605                .unwrap();
27606            assert!(server
27607                .request_bodies("/api/workflows")
27608                .last()
27609                .unwrap()
27610                .get("observability_context")
27611                .is_none());
27612            PHASE.store(2, Ordering::SeqCst);
27613            assert!(client.cluster_info().await.is_err());
27614            let before = server.captured_paths().len();
27615            client
27616                .start_workflow("orders", "orders", "order", &input)
27617                .await
27618                .unwrap();
27619            assert_eq!(server.captured_paths().len(), before + 1);
27620            assert!(server
27621                .request_bodies("/api/workflows")
27622                .last()
27623                .unwrap()
27624                .get("observability_context")
27625                .is_none());
27626        }
27627        .with_context(parent)
27628        .await;
27629    }
27630
27631    #[cfg(feature = "telemetry")]
27632    fn observability_worker_server(
27633        path: &str,
27634        _body: &str,
27635        _: usize,
27636    ) -> Option<(&'static str, String)> {
27637        let context = json!({"schema": "durable-workflow.trace-context", "version": 1,
27638            "carrier": {"traceparent": "00-12345678901234567890123456789012-1234567890123456-01",
27639                        "baggage": "credential=private"}});
27640        let link_context = json!({"schema": "durable-workflow.trace-context", "version": 1,
27641            "carrier": {"traceparent": "00-abcdef78901234567890123456789012-abcdef7890123456-01"}});
27642        if path == "/api/cluster/info" {
27643            return Some(("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
27644                "supported": true, "schema": "durable-workflow.trace-context", "version": 1,
27645                "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
27646                "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
27647            }}}}).to_string()));
27648        }
27649        if path.ends_with("/complete") {
27650            return Some(("200 OK", json!({"recorded": true}).to_string()));
27651        }
27652        let task_id = match path {
27653            "/api/worker/workflow-tasks/poll" => "workflow-task",
27654            "/api/worker/activity-tasks/poll" => "activity-task",
27655            "/api/worker/query-tasks/poll" => "query-task",
27656            _ => return None,
27657        };
27658        let input = encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap();
27659        let mut task = json!({"task_id": task_id, "query_task_id": task_id,
27660        "workflow_id": "workflow", "run_id": "run", "workflow_type": "wire.workflow",
27661        "activity_type": "wire.activity", "activity_execution_id": "activity",
27662        "activity_attempt_id": "attempt", "attempt_number": 3, "workflow_task_attempt": 1,
27663        "query_task_attempt": 1, "query_name": "state", "lease_owner": "test-worker",
27664        "namespace": "shipping", "task_queue": "shipping", "lease_expires_at": "2099-01-01T00:00:00Z",
27665        "payload_codec": DEFAULT_CODEC, "arguments": input, "workflow_arguments": input,
27666        "query_arguments": input, "history_events": [], "observability_context": context,
27667        "dispatch_observability_context": {"schema": "durable-workflow.queue-trace", "version": 1,
27668            "task_id": task_id, "context": link_context},
27669        "observability_links": {"schema": "durable-workflow.trace-links", "version": 1,
27670            "task_id": task_id, "run_id": "run", "namespace": "shipping", "links": [
27671                {"kind": "command", "command_id": "accepted-command", "context": link_context},
27672                {"kind": "child_outcome", "workflow_link_id": "link", "child_run_id": "child",
27673                 "child_task_id": null, "event_id": "terminal", "sequence": 7,
27674                 "event_type": "WorkflowCancelled", "context": link_context}
27675            ]}});
27676        if task_id == "workflow-task" {
27677            task["arguments"] = encode_value_envelope(
27678                &json!([{"observability_context": {"business": "preserved"}}]),
27679                DEFAULT_CODEC,
27680            )
27681            .unwrap();
27682        }
27683        Some((
27684            "200 OK",
27685            json!({"task": task, "poll_status": "leased"}).to_string(),
27686        ))
27687    }
27688
27689    #[cfg(feature = "telemetry")]
27690    #[tokio::test]
27691    async fn observability_polled_tasks_recover_parent_links_and_capture_the_actual_child_producer()
27692    {
27693        use opentelemetry::trace::TracerProvider;
27694        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
27695        opentelemetry::global::set_text_map_propagator(
27696            opentelemetry_sdk::propagation::TraceContextPropagator::new(),
27697        );
27698        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
27699        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
27700            .with_simple_exporter(exporter.clone())
27701            .build();
27702        let telemetry = telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test"));
27703        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27704            request_override: Some(observability_worker_server),
27705            ..MockWorkerBehavior::default()
27706        });
27707        let client = Client::builder(server.base_url())
27708            .namespace("shipping")
27709            .build()
27710            .unwrap();
27711        client.cluster_info().await.unwrap();
27712        let mut worker = Worker::new(client, "shipping")
27713            .worker_id("test-worker")
27714            .telemetry(telemetry);
27715        worker.register_workflow("wire.workflow", |ctx, input| async move {
27716            assert_eq!(telemetry::current_log_context()["workflow_run_id"], "run");
27717            assert_eq!(
27718                input,
27719                json!([{"observability_context": {"business": "preserved"}}])
27720            );
27721            ctx.start_child_workflow("child", ChildWorkflowOptions::new("child-workers"), input)
27722                .await?;
27723            Ok(Value::Null)
27724        });
27725        worker.register_activity("wire.activity", |_, _| async {
27726            let fields = telemetry::current_log_context();
27727            assert_eq!(fields["workflow_run_id"], "run");
27728            assert_eq!(fields["activity_id"], "activity");
27729            assert_eq!(fields["activity_attempt_id"], "attempt");
27730            assert_eq!(fields["activity_attempt_number"], "3");
27731            Ok(json!("original-result"))
27732        });
27733        worker.register_query("wire.workflow", "state", |_, _| async {
27734            assert_eq!(telemetry::current_log_context()["task_id"], "query-task");
27735            Ok(json!("original-query"))
27736        });
27737        assert_eq!(worker.run_once().await.unwrap(), 3);
27738        let spans = exporter.get_finished_spans().unwrap();
27739        assert_eq!(spans.len(), 4);
27740        let origin_trace = "12345678901234567890123456789012";
27741        for span in spans
27742            .iter()
27743            .filter(|span| span.name.as_ref() != "durable.activity.attempt")
27744        {
27745            assert_eq!(span.span_context.trace_id().to_string(), origin_trace);
27746            assert_eq!(span.parent_span_id.to_string(), "1234567890123456");
27747            assert_eq!(span.links.len(), 3);
27748            assert!(!format!("{:?}", span.attributes).contains("credential"));
27749        }
27750        let task = spans
27751            .iter()
27752            .find(|span| span.name.as_ref() == "durable.workflow.task")
27753            .unwrap();
27754        let body = server.request_body("/api/worker/workflow-tasks/workflow-task/complete");
27755        assert_eq!(body["commands"][0]["type"], "start_child_workflow");
27756        let parent = body["commands"][0]["observability_context"]["carrier"]["traceparent"]
27757            .as_str()
27758            .unwrap();
27759        assert_eq!(&parent[36..52], task.span_context.span_id().to_string());
27760        assert!(telemetry::current_log_context().is_empty());
27761        opentelemetry::global::set_text_map_propagator(
27762            opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
27763        );
27764    }
27765
27766    #[cfg(feature = "telemetry")]
27767    #[tokio::test]
27768    async fn observability_never_enters_a_query_with_a_refused_original_claim() {
27769        use opentelemetry::trace::TracerProvider;
27770        static REFUSAL: AtomicUsize = AtomicUsize::new(0);
27771        fn refused_query(path: &str, body: &str, count: usize) -> Option<(&'static str, String)> {
27772            let (status, reply) = observability_worker_server(path, body, count)?;
27773            if path != "/api/worker/query-tasks/poll" {
27774                return Some((status, reply));
27775            }
27776            let mut reply: Value = serde_json::from_str(&reply).unwrap();
27777            match REFUSAL.load(Ordering::SeqCst) {
27778                0 => reply["task"]["lease_owner"] = json!("other-worker"),
27779                1 => reply["task"]["query_task_attempt"] = json!(0),
27780                _ => reply["task"]["lease_expires_at"] = json!("2000-01-01T00:00:00Z"),
27781            }
27782            Some((status, reply.to_string()))
27783        }
27784        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
27785        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
27786            .with_simple_exporter(exporter.clone())
27787            .build();
27788        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27789            request_override: Some(refused_query),
27790            ..MockWorkerBehavior::default()
27791        });
27792        let client = Client::builder(server.base_url())
27793            .namespace("shipping")
27794            .build()
27795            .unwrap();
27796        client.cluster_info().await.unwrap();
27797        let mut worker = Worker::new(client, "shipping")
27798            .worker_id("test-worker")
27799            .telemetry(telemetry::ExecutionTelemetry::from_tracer(
27800                provider.tracer("test"),
27801            ));
27802        let calls = Arc::new(AtomicUsize::new(0));
27803        let query_calls = calls.clone();
27804        worker.register_query("wire.workflow", "state", move |_, _| {
27805            query_calls.fetch_add(1, Ordering::SeqCst);
27806            async { Ok(Value::Null) }
27807        });
27808        for refusal in 0..3 {
27809            REFUSAL.store(refusal, Ordering::SeqCst);
27810            assert!(matches!(
27811                worker.poll_query_once().await.unwrap(),
27812                ManagedPollOutcome::Handled
27813            ));
27814            assert_eq!(calls.load(Ordering::SeqCst), 0);
27815            assert!(exporter.get_finished_spans().unwrap().is_empty());
27816            assert!(telemetry::current_log_context().is_empty());
27817        }
27818        assert!(!server
27819            .captured_paths()
27820            .iter()
27821            .any(|path| path.ends_with("/complete") || path.ends_with("/fail")));
27822    }
27823
27824    fn keyed_command_request(path: &str, body: &str) -> Option<Value> {
27825        if path != KEYED_SIGNAL_PATH && path != KEYED_RUN_SIGNAL_PATH && path != KEYED_UPDATE_PATH {
27826            return None;
27827        }
27828        serde_json::from_str(body).ok()
27829    }
27830
27831    /// A #216 Server: echoes the key with `retained` and `intent_verified`.
27832    fn keyed_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27833        let request = keyed_command_request(path, body)?;
27834        let mut receipt = json!({
27835            "outcome": "accepted",
27836            "command_status": "accepted",
27837            "command_id": "cmd-keyed-1",
27838            "request_id": request["request_id"],
27839            "retained": false,
27840            "intent_verified": true,
27841        });
27842        if path == KEYED_UPDATE_PATH {
27843            receipt["update_id"] = json!("upd-keyed-1");
27844            receipt["result_envelope"] =
27845                encode_typed_envelope(&AvroValue::Long(42), DEFAULT_CODEC).expect("result");
27846        }
27847        Some(("202 Accepted", receipt.to_string()))
27848    }
27849
27850    /// A Server released before #216: accepts the body field but echoes nothing.
27851    fn legacy_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27852        keyed_command_request(path, body)?;
27853        Some((
27854            "202 Accepted",
27855            r#"{"outcome":"accepted","command_status":"accepted","command_id":"cmd-legacy"}"#
27856                .to_string(),
27857        ))
27858    }
27859
27860    fn retained_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27861        let request = keyed_command_request(path, body)?;
27862        Some((
27863            "202 Accepted",
27864            json!({
27865                "outcome": "accepted",
27866                "command_status": "accepted",
27867                "command_id": "cmd-first",
27868                "request_id": request["request_id"],
27869                "retained": true,
27870                "intent_verified": true,
27871            })
27872            .to_string(),
27873        ))
27874    }
27875
27876    fn conflicting_command_server(
27877        path: &str,
27878        body: &str,
27879        _: usize,
27880    ) -> Option<(&'static str, String)> {
27881        let request = keyed_command_request(path, body)?;
27882        let retained_type = if path == KEYED_UPDATE_PATH {
27883            "update"
27884        } else {
27885            "signal"
27886        };
27887        Some((
27888            "409 Conflict",
27889            json!({
27890                "reason": "request_id_conflict",
27891                "message": format!("request id is retained for a different {retained_type} intent"),
27892                "request_id": request["request_id"],
27893                "retained_command_id": "cmd-retained-1",
27894                "retained_command_type": retained_type,
27895                "retained_outcome": "accepted",
27896                "conflict": ["arguments", "target"],
27897                "control_plane": {"operation": retained_type},
27898            })
27899            .to_string(),
27900        ))
27901    }
27902
27903    fn closed_run_command_server(
27904        path: &str,
27905        body: &str,
27906        _: usize,
27907    ) -> Option<(&'static str, String)> {
27908        let request = keyed_command_request(path, body)?;
27909        Some((
27910            "409 Conflict",
27911            json!({
27912                "reason": "run_not_active",
27913                "message": "run is closed",
27914                "request_id": request["request_id"],
27915            })
27916            .to_string(),
27917        ))
27918    }
27919
27920    fn drop_first_keyed_signal(path: &str, request_number: usize) -> bool {
27921        path == KEYED_SIGNAL_PATH && request_number == 1
27922    }
27923
27924    fn keyed_client(server: &MockWorkerServer) -> Client {
27925        Client::builder(server.base_url())
27926            .timeout(Duration::from_secs(2))
27927            .build()
27928            .expect("client")
27929    }
27930
27931    fn keyed_handle(client: &Client) -> WorkflowHandle {
27932        WorkflowHandle {
27933            client: client.clone(),
27934            workflow_id: "keyed-1".to_string(),
27935            run_id: Some("run-keyed-1".to_string()),
27936            workflow_type: "keyed".to_string(),
27937        }
27938    }
27939
27940    fn assert_generated_request_id(request_id: &str, prefix: &str) {
27941        let suffix = request_id
27942            .strip_prefix(prefix)
27943            .unwrap_or_else(|| panic!("{request_id:?} does not start with {prefix:?}"));
27944        assert_eq!(suffix.len(), 32, "uuid4 simple hex suffix: {request_id:?}");
27945        assert!(
27946            suffix
27947                .bytes()
27948                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()),
27949            "lowercase hex suffix: {request_id:?}"
27950        );
27951        assert!(request_id.len() <= MAX_REQUEST_ID_CHARACTERS);
27952    }
27953
27954    fn assert_key_sent_only_in_body(server: &MockWorkerServer, path: &str) {
27955        let headers = server.request_headers(path);
27956        assert!(!headers.is_empty(), "no request captured for {path}");
27957        for headers in headers {
27958            let header_names: Vec<String> = headers
27959                .lines()
27960                .skip(1)
27961                .filter_map(|line| line.split_once(':'))
27962                .map(|(name, _)| name.trim().to_ascii_lowercase())
27963                .collect();
27964            assert!(
27965                !header_names.iter().any(|name| name == "x-request-id"),
27966                "the caller command key is a body field, never an X-Request-Id header: {headers}"
27967            );
27968        }
27969    }
27970
27971    #[tokio::test]
27972    async fn signal_without_key_sends_a_generated_sdk_rust_signal_key_and_returns_it() {
27973        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27974            request_override: Some(legacy_command_server),
27975            ..MockWorkerBehavior::default()
27976        });
27977        let client = keyed_client(&server);
27978
27979        let receipt = client
27980            .signal_workflow("keyed-1", "approve", json!(["ok"]))
27981            .await
27982            .expect("signal receipt");
27983
27984        let sent = server.request_body(KEYED_SIGNAL_PATH);
27985        let request_id = sent["request_id"].as_str().expect("generated request_id");
27986        assert_generated_request_id(request_id, "sdk-rust-signal-");
27987        assert_eq!(
27988            receipt,
27989            json!({
27990                "outcome": "accepted",
27991                "command_status": "accepted",
27992                "command_id": "cmd-legacy",
27993                "request_id": request_id,
27994            }),
27995            "the sent key is added when an older Server omits it"
27996        );
27997        assert_key_sent_only_in_body(&server, KEYED_SIGNAL_PATH);
27998
27999        let receipt = keyed_handle(&client)
28000            .signal_selected_run("approve", json!(["ok"]))
28001            .await
28002            .expect("selected-run signal receipt");
28003        let run_sent = server.request_body(KEYED_RUN_SIGNAL_PATH);
28004        let run_request_id = run_sent["request_id"]
28005            .as_str()
28006            .expect("generated request_id");
28007        assert_generated_request_id(run_request_id, "sdk-rust-signal-");
28008        assert_eq!(receipt["request_id"], run_request_id);
28009        assert_ne!(
28010            run_request_id, request_id,
28011            "each logical call gets its own key"
28012        );
28013        assert_key_sent_only_in_body(&server, KEYED_RUN_SIGNAL_PATH);
28014    }
28015
28016    #[tokio::test]
28017    async fn update_without_key_sends_a_generated_sdk_rust_update_key() {
28018        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28019            request_override: Some(keyed_command_server),
28020            ..MockWorkerBehavior::default()
28021        });
28022        let client = keyed_client(&server);
28023
28024        let result = client
28025            .update_workflow("keyed-1", "adjust", json!([1]), None)
28026            .await
28027            .expect("update result");
28028        assert_eq!(
28029            result,
28030            json!(42),
28031            "the decoded update result is returned unchanged"
28032        );
28033        let typed = client
28034            .update_workflow_avro_value("keyed-1", "adjust", json!([1]), None)
28035            .await
28036            .expect("typed update result");
28037        assert_eq!(typed, AvroValue::Long(42));
28038        keyed_handle(&client)
28039            .update("adjust", json!([1]), None)
28040            .await
28041            .expect("handle update result");
28042
28043        let bodies = server.request_bodies(KEYED_UPDATE_PATH);
28044        assert_eq!(bodies.len(), 3);
28045        for body in &bodies {
28046            assert_generated_request_id(
28047                body["request_id"].as_str().expect("generated request_id"),
28048                "sdk-rust-update-",
28049            );
28050            assert_eq!(body["wait_for"], "completed");
28051        }
28052        assert_ne!(bodies[0]["request_id"], bodies[1]["request_id"]);
28053        assert_ne!(bodies[1]["request_id"], bodies[2]["request_id"]);
28054        assert_key_sent_only_in_body(&server, KEYED_UPDATE_PATH);
28055    }
28056
28057    #[tokio::test]
28058    async fn explicit_command_keys_are_sent_verbatim_as_the_request_id_body_field() {
28059        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28060            request_override: Some(keyed_command_server),
28061            ..MockWorkerBehavior::default()
28062        });
28063        let client = keyed_client(&server);
28064        let handle = keyed_handle(&client);
28065
28066        let receipt = client
28067            .signal_workflow_with_request_id(
28068                "keyed-1",
28069                "approve",
28070                json!(["ok"]),
28071                "Order-42/approve",
28072            )
28073            .await
28074            .expect("signal receipt");
28075        assert_eq!(receipt["request_id"], "Order-42/approve");
28076        assert_eq!(receipt["retained"], false);
28077        assert_eq!(receipt["intent_verified"], true);
28078        handle
28079            .signal_with_request_id("approve", json!(["ok"]), "handle-signal-key")
28080            .await
28081            .expect("handle signal receipt");
28082        client
28083            .signal_workflow_run_with_request_id(
28084                "keyed-1",
28085                "run-keyed-1",
28086                "approve",
28087                json!(["ok"]),
28088                "run-signal-key",
28089            )
28090            .await
28091            .expect("selected-run signal receipt");
28092        handle
28093            .signal_selected_run_with_request_id("approve", json!(["ok"]), "handle-run-signal-key")
28094            .await
28095            .expect("handle selected-run signal receipt");
28096        let result = client
28097            .update_workflow("keyed-1", "adjust", json!([1]), Some("update-key"))
28098            .await
28099            .expect("update result");
28100        assert_eq!(result, json!(42));
28101        handle
28102            .update("adjust", json!([1]), Some("handle-update-key"))
28103            .await
28104            .expect("handle update result");
28105        handle
28106            .update_avro_value("adjust", json!([1]), Some("handle-typed-update-key"))
28107            .await
28108            .expect("handle typed update result");
28109
28110        let signal_keys: Vec<Value> = server
28111            .request_bodies(KEYED_SIGNAL_PATH)
28112            .into_iter()
28113            .map(|body| body["request_id"].clone())
28114            .collect();
28115        assert_eq!(
28116            signal_keys,
28117            [json!("Order-42/approve"), json!("handle-signal-key")]
28118        );
28119        let run_signal_keys: Vec<Value> = server
28120            .request_bodies(KEYED_RUN_SIGNAL_PATH)
28121            .into_iter()
28122            .map(|body| body["request_id"].clone())
28123            .collect();
28124        assert_eq!(
28125            run_signal_keys,
28126            [json!("run-signal-key"), json!("handle-run-signal-key")]
28127        );
28128        let update_keys: Vec<Value> = server
28129            .request_bodies(KEYED_UPDATE_PATH)
28130            .into_iter()
28131            .map(|body| body["request_id"].clone())
28132            .collect();
28133        assert_eq!(
28134            update_keys,
28135            [
28136                json!("update-key"),
28137                json!("handle-update-key"),
28138                json!("handle-typed-update-key")
28139            ]
28140        );
28141        for path in [KEYED_SIGNAL_PATH, KEYED_RUN_SIGNAL_PATH, KEYED_UPDATE_PATH] {
28142            assert_key_sent_only_in_body(&server, path);
28143        }
28144    }
28145
28146    #[tokio::test]
28147    async fn retained_receipts_are_returned_unchanged() {
28148        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28149            request_override: Some(retained_command_server),
28150            ..MockWorkerBehavior::default()
28151        });
28152        let client = keyed_client(&server);
28153
28154        let receipt = client
28155            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "retry-key")
28156            .await
28157            .expect("retained receipt");
28158
28159        assert_eq!(
28160            receipt,
28161            json!({
28162                "outcome": "accepted",
28163                "command_status": "accepted",
28164                "command_id": "cmd-first",
28165                "request_id": "retry-key",
28166                "retained": true,
28167                "intent_verified": true,
28168            })
28169        );
28170    }
28171
28172    #[tokio::test]
28173    async fn request_id_conflict_refusal_keeps_error_http_and_classifies_the_sent_key() {
28174        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28175            request_override: Some(conflicting_command_server),
28176            ..MockWorkerBehavior::default()
28177        });
28178        let client = keyed_client(&server);
28179
28180        let error = client
28181            .signal_workflow_with_request_id(
28182                "keyed-1",
28183                "approve",
28184                json!(["changed"]),
28185                "Order-42/approve",
28186            )
28187            .await
28188            .expect_err("different intent under a retained key");
28189        assert!(
28190            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT),
28191            "existing Error::Http matching keeps working: {error:?}"
28192        );
28193        assert!(error.is_request_id_conflict());
28194        assert_eq!(error.request_id().as_deref(), Some("Order-42/approve"));
28195        let conflict = error.request_id_conflict().expect("conflict details");
28196        assert_eq!(conflict.status, 409);
28197        assert_eq!(conflict.request_id, "Order-42/approve");
28198        assert_eq!(
28199            conflict.message,
28200            "request id is retained for a different signal intent"
28201        );
28202        assert_eq!(
28203            conflict.retained_command_id.as_deref(),
28204            Some("cmd-retained-1")
28205        );
28206        assert_eq!(conflict.retained_command_type.as_deref(), Some("signal"));
28207        assert_eq!(conflict.retained_outcome.as_deref(), Some("accepted"));
28208        assert_eq!(conflict.conflict, ["arguments", "target"]);
28209        assert_eq!(conflict.body["control_plane"]["operation"], "signal");
28210
28211        let error = client
28212            .update_workflow("keyed-1", "adjust", json!([2]), None)
28213            .await
28214            .expect_err("different intent under a retained generated key");
28215        let sent = server.request_body(KEYED_UPDATE_PATH);
28216        assert_eq!(
28217            error.request_id(),
28218            sent["request_id"].as_str().map(str::to_string)
28219        );
28220        assert_eq!(
28221            error
28222                .request_id_conflict()
28223                .expect("conflict details")
28224                .retained_command_type
28225                .as_deref(),
28226            Some("update")
28227        );
28228    }
28229
28230    #[tokio::test]
28231    async fn other_refusals_echoing_the_key_are_not_request_id_conflicts() {
28232        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28233            request_override: Some(closed_run_command_server),
28234            ..MockWorkerBehavior::default()
28235        });
28236        let client = keyed_client(&server);
28237
28238        let error = client
28239            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "closed-key")
28240            .await
28241            .expect_err("closed run");
28242
28243        assert!(matches!(error, Error::Http { status, .. } if status.as_u16() == 409));
28244        assert!(!error.is_request_id_conflict());
28245        assert_eq!(error.request_id_conflict(), None);
28246        assert_eq!(error.request_id().as_deref(), Some("closed-key"));
28247    }
28248
28249    #[tokio::test]
28250    async fn transport_failure_keeps_error_transport_and_the_held_key_retries_identically() {
28251        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28252            request_override: Some(keyed_command_server),
28253            drop_request: Some(drop_first_keyed_signal),
28254            ..MockWorkerBehavior::default()
28255        });
28256        let client = keyed_client(&server);
28257        let request_id = Client::generate_signal_request_id();
28258
28259        let error = client
28260            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
28261            .await
28262            .expect_err("connection closed before any response");
28263        assert!(
28264            matches!(error, Error::Transport(_)),
28265            "the transport variant is unchanged: {error:?}"
28266        );
28267        assert_eq!(
28268            error.request_id(),
28269            None,
28270            "nothing was echoed; the application holds the key it chose"
28271        );
28272
28273        let receipt = client
28274            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
28275            .await
28276            .expect("manual retry with the same key");
28277        assert_eq!(receipt["request_id"], request_id);
28278        let bodies = server.request_bodies(KEYED_SIGNAL_PATH);
28279        assert_eq!(bodies.len(), 2, "one attempt per call, no automatic retry");
28280        assert_eq!(
28281            bodies[0], bodies[1],
28282            "the retry resends the identical key and input"
28283        );
28284        assert_eq!(bodies[0]["request_id"], request_id);
28285    }
28286
28287    #[tokio::test]
28288    async fn invalid_command_keys_are_refused_before_sending() {
28289        let server = MockWorkerServer::start();
28290        let client = keyed_client(&server);
28291        let too_long = "k".repeat(MAX_REQUEST_ID_CHARACTERS + 1);
28292
28293        for request_id in ["", too_long.as_str()] {
28294            let error = client
28295                .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), request_id)
28296                .await
28297                .expect_err("invalid signal key");
28298            assert!(
28299                matches!(error, Error::Codec(ref message) if message.contains("1 to 255 Unicode characters")),
28300                "{error:?}"
28301            );
28302            let error = client
28303                .update_workflow("keyed-1", "adjust", json!([1]), Some(request_id))
28304                .await
28305                .expect_err("invalid update key");
28306            assert!(matches!(error, Error::Codec(_)), "{error:?}");
28307        }
28308        assert!(server.captured_paths().is_empty(), "nothing was sent");
28309
28310        let longest = "k".repeat(MAX_REQUEST_ID_CHARACTERS);
28311        let _ = client
28312            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &longest)
28313            .await;
28314        assert_eq!(
28315            server.request_body(KEYED_SIGNAL_PATH)["request_id"],
28316            longest
28317        );
28318    }
28319
28320    #[test]
28321    fn generated_command_keys_are_distinct_and_well_formed() {
28322        let signal = Client::generate_signal_request_id();
28323        let update = Client::generate_update_request_id();
28324        assert_generated_request_id(&signal, "sdk-rust-signal-");
28325        assert_generated_request_id(&update, "sdk-rust-update-");
28326        assert_ne!(Client::generate_signal_request_id(), signal);
28327        assert!(validate_request_id(&signal).is_ok());
28328    }
28329
28330    #[test]
28331    fn command_keys_preserve_the_published_server_unicode_character_limit() {
28332        assert!(validate_request_id(&"é".repeat(255)).is_ok());
28333        assert!(validate_request_id(&"😀".repeat(255)).is_ok());
28334        assert!(validate_request_id(&"é".repeat(256)).is_err());
28335    }
28336
28337    #[test]
28338    fn request_id_accessors_read_only_echoed_refusal_bodies() {
28339        let conflict = Error::Http {
28340            status: reqwest::StatusCode::CONFLICT,
28341            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(),
28342        };
28343        assert!(conflict.is_request_id_conflict());
28344        assert_eq!(conflict.request_id().as_deref(), Some("k1"));
28345        let details = conflict.request_id_conflict().expect("conflict details");
28346        assert_eq!(details.conflict, ["name"]);
28347        assert_eq!(
28348            details.message,
28349            "request id is retained for a different command intent"
28350        );
28351
28352        let echoed = Error::Http {
28353            status: reqwest::StatusCode::CONFLICT,
28354            body: r#"{"reason":"run_not_active","request_id":"k2"}"#.to_string(),
28355        };
28356        assert!(!echoed.is_request_id_conflict());
28357        assert_eq!(echoed.request_id().as_deref(), Some("k2"));
28358
28359        let blank = Error::Http {
28360            status: reqwest::StatusCode::UNPROCESSABLE_ENTITY,
28361            body: r#"{"request_id":""}"#.to_string(),
28362        };
28363        assert_eq!(blank.request_id(), None);
28364        let text = Error::Http {
28365            status: reqwest::StatusCode::BAD_GATEWAY,
28366            body: "upstream unavailable".to_string(),
28367        };
28368        assert_eq!(text.request_id(), None);
28369        assert!(!text.is_request_id_conflict());
28370
28371        let rejection = Error::WorkflowCommandRejected(WorkflowCommandRejection {
28372            command: WorkflowCommandKind::Cancel,
28373            status: 409,
28374            reason: "request_id_conflict".to_string(),
28375            message: "retained".to_string(),
28376            workflow_id: "wf".to_string(),
28377            run_id: None,
28378            target_scope: None,
28379            body: json!({"reason": "request_id_conflict", "request_id": "k3", "conflict": []}),
28380        });
28381        assert!(rejection.is_request_id_conflict());
28382        assert_eq!(rejection.request_id().as_deref(), Some("k3"));
28383
28384        assert_eq!(Error::Timeout.request_id(), None);
28385        assert!(!Error::Codec("local".to_string()).is_request_id_conflict());
28386    }
28387
28388    #[tokio::test]
28389    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
28390        let server = MockWorkerServer::start();
28391        let client = Client::builder(server.base_url())
28392            .timeout(Duration::from_secs(2))
28393            .build()
28394            .expect("client");
28395        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
28396
28397        client
28398            .start_workflow(
28399                "typed.echo",
28400                "rust-workers",
28401                "typed-start",
28402                arguments.clone(),
28403            )
28404            .await
28405            .expect("typed workflow start");
28406        assert_eq!(
28407            decode_wire_avro_value(
28408                &server.request_body("/api/workflows")["input"],
28409                DEFAULT_CODEC,
28410            )
28411            .expect("typed start input"),
28412            arguments
28413        );
28414
28415        client
28416            .signal_workflow("typed-1", "changed", arguments.clone())
28417            .await
28418            .expect("typed signal");
28419        assert_eq!(
28420            decode_wire_avro_value(
28421                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
28422                DEFAULT_CODEC,
28423            )
28424            .expect("typed signal input"),
28425            arguments
28426        );
28427
28428        assert_eq!(
28429            client
28430                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
28431                .await
28432                .expect("typed query"),
28433            typed_fidelity_probe()
28434        );
28435        assert_eq!(
28436            decode_wire_avro_value(
28437                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
28438                DEFAULT_CODEC,
28439            )
28440            .expect("typed query input"),
28441            arguments
28442        );
28443
28444        assert_eq!(
28445            client
28446                .update_workflow_avro_value(
28447                    "typed-1",
28448                    "replace",
28449                    arguments.clone(),
28450                    Some("typed-request"),
28451                )
28452                .await
28453                .expect("typed update"),
28454            typed_fidelity_probe()
28455        );
28456        let update = server.request_body("/api/workflows/typed-1/update/replace");
28457        assert_eq!(update["request_id"], "typed-request");
28458        assert_eq!(
28459            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
28460            arguments
28461        );
28462
28463        let handle = WorkflowHandle {
28464            client: client.clone(),
28465            workflow_id: "typed-1".to_string(),
28466            run_id: Some("run-typed-1".to_string()),
28467            workflow_type: "typed.echo".to_string(),
28468        };
28469        assert_eq!(
28470            handle
28471                .result_avro_value(WorkflowResultOptions::default())
28472                .await
28473                .expect("typed workflow result"),
28474            typed_fidelity_probe()
28475        );
28476
28477        client
28478            .complete_activity_task(
28479                "activity-typed",
28480                "attempt-typed",
28481                "rust-worker",
28482                typed_fidelity_probe(),
28483                DEFAULT_CODEC,
28484            )
28485            .await
28486            .expect("typed activity completion");
28487        assert_eq!(
28488            decode_wire_avro_value(
28489                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
28490                    ["result"],
28491                DEFAULT_CODEC,
28492            )
28493            .expect("typed activity result"),
28494            typed_fidelity_probe()
28495        );
28496        client
28497            .fail_activity_task(
28498                "activity-typed",
28499                "attempt-typed",
28500                "rust-worker",
28501                "typed failure",
28502                true,
28503            )
28504            .await
28505            .expect("activity failure");
28506    }
28507
28508    #[tokio::test]
28509    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
28510        let server = MockWorkerServer::start();
28511        let client = Client::builder(server.base_url())
28512            .timeout(Duration::from_secs(2))
28513            .build()
28514            .expect("client");
28515
28516        let options = WorkflowCommandOptions::new()
28517            .reason("cleanup requested")
28518            .request_id("cancel-17");
28519        let cancelled = client
28520            .cancel_workflow("wf-lifecycle", options)
28521            .await
28522            .expect("instance cancellation");
28523        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
28524        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
28525        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
28526        assert_eq!(
28527            server.request_body("/api/workflows/wf-lifecycle/cancel"),
28528            json!({"reason":"cleanup requested","request_id":"cancel-17"})
28529        );
28530
28531        let terminated = client
28532            .terminate_workflow(
28533                "wf-lifecycle",
28534                WorkflowCommandOptions::new().reason("forced stop"),
28535            )
28536            .await
28537            .expect("instance termination");
28538        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
28539        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
28540
28541        client
28542            .cancel_workflow_run(
28543                "wf-lifecycle",
28544                "run-current",
28545                WorkflowCommandOptions::default(),
28546            )
28547            .await
28548            .expect("selected run cancellation");
28549        client
28550            .terminate_workflow_run(
28551                "wf-lifecycle",
28552                "run-current",
28553                WorkflowCommandOptions::default(),
28554            )
28555            .await
28556            .expect("selected run termination");
28557
28558        for (command, error) in [
28559            (
28560                WorkflowCommandKind::Cancel,
28561                client
28562                    .cancel_workflow_run(
28563                        "wf-lifecycle",
28564                        "run-stale",
28565                        WorkflowCommandOptions::default(),
28566                    )
28567                    .await
28568                    .expect_err("stale cancellation must be rejected"),
28569            ),
28570            (
28571                WorkflowCommandKind::Terminate,
28572                client
28573                    .terminate_workflow_run(
28574                        "wf-lifecycle",
28575                        "run-stale",
28576                        WorkflowCommandOptions::default(),
28577                    )
28578                    .await
28579                    .expect_err("stale termination must be rejected"),
28580            ),
28581        ] {
28582            let Error::WorkflowCommandRejected(rejection) = error else {
28583                panic!("expected typed command rejection");
28584            };
28585            assert_eq!(rejection.command, command);
28586            assert_eq!(rejection.status, 409);
28587            assert_eq!(rejection.reason, "historical_run_command_rejected");
28588            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
28589            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
28590        }
28591    }
28592
28593    #[tokio::test]
28594    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
28595        let server = MockWorkerServer::start();
28596        let client = Client::builder(server.base_url())
28597            .timeout(Duration::from_secs(2))
28598            .build()
28599            .expect("client");
28600
28601        let result = client
28602            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
28603            .await
28604            .expect("redrive accepted");
28605        assert_eq!(result.workflow_id, "wf-lifecycle");
28606        assert_eq!(result.source_run_id, "run-failed");
28607        assert_eq!(result.run_id, "run-successor");
28608        assert_eq!(result.resume_step_sequence, 2);
28609        assert_eq!(
28610            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
28611            json!({"request_id":"retry-1"})
28612        );
28613
28614        let repeated = client
28615            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
28616            .await
28617            .expect("idempotent redrive response accepted");
28618        assert_eq!(repeated.run_id, "run-successor");
28619
28620        let error = client
28621            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
28622            .await
28623            .expect_err("completed run must be rejected");
28624        let Error::Http { status, body } = error else {
28625            panic!("expected HTTP redrive rejection");
28626        };
28627        assert_eq!(status.as_u16(), 409);
28628        assert!(body.contains("run_not_failed"));
28629        assert_eq!(
28630            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
28631            json!({})
28632        );
28633
28634        let handle = WorkflowHandle {
28635            client: client.clone(),
28636            workflow_id: "wf-lifecycle".to_string(),
28637            run_id: Some("run-failed".to_string()),
28638            workflow_type: "test".to_string(),
28639        };
28640        assert_eq!(
28641            handle.redrive(None).await.expect("handle redrive").run_id,
28642            "run-successor"
28643        );
28644        let missing_run = WorkflowHandle {
28645            run_id: None,
28646            ..handle
28647        };
28648        assert!(matches!(
28649            missing_run.redrive(None).await,
28650            Err(Error::Codec(_))
28651        ));
28652    }
28653
28654    #[tokio::test]
28655    async fn workflow_start_options_send_server_enforced_deadlines() {
28656        let server = MockWorkerServer::start();
28657        let client = Client::builder(server.base_url())
28658            .timeout(Duration::from_secs(2))
28659            .build()
28660            .expect("client");
28661
28662        let handle = client
28663            .start_workflow_with_options(
28664                "rust.timeout",
28665                "rust-timeouts",
28666                "wf-start-options",
28667                WorkflowStartOptions::new()
28668                    .execution_timeout_seconds(30)
28669                    .run_timeout_seconds(1),
28670                json!([]),
28671            )
28672            .await
28673            .expect("workflow start");
28674
28675        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
28676        let body = server.request_body("/api/workflows");
28677        assert_eq!(body["execution_timeout_seconds"], 30);
28678        assert_eq!(body["run_timeout_seconds"], 1);
28679
28680        let invalid = client
28681            .start_workflow_with_options(
28682                "rust.timeout",
28683                "rust-timeouts",
28684                "wf-invalid-options",
28685                WorkflowStartOptions::new()
28686                    .execution_timeout_seconds(1)
28687                    .run_timeout_seconds(2),
28688                json!([]),
28689            )
28690            .await
28691            .expect_err("invalid deadline ordering");
28692        assert!(invalid
28693            .to_string()
28694            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
28695    }
28696
28697    #[tokio::test]
28698    async fn workflow_result_returns_each_typed_terminal_outcome() {
28699        let server = MockWorkerServer::start();
28700        let client = Client::builder(server.base_url())
28701            .timeout(Duration::from_secs(2))
28702            .build()
28703            .expect("client");
28704        let options = WorkflowResultOptions {
28705            poll_interval: Duration::ZERO,
28706            timeout: Duration::from_secs(1),
28707        };
28708
28709        let failed = WorkflowHandle {
28710            client: client.clone(),
28711            workflow_id: "wf-failed".to_string(),
28712            run_id: Some("run-failed".to_string()),
28713            workflow_type: "failure".to_string(),
28714        }
28715        .result(options)
28716        .await
28717        .expect_err("failed outcome");
28718        let Error::WorkflowFailed(failure) = failed else {
28719            panic!("expected WorkflowFailed");
28720        };
28721        assert_eq!(failure.workflow_id, "wf-failed");
28722        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
28723        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
28724        assert_eq!(failure.failure_category.as_deref(), Some("application"));
28725        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
28726        assert_eq!(
28727            failure.exception_class.as_deref(),
28728            Some("billing::PaymentError")
28729        );
28730        assert_eq!(failure.non_retryable, Some(true));
28731
28732        for (workflow_id, expected_kind, expected_reason) in [
28733            (
28734                "wf-cancelled",
28735                WorkflowTerminalKind::Cancelled,
28736                "cleanup requested",
28737            ),
28738            (
28739                "wf-terminated",
28740                WorkflowTerminalKind::Terminated,
28741                "forced stop",
28742            ),
28743            (
28744                "wf-timed-out",
28745                WorkflowTerminalKind::TimedOut,
28746                "run_timeout",
28747            ),
28748        ] {
28749            let error = WorkflowHandle {
28750                client: client.clone(),
28751                workflow_id: workflow_id.to_string(),
28752                run_id: None,
28753                workflow_type: "terminal".to_string(),
28754            }
28755            .result(options)
28756            .await
28757            .expect_err("typed terminal outcome");
28758            let outcome = match error {
28759                Error::WorkflowCancelled(outcome) => outcome,
28760                Error::WorkflowTerminated(outcome) => outcome,
28761                Error::WorkflowTimedOut(outcome) => outcome,
28762                other => panic!("unexpected terminal error: {other}"),
28763            };
28764            assert_eq!(outcome.kind, expected_kind);
28765            assert_eq!(outcome.workflow_id, workflow_id);
28766            assert_eq!(outcome.reason, expected_reason);
28767        }
28768
28769        let wait_timeout = WorkflowHandle {
28770            client,
28771            workflow_id: "wf-waiting".to_string(),
28772            run_id: Some("run-waiting".to_string()),
28773            workflow_type: "waiting".to_string(),
28774        }
28775        .result(WorkflowResultOptions {
28776            poll_interval: Duration::ZERO,
28777            timeout: Duration::ZERO,
28778        })
28779        .await
28780        .expect_err("client wait timeout");
28781        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
28782            panic!("expected typed client timeout");
28783        };
28784        assert_eq!(timeout.reason, "result_wait_timeout");
28785        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
28786        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
28787    }
28788
28789    #[tokio::test]
28790    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
28791        let server = MockWorkerServer::start();
28792        let client = Client::builder(server.base_url())
28793            .timeout(Duration::from_secs(2))
28794            .build()
28795            .expect("client");
28796
28797        let handle = WorkflowHandle {
28798            client,
28799            workflow_id: "wf-selected".to_string(),
28800            run_id: Some("run-selected".to_string()),
28801            workflow_type: "selected".to_string(),
28802        };
28803        let options = WorkflowResultOptions {
28804            poll_interval: Duration::ZERO,
28805            timeout: Duration::from_secs(1),
28806        };
28807
28808        let current = handle
28809            .result(options)
28810            .await
28811            .expect("instance result follows the current run");
28812        assert_eq!(current, json!("current run output"));
28813
28814        let error = handle
28815            .result_selected_run(options)
28816            .await
28817            .expect_err("the selected run is cancelled even though the current run completed");
28818
28819        let Error::WorkflowCancelled(outcome) = error else {
28820            panic!("expected selected run cancellation");
28821        };
28822        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
28823        assert_eq!(outcome.reason, "selected run cancelled");
28824        assert_eq!(
28825            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
28826            1
28827        );
28828        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
28829    }
28830
28831    #[tokio::test]
28832    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
28833        let server = MockWorkerServer::draining_polls();
28834        let client = Client::builder(server.base_url())
28835            .timeout(Duration::from_secs(2))
28836            .build()
28837            .expect("client");
28838
28839        let workflow = client
28840            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
28841            .await
28842            .expect("workflow drain response");
28843        let activity = client
28844            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
28845            .await
28846            .expect("activity drain response");
28847        let query = client
28848            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
28849            .await
28850            .expect("query drain response");
28851
28852        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
28853            assert_eq!(
28854                outcome,
28855                WorkerPollOutcome::Stop {
28856                    poll_status: Some("draining".to_string()),
28857                    reason: Some("worker_draining".to_string()),
28858                }
28859            );
28860        }
28861
28862        assert!(client
28863            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
28864            .await
28865            .expect("compatibility poll")
28866            .is_none());
28867    }
28868
28869    #[tokio::test]
28870    async fn managed_worker_honors_drain_stop_for_every_task_family() {
28871        let server = MockWorkerServer::draining_polls();
28872        let client = Client::builder(server.base_url())
28873            .timeout(Duration::from_secs(2))
28874            .build()
28875            .expect("client");
28876
28877        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
28878            .worker_id("draining-workflow-worker")
28879            .poll_timeout(Duration::ZERO);
28880        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
28881        workflow_worker
28882            .run()
28883            .await
28884            .expect("workflow drain is a clean stop");
28885
28886        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
28887            .worker_id("draining-activity-worker")
28888            .poll_timeout(Duration::ZERO);
28889        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
28890        activity_worker
28891            .run()
28892            .await
28893            .expect("activity drain is a clean stop");
28894
28895        let mut query_worker = Worker::new(client, "rust-workers")
28896            .worker_id("draining-query-worker")
28897            .poll_timeout(Duration::ZERO);
28898        query_worker.register_query("counter", "current", |_ctx, _args| async {
28899            Ok(Value::Null)
28900        });
28901        query_worker
28902            .run()
28903            .await
28904            .expect("query drain is a clean stop");
28905    }
28906
28907    #[tokio::test]
28908    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
28909        let server = MockWorkerServer::start();
28910        let client = Client::builder(server.base_url())
28911            .timeout(Duration::from_secs(2))
28912            .build()
28913            .expect("client");
28914
28915        let details: Value = serde_json::from_str(include_str!(
28916            "../tests/fixtures/activity-heartbeat-progress.json"
28917        ))
28918        .expect("heartbeat progress fixture");
28919        // Every individual field fits Server's progress contract, while the
28920        // obsolete encoded envelope exceeded its 191-character string limit.
28921        assert!(
28922            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
28923                .unwrap()["blob"]
28924                .as_str()
28925                .unwrap()
28926                .len()
28927                > 191
28928        );
28929        let heartbeat = client
28930            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
28931            .await
28932            .expect("cancellation heartbeat");
28933        assert!(heartbeat.cancel_requested);
28934        assert!(heartbeat.should_stop());
28935        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
28936        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
28937        let heartbeat_body =
28938            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
28939        assert_eq!(heartbeat_body["details"], details);
28940        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
28941        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
28942
28943        let error = client
28944            .complete_activity_task(
28945                "activity-cancel",
28946                "attempt-cancel",
28947                "rust-worker",
28948                json!({"late":true}),
28949                DEFAULT_CODEC,
28950            )
28951            .await
28952            .expect_err("late completion must be refused");
28953        assert!(activity_task_rejection_is_final(&error));
28954        let Error::ActivityTaskRejected(rejection) = error else {
28955            panic!("expected typed activity rejection");
28956        };
28957        assert_eq!(rejection.status, 409);
28958        assert_eq!(rejection.reason, "run_cancelled");
28959        assert!(rejection.cancel_requested);
28960        assert_eq!(rejection.can_continue, Some(false));
28961    }
28962
28963    #[tokio::test]
28964    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
28965        let server = MockWorkerServer::cancelled_activity();
28966        let client = Client::builder(server.base_url())
28967            .timeout(Duration::from_secs(2))
28968            .build()
28969            .expect("client");
28970        let cancellation_observed = Arc::new(AtomicBool::new(false));
28971        let observed = Arc::clone(&cancellation_observed);
28972        let mut worker = Worker::new(client.clone(), "rust-workers")
28973            .worker_id("rust-cancel-worker")
28974            .poll_timeout(Duration::from_millis(10));
28975        worker.register_activity("cancel-aware", move |ctx, _args| {
28976            let observed = Arc::clone(&observed);
28977            async move {
28978                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
28979                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
28980                Ok(json!({"late":"completion"}))
28981            }
28982        });
28983
28984        assert_eq!(
28985            worker.run_once().await.expect("cancelled attempt handled"),
28986            1
28987        );
28988        assert!(cancellation_observed.load(Ordering::SeqCst));
28989        assert_eq!(
28990            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
28991            1
28992        );
28993
28994        let mut restarted = Worker::new(client, "rust-workers")
28995            .worker_id("rust-cancel-worker-restarted")
28996            .poll_timeout(Duration::from_millis(10));
28997        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
28998        assert_eq!(
28999            restarted
29000                .run_once()
29001                .await
29002                .expect("replacement worker continues polling"),
29003            0
29004        );
29005    }
29006
29007    #[tokio::test]
29008    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
29009        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"}"#;
29010        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
29011        let client = Client::builder(server.base_url())
29012            .timeout(Duration::from_secs(2))
29013            .build()
29014            .expect("client");
29015
29016        let direct_error = client
29017            .complete_workflow_task(
29018                "workflow-timeout-task",
29019                "timeout-worker",
29020                3,
29021                vec![json!({
29022                    "type": "complete_workflow",
29023                    "result": fixture_envelope(Value::Null)
29024                })],
29025            )
29026            .await
29027            .expect_err("the low-level client preserves the completion rejection");
29028        let Error::Http { status, body } = direct_error else {
29029            panic!("expected the original HTTP completion rejection");
29030        };
29031        assert_eq!(status, reqwest::StatusCode::CONFLICT);
29032        assert_eq!(
29033            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
29034            "run_timed_out"
29035        );
29036
29037        let mut worker = Worker::new(client, "rust-workers")
29038            .worker_id("timeout-worker")
29039            .poll_timeout(Duration::from_millis(10));
29040        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
29041            Ok(json!({"late": "result"}))
29042        });
29043
29044        assert_eq!(
29045            worker
29046                .run_once()
29047                .await
29048                .expect("authoritative selected-run timeout settles the tick"),
29049            1
29050        );
29051        assert_eq!(
29052            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
29053            2,
29054            "both the direct client proof and managed worker must see the rejection"
29055        );
29056    }
29057
29058    #[tokio::test]
29059    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
29060        for (name, status, response) in [
29061            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
29062            (
29063                "command was recorded",
29064                "409 Conflict",
29065                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29066            ),
29067            (
29068                "lease conflict",
29069                "409 Conflict",
29070                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
29071            ),
29072            (
29073                "nonterminal run",
29074                "409 Conflict",
29075                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
29076            ),
29077            (
29078                "different selected run",
29079                "409 Conflict",
29080                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"}"#,
29081            ),
29082            (
29083                "different task attempt",
29084                "409 Conflict",
29085                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29086            ),
29087            (
29088                "authentication failure",
29089                "401 Unauthorized",
29090                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29091            ),
29092            (
29093                "authorization failure",
29094                "403 Forbidden",
29095                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29096            ),
29097            (
29098                "protocol failure",
29099                "400 Bad Request",
29100                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
29101            ),
29102            (
29103                "malformed command",
29104                "422 Unprocessable Entity",
29105                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29106            ),
29107            (
29108                "transient server failure",
29109                "503 Service Unavailable",
29110                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29111            ),
29112        ] {
29113            let server = MockWorkerServer::workflow_completion(status, response);
29114            let client = Client::builder(server.base_url())
29115                .timeout(Duration::from_secs(2))
29116                .build()
29117                .expect("client");
29118            let mut worker = Worker::new(client, "rust-workers")
29119                .worker_id("timeout-worker")
29120                .poll_timeout(Duration::from_millis(10));
29121            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
29122                Ok(json!({"late": "result"}))
29123            });
29124
29125            let error = worker
29126                .run_once()
29127                .await
29128                .expect_err(&format!("{name} must remain an error"));
29129            assert!(
29130                matches!(error, Error::Http { .. } | Error::Protocol(_)),
29131                "{name} returned an unexpected error variant: {error}"
29132            );
29133        }
29134    }
29135
29136    #[tokio::test]
29137    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
29138        let server = MockWorkerServer::start();
29139        let client = Client::builder(server.base_url())
29140            .worker_token(Some("worker-secret".to_string()))
29141            .namespace("orders")
29142            .timeout(Duration::from_secs(2))
29143            .build()
29144            .expect("client");
29145        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
29146
29147        let result = client
29148            .deregister_worker_registration("worker/α space")
29149            .await
29150            .expect("deregister worker registration");
29151
29152        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
29153        assert_eq!(
29154            server.worker_protocol_for(path).as_deref(),
29155            Some(WORKER_PROTOCOL_VERSION)
29156        );
29157        assert_eq!(server.control_protocol_for(path), None);
29158        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
29159        assert_eq!(
29160            server.authorization_for(path).as_deref(),
29161            Some("Bearer worker-secret")
29162        );
29163        assert_eq!(
29164            result,
29165            WorkerDeregistrationEnvelope {
29166                worker_id: "deregistered-worker".to_string(),
29167                outcome: "deregistered".to_string(),
29168                recovered_workflow_task_count: 2,
29169            }
29170        );
29171    }
29172
29173    #[tokio::test]
29174    async fn low_level_registration_rejects_update_validators_before_transport() {
29175        let server = MockWorkerServer::start();
29176        let client = Client::builder(server.base_url())
29177            .timeout(Duration::from_secs(2))
29178            .build()
29179            .expect("client");
29180
29181        for update_validators in [json!(["approve"]), json!("approve")] {
29182            let error = client
29183                .register_worker_with_command_contracts(
29184                    "validator-claiming-worker",
29185                    "rust-workers",
29186                    vec!["orders".to_string()],
29187                    vec![],
29188                    1,
29189                    1,
29190                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
29191                    json!({
29192                        "orders": {
29193                            "queries": ["current"],
29194                            "updates": ["approve"],
29195                            "update_validators": update_validators,
29196                        },
29197                    }),
29198                )
29199                .await
29200                .expect_err("unsupported validator claims must fail before registration");
29201
29202            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
29203                panic!("expected typed unsupported-validator failure");
29204            };
29205            assert_eq!(workflow_type, "orders");
29206        }
29207        assert_eq!(server.request_count("/api/worker/register"), 0);
29208    }
29209
29210    #[tokio::test]
29211    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
29212        let server = MockWorkerServer::start();
29213        let client = Client::builder(server.base_url())
29214            .timeout(Duration::from_secs(2))
29215            .build()
29216            .expect("client");
29217        let mut worker = Worker::new(client, "rust-workers");
29218        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
29219        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
29220        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
29221        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
29222        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
29223        worker
29224            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
29225            .expect("declare workflow signals");
29226
29227        worker.register().await.expect("register handler contracts");
29228
29229        let declaration =
29230            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
29231        let expected_contracts = json!([
29232            {
29233                "name": "a-avro",
29234                "parameters": [{
29235                    "name": "args", "position": 0, "required": false,
29236                    "variadic": true, "type": null, "allows_null": true,
29237                    "default_available": false, "default": null,
29238                }],
29239            },
29240            {
29241                "name": "z-json",
29242                "parameters": [{
29243                    "name": "args", "position": 0, "required": false,
29244                    "variadic": true, "type": null, "allows_null": true,
29245                    "default_available": false, "default": null,
29246                }],
29247            },
29248        ]);
29249        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
29250        assert_eq!(declaration["query_contracts"], expected_contracts);
29251        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
29252        assert_eq!(declaration["update_contracts"], expected_contracts);
29253        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
29254        assert_eq!(declaration["signal_contracts"], expected_contracts);
29255        assert_eq!(declaration["update_validators"], json!([]));
29256    }
29257
29258    #[tokio::test]
29259    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
29260        let server = MockWorkerServer::start();
29261        let client = Client::new(server.base_url()).expect("client");
29262        let mut worker = Worker::new(client, "rust-workers");
29263        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
29264        assert!(worker
29265            .declare_workflow_signals("missing", &["finish"])
29266            .is_err());
29267        worker
29268            .declare_workflow_signals("orders", &["finish"])
29269            .unwrap();
29270        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
29271            assert!(worker.declare_workflow_signals("orders", names).is_err());
29272        }
29273        worker.register().await.unwrap();
29274        assert_eq!(
29275            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
29276                ["signals"],
29277            json!(["finish"])
29278        );
29279        worker.declare_workflow_signals("orders", &[]).unwrap();
29280        worker.register().await.unwrap();
29281        let registrations = server.request_bodies("/api/worker/register");
29282        assert_eq!(
29283            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
29284            json!([])
29285        );
29286        assert_eq!(
29287            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
29288            json!([])
29289        );
29290    }
29291
29292    #[tokio::test]
29293    async fn low_level_registration_preserves_query_and_update_contracts() {
29294        let server = MockWorkerServer::start();
29295        let client = Client::builder(server.base_url())
29296            .timeout(Duration::from_secs(2))
29297            .build()
29298            .expect("client");
29299        let contracts = json!({
29300            "orders": {
29301                "queries": ["current"],
29302                "updates": ["approve"],
29303                "update_validators": [],
29304            },
29305            "payments": {
29306                "queries": ["status"],
29307                "updates": ["capture"],
29308            },
29309        });
29310
29311        client
29312            .register_worker_with_command_contracts(
29313                "command-worker",
29314                "rust-workers",
29315                vec!["orders".to_string(), "payments".to_string()],
29316                vec![],
29317                1,
29318                1,
29319                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
29320                contracts.clone(),
29321            )
29322            .await
29323            .expect("query and update contracts must remain supported");
29324
29325        assert_eq!(
29326            server.request_body("/api/worker/register")["workflow_command_contracts"],
29327            contracts
29328        );
29329        assert!(server
29330            .request_body("/api/worker/register")
29331            .get("workflow_definition_fingerprints")
29332            .is_none());
29333    }
29334
29335    #[tokio::test]
29336    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
29337        let server = MockWorkerServer::start();
29338        let client = Client::builder(server.base_url())
29339            .timeout(Duration::from_secs(2))
29340            .build()
29341            .expect("client");
29342        let mut worker = Worker::new(client.clone(), "rust-workers");
29343        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
29344
29345        assert!(worker
29346            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
29347            .is_err());
29348        assert!(worker
29349            .set_workflow_definition_sources("orders", &[])
29350            .is_err());
29351        worker
29352            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
29353            .expect("embed workflow source");
29354        worker.register().await.expect("register worker");
29355        let first = server.request_bodies("/api/worker/register")[0]
29356            ["workflow_definition_fingerprints"]["orders"]
29357            .as_str()
29358            .expect("source-backed fingerprint")
29359            .to_string();
29360        assert!(first.starts_with("sha256:"));
29361
29362        worker
29363            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
29364            .expect("change embedded helper source");
29365        worker.register().await.expect("register changed source");
29366        let changed = server.request_bodies("/api/worker/register")[1]
29367            ["workflow_definition_fingerprints"]["orders"]
29368            .as_str()
29369            .expect("changed fingerprint")
29370            .to_string();
29371        assert_ne!(first, changed);
29372
29373        let mut replacement =
29374            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
29375        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
29376        replacement
29377            .register()
29378            .await
29379            .expect("register replacement handler");
29380        assert_eq!(
29381            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
29382            json!({})
29383        );
29384    }
29385
29386    #[tokio::test]
29387    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
29388        let server = MockWorkerServer::start();
29389        let control_only = Client::builder(server.base_url())
29390            .control_token(Some("control-secret".to_string()))
29391            .build()
29392            .expect("control client");
29393
29394        let error = control_only
29395            .register_worker("worker", "queue", vec![], vec![], 1, 1)
29396            .await
29397            .expect_err("control token must not authorize a worker request");
29398        assert!(matches!(
29399            error,
29400            Error::MissingRoleCredentials { role: "worker", .. }
29401        ));
29402        assert_eq!(server.request_count("/api/worker/register"), 0);
29403
29404        let worker_only = Client::builder(server.base_url())
29405            .worker_token(Some("worker-secret".to_string()))
29406            .build()
29407            .expect("worker client");
29408        let error = worker_only
29409            .health()
29410            .await
29411            .expect_err("worker token must not authorize a control request");
29412        assert!(matches!(
29413            error,
29414            Error::MissingRoleCredentials {
29415                role: "control",
29416                ..
29417            }
29418        ));
29419        assert_eq!(server.request_count("/api/health"), 0);
29420    }
29421
29422    #[tokio::test]
29423    async fn shared_token_supports_worker_and_control_planes() {
29424        let server = MockWorkerServer::start();
29425        let client = Client::builder(server.base_url())
29426            .token(Some("shared-secret".to_string()))
29427            .build()
29428            .expect("client");
29429
29430        client.health().await.expect("control request");
29431        client
29432            .register_worker("worker", "queue", vec![], vec![], 1, 1)
29433            .await
29434            .expect("worker request");
29435
29436        assert_eq!(
29437            server.authorization_for("/api/health").as_deref(),
29438            Some("Bearer shared-secret")
29439        );
29440        assert_eq!(
29441            server.control_protocol_for("/api/health").as_deref(),
29442            Some(CONTROL_PLANE_VERSION)
29443        );
29444        assert_eq!(
29445            server.authorization_for("/api/worker/register").as_deref(),
29446            Some("Bearer shared-secret")
29447        );
29448        assert_eq!(
29449            server
29450                .worker_protocol_for("/api/worker/register")
29451                .as_deref(),
29452            Some(WORKER_PROTOCOL_VERSION)
29453        );
29454    }
29455
29456    #[tokio::test]
29457    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
29458        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
29459        let server = MockWorkerServer::start();
29460        let client = Client::builder(server.base_url())
29461            .timeout(Duration::from_secs(2))
29462            .build()
29463            .expect("client");
29464
29465        client
29466            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
29467            .await
29468            .expect("register");
29469        client
29470            .heartbeat_worker("capture-worker", 1, 1)
29471            .await
29472            .expect("heartbeat");
29473        client
29474            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
29475            .await
29476            .expect("workflow poll");
29477        client
29478            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
29479            .await
29480            .expect("activity poll");
29481
29482        for path in [
29483            "/api/worker/register",
29484            "/api/worker/heartbeat",
29485            "/api/worker/workflow-tasks/poll",
29486            "/api/worker/activity-tasks/poll",
29487        ] {
29488            assert_eq!(
29489                server.worker_protocol_for(path).as_deref(),
29490                Some(WORKER_PROTOCOL_VERSION),
29491                "unexpected protocol for {path}"
29492            );
29493        }
29494
29495        assert_eq!(
29496            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
29497            1
29498        );
29499        assert_eq!(
29500            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
29501            500
29502        );
29503        assert_eq!(
29504            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
29505            1
29506        );
29507        assert!(
29508            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
29509                .as_str()
29510                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
29511        );
29512        assert!(
29513            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
29514                .as_str()
29515                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
29516        );
29517        let registration = server.request_body("/api/worker/register");
29518        for optional in [
29519            "cooperative_cancellation",
29520            "local_activities",
29521            "worker_sessions",
29522            "sticky_execution",
29523        ] {
29524            assert!(!registration["capabilities"]
29525                .as_array()
29526                .is_some_and(|capabilities| capabilities
29527                    .iter()
29528                    .any(|capability| capability.as_str() == Some(optional))));
29529        }
29530    }
29531
29532    #[tokio::test]
29533    async fn explicit_previous_worker_protocol_preserves_headers() {
29534        let server = MockWorkerServer::start();
29535        let client = Client::builder(server.base_url())
29536            .worker_protocol_version(WorkerProtocolVersion::V119)
29537            .timeout(Duration::from_secs(2))
29538            .build()
29539            .expect("client");
29540        client
29541            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
29542            .await
29543            .expect("register");
29544        client
29545            .heartbeat_worker("legacy-worker", 1, 1)
29546            .await
29547            .expect("heartbeat");
29548        client
29549            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
29550            .await
29551            .expect("workflow poll");
29552        client
29553            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
29554            .await
29555            .expect("activity poll");
29556        client
29557            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
29558            .await
29559            .expect("query poll");
29560        client
29561            .deregister_worker_registration("legacy-worker")
29562            .await
29563            .expect("deregister");
29564        for path in [
29565            "/api/worker/register",
29566            "/api/worker/heartbeat",
29567            "/api/worker/workflow-tasks/poll",
29568            "/api/worker/activity-tasks/poll",
29569            "/api/worker/query-tasks/poll",
29570            "/api/worker/registrations/legacy-worker",
29571        ] {
29572            assert_eq!(
29573                server.worker_protocol_for(path).as_deref(),
29574                Some("1.19"),
29575                "{path}"
29576            );
29577            assert_eq!(server.control_protocol_for(path), None, "{path}");
29578        }
29579    }
29580
29581    #[tokio::test]
29582    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
29583        let server = MockWorkerServer::start();
29584        let client = Client::builder(server.base_url())
29585            .worker_protocol_version(WorkerProtocolVersion::V119)
29586            .timeout(Duration::from_secs(2))
29587            .build()
29588            .expect("client");
29589        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
29590        let error = worker
29591            .register()
29592            .await
29593            .expect_err("legacy cooperation must be refused");
29594        assert!(matches!(
29595            error,
29596            Error::CooperativeCancellationUnavailable(_)
29597        ));
29598        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
29599    }
29600
29601    #[tokio::test]
29602    async fn query_task_endpoints_send_the_selected_worker_protocol() {
29603        let server = MockWorkerServer::start();
29604        let client = Client::builder(server.base_url())
29605            .timeout(Duration::from_secs(2))
29606            .build()
29607            .expect("client");
29608
29609        client
29610            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
29611            .await
29612            .expect("query poll");
29613        client
29614            .complete_query_task(
29615                "query-capture",
29616                "capture-worker",
29617                1,
29618                json!(8),
29619                DEFAULT_CODEC,
29620            )
29621            .await
29622            .expect("query complete");
29623        client
29624            .fail_query_task(
29625                "query-capture",
29626                "capture-worker",
29627                1,
29628                "failed",
29629                "query_rejected",
29630                "QueryFailed",
29631            )
29632            .await
29633            .expect("query fail");
29634
29635        for path in [
29636            "/api/worker/query-tasks/poll",
29637            "/api/worker/query-tasks/query-capture/complete",
29638            "/api/worker/query-tasks/query-capture/fail",
29639        ] {
29640            assert_eq!(
29641                server.worker_protocol_for(path).as_deref(),
29642                Some(WORKER_PROTOCOL_VERSION),
29643                "unexpected protocol for {path}"
29644            );
29645        }
29646
29647        assert_eq!(
29648            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
29649            1
29650        );
29651        assert!(
29652            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
29653                .as_str()
29654                .is_some_and(|id| id.starts_with("rust-query-poll-"))
29655        );
29656    }
29657
29658    #[tokio::test]
29659    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
29660        let server = MockWorkerServer::transient_worker_failures();
29661        let client = Client::builder(server.base_url())
29662            .timeout(Duration::from_secs(2))
29663            .build()
29664            .expect("client");
29665
29666        client
29667            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
29668            .await
29669            .expect("workflow poll retry");
29670        client
29671            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
29672            .await
29673            .expect("activity poll retry");
29674        client
29675            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
29676            .await
29677            .expect("query poll retry");
29678
29679        for path in [
29680            "/api/worker/workflow-tasks/poll",
29681            "/api/worker/activity-tasks/poll",
29682            "/api/worker/query-tasks/poll",
29683        ] {
29684            let bodies = server.request_bodies(path);
29685            assert_eq!(bodies.len(), 2, "{path} must be retried once");
29686            assert_eq!(
29687                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
29688                "{path} must preserve the request binding across retry"
29689            );
29690        }
29691    }
29692
29693    #[tokio::test]
29694    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
29695        let server = MockWorkerServer::consecutive_poll_failures(2);
29696        let client = Client::builder(server.base_url())
29697            .timeout(Duration::from_secs(2))
29698            .build()
29699            .expect("client");
29700        let mut worker = Worker::new(client, "capture")
29701            .worker_id("capture-worker")
29702            .poll_timeout(Duration::from_millis(10))
29703            .retry_policy(WorkerRetryPolicy {
29704                max_retries: 2,
29705                initial_backoff: Duration::from_millis(1),
29706                max_backoff: Duration::from_millis(1),
29707            });
29708        worker.register_workflow(
29709            "capture.workflow",
29710            |_ctx, _input| async move { Ok(Value::Null) },
29711        );
29712        worker.register_activity(
29713            "capture.activity",
29714            |_ctx, _input| async move { Ok(Value::Null) },
29715        );
29716        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
29717            Ok(Value::Null)
29718        });
29719
29720        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
29721
29722        for path in [
29723            "/api/worker/workflow-tasks/poll",
29724            "/api/worker/activity-tasks/poll",
29725            "/api/worker/query-tasks/poll",
29726        ] {
29727            let bodies = server.request_bodies(path);
29728            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
29729            assert!(
29730                bodies
29731                    .iter()
29732                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
29733                "{path} must preserve one request binding across every retry"
29734            );
29735        }
29736    }
29737
29738    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
29739        let reason = if unavailable {
29740            "storage_admission_unavailable"
29741        } else {
29742            "storage_pressure"
29743        };
29744        let mut body = json!({
29745            "reason": reason,
29746            "storage_state": if unavailable { "fenced" } else { "draining" },
29747            "retryable": true,
29748            "retry_after_seconds": 1,
29749        });
29750        if !mid_poll {
29751            body["request_admitted"] = json!(false);
29752        }
29753        if let Some(id) = poll_id {
29754            body["task"] = Value::Null;
29755            body["poll_status"] = json!(reason);
29756            body["poll_request_id"] = json!(id);
29757            body["retry_same_poll_request_id"] = json!(true);
29758            body["claim_admitted"] = json!(false);
29759        }
29760        body
29761    }
29762
29763    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
29764        let operation = match path {
29765            "/api/worker/register" => "register_worker",
29766            "/api/worker/heartbeat" => "heartbeat_worker",
29767            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
29768            "/api/worker/activity-tasks/poll" => "poll_activity_task",
29769            "/api/worker/query-tasks/poll" => "poll_query_task",
29770            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
29771            _ => return None,
29772        };
29773        let request: Value = serde_json::from_str(request).ok()?;
29774        let mut response = json!({
29775            "reason": "backend_unavailable",
29776            "operation": operation,
29777            "outcome": "unknown",
29778            "retryable": true,
29779            "retry_after_seconds": 1,
29780            "worker_id": request["worker_id"],
29781            "task_queue": request.get("task_queue"),
29782        });
29783        if path.ends_with("/poll") {
29784            response["task"] = Value::Null;
29785            response["poll_status"] = json!("backend_unavailable");
29786            response["poll_request_id"] = request["poll_request_id"].clone();
29787            response["retry_same_poll_request_id"] = json!(true);
29788        }
29789        Some(response)
29790    }
29791
29792    fn backend_retry_override(
29793        path: &str,
29794        request: &str,
29795        number: usize,
29796    ) -> Option<(&'static str, String)> {
29797        if number > 8 {
29798            return None;
29799        }
29800        Some((
29801            "503 Service Unavailable",
29802            backend_refusal(path, request)?.to_string(),
29803        ))
29804    }
29805
29806    fn backend_unavailable_override(
29807        path: &str,
29808        request: &str,
29809        _number: usize,
29810    ) -> Option<(&'static str, String)> {
29811        Some((
29812            "503 Service Unavailable",
29813            backend_refusal(path, request)?.to_string(),
29814        ))
29815    }
29816
29817    fn storage_worker(server: &MockWorkerServer) -> Worker {
29818        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
29819            .worker_id("storage-worker")
29820            .retry_policy(WorkerRetryPolicy {
29821                max_retries: 1,
29822                initial_backoff: Duration::from_millis(1),
29823                max_backoff: Duration::from_millis(1),
29824            })
29825    }
29826
29827    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
29828        let requests = server.requests.lock().expect("requests");
29829        let bodies: Vec<_> = requests
29830            .iter()
29831            .filter(|request| request.path == path)
29832            .map(|request| &request.body)
29833            .collect();
29834        assert_eq!(bodies.len(), count, "{path}");
29835        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
29836    }
29837
29838    #[test]
29839    fn backend_recovery_requires_the_explicit_worker_contract() {
29840        for (path, operation) in [
29841            ("/worker/register", "register_worker"),
29842            ("/worker/heartbeat", "heartbeat_worker"),
29843            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
29844            ("/worker/activity-tasks/poll", "poll_activity_task"),
29845            ("/worker/query-tasks/poll", "poll_query_task"),
29846            (
29847                "/worker/update-validation-tasks/poll",
29848                "poll_update_validation_task",
29849            ),
29850        ] {
29851            let poll_id = path.ends_with("/poll").then_some("same-poll");
29852            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
29853            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
29854                .expect("worker operation");
29855            assert_eq!(body["operation"], operation);
29856            let error = Error::Http {
29857                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29858                body: body.to_string(),
29859            };
29860            assert_eq!(
29861                worker_backend_unavailable_retry_after(&error, path, poll_id),
29862                Some(Duration::from_secs(1))
29863            );
29864            assert!(!worker_operation_is_retryable(&error));
29865            for (field, value) in [
29866                ("operation", json!("wrong_operation")),
29867                ("outcome", json!("completed")),
29868                ("retryable", json!(false)),
29869                ("retry_after_seconds", json!(0)),
29870                ("worker_id", json!("")),
29871            ] {
29872                let mut invalid = body.clone();
29873                invalid[field] = value;
29874                let error = Error::Http {
29875                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29876                    body: invalid.to_string(),
29877                };
29878                assert!(
29879                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
29880                    "{path}: {field}"
29881                );
29882                assert!(!worker_operation_is_retryable(&error));
29883            }
29884            if let Some(poll_id) = poll_id {
29885                for (field, value) in [
29886                    ("poll_request_id", json!("wrong-poll")),
29887                    ("poll_status", json!("empty")),
29888                    ("task", json!({"task_id":"claimed"})),
29889                    ("retry_same_poll_request_id", json!(false)),
29890                ] {
29891                    let mut invalid = body.clone();
29892                    invalid[field] = value;
29893                    let error = Error::Http {
29894                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29895                        body: invalid.to_string(),
29896                    };
29897                    assert!(
29898                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
29899                            .is_none(),
29900                        "{path}: {field}"
29901                    );
29902                }
29903            }
29904            let error = Error::Http {
29905                status: reqwest::StatusCode::UNAUTHORIZED,
29906                body: body.to_string(),
29907            };
29908            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
29909            assert!(!worker_operation_is_retryable(&error));
29910        }
29911    }
29912
29913    #[tokio::test]
29914    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
29915        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29916            request_override: Some(backend_retry_override),
29917            ..MockWorkerBehavior::default()
29918        });
29919        let mut worker =
29920            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
29921        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
29922        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
29923        worker.register_query("backend.workflow", "state", |_, _| async {
29924            Ok(Value::Null)
29925        });
29926        worker.register().await.expect("registration recovery");
29927        worker
29928            .client
29929            .heartbeat_worker("storage-worker", 1, 1)
29930            .await
29931            .expect("heartbeat recovery");
29932        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
29933        for path in [
29934            "/api/worker/register",
29935            "/api/worker/heartbeat",
29936            "/api/worker/workflow-tasks/poll",
29937            "/api/worker/activity-tasks/poll",
29938            "/api/worker/query-tasks/poll",
29939        ] {
29940            assert_identical_requests(&server, path, 9);
29941        }
29942    }
29943
29944    #[tokio::test]
29945    async fn backend_recovery_wait_stops_with_worker() {
29946        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29947            request_override: Some(backend_unavailable_override),
29948            ..MockWorkerBehavior::default()
29949        });
29950        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
29951            max_retries: 1,
29952            initial_backoff: Duration::from_secs(2),
29953            max_backoff: Duration::from_secs(2),
29954        });
29955        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
29956        let started = tokio::time::Instant::now();
29957        let _ = tokio::time::timeout(
29958            Duration::from_secs(1),
29959            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
29960        )
29961        .await
29962        .expect("shutdown interrupts backend wait");
29963        assert!(started.elapsed() < Duration::from_secs(1));
29964        assert!(server.request_count("/api/worker/register") >= 1);
29965    }
29966
29967    #[test]
29968    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
29969        for unavailable in [false, true] {
29970            for mid_poll in [false, true] {
29971                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
29972                let error = Error::Http {
29973                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29974                    body: body.to_string(),
29975                };
29976                assert_eq!(
29977                    worker_storage_admission_retry_after(&error, Some("same-poll")),
29978                    Some(Duration::from_secs(1))
29979                );
29980                assert!(
29981                    !worker_operation_is_retryable(&error),
29982                    "storage is not a bounded generic retry"
29983                );
29984                for (field, value) in [
29985                    ("poll_request_id", json!("wrong-poll")),
29986                    ("task", json!({"task_id":"claimed"})),
29987                    ("retryable", json!(false)),
29988                    ("retry_after_seconds", json!(0)),
29989                    ("retry_after_seconds", json!(true)),
29990                    ("retry_after_seconds", json!(1.0)),
29991                    ("storage_state", json!("normal")),
29992                    ("poll_status", json!("empty")),
29993                    ("claim_admitted", json!(true)),
29994                    ("retry_same_poll_request_id", json!(false)),
29995                    ("request_admitted", json!(true)),
29996                ] {
29997                    let mut invalid = body.clone();
29998                    invalid[field] = value;
29999                    let error = Error::Http {
30000                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30001                        body: invalid.to_string(),
30002                    };
30003                    assert!(
30004                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
30005                        "{field}"
30006                    );
30007                }
30008            }
30009        }
30010        let body = storage_refusal(None, false, false);
30011        let error = Error::Http {
30012            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30013            body: body.to_string(),
30014        };
30015        assert!(worker_storage_admission_retry_after(&error, None).is_some());
30016        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
30017        let error = Error::Http {
30018            status: reqwest::StatusCode::FORBIDDEN,
30019            body: body.to_string(),
30020        };
30021        assert!(worker_storage_admission_retry_after(&error, None).is_none());
30022        let body = storage_refusal(None, false, true);
30023        let error = Error::Http {
30024            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30025            body: body.to_string(),
30026        };
30027        assert!(worker_storage_admission_retry_after(&error, None).is_none());
30028    }
30029
30030    #[tokio::test]
30031    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
30032        for unavailable in [false, true] {
30033            for mid_poll in [false, true] {
30034                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30035                    poll_failures_per_path: 1,
30036                    storage_refusals: 7,
30037                    storage_path: Some("/poll"),
30038                    storage_unavailable: unavailable,
30039                    storage_mid_poll: mid_poll,
30040                    ..MockWorkerBehavior::default()
30041                });
30042                let mut worker = storage_worker(&server);
30043                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
30044                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
30045                for path in [
30046                    "/api/worker/workflow-tasks/poll",
30047                    "/api/worker/activity-tasks/poll",
30048                    "/api/worker/query-tasks/poll",
30049                ] {
30050                    assert_identical_requests(&server, path, 9);
30051                }
30052            }
30053        }
30054    }
30055
30056    #[tokio::test]
30057    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
30058        struct CountedBody(Arc<AtomicUsize>);
30059        impl Serialize for CountedBody {
30060            fn serialize<S: Serializer>(
30061                &self,
30062                serializer: S,
30063            ) -> std::result::Result<S::Ok, S::Error> {
30064                let count = self.0.fetch_add(1, Ordering::SeqCst);
30065                json!({"serialization":count,"lease_owner":"worker","attempt":7})
30066                    .serialize(serializer)
30067            }
30068        }
30069        for path in [
30070            "/api/worker/register",
30071            "/api/worker/heartbeat",
30072            "/api/worker/workflow-tasks/storage-task/complete",
30073            "/api/worker/workflow-tasks/storage-task/fail",
30074            "/api/worker/activity-tasks/storage-task/complete",
30075            "/api/worker/activity-tasks/storage-task/fail",
30076            "/api/worker/activity-tasks/storage-task/heartbeat",
30077            "/api/worker/query-tasks/storage-task/complete",
30078            "/api/worker/query-tasks/storage-task/fail",
30079        ] {
30080            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30081                storage_refusals: 7,
30082                storage_path: Some(path),
30083                ..MockWorkerBehavior::default()
30084            });
30085            let worker =
30086                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
30087            let calls = Arc::new(AtomicUsize::new(0));
30088            let _: Value = worker
30089                .client
30090                .request_json(
30091                    reqwest::Method::POST,
30092                    &path[4..],
30093                    RequestProtocol::DefaultWorker,
30094                    Some(&CountedBody(Arc::clone(&calls))),
30095                )
30096                .await
30097                .expect("prepared request recovery");
30098            assert_eq!(calls.load(Ordering::SeqCst), 1);
30099            assert_identical_requests(&server, path, 8);
30100        }
30101        for worker_scope in [false, true] {
30102            let path = if worker_scope {
30103                "/api/health"
30104            } else {
30105                "/api/worker/register"
30106            };
30107            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30108                storage_refusals: usize::MAX,
30109                storage_path: Some(path),
30110                ..MockWorkerBehavior::default()
30111            });
30112            let worker = storage_worker(&server);
30113            let client = worker.client.clone();
30114            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
30115            let error = if worker_scope {
30116                worker
30117                    .client
30118                    .health()
30119                    .await
30120                    .expect_err("control plane is not retried")
30121            } else {
30122                client
30123                    .request_json::<Value, Value>(
30124                        reqwest::Method::POST,
30125                        "/worker/register",
30126                        RequestProtocol::DefaultWorker,
30127                        Some(&json!({})),
30128                    )
30129                    .await
30130                    .expect_err("direct client is not retried")
30131            };
30132            assert!(worker_storage_admission_body(&error).is_some());
30133            assert_eq!(server.request_count(path), 1);
30134        }
30135    }
30136
30137    #[tokio::test]
30138    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
30139        for fail in [false, true] {
30140            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30141                storage_activity: true,
30142                storage_refusals: 7,
30143                storage_path: Some("/storage-activity/"),
30144                ..MockWorkerBehavior::default()
30145            });
30146            let mut worker = storage_worker(&server);
30147            let calls = Arc::new(AtomicUsize::new(0));
30148            let observed = Arc::clone(&calls);
30149            worker.register_activity("storage.activity", move |ctx, _| {
30150                let calls = Arc::clone(&observed);
30151                async move {
30152                    calls.fetch_add(1, Ordering::SeqCst);
30153                    ctx.heartbeat(json!({"step":2})).await?;
30154                    if fail {
30155                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
30156                    } else {
30157                        Ok(json!({"receipt":true}))
30158                    }
30159                }
30160            });
30161            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
30162            assert_eq!(calls.load(Ordering::SeqCst), 1);
30163            assert_identical_requests(
30164                &server,
30165                "/api/worker/activity-tasks/storage-activity/heartbeat",
30166                8,
30167            );
30168            let suffix = if fail { "fail" } else { "complete" };
30169            assert_identical_requests(
30170                &server,
30171                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
30172                8,
30173            );
30174            let other = if fail { "complete" } else { "fail" };
30175            assert_eq!(
30176                server.request_count(&format!(
30177                    "/api/worker/activity-tasks/storage-activity/{other}"
30178                )),
30179                0
30180            );
30181        }
30182    }
30183
30184    #[tokio::test]
30185    async fn storage_waits_are_interruptible_without_false_activity_failure() {
30186        for path in [
30187            "/api/worker/register",
30188            "/api/worker/heartbeat",
30189            "/api/worker/activity-tasks/poll",
30190            "/api/worker/activity-tasks/storage-activity/heartbeat",
30191            "/api/worker/activity-tasks/storage-activity/complete",
30192        ] {
30193            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30194                storage_activity: true,
30195                storage_refusals: usize::MAX,
30196                storage_path: Some(path),
30197                ..MockWorkerBehavior::default()
30198            });
30199            let mut worker = storage_worker(&server)
30200                .max_concurrent_workflow_tasks(1)
30201                .max_concurrent_activity_tasks(1)
30202                .retry_policy(WorkerRetryPolicy::default());
30203            worker.register_activity("storage.activity", |ctx, _| async move {
30204                ctx.heartbeat(json!({"step":2})).await?;
30205                Ok(json!({"receipt":true}))
30206            });
30207            let shutdown = async {
30208                while server.request_count(path) == 0 {
30209                    tokio::time::sleep(Duration::from_millis(1)).await;
30210                }
30211            };
30212            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
30213                .await
30214                .expect("shutdown interrupts admission");
30215            assert!(
30216                result.is_err(),
30217                "a refused operation must not appear acknowledged: {path}, {result:?}"
30218            );
30219            assert_eq!(server.request_count(path), 1);
30220            assert_eq!(
30221                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
30222                0
30223            );
30224            assert_eq!(
30225                server.request_count("/api/worker/registrations/mock-worker"),
30226                usize::from(!path.ends_with("/register"))
30227            );
30228        }
30229    }
30230
30231    #[tokio::test]
30232    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
30233        for fail in [false, true] {
30234            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30235                storage_query: true,
30236                storage_refusals: 7,
30237                storage_path: Some("/storage-query/"),
30238                ..MockWorkerBehavior::default()
30239            });
30240            let mut worker = storage_worker(&server);
30241            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
30242            let calls = Arc::new(AtomicUsize::new(0));
30243            let observed = Arc::clone(&calls);
30244            worker.register_query("storage.workflow", "state", move |_, _| {
30245                let calls = Arc::clone(&observed);
30246                async move {
30247                    calls.fetch_add(1, Ordering::SeqCst);
30248                    if fail {
30249                        Err(Error::WorkerLoop("intentional query failure".to_string()))
30250                    } else {
30251                        Ok(json!({"state":"waiting"}))
30252                    }
30253                }
30254            });
30255            assert_eq!(worker.run_once().await.expect("query settled"), 1);
30256            assert_eq!(calls.load(Ordering::SeqCst), 1);
30257            let suffix = if fail { "fail" } else { "complete" };
30258            assert_identical_requests(
30259                &server,
30260                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
30261                8,
30262            );
30263            let other = if fail { "complete" } else { "fail" };
30264            assert_eq!(
30265                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
30266                0
30267            );
30268        }
30269    }
30270
30271    #[tokio::test]
30272    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
30273        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30274            storage_refusals: 7,
30275            storage_path: Some("/poll"),
30276            unauthorized_polls: true,
30277            ..MockWorkerBehavior::default()
30278        });
30279        let error = storage_worker(&server)
30280            .run_once()
30281            .await
30282            .expect_err("auth remains terminal");
30283        assert!(matches!(
30284            error,
30285            Error::Http {
30286                status: reqwest::StatusCode::UNAUTHORIZED,
30287                ..
30288            }
30289        ));
30290        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
30291
30292        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30293            storage_refusals: 7,
30294            storage_path: Some("/activity-cancel/complete"),
30295            ..MockWorkerBehavior::default()
30296        });
30297        let worker =
30298            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
30299        let error = worker
30300            .client
30301            .complete_activity_task(
30302                "activity-cancel",
30303                "attempt-cancel",
30304                "worker",
30305                json!({}),
30306                DEFAULT_CODEC,
30307            )
30308            .await
30309            .expect_err("cancellation remains terminal");
30310        assert!(activity_task_rejection_is_final(&error));
30311        assert_identical_requests(
30312            &server,
30313            "/api/worker/activity-tasks/activity-cancel/complete",
30314            8,
30315        );
30316
30317        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30318            storage_refusals: usize::MAX,
30319            storage_path: Some("/poll"),
30320            storage_wrong_poll_id: true,
30321            ..MockWorkerBehavior::default()
30322        });
30323        assert!(storage_worker(&server).run_once().await.is_err());
30324        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
30325    }
30326
30327    #[tokio::test]
30328    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
30329        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30330            storage_refusals: usize::MAX,
30331            storage_path: Some("/poll"),
30332            ..MockWorkerBehavior::default()
30333        });
30334        let mut worker = storage_worker(&server)
30335            .max_concurrent_workflow_tasks(1)
30336            .max_concurrent_activity_tasks(1)
30337            .retry_policy(WorkerRetryPolicy::default());
30338        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
30339        let run = tokio::spawn(async move { worker.run().await });
30340        tokio::time::timeout(Duration::from_secs(2), async {
30341            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
30342                tokio::time::sleep(Duration::from_millis(1)).await;
30343            }
30344        })
30345        .await
30346        .expect("poll started");
30347        run.abort();
30348        assert!(run.await.expect_err("cancelled run").is_cancelled());
30349        tokio::time::sleep(Duration::from_millis(250)).await;
30350        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
30351    }
30352
30353    #[tokio::test]
30354    async fn query_protocol_rejection_from_older_server_is_typed() {
30355        let server = MockWorkerServer::reject_query_protocol();
30356        let client = Client::builder(server.base_url())
30357            .timeout(Duration::from_secs(2))
30358            .build()
30359            .expect("client");
30360
30361        let error = client
30362            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
30363            .await
30364            .expect_err("server below query protocol floor must reject");
30365        let Error::Protocol(failure) = error else {
30366            panic!("expected typed protocol failure");
30367        };
30368
30369        assert_eq!(failure.status, 400);
30370        assert_eq!(failure.reason, "unsupported_protocol_version");
30371        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
30372        assert_eq!(
30373            failure.requested_version.as_deref(),
30374            Some(WORKER_PROTOCOL_VERSION)
30375        );
30376        assert_eq!(
30377            server
30378                .worker_protocol_for("/api/worker/query-tasks/poll")
30379                .as_deref(),
30380            Some(WORKER_PROTOCOL_VERSION)
30381        );
30382    }
30383
30384    #[tokio::test]
30385    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
30386        let server = MockWorkerServer::reject_query_protocol();
30387        let client = Client::builder(server.base_url())
30388            .timeout(Duration::from_secs(2))
30389            .build()
30390            .expect("client");
30391        let mut worker = Worker::new(client, "rust-workers")
30392            .worker_id("baseline-worker")
30393            .poll_timeout(Duration::from_millis(10));
30394
30395        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
30396            Ok(Value::Null)
30397        });
30398
30399        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
30400        assert_eq!(
30401            server
30402                .worker_protocol_for("/api/worker/workflow-tasks/poll")
30403                .as_deref(),
30404            Some(WORKER_PROTOCOL_VERSION)
30405        );
30406        assert_eq!(
30407            server.worker_protocol_for("/api/worker/query-tasks/poll"),
30408            None,
30409            "a worker without query handlers must not use the query-task endpoint"
30410        );
30411    }
30412
30413    #[tokio::test]
30414    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
30415        let server = MockWorkerServer::reject_query_completion();
30416        let client = Client::builder(server.base_url())
30417            .timeout(Duration::from_secs(2))
30418            .build()
30419            .expect("client");
30420
30421        let error = client
30422            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
30423            .await
30424            .expect_err("expired completion must be rejected");
30425        let Error::QueryFailed(failure) = error else {
30426            panic!("expected typed query failure");
30427        };
30428        assert_eq!(failure.status, 409);
30429        assert_eq!(failure.reason, "query_task_timed_out");
30430
30431        let mut worker = Worker::new(client, "rust-workers")
30432            .worker_id("late-worker")
30433            .poll_timeout(Duration::from_millis(10));
30434        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
30435        worker.register_query(
30436            "counter",
30437            "current",
30438            |_ctx, _args| async move { Ok(json!(8)) },
30439        );
30440
30441        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
30442        assert_eq!(
30443            worker
30444                .run_once()
30445                .await
30446                .expect("worker continues after late completion"),
30447            0
30448        );
30449        assert_eq!(
30450            server.request_count("/api/worker/query-tasks/query-late/complete"),
30451            2
30452        );
30453        assert_eq!(
30454            server.request_count("/api/worker/query-tasks/query-late/fail"),
30455            0,
30456            "a server completion rejection must not be reported as an encoding failure"
30457        );
30458    }
30459
30460    #[tokio::test]
30461    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
30462        let server = MockWorkerServer::start();
30463        let client = Client::builder(server.base_url())
30464            .timeout(Duration::from_secs(2))
30465            .build()
30466            .expect("client");
30467        let mut worker = Worker::new(client, "rust-workers")
30468            .worker_id("joined-worker")
30469            .poll_timeout(Duration::from_millis(10));
30470        worker.register_workflow(
30471            "joined.workflow",
30472            |_ctx, _input| async move { Ok(Value::Null) },
30473        );
30474        worker.register_activity(
30475            "joined.activity",
30476            |_ctx, _input| async move { Ok(Value::Null) },
30477        );
30478        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
30479            Ok(Value::Null)
30480        });
30481
30482        worker
30483            .run_until(tokio::time::sleep(Duration::from_millis(20)))
30484            .await
30485            .expect("normal shutdown");
30486
30487        let deregistration_path = "/api/worker/registrations/mock-worker";
30488        assert_eq!(server.request_count(deregistration_path), 1);
30489        for poll_path in [
30490            "/api/worker/workflow-tasks/poll",
30491            "/api/worker/activity-tasks/poll",
30492            "/api/worker/query-tasks/poll",
30493        ] {
30494            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
30495        }
30496        assert_eq!(
30497            server.captured_paths().last().map(String::as_str),
30498            Some(deregistration_path),
30499            "deregistration must start only after every poller has joined"
30500        );
30501    }
30502
30503    #[tokio::test]
30504    async fn registration_failure_does_not_deregister() {
30505        let server = MockWorkerServer::rejected_registration();
30506        let client = Client::builder(server.base_url())
30507            .timeout(Duration::from_secs(2))
30508            .build()
30509            .expect("client");
30510        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
30511
30512        let error = worker
30513            .run_until(async {})
30514            .await
30515            .expect_err("registration must fail");
30516        assert!(matches!(
30517            error,
30518            Error::Http {
30519                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30520                ..
30521            }
30522        ));
30523        assert!(server
30524            .captured_paths()
30525            .iter()
30526            .all(|path| !path.starts_with("/api/worker/registrations/")));
30527    }
30528
30529    #[tokio::test]
30530    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
30531        let server = MockWorkerServer::rejected_registration_protocol();
30532        let client = Client::builder(server.base_url())
30533            .timeout(Duration::from_secs(2))
30534            .build()
30535            .expect("client");
30536        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
30537
30538        let error = worker
30539            .run_until(async {})
30540            .await
30541            .expect_err("a protocol 1.16 server must reject this worker");
30542        let Error::Protocol(failure) = error else {
30543            panic!("expected typed protocol rejection");
30544        };
30545        assert_eq!(failure.reason, "unsupported_protocol_version");
30546        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
30547        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
30548        assert_eq!(
30549            server
30550                .worker_protocol_for("/api/worker/register")
30551                .as_deref(),
30552            Some(WORKER_PROTOCOL_VERSION)
30553        );
30554    }
30555
30556    #[tokio::test]
30557    async fn declined_registration_does_not_deregister() {
30558        let server = MockWorkerServer::declined_registration();
30559        let client = Client::builder(server.base_url())
30560            .timeout(Duration::from_secs(2))
30561            .build()
30562            .expect("client");
30563        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
30564
30565        let error = worker
30566            .run_until(async {})
30567            .await
30568            .expect_err("declined registration must fail");
30569        assert!(matches!(error, Error::WorkerLoop(_)));
30570        assert!(error.to_string().contains("was not accepted"));
30571        assert!(server
30572            .captured_paths()
30573            .iter()
30574            .all(|path| !path.starts_with("/api/worker/registrations/")));
30575    }
30576
30577    #[tokio::test]
30578    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
30579        let server = MockWorkerServer::rejected_deregistration();
30580        let client = Client::builder(server.base_url())
30581            .timeout(Duration::from_secs(2))
30582            .build()
30583            .expect("client");
30584        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
30585
30586        let error = worker
30587            .run_until(async {})
30588            .await
30589            .expect_err("deregistration must fail");
30590        assert!(matches!(
30591            error,
30592            Error::Http {
30593                status: reqwest::StatusCode::FORBIDDEN,
30594                ..
30595            }
30596        ));
30597        assert_eq!(
30598            server.request_count("/api/worker/registrations/mock-worker"),
30599            1
30600        );
30601    }
30602
30603    #[tokio::test]
30604    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
30605        let server = MockWorkerServer::rejected_deregistration_protocol();
30606        let client = Client::builder(server.base_url())
30607            .timeout(Duration::from_secs(2))
30608            .build()
30609            .expect("client");
30610        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
30611
30612        let error = worker
30613            .run_until(async {})
30614            .await
30615            .expect_err("protocol rejection must fail shutdown");
30616        let Error::Protocol(failure) = error else {
30617            panic!("expected typed protocol failure");
30618        };
30619        assert_eq!(failure.reason, "unsupported_protocol_version");
30620        assert_eq!(
30621            failure.requested_version.as_deref(),
30622            Some(WORKER_PROTOCOL_VERSION)
30623        );
30624        assert_eq!(
30625            server.request_count("/api/worker/registrations/mock-worker"),
30626            1
30627        );
30628    }
30629
30630    #[tokio::test]
30631    async fn primary_poller_error_retains_deregistration_failure_context() {
30632        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
30633        let client = Client::builder(server.base_url())
30634            .timeout(Duration::from_secs(2))
30635            .build()
30636            .expect("client");
30637        let mut worker = Worker::new(client, "rust-workers")
30638            .worker_id("combined-failure")
30639            .poll_timeout(Duration::from_millis(10));
30640        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
30641            Ok(Value::Null)
30642        });
30643
30644        let error = worker
30645            .run()
30646            .await
30647            .expect_err("worker and cleanup must fail");
30648        let summary = error.to_string();
30649        assert!(summary.contains("authentication_failed"));
30650        assert!(summary.contains("worker cannot deregister"));
30651        let Error::WorkerShutdown {
30652            primary,
30653            deregistration,
30654        } = error
30655        else {
30656            panic!("expected combined worker shutdown error");
30657        };
30658        assert!(matches!(
30659            *primary,
30660            Error::Http {
30661                status: reqwest::StatusCode::UNAUTHORIZED,
30662                ..
30663            }
30664        ));
30665        assert!(matches!(
30666            *deregistration,
30667            Error::Http {
30668                status: reqwest::StatusCode::FORBIDDEN,
30669                ..
30670            }
30671        ));
30672        assert_eq!(
30673            server.request_count("/api/worker/registrations/mock-worker"),
30674            1
30675        );
30676    }
30677
30678    #[tokio::test]
30679    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
30680        let server = MockWorkerServer::start();
30681        let client = Client::builder(server.base_url())
30682            .timeout(Duration::from_secs(2))
30683            .build()
30684            .expect("client");
30685        let mut worker = Worker::new(client, "rust-workers")
30686            .worker_id("activity-only-worker")
30687            .poll_timeout(Duration::from_millis(10));
30688
30689        worker.register_activity(
30690            "activity.only",
30691            |_ctx, _args| async move { Ok(Value::Null) },
30692        );
30693
30694        worker.run_until(async {}).await.expect("run worker");
30695    }
30696
30697    #[tokio::test]
30698    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
30699        let server = MockWorkerServer::start();
30700        let client = Client::builder(server.base_url())
30701            .timeout(Duration::from_secs(2))
30702            .build()
30703            .expect("client");
30704        let mut worker = Worker::new(client, "rust-workers")
30705            .worker_id("workflow-only-worker")
30706            .poll_timeout(Duration::from_millis(10));
30707
30708        worker.register_workflow(
30709            "workflow.only",
30710            |_ctx, _input| async move { Ok(Value::Null) },
30711        );
30712
30713        worker.run_until(async {}).await.expect("run worker");
30714    }
30715
30716    #[tokio::test]
30717    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
30718        let server = MockWorkerServer::start();
30719        let client = Client::builder(server.base_url())
30720            .timeout(Duration::from_secs(2))
30721            .build()
30722            .expect("client");
30723        let observations = Arc::new(Mutex::new(Vec::new()));
30724        let observed = Arc::clone(&observations);
30725        let mut worker = Worker::new(client, "rust-workers")
30726            .worker_id("observed-heartbeat-worker")
30727            .poll_timeout(Duration::from_millis(10))
30728            .on_worker_heartbeat(move |observation| {
30729                observed
30730                    .lock()
30731                    .expect("heartbeat observations")
30732                    .push(observation.clone());
30733            });
30734
30735        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
30736            Ok(Value::Null)
30737        });
30738        let acknowledged = Arc::clone(&observations);
30739        worker
30740            .run_until(async move {
30741                tokio::time::timeout(Duration::from_secs(2), async move {
30742                    loop {
30743                        if !acknowledged
30744                            .lock()
30745                            .expect("heartbeat observations")
30746                            .is_empty()
30747                        {
30748                            break;
30749                        }
30750                        tokio::time::sleep(Duration::from_millis(1)).await;
30751                    }
30752                })
30753                .await
30754                .expect("heartbeat acknowledgement within timeout");
30755            })
30756            .await
30757            .expect("run worker");
30758
30759        let observations = observations.lock().expect("heartbeat observations");
30760        let first = observations.first().expect("heartbeat acknowledgement");
30761        assert_eq!(first.worker_id, "observed-heartbeat-worker");
30762        assert_eq!(first.task_queue, "rust-workers");
30763        assert!(first.acknowledged_at_unix_millis > 0);
30764        assert_eq!(first.acknowledgement, json!({}));
30765    }
30766
30767    #[tokio::test]
30768    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
30769        let server = MockWorkerServer::delayed_heartbeat_worker();
30770        let client = Client::builder(server.base_url())
30771            .timeout(Duration::from_secs(3))
30772            .build()
30773            .expect("client");
30774        let observations = Arc::new(Mutex::new(Vec::new()));
30775        let observed = Arc::clone(&observations);
30776        let mut worker = Worker::new(client, "rust-snapshot-workers")
30777            .max_concurrent_workflow_tasks(1)
30778            .max_concurrent_activity_tasks(1)
30779            .worker_id("rust-snapshot-worker")
30780            .poll_timeout(Duration::from_millis(10))
30781            .on_worker_heartbeat(move |observation| {
30782                observed
30783                    .lock()
30784                    .expect("heartbeat observations")
30785                    .push(observation.clone());
30786            });
30787
30788        worker.register_workflow("snapshot", |ctx, _input| async move {
30789            ctx.wait_signal("finish").await?;
30790            Ok(json!({"status": "finished"}))
30791        });
30792        worker.register_query("snapshot", "current", |ctx, _args| async move {
30793            Ok(json!(ctx
30794                .signals("increment")
30795                .iter()
30796                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
30797                .sum::<i64>()))
30798        });
30799        worker.register_activity("cancel-aware", |_ctx, _args| async move {
30800            Ok(json!({"late": "completion"}))
30801        });
30802
30803        worker
30804            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
30805            .await
30806            .expect("delayed heartbeat must allow a clean worker shutdown");
30807
30808        let observations = observations.lock().expect("heartbeat observations");
30809        assert!(
30810            observations.len() >= 3,
30811            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
30812        );
30813        assert!(
30814            observations.windows(2).all(|pair| {
30815                pair[1].acknowledged_at_unix_millis
30816                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
30817                    >= 850
30818            }),
30819            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
30820        );
30821        drop(observations);
30822
30823        let heartbeat_times = server.request_times("/api/worker/heartbeat");
30824        let delayed_request_at = *heartbeat_times
30825            .get(1)
30826            .expect("intentionally delayed heartbeat request");
30827        let delay_window_start = delayed_request_at + Duration::from_millis(100);
30828        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
30829        for path in [
30830            "/api/worker/workflow-tasks/poll",
30831            "/api/worker/activity-tasks/poll",
30832            "/api/worker/query-tasks/poll",
30833        ] {
30834            assert!(
30835                server
30836                    .request_times(path)
30837                    .iter()
30838                    .any(|received_at| *received_at >= delay_window_start
30839                        && *received_at <= delay_window_end),
30840                "{path} must keep polling while a heartbeat acknowledgement is delayed"
30841            );
30842        }
30843        assert!(
30844            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
30845            "workflow work must be settled"
30846        );
30847        assert!(
30848            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
30849            "activity work must be settled"
30850        );
30851        assert!(
30852            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
30853            "query work must be settled"
30854        );
30855    }
30856
30857    #[tokio::test]
30858    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
30859        let server = MockWorkerServer::heartbeat_retry_worker();
30860        let client = Client::builder(server.base_url())
30861            .timeout(Duration::from_secs(2))
30862            .build()
30863            .expect("client");
30864        let observations = Arc::new(Mutex::new(Vec::new()));
30865        let observed = Arc::clone(&observations);
30866        let worker = Worker::new(client, "rust-workers")
30867            .worker_id("heartbeat-retry-worker")
30868            .retry_policy(WorkerRetryPolicy {
30869                max_retries: 1,
30870                initial_backoff: Duration::from_millis(300),
30871                max_backoff: Duration::from_millis(300),
30872            })
30873            .on_worker_heartbeat(move |observation| {
30874                observed
30875                    .lock()
30876                    .expect("heartbeat observations")
30877                    .push(observation.clone());
30878            });
30879
30880        worker
30881            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
30882            .await
30883            .expect("retryable heartbeat failure must remain bounded and recover");
30884
30885        let observations = observations.lock().expect("heartbeat observations");
30886        assert!(observations.len() >= 3, "heartbeat retry must recover");
30887        assert!(
30888            observations.windows(2).all(|pair| {
30889                pair[1]
30890                    .acknowledged_at_unix_millis
30891                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
30892                    >= 850
30893            }),
30894            "a successful retry must start a fresh advertised cadence: {observations:?}"
30895        );
30896        assert_eq!(
30897            server.request_count("/api/worker/heartbeat"),
30898            observations.len() + 1,
30899            "one retryable failure must add exactly one bounded request"
30900        );
30901    }
30902
30903    #[tokio::test]
30904    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
30905        let server = MockWorkerServer::waiting_query_worker();
30906        let client = Client::builder(server.base_url())
30907            .timeout(Duration::from_secs(2))
30908            .build()
30909            .expect("client");
30910        let observations = Arc::new(Mutex::new(Vec::new()));
30911        let observed = Arc::clone(&observations);
30912        let mut worker = Worker::new(client, "rust-snapshot-workers")
30913            .worker_id("rust-snapshot-worker")
30914            .poll_timeout(Duration::from_millis(10))
30915            .on_worker_heartbeat(move |observation| {
30916                observed
30917                    .lock()
30918                    .expect("heartbeat observations")
30919                    .push(observation.clone());
30920            });
30921
30922        worker.register_workflow("snapshot", |ctx, _input| async move {
30923            ctx.wait_signal("finish").await?;
30924            Ok(json!({"status": "finished"}))
30925        });
30926        worker.register_query("snapshot", "current", |ctx, _args| async move {
30927            let current = ctx
30928                .signals("increment")
30929                .iter()
30930                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
30931                .sum::<i64>();
30932            Ok(json!(current))
30933        });
30934        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
30935        worker
30936            .declare_workflow_signals("snapshot", &["finish"])
30937            .expect("declare finish signal");
30938
30939        worker
30940            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
30941            .await
30942            .expect("pending workflow and query poller must remain live until shutdown");
30943
30944        assert!(
30945            observations.lock().expect("heartbeat observations").len() >= 4,
30946            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
30947        );
30948        assert!(
30949            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
30950            "workflow polling must continue after empty replay acknowledgements"
30951        );
30952        assert!(
30953            server.request_count("/api/worker/query-tasks/poll") >= 2,
30954            "query polling must continue after serving the current query"
30955        );
30956        assert_eq!(
30957            server.request_body("/api/worker/register")["capabilities"],
30958            json!([
30959                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
30960                "workflow_entry_arguments_validation",
30961                DURABLE_SELECTION_CAPABILITY,
30962                MEMO_UPSERTS_CAPABILITY,
30963                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
30964                QUERY_TASKS_CAPABILITY,
30965                WORKFLOW_UPDATES_CAPABILITY,
30966                MESSAGE_STREAMS_CAPABILITY
30967            ])
30968        );
30969        assert_eq!(
30970            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
30971            json!({
30972                "queries": ["current"],
30973                "query_contracts": [{
30974                    "name": "current",
30975                    "parameters": [{
30976                        "name": "args", "position": 0, "required": false,
30977                        "variadic": true, "type": null, "allows_null": true,
30978                        "default_available": false, "default": null,
30979                    }],
30980                }],
30981                "signals": ["finish"],
30982                "signal_contracts": [{
30983                    "name": "finish",
30984                    "parameters": [{
30985                        "name": "args", "position": 0, "required": false,
30986                        "variadic": true, "type": null, "allows_null": true,
30987                        "default_available": false, "default": null,
30988                    }],
30989                }],
30990                "updates": ["replace"],
30991                "update_contracts": [{
30992                    "name": "replace",
30993                    "parameters": [{
30994                        "name": "args", "position": 0, "required": false,
30995                        "variadic": true, "type": null, "allows_null": true,
30996                        "default_available": false, "default": null,
30997                    }],
30998                }],
30999                "update_validators": [],
31000            })
31001        );
31002
31003        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
31004        assert_eq!(
31005            opened["commands"],
31006            json!([{
31007                "type": "open_signal_wait",
31008                "signal_name": "finish",
31009            }])
31010        );
31011
31012        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
31013            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
31014            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
31015            let failure = server.request_body(&fail_path);
31016            assert_eq!(
31017                failure["failure"]["type"],
31018                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
31019            );
31020            assert_eq!(server.request_count(&completion_path), 0);
31021        }
31022
31023        let query_completion =
31024            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
31025        assert_eq!(query_completion["result"], json!(8));
31026
31027        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
31028        assert_eq!(
31029            server.request_count(terminal_path),
31030            1,
31031            "the matching signal must settle the workflow exactly once"
31032        );
31033        let terminal = server.request_body(terminal_path);
31034        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
31035        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
31036        assert_eq!(
31037            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
31038                .expect("terminal workflow result"),
31039            json!({"status": "finished"})
31040        );
31041    }
31042
31043    #[tokio::test]
31044    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
31045        let server = MockWorkerServer::transient_worker_failures();
31046        let client = Client::builder(server.base_url())
31047            .timeout(Duration::from_secs(2))
31048            .build()
31049            .expect("client");
31050        let mut worker = Worker::new(client, "rust-workers")
31051            .max_concurrent_workflow_tasks(1)
31052            .max_concurrent_activity_tasks(1)
31053            .worker_id("retry-worker")
31054            .poll_timeout(Duration::from_millis(10))
31055            .retry_policy(WorkerRetryPolicy {
31056                max_retries: 2,
31057                initial_backoff: Duration::from_millis(1),
31058                max_backoff: Duration::from_millis(1),
31059            });
31060        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31061        worker.register_activity(
31062            "counter.activity",
31063            |_ctx, _input| async move { Ok(Value::Null) },
31064        );
31065        worker.register_query(
31066            "counter",
31067            "current",
31068            |_ctx, _args| async move { Ok(json!(8)) },
31069        );
31070
31071        worker
31072            .run_until(tokio::time::sleep(Duration::from_millis(75)))
31073            .await
31074            .expect("transient failures must not stop the worker");
31075
31076        for path in [
31077            "/api/worker/heartbeat",
31078            "/api/worker/workflow-tasks/poll",
31079            "/api/worker/activity-tasks/poll",
31080            "/api/worker/query-tasks/poll",
31081        ] {
31082            assert!(
31083                server.request_count(path) >= 2,
31084                "{path} must continue after its transient failure"
31085            );
31086        }
31087    }
31088
31089    #[tokio::test]
31090    async fn worker_continues_after_long_poll_capacity_backpressure() {
31091        let server = MockWorkerServer::capacity_limited_activity_poll();
31092        let client = Client::builder(server.base_url())
31093            .timeout(Duration::from_secs(2))
31094            .build()
31095            .expect("client");
31096        let mut worker = Worker::new(client, "rust-workers")
31097            .worker_id("capacity-worker")
31098            .poll_timeout(Duration::from_millis(10))
31099            .retry_policy(WorkerRetryPolicy {
31100                max_retries: 0,
31101                initial_backoff: Duration::from_millis(1),
31102                max_backoff: Duration::from_millis(1),
31103            });
31104        worker.register_activity("capacity.activity", |_ctx, _input| async move {
31105            Ok(json!({"handled": true}))
31106        });
31107
31108        worker
31109            .run_until(tokio::time::sleep(Duration::from_millis(50)))
31110            .await
31111            .expect("capacity backpressure must not stop the worker");
31112
31113        assert!(
31114            server.request_count("/api/worker/activity-tasks/poll") >= 2,
31115            "the activity poller must continue after capacity backpressure"
31116        );
31117        assert_eq!(
31118            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
31119            1,
31120            "the worker must complete work returned after capacity recovers"
31121        );
31122    }
31123
31124    #[test]
31125    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
31126        let capacity = Error::Http {
31127            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31128            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
31129        };
31130        assert_eq!(
31131            worker_poll_capacity_retry_after(&capacity),
31132            Some(Duration::from_secs(3))
31133        );
31134
31135        let rejected_capacity = Error::Http {
31136            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31137            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
31138        };
31139        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
31140        assert!(!worker_operation_is_retryable(&rejected_capacity));
31141
31142        let ordinary_rate_limit = Error::Http {
31143            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31144            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
31145                .to_string(),
31146        };
31147        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
31148        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
31149    }
31150
31151    #[tokio::test]
31152    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
31153        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31154            poll_failures_per_path: 8,
31155            heartbeat_failures: 8,
31156            ..MockWorkerBehavior::default()
31157        });
31158        let client = Client::builder(server.base_url())
31159            .timeout(Duration::from_secs(2))
31160            .build()
31161            .expect("client");
31162        let acknowledgements = Arc::new(AtomicUsize::new(0));
31163        let observed = Arc::clone(&acknowledgements);
31164        let mut worker = Worker::new(client, "rust-workers")
31165            .max_concurrent_workflow_tasks(1)
31166            .max_concurrent_activity_tasks(1)
31167            .recover_transient_outages(true)
31168            .poll_timeout(Duration::from_millis(10))
31169            .retry_policy(WorkerRetryPolicy {
31170                max_retries: 2,
31171                initial_backoff: Duration::from_millis(2),
31172                max_backoff: Duration::from_millis(5),
31173            })
31174            .on_worker_heartbeat(move |_| {
31175                observed.fetch_add(1, Ordering::SeqCst);
31176            });
31177        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31178        worker.register_activity(
31179            "counter.activity",
31180            |_ctx, _input| async move { Ok(Value::Null) },
31181        );
31182        worker.register_query("counter", "current", |_ctx, _args| async move {
31183            Ok(Value::Null)
31184        });
31185
31186        worker
31187            .run_until(tokio::time::sleep(Duration::from_millis(500)))
31188            .await
31189            .expect("a recoverable outage must not stop the service worker");
31190
31191        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
31192        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
31193        for path in [
31194            "/api/worker/workflow-tasks/poll",
31195            "/api/worker/activity-tasks/poll",
31196            "/api/worker/query-tasks/poll",
31197        ] {
31198            let bodies = server.request_bodies(path);
31199            assert!(bodies.len() >= 10, "{path} must resume after recovery");
31200            let first = &bodies[0]["poll_request_id"];
31201            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
31202            for body in &bodies[..9] {
31203                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
31204            }
31205            assert_ne!(&bodies[9]["poll_request_id"], first);
31206            let times = server.request_times(path);
31207            for pair in times[..9].windows(2) {
31208                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
31209            }
31210        }
31211    }
31212
31213    #[tokio::test]
31214    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
31215        for heartbeat_outage in [false, true] {
31216            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31217                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
31218                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
31219                ..MockWorkerBehavior::default()
31220            });
31221            let client = Client::builder(server.base_url()).build().expect("client");
31222            let mut worker = Worker::new(client, "rust-workers")
31223                .max_concurrent_workflow_tasks(1)
31224                .max_concurrent_activity_tasks(1)
31225                .recover_transient_outages(true)
31226                .retry_policy(WorkerRetryPolicy {
31227                    max_retries: 1,
31228                    initial_backoff: Duration::from_secs(5),
31229                    max_backoff: Duration::from_secs(5),
31230                });
31231            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31232            let started = Instant::now();
31233            worker
31234                .run_until(tokio::time::sleep(Duration::from_millis(200)))
31235                .await
31236                .expect("shutdown during an outage is a normal stop");
31237            assert!(started.elapsed() < Duration::from_secs(1));
31238            let path = if heartbeat_outage {
31239                "/api/worker/heartbeat"
31240            } else {
31241                "/api/worker/workflow-tasks/poll"
31242            };
31243            assert_eq!(server.request_count(path), 1);
31244            assert_eq!(
31245                server.request_count("/api/worker/registrations/mock-worker"),
31246                1
31247            );
31248        }
31249    }
31250
31251    #[tokio::test]
31252    async fn worker_outage_recovery_keeps_run_once_bounded() {
31253        let server = MockWorkerServer::unavailable_polls();
31254        let client = Client::builder(server.base_url()).build().expect("client");
31255        let mut worker = Worker::new(client, "rust-workers")
31256            .recover_transient_outages(true)
31257            .retry_policy(WorkerRetryPolicy {
31258                max_retries: 2,
31259                initial_backoff: Duration::from_millis(1),
31260                max_backoff: Duration::from_millis(1),
31261            });
31262        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31263        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
31264        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
31265    }
31266
31267    #[tokio::test]
31268    async fn worker_outage_recovery_respects_disabled_retries() {
31269        let server = MockWorkerServer::unavailable_polls();
31270        let client = Client::builder(server.base_url()).build().expect("client");
31271        let mut worker = Worker::new(client, "rust-workers")
31272            .max_concurrent_workflow_tasks(1)
31273            .max_concurrent_activity_tasks(1)
31274            .recover_transient_outages(true)
31275            .retry_policy(WorkerRetryPolicy {
31276                max_retries: 0,
31277                ..WorkerRetryPolicy::default()
31278            });
31279        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31280        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
31281        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
31282    }
31283
31284    #[tokio::test]
31285    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
31286        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31287            heartbeat_failures: usize::MAX,
31288            unauthorized_polls: true,
31289            ..MockWorkerBehavior::default()
31290        });
31291        let client = Client::builder(server.base_url()).build().expect("client");
31292        let mut worker = Worker::new(client, "rust-workers")
31293            .max_concurrent_workflow_tasks(1)
31294            .max_concurrent_activity_tasks(1)
31295            .recover_transient_outages(true)
31296            .retry_policy(WorkerRetryPolicy {
31297                max_retries: 1,
31298                initial_backoff: Duration::from_secs(5),
31299                max_backoff: Duration::from_secs(5),
31300            });
31301        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31302        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
31303            .await
31304            .expect("fatal poll errors must interrupt heartbeat recovery")
31305            .expect_err("authentication failure is terminal");
31306        assert!(
31307            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
31308        );
31309        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
31310    }
31311
31312    #[tokio::test]
31313    async fn worker_bounds_transport_retries() {
31314        let server = MockWorkerServer::unavailable_polls();
31315        let client = Client::builder(server.base_url())
31316            .timeout(Duration::from_secs(2))
31317            .build()
31318            .expect("client");
31319        let mut worker = Worker::new(client, "rust-workers")
31320            .max_concurrent_workflow_tasks(1)
31321            .max_concurrent_activity_tasks(1)
31322            .worker_id("bounded-retry-worker")
31323            .poll_timeout(Duration::from_millis(10))
31324            .retry_policy(WorkerRetryPolicy {
31325                max_retries: 2,
31326                initial_backoff: Duration::from_millis(1),
31327                max_backoff: Duration::from_millis(1),
31328            });
31329        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31330
31331        let error = worker.run().await.expect_err("retry bound must terminate");
31332        assert!(matches!(error, Error::Transport(_)));
31333        assert_eq!(
31334            server.request_count("/api/worker/workflow-tasks/poll"),
31335            3,
31336            "one initial request plus exactly two retries"
31337        );
31338    }
31339
31340    #[tokio::test]
31341    async fn worker_retry_policy_can_disable_poll_retries() {
31342        let server = MockWorkerServer::unavailable_polls();
31343        let client = Client::builder(server.base_url())
31344            .timeout(Duration::from_secs(2))
31345            .build()
31346            .expect("client");
31347        let mut worker = Worker::new(client, "rust-workers")
31348            .worker_id("no-retry-worker")
31349            .poll_timeout(Duration::from_millis(10))
31350            .retry_policy(WorkerRetryPolicy {
31351                max_retries: 0,
31352                initial_backoff: Duration::from_millis(1),
31353                max_backoff: Duration::from_millis(1),
31354            });
31355        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31356
31357        let error = worker
31358            .run_once()
31359            .await
31360            .expect_err("disabled retries must return the first transport failure");
31361        assert!(matches!(error, Error::Transport(_)));
31362        assert_eq!(
31363            server.request_count("/api/worker/workflow-tasks/poll"),
31364            1,
31365            "max_retries=0 must send only the initial request"
31366        );
31367    }
31368
31369    #[tokio::test]
31370    async fn worker_does_not_retry_authentication_failures() {
31371        let server = MockWorkerServer::unauthorized_polls();
31372        let client = Client::builder(server.base_url())
31373            .timeout(Duration::from_secs(2))
31374            .build()
31375            .expect("client");
31376        let mut worker = Worker::new(client, "rust-workers")
31377            .max_concurrent_workflow_tasks(1)
31378            .max_concurrent_activity_tasks(1)
31379            .worker_id("unauthorized-worker")
31380            .recover_transient_outages(true)
31381            .poll_timeout(Duration::from_millis(10));
31382        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31383
31384        let error = worker
31385            .run()
31386            .await
31387            .expect_err("authentication must terminate");
31388        let Error::Http { status, body } = error else {
31389            panic!("expected stable HTTP authentication error");
31390        };
31391        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
31392        assert!(body.contains("authentication_failed"));
31393        assert_eq!(
31394            server.request_count("/api/worker/workflow-tasks/poll"),
31395            1,
31396            "authentication failures must not be retried"
31397        );
31398    }
31399
31400    #[test]
31401    fn duplicate_registration_keeps_the_original_workflow() {
31402        let client = Client::new("http://127.0.0.1:9").expect("client");
31403        let mut worker = Worker::new(client, "registration-tests");
31404        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
31405        let original = Arc::clone(&worker.workflows["same"].execute);
31406        worker
31407            .set_workflow_definition_sources("same", &["first workflow source"])
31408            .expect("source identity");
31409        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
31410        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
31411        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
31412        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
31413    }
31414
31415    #[test]
31416    fn duplicate_registration_keeps_the_original_activity() {
31417        let client = Client::new("http://127.0.0.1:9").expect("client");
31418        let mut worker = Worker::new(client, "registration-tests");
31419        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
31420        let original = Arc::clone(&worker.activities["same"]);
31421        worker.register_activity_avro_value("same", |_ctx, _input| async {
31422            Ok(AvroValue::String("second".into()))
31423        });
31424        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
31425    }
31426
31427    #[test]
31428    fn duplicate_registration_keeps_original_query_and_update_handlers() {
31429        let client = Client::new("http://127.0.0.1:9").expect("client");
31430        let mut worker = Worker::new(client, "registration-tests");
31431        worker.register_query("orders", "same", |_ctx, _input| async {
31432            Ok(json!("first"))
31433        });
31434        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
31435            panic!("snapshot query");
31436        };
31437        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
31438            Ok(json!("second"))
31439        });
31440        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
31441            panic!("duplicate replaced the query adapter");
31442        };
31443        assert!(Arc::ptr_eq(&original, retained));
31444        worker.register_update("orders", "same", |_ctx, _input| async {
31445            Ok(json!("first"))
31446        });
31447        let original = Arc::clone(&worker.updates["orders"]["same"]);
31448        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
31449            Ok(AvroValue::Null)
31450        });
31451        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
31452    }
31453
31454    #[tokio::test]
31455    async fn duplicate_registration_fails_before_server_contact() {
31456        let server = MockWorkerServer::start();
31457        let client = Client::builder(server.base_url()).build().expect("client");
31458        let mut worker =
31459            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
31460        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
31461        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
31462        let error = worker
31463            .run_once()
31464            .await
31465            .expect_err("ambiguous worker must not poll");
31466        assert!(
31467            error.to_string().contains("duplicate_registration"),
31468            "{error}"
31469        );
31470        assert!(server.requests.lock().expect("requests").is_empty());
31471    }
31472
31473    #[derive(Clone, Debug)]
31474    struct CapturedRequest {
31475        headers: String,
31476        method: String,
31477        path: String,
31478        authorization: Option<String>,
31479        namespace: Option<String>,
31480        worker_protocol: Option<String>,
31481        control_protocol: Option<String>,
31482        body: String,
31483        received_at: Instant,
31484    }
31485
31486    struct MockWorkerServer {
31487        addr: SocketAddr,
31488        stop: Arc<AtomicBool>,
31489        requests: Arc<Mutex<Vec<CapturedRequest>>>,
31490        thread: Option<thread::JoinHandle<()>>,
31491    }
31492
31493    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
31494
31495    #[derive(Clone, Copy, Default)]
31496    struct MockWorkerBehavior {
31497        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
31498        request_override: Option<RequestOverride>,
31499        /// Close the connection after reading the request, without any response.
31500        drop_request: Option<fn(&str, usize) -> bool>,
31501        storage_refusals: usize,
31502        storage_path: Option<&'static str>,
31503        storage_unavailable: bool,
31504        storage_mid_poll: bool,
31505        storage_activity: bool,
31506        storage_query: bool,
31507        storage_wrong_poll_id: bool,
31508        reject_query_protocol: bool,
31509        reject_query_completion: bool,
31510        waiting_query_worker: bool,
31511        decline_registration: bool,
31512        complete_named_signal: bool,
31513        poll_failures_per_path: usize,
31514        long_poll_capacity_responses_per_path: usize,
31515        heartbeat_failures: usize,
31516        heartbeat_failure_request: Option<usize>,
31517        delayed_heartbeat_request: Option<usize>,
31518        heartbeat_response_delay: Duration,
31519        concurrent_requests: bool,
31520        unauthorized_polls: bool,
31521        reject_registration: bool,
31522        reject_registration_protocol: bool,
31523        reject_deregistration: bool,
31524        reject_deregistration_protocol: bool,
31525        cancelled_activity: bool,
31526        draining_polls: bool,
31527        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
31528        workflow_completion_status: Option<&'static str>,
31529        workflow_completion_body: Option<&'static str>,
31530    }
31531
31532    impl MockWorkerServer {
31533        fn start() -> Self {
31534            Self::start_with_behavior(MockWorkerBehavior::default())
31535        }
31536
31537        fn reject_query_protocol() -> Self {
31538            Self::start_with_behavior(MockWorkerBehavior {
31539                reject_query_protocol: true,
31540                ..MockWorkerBehavior::default()
31541            })
31542        }
31543
31544        fn reject_query_completion() -> Self {
31545            Self::start_with_behavior(MockWorkerBehavior {
31546                reject_query_completion: true,
31547                ..MockWorkerBehavior::default()
31548            })
31549        }
31550
31551        fn waiting_query_worker() -> Self {
31552            Self::start_with_behavior(MockWorkerBehavior {
31553                waiting_query_worker: true,
31554                complete_named_signal: true,
31555                ..MockWorkerBehavior::default()
31556            })
31557        }
31558
31559        fn transient_worker_failures() -> Self {
31560            Self::start_with_behavior(MockWorkerBehavior {
31561                poll_failures_per_path: 1,
31562                heartbeat_failures: 1,
31563                ..MockWorkerBehavior::default()
31564            })
31565        }
31566
31567        fn consecutive_poll_failures(count: usize) -> Self {
31568            Self::start_with_behavior(MockWorkerBehavior {
31569                poll_failures_per_path: count,
31570                ..MockWorkerBehavior::default()
31571            })
31572        }
31573
31574        fn capacity_limited_activity_poll() -> Self {
31575            Self::start_with_behavior(MockWorkerBehavior {
31576                long_poll_capacity_responses_per_path: 1,
31577                ..MockWorkerBehavior::default()
31578            })
31579        }
31580
31581        fn delayed_heartbeat_worker() -> Self {
31582            Self::start_with_behavior(MockWorkerBehavior {
31583                waiting_query_worker: true,
31584                delayed_heartbeat_request: Some(2),
31585                heartbeat_response_delay: Duration::from_millis(1_500),
31586                concurrent_requests: true,
31587                cancelled_activity: true,
31588                ..MockWorkerBehavior::default()
31589            })
31590        }
31591
31592        fn heartbeat_retry_worker() -> Self {
31593            Self::start_with_behavior(MockWorkerBehavior {
31594                waiting_query_worker: true,
31595                heartbeat_failure_request: Some(2),
31596                concurrent_requests: true,
31597                ..MockWorkerBehavior::default()
31598            })
31599        }
31600
31601        fn unavailable_polls() -> Self {
31602            Self::start_with_behavior(MockWorkerBehavior {
31603                poll_failures_per_path: usize::MAX,
31604                ..MockWorkerBehavior::default()
31605            })
31606        }
31607
31608        fn unauthorized_polls() -> Self {
31609            Self::start_with_behavior(MockWorkerBehavior {
31610                unauthorized_polls: true,
31611                ..MockWorkerBehavior::default()
31612            })
31613        }
31614
31615        fn rejected_registration() -> Self {
31616            Self::start_with_behavior(MockWorkerBehavior {
31617                reject_registration: true,
31618                ..MockWorkerBehavior::default()
31619            })
31620        }
31621
31622        fn rejected_registration_protocol() -> Self {
31623            Self::start_with_behavior(MockWorkerBehavior {
31624                reject_registration_protocol: true,
31625                ..MockWorkerBehavior::default()
31626            })
31627        }
31628
31629        fn declined_registration() -> Self {
31630            Self::start_with_behavior(MockWorkerBehavior {
31631                decline_registration: true,
31632                ..MockWorkerBehavior::default()
31633            })
31634        }
31635
31636        fn rejected_deregistration() -> Self {
31637            Self::start_with_behavior(MockWorkerBehavior {
31638                reject_deregistration: true,
31639                ..MockWorkerBehavior::default()
31640            })
31641        }
31642
31643        fn rejected_deregistration_protocol() -> Self {
31644            Self::start_with_behavior(MockWorkerBehavior {
31645                reject_deregistration_protocol: true,
31646                ..MockWorkerBehavior::default()
31647            })
31648        }
31649
31650        fn unauthorized_polls_and_rejected_deregistration() -> Self {
31651            Self::start_with_behavior(MockWorkerBehavior {
31652                unauthorized_polls: true,
31653                reject_deregistration: true,
31654                ..MockWorkerBehavior::default()
31655            })
31656        }
31657
31658        fn cancelled_activity() -> Self {
31659            Self::start_with_behavior(MockWorkerBehavior {
31660                cancelled_activity: true,
31661                ..MockWorkerBehavior::default()
31662            })
31663        }
31664
31665        fn draining_polls() -> Self {
31666            Self::start_with_behavior(MockWorkerBehavior {
31667                draining_polls: true,
31668                ..MockWorkerBehavior::default()
31669            })
31670        }
31671
31672        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
31673            Self::start_with_behavior(MockWorkerBehavior {
31674                invalid_task_payload_codec: Some(codec),
31675                ..MockWorkerBehavior::default()
31676            })
31677        }
31678
31679        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
31680            Self::start_with_behavior(MockWorkerBehavior {
31681                workflow_completion_status: Some(status),
31682                workflow_completion_body: Some(body),
31683                ..MockWorkerBehavior::default()
31684            })
31685        }
31686
31687        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
31688            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
31689            listener
31690                .set_nonblocking(true)
31691                .expect("configure mock listener");
31692            let addr = listener.local_addr().expect("mock server address");
31693            let stop = Arc::new(AtomicBool::new(false));
31694            let server_stop = Arc::clone(&stop);
31695            let requests = Arc::new(Mutex::new(Vec::new()));
31696            let server_requests = Arc::clone(&requests);
31697            let thread = thread::spawn(move || {
31698                let mut request_threads = Vec::new();
31699                while !server_stop.load(Ordering::SeqCst) {
31700                    match listener.accept() {
31701                        Ok((mut stream, _)) => {
31702                            if behavior.concurrent_requests {
31703                                let requests = Arc::clone(&server_requests);
31704                                request_threads.push(thread::spawn(move || {
31705                                    handle_mock_worker_request(&mut stream, &requests, behavior)
31706                                }));
31707                            } else {
31708                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
31709                            }
31710                        }
31711                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
31712                            let mut index = 0;
31713                            while index < request_threads.len() {
31714                                if request_threads[index].is_finished() {
31715                                    request_threads
31716                                        .swap_remove(index)
31717                                        .join()
31718                                        .expect("join mock request");
31719                                } else {
31720                                    index += 1;
31721                                }
31722                            }
31723                            thread::sleep(Duration::from_millis(5));
31724                        }
31725                        Err(_) => break,
31726                    }
31727                }
31728                for request_thread in request_threads {
31729                    request_thread.join().expect("join mock request");
31730                }
31731            });
31732
31733            Self {
31734                addr,
31735                stop,
31736                requests,
31737                thread: Some(thread),
31738            }
31739        }
31740
31741        fn base_url(&self) -> String {
31742            format!("http://{}", self.addr)
31743        }
31744
31745        fn worker_protocol_for(&self, path: &str) -> Option<String> {
31746            self.requests
31747                .lock()
31748                .expect("captured requests")
31749                .iter()
31750                .find(|request| request.path == path)
31751                .and_then(|request| request.worker_protocol.clone())
31752        }
31753
31754        fn control_protocol_for(&self, path: &str) -> Option<String> {
31755            self.requests
31756                .lock()
31757                .expect("captured requests")
31758                .iter()
31759                .find(|request| request.path == path)
31760                .and_then(|request| request.control_protocol.clone())
31761        }
31762
31763        fn method_for(&self, path: &str) -> Option<String> {
31764            self.requests
31765                .lock()
31766                .expect("captured requests")
31767                .iter()
31768                .find(|request| request.path == path)
31769                .map(|request| request.method.clone())
31770        }
31771
31772        fn authorization_for(&self, path: &str) -> Option<String> {
31773            self.requests
31774                .lock()
31775                .expect("captured requests")
31776                .iter()
31777                .find(|request| request.path == path)
31778                .and_then(|request| request.authorization.clone())
31779        }
31780
31781        fn namespace_for(&self, path: &str) -> Option<String> {
31782            self.requests
31783                .lock()
31784                .expect("captured requests")
31785                .iter()
31786                .find(|request| request.path == path)
31787                .and_then(|request| request.namespace.clone())
31788        }
31789
31790        fn request_count(&self, path: &str) -> usize {
31791            self.requests
31792                .lock()
31793                .expect("captured requests")
31794                .iter()
31795                .filter(|request| request.path == path)
31796                .count()
31797        }
31798
31799        fn captured_paths(&self) -> Vec<String> {
31800            self.requests
31801                .lock()
31802                .expect("captured requests")
31803                .iter()
31804                .map(|request| request.path.clone())
31805                .collect()
31806        }
31807
31808        fn request_times(&self, path: &str) -> Vec<Instant> {
31809            self.requests
31810                .lock()
31811                .expect("captured requests")
31812                .iter()
31813                .filter(|request| request.path == path)
31814                .map(|request| request.received_at)
31815                .collect()
31816        }
31817
31818        fn request_body(&self, path: &str) -> Value {
31819            let requests = self.requests.lock().expect("captured requests");
31820            let body = &requests
31821                .iter()
31822                .find(|request| request.path == path)
31823                .unwrap_or_else(|| panic!("missing request for {path}"))
31824                .body;
31825            serde_json::from_str(body).unwrap_or_else(|error| {
31826                panic!("invalid JSON request body for {path}: {error}: {body:?}")
31827            })
31828        }
31829
31830        fn request_bodies(&self, path: &str) -> Vec<Value> {
31831            self.requests
31832                .lock()
31833                .expect("captured requests")
31834                .iter()
31835                .filter(|request| request.path == path)
31836                .map(|request| {
31837                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
31838                        panic!(
31839                            "invalid JSON request body for {path}: {error}: {:?}",
31840                            request.body
31841                        )
31842                    })
31843                })
31844                .collect()
31845        }
31846
31847        fn request_headers(&self, path: &str) -> Vec<String> {
31848            self.requests
31849                .lock()
31850                .expect("captured requests")
31851                .iter()
31852                .filter(|request| request.path == path)
31853                .map(|request| request.headers.clone())
31854                .collect()
31855        }
31856    }
31857
31858    impl Drop for MockWorkerServer {
31859        fn drop(&mut self) {
31860            self.stop.store(true, Ordering::SeqCst);
31861            let _ = TcpStream::connect(self.addr);
31862
31863            if let Some(thread) = self.thread.take() {
31864                thread.join().expect("join mock server");
31865            }
31866        }
31867    }
31868
31869    #[test]
31870    fn closed_mock_connection_is_not_a_worker_request() {
31871        let listener = TcpListener::bind("127.0.0.1:0").expect("bind closed connection control");
31872        let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
31873        let (mut stream, _) = listener.accept().unwrap();
31874        drop(client);
31875        let requests = Arc::new(Mutex::new(Vec::new()));
31876        handle_mock_worker_request(
31877            &mut stream,
31878            &requests,
31879            MockWorkerBehavior {
31880                request_override: Some(|_, _, _| {
31881                    panic!("closed connection cannot invoke an HTTP handler")
31882                }),
31883                ..MockWorkerBehavior::default()
31884            },
31885        );
31886        assert!(requests.lock().unwrap().is_empty());
31887    }
31888
31889    fn handle_mock_worker_request(
31890        stream: &mut TcpStream,
31891        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
31892        behavior: MockWorkerBehavior,
31893    ) {
31894        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
31895        let mut buffer = [0_u8; 8192];
31896        let mut request = Vec::new();
31897
31898        loop {
31899            match stream.read(&mut buffer) {
31900                Ok(0) => break,
31901                Ok(read) => {
31902                    request.extend_from_slice(&buffer[..read]);
31903                    if mock_request_is_complete(&request) {
31904                        break;
31905                    }
31906                }
31907                Err(error)
31908                    if matches!(
31909                        error.kind(),
31910                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
31911                    ) =>
31912                {
31913                    break;
31914                }
31915                Err(_) => return,
31916            }
31917        }
31918
31919        if !mock_request_is_complete(&request) {
31920            return;
31921        }
31922
31923        let request = String::from_utf8_lossy(&request);
31924        let body = request
31925            .split_once("\r\n\r\n")
31926            .map(|(_, body)| body)
31927            .unwrap_or_default();
31928        let path = request
31929            .lines()
31930            .next()
31931            .and_then(|line| line.split_whitespace().nth(1))
31932            .unwrap_or_default();
31933        let method = request
31934            .lines()
31935            .next()
31936            .and_then(|line| line.split_whitespace().next())
31937            .unwrap_or_default();
31938        let authorization = request.lines().find_map(|line| {
31939            let (name, value) = line.split_once(':')?;
31940            name.eq_ignore_ascii_case("Authorization")
31941                .then(|| value.trim().to_string())
31942        });
31943        let namespace = request.lines().find_map(|line| {
31944            let (name, value) = line.split_once(':')?;
31945            name.eq_ignore_ascii_case("X-Namespace")
31946                .then(|| value.trim().to_string())
31947        });
31948        let worker_protocol = request.lines().find_map(|line| {
31949            let (name, value) = line.split_once(':')?;
31950            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
31951                .then(|| value.trim().to_string())
31952        });
31953        let control_protocol = request.lines().find_map(|line| {
31954            let (name, value) = line.split_once(':')?;
31955            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
31956                .then(|| value.trim().to_string())
31957        });
31958        let request_number = {
31959            let mut requests = requests.lock().expect("captured requests");
31960            requests.push(CapturedRequest {
31961                headers: request
31962                    .split_once("\r\n\r\n")
31963                    .map_or("", |(headers, _)| headers)
31964                    .to_owned(),
31965                method: method.to_string(),
31966                path: path.to_string(),
31967                authorization,
31968                namespace,
31969                worker_protocol: worker_protocol.clone(),
31970                control_protocol,
31971                body: body.to_string(),
31972                received_at: Instant::now(),
31973            });
31974            requests
31975                .iter()
31976                .filter(|request| request.path == path)
31977                .count()
31978        };
31979
31980        if behavior
31981            .drop_request
31982            .is_some_and(|dropped| dropped(path, request_number))
31983        {
31984            return;
31985        }
31986        if let Some(response) = behavior
31987            .request_override
31988            .and_then(|handler| handler(path, body, request_number))
31989        {
31990            write_mock_response(stream, response.0, &response.1);
31991            return;
31992        }
31993        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
31994            write_mock_response(stream, response.0, &response.1);
31995            return;
31996        }
31997        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
31998            return;
31999        }
32000        let pressure_path = behavior
32001            .storage_path
32002            .is_some_and(|part| path.contains(part));
32003        let prior_failures = if path.ends_with("/poll") {
32004            behavior.poll_failures_per_path
32005        } else {
32006            0
32007        };
32008        if pressure_path
32009            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
32010        {
32011            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
32012            let poll_id = path
32013                .ends_with("/poll")
32014                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
32015            let mut refusal = storage_refusal(
32016                poll_id,
32017                behavior.storage_unavailable,
32018                behavior.storage_mid_poll,
32019            );
32020            if behavior.storage_wrong_poll_id {
32021                refusal["poll_request_id"] = json!("wrong-poll");
32022            }
32023            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
32024            return;
32025        }
32026        if path.contains("/storage-task/")
32027            || path.contains("/storage-activity/")
32028            || path.contains("/storage-query/")
32029        {
32030            write_mock_response(stream, "200 OK", "{}");
32031            return;
32032        }
32033        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
32034            write_mock_response(stream, "200 OK", &json!({"task":{
32035                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
32036                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
32037                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32038                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32039                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
32040            }}).to_string());
32041            return;
32042        }
32043        if behavior.storage_activity
32044            && path == "/api/worker/activity-tasks/poll"
32045            && request_number == 1
32046        {
32047            write_mock_response(stream, "200 OK", &json!({"task":{
32048                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
32049                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32050                "attempt_number":7, "lease_owner":"storage-worker"
32051            }}).to_string());
32052            return;
32053        }
32054
32055        if path == "/api/worker/register" {
32056            if behavior.reject_registration_protocol {
32057                write_mock_response(
32058                    stream,
32059                    "400 Bad Request",
32060                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
32061                );
32062                return;
32063            }
32064            if behavior.reject_registration {
32065                write_mock_response(
32066                    stream,
32067                    "503 Service Unavailable",
32068                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
32069                );
32070                return;
32071            }
32072        }
32073
32074        if path.starts_with("/api/worker/registrations/") {
32075            if behavior.reject_deregistration_protocol {
32076                write_mock_response(
32077                    stream,
32078                    "400 Bad Request",
32079                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
32080                );
32081            } else if behavior.reject_deregistration {
32082                write_mock_response(
32083                    stream,
32084                    "403 Forbidden",
32085                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
32086                );
32087            } else {
32088                write_mock_response(
32089                    stream,
32090                    "200 OK",
32091                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
32092                );
32093            }
32094            return;
32095        }
32096
32097        let is_poll = matches!(
32098            path,
32099            "/api/worker/workflow-tasks/poll"
32100                | "/api/worker/activity-tasks/poll"
32101                | "/api/worker/query-tasks/poll"
32102        );
32103        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
32104            write_mock_response(
32105                stream,
32106                "429 Too Many Requests",
32107                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
32108            );
32109            return;
32110        }
32111        if is_poll && request_number <= behavior.poll_failures_per_path {
32112            return;
32113        }
32114        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
32115            return;
32116        }
32117        if path == "/api/worker/heartbeat"
32118            && behavior.heartbeat_failure_request == Some(request_number)
32119        {
32120            return;
32121        }
32122        if path == "/api/worker/heartbeat"
32123            && behavior.delayed_heartbeat_request == Some(request_number)
32124        {
32125            thread::sleep(behavior.heartbeat_response_delay);
32126        }
32127        if behavior.unauthorized_polls && is_poll {
32128            write_mock_response(
32129                stream,
32130                "401 Unauthorized",
32131                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
32132            );
32133            return;
32134        }
32135        if behavior.draining_polls && is_poll {
32136            write_mock_response(
32137                stream,
32138                "409 Conflict",
32139                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
32140            );
32141            return;
32142        }
32143
32144        if let Some(codec_case) = behavior.invalid_task_payload_codec {
32145            if is_poll && request_number == 1 {
32146                let mut task = match path {
32147                    "/api/worker/workflow-tasks/poll" => json!({
32148                        "task_id": "codec-workflow",
32149                        "workflow_type": "codec.workflow",
32150                        "payload_codec": DEFAULT_CODEC,
32151                        "workflow_task_attempt": 1,
32152                        "lease_owner": "codec-worker"
32153                    }),
32154                    "/api/worker/activity-tasks/poll" => json!({
32155                        "task_id": "codec-activity",
32156                        "activity_attempt_id": "codec-activity-attempt",
32157                        "activity_type": "codec.activity",
32158                        "payload_codec": DEFAULT_CODEC,
32159                        "attempt_number": 1,
32160                        "lease_owner": "codec-worker"
32161                    }),
32162                    "/api/worker/query-tasks/poll" => json!({
32163                        "query_task_id": "codec-query",
32164                        "query_task_attempt": 1,
32165                        "workflow_type": "codec.workflow",
32166                        "query_name": "known",
32167                        "payload_codec": DEFAULT_CODEC,
32168                        "lease_owner": "codec-worker"
32169                    }),
32170                    _ => unreachable!("is_poll limits task codec probe paths"),
32171                };
32172                codec_case.apply(&mut task);
32173                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
32174                return;
32175            }
32176
32177            if matches!(
32178                path,
32179                "/api/worker/workflow-tasks/codec-workflow/fail"
32180                    | "/api/worker/activity-tasks/codec-activity/fail"
32181                    | "/api/worker/query-tasks/codec-query/fail"
32182            ) {
32183                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
32184                return;
32185            }
32186        }
32187
32188        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
32189            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
32190            let body = format!(
32191                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
32192            );
32193            write_mock_response(stream, "400 Bad Request", &body);
32194            return;
32195        }
32196
32197        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
32198        {
32199            write_mock_response(
32200                stream,
32201                "409 Conflict",
32202                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
32203            );
32204            return;
32205        }
32206
32207        if behavior.workflow_completion_status.is_some()
32208            && path == "/api/worker/workflow-tasks/poll"
32209            && request_number == 1
32210        {
32211            write_mock_response(
32212                stream,
32213                "200 OK",
32214                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"}}"#,
32215            );
32216            return;
32217        }
32218
32219        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
32220            if let (Some(status), Some(body)) = (
32221                behavior.workflow_completion_status,
32222                behavior.workflow_completion_body,
32223            ) {
32224                write_mock_response(stream, status, body);
32225                return;
32226            }
32227        }
32228
32229        if behavior.waiting_query_worker {
32230            if behavior.complete_named_signal
32231                && path == "/api/worker/workflow-tasks/poll"
32232                && request_number == 1
32233            {
32234                let body = json!({
32235                    "task": {
32236                        "task_id": "snapshot-open",
32237                        "workflow_id": "snapshot-1",
32238                        "run_id": "snapshot-run-1",
32239                        "workflow_type": "snapshot",
32240                        "payload_codec": DEFAULT_CODEC,
32241                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32242                            .expect("Avro workflow arguments"),
32243                        "history_events": [],
32244                        "workflow_task_attempt": 1,
32245                        "lease_owner": "rust-snapshot-worker"
32246                    }
32247                })
32248                .to_string();
32249                write_mock_response(stream, "200 OK", &body);
32250                return;
32251            }
32252
32253            let signal_request = request_number - usize::from(behavior.complete_named_signal);
32254            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
32255            if path == "/api/worker/workflow-tasks/poll"
32256                && signal_request >= 1
32257                && signal_request <= signal_request_limit
32258            {
32259                let finish = behavior.complete_named_signal && signal_request == 3;
32260                let amounts = if signal_request == 1 {
32261                    vec![3]
32262                } else {
32263                    vec![3, 5]
32264                };
32265                let task_id = if signal_request == 1 {
32266                    "snapshot-wait-3"
32267                } else if finish {
32268                    "snapshot-finish"
32269                } else {
32270                    "snapshot-wait-5"
32271                };
32272                let mut history_events = std::iter::once(json!({
32273                    "event_type": "SignalWaitOpened",
32274                    "payload": {"sequence": 1, "signal_name": "finish"}
32275                }))
32276                .chain(amounts.iter().enumerate().map(|(index, amount)| {
32277                    json!({
32278                        "event_type": "SignalReceived",
32279                        "payload": {
32280                            "signal_id": format!("increment-{amount}"),
32281                            "signal_name": "increment",
32282                            "workflow_sequence": index + 2,
32283                            "payload_codec": DEFAULT_CODEC,
32284                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32285                                .expect("Avro signal envelope")
32286                        }
32287                    })
32288                }))
32289                .collect::<Vec<_>>();
32290                let (resume_id, resume_name, resume_arguments) = if finish {
32291                    history_events.push(json!({
32292                        "event_type": "SignalReceived",
32293                        "payload": {
32294                            "signal_id": "finish",
32295                            "signal_name": "finish",
32296                            "workflow_sequence": 4,
32297                            "payload_codec": DEFAULT_CODEC,
32298                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32299                                .expect("Avro finish signal envelope")
32300                        }
32301                    }));
32302                    (
32303                        "finish".to_string(),
32304                        "finish".to_string(),
32305                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
32306                            .expect("Avro finish resume signal"),
32307                    )
32308                } else {
32309                    let amount = amounts.last().expect("amount");
32310                    (
32311                        format!("increment-{amount}"),
32312                        "increment".to_string(),
32313                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32314                            .expect("Avro increment resume signal"),
32315                    )
32316                };
32317                let body = json!({
32318                    "task": {
32319                        "task_id": task_id,
32320                        "workflow_id": "snapshot-1",
32321                        "run_id": "snapshot-run-1",
32322                        "workflow_type": "snapshot",
32323                        "payload_codec": DEFAULT_CODEC,
32324                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32325                            .expect("Avro workflow arguments"),
32326                        "history_events": history_events,
32327                        "workflow_task_attempt": 1,
32328                        "workflow_signal_id": resume_id,
32329                        "signal_name": resume_name,
32330                        "signal_arguments": resume_arguments,
32331                        "lease_owner": "rust-snapshot-worker"
32332                    }
32333                })
32334                .to_string();
32335                write_mock_response(stream, "200 OK", &body);
32336                return;
32337            }
32338
32339            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
32340                let history_events = [3, 5]
32341                    .into_iter()
32342                    .enumerate()
32343                    .map(|(index, amount)| {
32344                        json!({
32345                            "event_type": "SignalReceived",
32346                            "payload": {
32347                                "signal_id": format!("increment-{amount}"),
32348                                "signal_name": "increment",
32349                                "workflow_sequence": index + 2,
32350                                "payload_codec": DEFAULT_CODEC,
32351                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32352                                    .expect("Avro query signal envelope")
32353                            }
32354                        })
32355                    })
32356                    .collect::<Vec<_>>();
32357                let body = json!({
32358                    "task": {
32359                        "query_task_id": "snapshot-current",
32360                        "query_task_attempt": 1,
32361                        "lease_owner": "rust-snapshot-worker",
32362                        "workflow_id": "snapshot-1",
32363                        "run_id": "snapshot-run-1",
32364                        "workflow_type": "snapshot",
32365                        "query_name": "current",
32366                        "payload_codec": DEFAULT_CODEC,
32367                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32368                            .expect("Avro workflow arguments"),
32369                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32370                            .expect("Avro query arguments"),
32371                        "history_events": history_events,
32372                        "run_status": "waiting"
32373                    }
32374                })
32375                .to_string();
32376                write_mock_response(stream, "200 OK", &body);
32377                return;
32378            }
32379
32380            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
32381                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
32382            {
32383                write_mock_response(
32384                    stream,
32385                    "200 OK",
32386                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
32387                );
32388                return;
32389            }
32390
32391            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
32392                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
32393                return;
32394            }
32395
32396            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
32397                write_mock_response(
32398                    stream,
32399                    "200 OK",
32400                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
32401                );
32402                return;
32403            }
32404
32405            if path == "/api/worker/query-tasks/snapshot-current/complete" {
32406                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
32407                return;
32408            }
32409        }
32410
32411        if matches!(
32412            path,
32413            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
32414        ) {
32415            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
32416                .expect("typed mock result");
32417            let body = json!({
32418                "result": typed_fidelity_probe().into_json().expect("result projection"),
32419                "result_envelope": result,
32420            })
32421            .to_string();
32422            write_mock_response(stream, "200 OK", &body);
32423            return;
32424        }
32425
32426        if path == "/api/workflows/typed-1" {
32427            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
32428                .expect("typed mock result");
32429            let body = json!({
32430                "workflow_id": "typed-1",
32431                "run_id": "run-typed-1",
32432                "workflow_type": "typed.echo",
32433                "status": "completed",
32434                "output": typed_fidelity_probe().into_json().expect("output projection"),
32435                "output_envelope": result,
32436            })
32437            .to_string();
32438            write_mock_response(stream, "200 OK", &body);
32439            return;
32440        }
32441
32442        let (status, body) = match path {
32443            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
32444            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
32445            "/api/workflows" => (
32446                "201 Created",
32447                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
32448            ),
32449            "/api/worker/register" if behavior.decline_registration => (
32450                "200 OK",
32451                r#"{"worker_id":"declined-worker","registered":false}"#,
32452            ),
32453            "/api/worker/register" if behavior.waiting_query_worker => (
32454                "200 OK",
32455                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
32456            ),
32457            "/api/worker/register" => (
32458                "200 OK",
32459                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
32460            ),
32461            "/api/worker/heartbeat" => ("200 OK", "{}"),
32462            "/api/worker/activity-tasks/poll"
32463                if behavior.cancelled_activity && request_number == 1 =>
32464            {
32465                (
32466                    "200 OK",
32467                    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"}}"#,
32468                )
32469            }
32470            "/api/worker/activity-tasks/poll"
32471                if behavior.long_poll_capacity_responses_per_path > 0
32472                    && request_number
32473                        == behavior
32474                            .long_poll_capacity_responses_per_path
32475                            .saturating_add(1) =>
32476            {
32477                (
32478                    "200 OK",
32479                    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"}}"#,
32480                )
32481            }
32482            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
32483                ("200 OK", r#"{"task":null}"#)
32484            }
32485            "/api/worker/query-tasks/poll"
32486                if behavior.reject_query_completion && request_number == 1 =>
32487            {
32488                (
32489                    "200 OK",
32490                    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"}}"#,
32491                )
32492            }
32493            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
32494            "/api/worker/query-tasks/query-capture/complete"
32495            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
32496            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
32497                "200 OK",
32498                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
32499            ),
32500            "/api/worker/activity-tasks/activity-cancel/complete" => (
32501                "409 Conflict",
32502                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
32503            ),
32504            "/api/worker/activity-tasks/activity-typed/complete"
32505            | "/api/worker/activity-tasks/activity-typed/fail"
32506            | "/api/worker/activity-tasks/capacity-activity/complete"
32507            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
32508            "/api/workflows/counter-1/query/current" => (
32509                "200 OK",
32510                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
32511            ),
32512            "/api/workflows/counter-1/query/missing" => (
32513                "404 Not Found",
32514                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
32515            ),
32516            "/api/workflows/wf-lifecycle/cancel" => (
32517                "200 OK",
32518                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
32519            ),
32520            "/api/workflows/wf-lifecycle/terminate" => (
32521                "200 OK",
32522                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
32523            ),
32524            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
32525                "200 OK",
32526                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
32527            ),
32528            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
32529                "200 OK",
32530                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
32531            ),
32532            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
32533                "202 Accepted",
32534                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
32535            ),
32536            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
32537                "200 OK",
32538                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}"#,
32539            ),
32540            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
32541                "409 Conflict",
32542                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
32543            ),
32544            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
32545            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
32546                "409 Conflict",
32547                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
32548            ),
32549            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
32550                "200 OK",
32551                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"}]}}"#,
32552            ),
32553            "/api/workflows/wf-cancelled" => (
32554                "200 OK",
32555                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
32556            ),
32557            "/api/workflows/wf-terminated" => (
32558                "200 OK",
32559                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
32560            ),
32561            "/api/workflows/wf-timed-out" => (
32562                "200 OK",
32563                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
32564            ),
32565            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
32566                "200 OK",
32567                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
32568            ),
32569            "/api/workflows/wf-selected" => (
32570                "200 OK",
32571                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
32572            ),
32573            "/api/workflows/wf-selected/runs/run-selected" => (
32574                "200 OK",
32575                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
32576            ),
32577            _ => ("404 Not Found", r#"{"message":"not found"}"#),
32578        };
32579        write_mock_response(stream, status, body);
32580    }
32581
32582    fn mock_request_is_complete(request: &[u8]) -> bool {
32583        let Some(header_end) = request
32584            .windows(4)
32585            .position(|window| window == b"\r\n\r\n")
32586            .map(|position| position + 4)
32587        else {
32588            return false;
32589        };
32590        let headers = String::from_utf8_lossy(&request[..header_end]);
32591        let content_length = headers.lines().find_map(|line| {
32592            let (name, value) = line.split_once(':')?;
32593            name.eq_ignore_ascii_case("content-length")
32594                .then(|| value.trim().parse::<usize>().ok())
32595                .flatten()
32596        });
32597
32598        request.len() >= header_end + content_length.unwrap_or(0)
32599    }
32600
32601    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
32602        let response = format!(
32603            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
32604            body.len()
32605        );
32606
32607        let _ = stream.write_all(response.as_bytes());
32608        let _ = stream.flush();
32609    }
32610
32611    fn typed_activity_failure_server(
32612        path: &str,
32613        _body: &str,
32614        request_number: usize,
32615    ) -> Option<(&'static str, String)> {
32616        match path {
32617            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
32618                "200 OK",
32619                r#"{"task":{"task_id":"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(),
32620            )),
32621            "/api/worker/activity-tasks/typed-failure/fail" => Some(("200 OK", "{}".into())),
32622            _ => None,
32623        }
32624    }
32625
32626    #[tokio::test]
32627    async fn managed_activity_reports_application_type_and_non_retryable_marker() {
32628        for non_retryable in [false, true] {
32629            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32630                request_override: Some(typed_activity_failure_server),
32631                ..MockWorkerBehavior::default()
32632            });
32633            let client = Client::builder(server.base_url()).build().unwrap();
32634            let mut worker = Worker::new(client, "typed-queue").worker_id("typed-worker");
32635            worker.register_activity("typed.failure", move |_, _| async move {
32636                Err(ActivityError::new("PaymentDeclined", "card declined")
32637                    .non_retryable(non_retryable)
32638                    .into())
32639            });
32640            assert_eq!(worker.run_once().await.unwrap(), 1);
32641            assert_eq!(
32642                server.request_body("/api/worker/activity-tasks/typed-failure/fail"),
32643                json!({
32644                    "activity_attempt_id": "typed-attempt",
32645                    "lease_owner": "typed-worker",
32646                    "failure": {"type": "PaymentDeclined", "message": "card declined",
32647                                "non_retryable": non_retryable}
32648                })
32649            );
32650        }
32651    }
32652
32653    fn activity_completion_backend_recovery(
32654        path: &str,
32655        _body: &str,
32656        request_number: usize,
32657    ) -> Option<(&'static str, String)> {
32658        match path {
32659            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
32660                "200 OK",
32661                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(),
32662            )),
32663            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
32664                "503 Service Unavailable",
32665                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(),
32666            )),
32667            "/api/worker/activity-tasks/recover-activity/complete" => Some((
32668                "200 OK",
32669                r#"{"outcome":"completed","recorded":true}"#.to_string(),
32670            )),
32671            _ => None,
32672        }
32673    }
32674
32675    fn workflow_completion_backend_recovery(
32676        path: &str,
32677        _body: &str,
32678        request_number: usize,
32679    ) -> Option<(&'static str, String)> {
32680        match path {
32681            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
32682                "200 OK",
32683                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
32684            )),
32685            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
32686                "503 Service Unavailable",
32687                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(),
32688            )),
32689            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
32690                "200 OK",
32691                r#"{"outcome":"completed","recorded":true}"#.to_string(),
32692            )),
32693            _ => None,
32694        }
32695    }
32696
32697    fn workflow_completion_lock_pressure(
32698        path: &str,
32699        body: &str,
32700        request_number: usize,
32701    ) -> Option<(&'static str, String)> {
32702        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number == 1 {
32703            return Some((
32704                "503 Service Unavailable",
32705                json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
32706                    "outcome":"deferred", "recorded":false, "retryable":true,
32707                    "retry_after_seconds":1, "task_id":"recover-workflow",
32708                    "lease_owner":"recover-worker", "workflow_task_attempt":3,
32709                    "backend":{"driver":"sqlite", "lock_pressure":true}})
32710                .to_string(),
32711            ));
32712        }
32713        workflow_completion_backend_recovery(path, body, request_number)
32714    }
32715
32716    fn workflow_completion_lock_pressure_forever(
32717        path: &str,
32718        body: &str,
32719        request_number: usize,
32720    ) -> Option<(&'static str, String)> {
32721        if path == "/api/worker/workflow-tasks/recover-workflow/complete" {
32722            return workflow_completion_lock_pressure(path, body, 1);
32723        }
32724        workflow_completion_lock_pressure(path, body, request_number)
32725    }
32726
32727    fn workflow_completion_lock_pressure_then_expired(
32728        path: &str,
32729        body: &str,
32730        request_number: usize,
32731    ) -> Option<(&'static str, String)> {
32732        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32733            return Some(("409 Conflict", json!({"reason":"lease_expired", "recorded":false,
32734                "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3}).to_string()));
32735        }
32736        workflow_completion_lock_pressure(path, body, request_number)
32737    }
32738
32739    fn workflow_completion_lock_pressure_then_slow(
32740        path: &str,
32741        body: &str,
32742        request_number: usize,
32743    ) -> Option<(&'static str, String)> {
32744        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32745            thread::sleep(Duration::from_secs(2));
32746        }
32747        workflow_completion_lock_pressure(path, body, request_number)
32748    }
32749
32750    fn workflow_completion_pressure_then_backend_loss(
32751        path: &str,
32752        body: &str,
32753        request_number: usize,
32754    ) -> Option<(&'static str, String)> {
32755        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32756            return Some((
32757                "503 Service Unavailable",
32758                json!({"reason":"backend_unavailable", "operation":"complete_workflow_task",
32759                    "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
32760                    "retryable":true, "retry_after_seconds":3, "task_id":"recover-workflow",
32761                    "lease_owner":"recover-worker", "workflow_task_attempt":3})
32762                .to_string(),
32763            ));
32764        }
32765        workflow_completion_lock_pressure(path, body, request_number)
32766    }
32767
32768    fn completion_deferral_worker(server: &MockWorkerServer, calls: Arc<AtomicUsize>) -> Worker {
32769        let client = Client::builder(server.base_url())
32770            .timeout(Duration::from_secs(4))
32771            .build()
32772            .unwrap();
32773        let mut worker = Worker::new(client, "recover-queue")
32774            .worker_id("recover-worker")
32775            .poll_timeout(Duration::from_millis(10));
32776        worker.register_workflow("recover.workflow", move |_ctx, _args| {
32777            let calls = Arc::clone(&calls);
32778            async move {
32779                calls.fetch_add(1, Ordering::SeqCst);
32780                Ok(json!("done"))
32781            }
32782        });
32783        worker
32784    }
32785
32786    #[tokio::test]
32787    async fn workflow_completion_deferral_stops_at_original_cleanup_budget() {
32788        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32789            request_override: Some(workflow_completion_lock_pressure_forever),
32790            ..MockWorkerBehavior::default()
32791        });
32792        let calls = Arc::new(AtomicUsize::new(0));
32793        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32794            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32795        worker
32796            .client
32797            .worker_storage_admission
32798            .as_mut()
32799            .unwrap()
32800            .workflow_completion_retry_deadline =
32801            Some(tokio::time::Instant::now() + Duration::from_millis(250));
32802        let result = tokio::time::timeout(Duration::from_secs(2), worker.poll_workflow_once())
32803            .await
32804            .unwrap();
32805        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32806        assert_eq!(calls.load(Ordering::SeqCst), 1);
32807        assert_eq!(
32808            server
32809                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32810                .len(),
32811            1
32812        );
32813    }
32814
32815    #[tokio::test]
32816    async fn workflow_completion_deferral_bounds_the_inflight_retry() {
32817        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32818            request_override: Some(workflow_completion_lock_pressure_then_slow),
32819            ..MockWorkerBehavior::default()
32820        });
32821        let calls = Arc::new(AtomicUsize::new(0));
32822        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32823            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32824        let start = tokio::time::Instant::now();
32825        worker
32826            .client
32827            .worker_storage_admission
32828            .as_mut()
32829            .unwrap()
32830            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
32831        assert!(matches!(
32832            worker.poll_workflow_once().await,
32833            Err(Error::Timeout)
32834        ));
32835        assert!(start.elapsed() < Duration::from_secs(2));
32836        assert_eq!(calls.load(Ordering::SeqCst), 1);
32837        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32838        assert_eq!(bodies.len(), 2);
32839        assert_eq!(bodies[0], bodies[1]);
32840    }
32841
32842    #[tokio::test]
32843    async fn workflow_completion_deferral_retains_deadline_when_backend_reason_changes() {
32844        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32845            request_override: Some(workflow_completion_pressure_then_backend_loss),
32846            ..MockWorkerBehavior::default()
32847        });
32848        let calls = Arc::new(AtomicUsize::new(0));
32849        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32850            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32851        let start = tokio::time::Instant::now();
32852        worker
32853            .client
32854            .worker_storage_admission
32855            .as_mut()
32856            .unwrap()
32857            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
32858        let result = worker.poll_workflow_once().await;
32859        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32860        assert!(start.elapsed() < Duration::from_secs(2));
32861        assert_eq!(calls.load(Ordering::SeqCst), 1);
32862        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32863        assert_eq!(bodies.len(), 2);
32864        assert_eq!(bodies[0], bodies[1]);
32865    }
32866
32867    #[tokio::test]
32868    async fn workflow_completion_deferral_shutdown_interrupts_prolonged_pressure() {
32869        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32870            request_override: Some(workflow_completion_lock_pressure_forever),
32871            ..MockWorkerBehavior::default()
32872        });
32873        let calls = Arc::new(AtomicUsize::new(0));
32874        let stop = Arc::new(AtomicBool::new(false));
32875        let worker = completion_deferral_worker(&server, Arc::clone(&calls))
32876            .with_storage_admission(Arc::clone(&stop));
32877        let shutdown = async {
32878            while server
32879                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32880                .is_empty()
32881            {
32882                tokio::time::sleep(Duration::from_millis(10)).await;
32883            }
32884            stop.store(true, Ordering::SeqCst);
32885        };
32886        let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
32887            tokio::join!(worker.poll_workflow_once(), shutdown)
32888        })
32889        .await
32890        .unwrap();
32891        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32892        assert_eq!(calls.load(Ordering::SeqCst), 1);
32893        assert_eq!(
32894            server
32895                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32896                .len(),
32897            1
32898        );
32899    }
32900
32901    #[tokio::test]
32902    async fn workflow_completion_deferral_preserves_later_expiry_refusal() {
32903        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32904            request_override: Some(workflow_completion_lock_pressure_then_expired),
32905            ..MockWorkerBehavior::default()
32906        });
32907        let calls = Arc::new(AtomicUsize::new(0));
32908        let worker = completion_deferral_worker(&server, Arc::clone(&calls));
32909        let result = worker.run_once().await;
32910        assert!(
32911            matches!(result, Err(Error::Http { status, ref body }) if status.as_u16() == 409 && body.contains("lease_expired"))
32912        );
32913        assert_eq!(calls.load(Ordering::SeqCst), 1);
32914        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32915        assert_eq!(bodies.len(), 2);
32916        assert_eq!(bodies[0], bodies[1]);
32917        assert!(server
32918            .request_bodies("/api/worker/workflow-tasks/recover-workflow/fail")
32919            .is_empty());
32920    }
32921
32922    #[tokio::test]
32923    async fn managed_workflow_completion_deferral_preserves_bytes_and_server_delay() {
32924        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32925            request_override: Some(workflow_completion_lock_pressure),
32926            ..MockWorkerBehavior::default()
32927        });
32928        let client = Client::builder(server.base_url())
32929            .timeout(Duration::from_secs(2))
32930            .build()
32931            .unwrap();
32932        let calls = Arc::new(AtomicUsize::new(0));
32933        let mut worker = Worker::new(client, "recover-queue")
32934            .worker_id("recover-worker")
32935            .recover_transient_outages(true)
32936            .poll_timeout(Duration::from_millis(10))
32937            .retry_policy(WorkerRetryPolicy {
32938                max_retries: 1,
32939                initial_backoff: Duration::from_millis(10),
32940                max_backoff: Duration::from_millis(10),
32941            });
32942        worker.register_workflow("recover.workflow", {
32943            let calls = Arc::clone(&calls);
32944            move |_ctx, _args| {
32945                let calls = Arc::clone(&calls);
32946                async move {
32947                    calls.fetch_add(1, Ordering::SeqCst);
32948                    Ok(json!("done"))
32949                }
32950            }
32951        });
32952        let start = tokio::time::Instant::now();
32953        assert_eq!(worker.run_once().await.unwrap(), 1);
32954        assert!(start.elapsed() >= Duration::from_secs(1));
32955        assert_eq!(calls.load(Ordering::SeqCst), 1);
32956        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32957        assert_eq!(bodies.len(), 2);
32958        assert_eq!(bodies[0], bodies[1]);
32959    }
32960
32961    #[test]
32962    fn workflow_completion_deferral_requires_an_exact_unrecorded_fence() {
32963        let path = "/worker/workflow-tasks/recover-workflow/complete";
32964        let request = json!({"lease_owner":"recover-worker", "workflow_task_attempt":3});
32965        let response = json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
32966            "outcome":"deferred", "recorded":false, "retryable":true, "retry_after_seconds":1,
32967            "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3,
32968            "backend":{"driver":"sqlite", "lock_pressure":true}});
32969        let error = |body: Value| Error::Http {
32970            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
32971            body: body.to_string(),
32972        };
32973        assert_eq!(
32974            worker_deferred_workflow_completion_retry_after(
32975                &error(response.clone()),
32976                path,
32977                Some(&request)
32978            ),
32979            Some(Duration::from_secs(1))
32980        );
32981        for (field, value) in [
32982            ("reason", json!("backend_unavailable")),
32983            ("operation", json!("complete_activity_task")),
32984            ("task_id", json!("other-task")),
32985            ("lease_owner", json!("other-owner")),
32986            ("workflow_task_attempt", json!(4)),
32987            ("recorded", json!(true)),
32988            ("recorded", Value::Null),
32989            ("recorded", json!("false")),
32990            ("retryable", json!(false)),
32991            ("retry_after_seconds", json!(0)),
32992            ("retry_after_seconds", json!(-1)),
32993            ("retry_after_seconds", json!(1.0)),
32994            ("retry_after_seconds", json!("1")),
32995            ("retry_after_seconds", json!(6)),
32996            ("backend", json!({"lock_pressure":false})),
32997        ] {
32998            let mut invalid = response.clone();
32999            invalid[field] = value;
33000            assert_eq!(
33001                worker_deferred_workflow_completion_retry_after(
33002                    &error(invalid),
33003                    path,
33004                    Some(&request)
33005                ),
33006                None,
33007                "invalid {field}"
33008            );
33009        }
33010        for field in [
33011            "reason",
33012            "operation",
33013            "task_id",
33014            "lease_owner",
33015            "workflow_task_attempt",
33016            "recorded",
33017            "retryable",
33018            "retry_after_seconds",
33019            "backend",
33020        ] {
33021            let mut missing = response.clone();
33022            missing.as_object_mut().unwrap().remove(field);
33023            assert_eq!(
33024                worker_deferred_workflow_completion_retry_after(
33025                    &error(missing),
33026                    path,
33027                    Some(&request)
33028                ),
33029                None,
33030                "missing {field}"
33031            );
33032        }
33033        assert_eq!(
33034            worker_deferred_workflow_completion_retry_after(
33035                &error(response.clone()),
33036                "/worker/activity-tasks/recover-workflow/complete",
33037                Some(&request)
33038            ),
33039            None
33040        );
33041        assert_eq!(
33042            worker_deferred_workflow_completion_retry_after(&error(response.clone()), path, None),
33043            None
33044        );
33045        let wrong_status = Error::Http {
33046            status: reqwest::StatusCode::CONFLICT,
33047            body: response.to_string(),
33048        };
33049        assert_eq!(
33050            worker_deferred_workflow_completion_retry_after(&wrong_status, path, Some(&request)),
33051            None
33052        );
33053    }
33054
33055    fn activity_completion_stale_after_backend_recovery(
33056        path: &str,
33057        body: &str,
33058        request_number: usize,
33059    ) -> Option<(&'static str, String)> {
33060        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
33061            return Some((
33062                "409 Conflict",
33063                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(),
33064            ));
33065        }
33066        activity_completion_backend_recovery(path, body, request_number)
33067    }
33068
33069    fn activity_completion_remains_unavailable(
33070        path: &str,
33071        body: &str,
33072        request_number: usize,
33073    ) -> Option<(&'static str, String)> {
33074        if path == "/api/worker/activity-tasks/recover-activity/complete" {
33075            return activity_completion_backend_recovery(path, body, 1);
33076        }
33077        activity_completion_backend_recovery(path, body, request_number)
33078    }
33079
33080    #[tokio::test]
33081    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
33082        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33083            request_override: Some(activity_completion_backend_recovery),
33084            ..MockWorkerBehavior::default()
33085        });
33086        let client = Client::builder(server.base_url())
33087            .timeout(Duration::from_secs(2))
33088            .build()
33089            .expect("client");
33090        let handler_calls = Arc::new(AtomicUsize::new(0));
33091        let mut worker = Worker::new(client, "recover-queue")
33092            .worker_id("recover-worker")
33093            .poll_timeout(Duration::from_millis(10));
33094        worker.register_activity("recover.activity", {
33095            let handler_calls = Arc::clone(&handler_calls);
33096            move |_ctx, _args| {
33097                let handler_calls = Arc::clone(&handler_calls);
33098                async move {
33099                    handler_calls.fetch_add(1, Ordering::SeqCst);
33100                    Ok(json!("done"))
33101                }
33102            }
33103        });
33104
33105        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
33106        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33107        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
33108        assert_eq!(bodies.len(), 2);
33109        assert_eq!(bodies[0], bodies[1]);
33110    }
33111
33112    #[tokio::test]
33113    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
33114        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33115            request_override: Some(workflow_completion_backend_recovery),
33116            ..MockWorkerBehavior::default()
33117        });
33118        let client = Client::builder(server.base_url())
33119            .timeout(Duration::from_secs(2))
33120            .build()
33121            .expect("client");
33122        let handler_calls = Arc::new(AtomicUsize::new(0));
33123        let mut worker = Worker::new(client, "recover-queue")
33124            .worker_id("recover-worker")
33125            .poll_timeout(Duration::from_millis(10));
33126        worker.register_workflow("recover.workflow", {
33127            let handler_calls = Arc::clone(&handler_calls);
33128            move |_ctx, _args| {
33129                let handler_calls = Arc::clone(&handler_calls);
33130                async move {
33131                    handler_calls.fetch_add(1, Ordering::SeqCst);
33132                    Ok(json!("done"))
33133                }
33134            }
33135        });
33136
33137        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
33138        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33139        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
33140        assert_eq!(bodies.len(), 2);
33141        assert_eq!(bodies[0], bodies[1]);
33142    }
33143
33144    #[tokio::test]
33145    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
33146        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33147            request_override: Some(activity_completion_stale_after_backend_recovery),
33148            ..MockWorkerBehavior::default()
33149        });
33150        let client = Client::builder(server.base_url())
33151            .timeout(Duration::from_secs(2))
33152            .build()
33153            .expect("client");
33154        let handler_calls = Arc::new(AtomicUsize::new(0));
33155        let mut worker = Worker::new(client, "recover-queue")
33156            .worker_id("recover-worker")
33157            .poll_timeout(Duration::from_millis(10));
33158        worker.register_activity("recover.activity", {
33159            let handler_calls = Arc::clone(&handler_calls);
33160            move |_ctx, _args| {
33161                let handler_calls = Arc::clone(&handler_calls);
33162                async move {
33163                    handler_calls.fetch_add(1, Ordering::SeqCst);
33164                    Ok(json!("done"))
33165                }
33166            }
33167        });
33168
33169        assert_eq!(
33170            worker
33171                .run_once()
33172                .await
33173                .expect("authoritative stale outcome"),
33174            1
33175        );
33176        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33177        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
33178        assert_eq!(bodies.len(), 2);
33179        assert_eq!(bodies[0], bodies[1]);
33180    }
33181
33182    #[test]
33183    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
33184        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
33185        let response = json!({
33186            "reason":"backend_unavailable", "operation":"complete_activity_task",
33187            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
33188            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
33189            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
33190        });
33191        let path = "/worker/activity-tasks/recover-activity/complete";
33192        let error = |body: Value| Error::Http {
33193            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33194            body: body.to_string(),
33195        };
33196        assert_eq!(
33197            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
33198            Some(Duration::from_secs(1))
33199        );
33200
33201        for (field, invalid) in [
33202            ("operation", json!("poll_activity_task")),
33203            ("outcome", json!("rejected")),
33204            ("worker_id", json!("another-worker")),
33205            ("task_queue", json!("recover-queue")),
33206            ("retryable", json!(false)),
33207            ("retry_after_seconds", json!(0)),
33208            ("task_id", json!("another-task")),
33209            ("lease_owner", json!("another-worker")),
33210            ("activity_attempt_id", json!("another-attempt")),
33211        ] {
33212            let mut invalid_response = response.clone();
33213            invalid_response[field] = invalid;
33214            assert_eq!(
33215                worker_fenced_completion_retry_after(
33216                    &error(invalid_response),
33217                    path,
33218                    Some(&request)
33219                ),
33220                None,
33221                "must not retry mismatched {field}"
33222            );
33223        }
33224        assert_eq!(
33225            worker_fenced_completion_retry_after(&error(response), path, None),
33226            None
33227        );
33228    }
33229
33230    #[tokio::test]
33231    async fn shutdown_interrupts_fenced_completion_backend_wait() {
33232        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33233            request_override: Some(activity_completion_remains_unavailable),
33234            ..MockWorkerBehavior::default()
33235        });
33236        let client = Client::builder(server.base_url())
33237            .timeout(Duration::from_secs(2))
33238            .build()
33239            .expect("client");
33240        let stop = Arc::new(AtomicBool::new(false));
33241        let worker = Worker::new(client, "recover-queue")
33242            .worker_id("recover-worker")
33243            .with_storage_admission(Arc::clone(&stop));
33244        let completion = tokio::spawn(async move {
33245            worker
33246                .client
33247                .complete_activity_task(
33248                    "recover-activity",
33249                    "recover-attempt",
33250                    "recover-worker",
33251                    json!("done"),
33252                    DEFAULT_CODEC,
33253                )
33254                .await
33255        });
33256        let path = "/api/worker/activity-tasks/recover-activity/complete";
33257        tokio::time::timeout(Duration::from_secs(2), async {
33258            while server.request_count(path) == 0 {
33259                tokio::time::sleep(Duration::from_millis(10)).await;
33260            }
33261        })
33262        .await
33263        .expect("first completion request");
33264        stop.store(true, Ordering::SeqCst);
33265        let error = tokio::time::timeout(Duration::from_secs(1), completion)
33266            .await
33267            .expect("shutdown must interrupt retry wait")
33268            .expect("completion task")
33269            .expect_err("backend is still unavailable");
33270        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
33271        assert_eq!(server.request_count(path), 1);
33272    }
33273}