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 activity_retry;
7mod cancellation_context;
8mod cancellation_replay_clock;
9mod cancellation_scope;
10mod cancellation_scope_history;
11mod cancellation_scope_replay;
12mod cooperative_cancellation;
13mod local_activity;
14pub mod metrics;
15mod nexus;
16pub mod pagination;
17mod query_authority;
18mod runtime_payloads;
19mod runtime_uploads;
20mod sticky_worker;
21mod sticky_workflow_cache;
22#[cfg(feature = "telemetry")]
23pub mod telemetry;
24pub mod testing;
25pub use pagination::{
26    PaginationError, WorkflowHistoryIterator, WorkflowHistoryOptions, WorkflowHistoryPage,
27    WorkflowIterator, WorkflowListOptions, WorkflowListPage, WorkflowSummary,
28};
29mod tls;
30mod worker_capacity;
31mod worker_session;
32mod workflow_hydration;
33
34pub use activity_error::ActivityError;
35pub use activity_retry::{ActivityAttemptLimit, ActivityRetryInfo};
36pub use cancellation_context::{
37    CancellationContext, CancellationLineage, ScopedCancellationContext, ScopedCancellationLineage,
38};
39pub use cancellation_scope::CancellationScopeOpenReceipt;
40#[doc(hidden)]
41pub use cancellation_scope_history::{
42    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
43};
44#[doc(hidden)]
45pub use cancellation_scope_replay::CancellationScopeRequested;
46
47pub use cooperative_cancellation::{
48    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
49    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
50    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
51    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
52};
53
54use std::{
55    any::{type_name, Any, TypeId},
56    collections::{BTreeMap, BTreeSet, HashMap},
57    future::Future,
58    io::{self, Read},
59    pin::Pin,
60    sync::{
61        atomic::{AtomicBool, Ordering},
62        Arc, Mutex, OnceLock,
63    },
64    task::{Context as TaskContext, Poll},
65    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
66};
67
68use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
69use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
70use chrono::DateTime;
71use futures_util::{future::OptionFuture, task::noop_waker_ref};
72pub use local_activity::LocalActivityOptions;
73use serde::{
74    de::DeserializeOwned,
75    ser::{SerializeMap, SerializeSeq},
76    Deserialize, Deserializer, Serialize, Serializer,
77};
78pub use serde_json::{json, Value};
79use sha2::{Digest, Sha256};
80pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
81use thiserror::Error;
82pub use uuid::Uuid;
83pub use worker_session::{WorkerSession, WorkerSessionOptions};
84
85pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
86pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
87
88/// Select the worker request protocol without enabling optional capabilities.
89#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
90#[non_exhaustive]
91pub enum WorkerProtocolVersion {
92    /// Compatibility with Servers that implement only worker protocol 1.19.
93    V119,
94    /// The default worker protocol.
95    #[default]
96    V120,
97}
98
99impl WorkerProtocolVersion {
100    fn as_str(self) -> &'static str {
101        match self {
102            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
103            Self::V120 => WORKER_PROTOCOL_VERSION,
104        }
105    }
106}
107const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
108/// First additive worker protocol that defines portable worker-affinity features.
109pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
110pub const CONTROL_PLANE_VERSION: &str = "2";
111pub const DEFAULT_CODEC: &str = "avro";
112pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
113/// Worker-registration capability for authored condition-wait occurrence identity.
114pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
115    "condition_wait_occurrence_identity";
116/// Worker-registration capability for portable memo upserts.
117pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
118/// Worker-registration capability for server-routed read-only queries.
119pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
120/// Worker-registration capability for canonical typed search attributes.
121pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
122/// Worker-registration capability for synchronous workflow updates.
123pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
124/// Worker-registration capability for durable named input streams.
125pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
126/// Worker-registration capability for persisted first-completion selection.
127pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
128pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
129pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
130pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
131pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
132pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
133/// First additive worker protocol that defines query-task transport.
134pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
135/// First additive worker protocol that defines typed search-attribute upserts.
136pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
137/// First additive worker protocol that defines portable memo upserts.
138pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
139/// First additive worker protocol that preserves declared search-attribute types.
140pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
141/// First additive worker protocol that defines external durable condition waits.
142pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
143/// First additive worker protocol that preserves authored condition-wait occurrences.
144pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
145/// First additive worker protocol that defines durable selection groups.
146pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
147
148pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
149    let Some((major, minor)) = version.split_once('.') else {
150        return false;
151    };
152    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
153}
154
155fn validate_user_signal_name(signal_name: &str) -> Result<()> {
156    if signal_name == MESSAGE_STREAM_SIGNAL {
157        return Err(Error::Codec(format!(
158            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
159        )));
160    }
161    Ok(())
162}
163
164const REQUEST_ID_CONFLICT_REASON: &str = "request_id_conflict";
165const MAX_REQUEST_ID_CHARACTERS: usize = 255;
166
167/// The caller command key is a case-sensitive body field of 1 to 255 Unicode characters.
168fn validate_request_id(request_id: &str) -> Result<()> {
169    if request_id.is_empty() || request_id.chars().count() > MAX_REQUEST_ID_CHARACTERS {
170        return Err(Error::Codec(format!(
171            "request_id must be 1 to {MAX_REQUEST_ID_CHARACTERS} Unicode characters"
172        )));
173    }
174    Ok(())
175}
176
177fn generated_request_id(command: &str) -> String {
178    format!("sdk-rust-{command}-{}", Uuid::new_v4().simple())
179}
180
181/// Guarantee the sent caller command key on a receipt from a Server that does not echo it.
182fn with_request_id(mut receipt: Value, request_id: &str) -> Value {
183    if receipt.is_null() {
184        return json!({ "request_id": request_id });
185    }
186    if let Some(receipt) = receipt.as_object_mut() {
187        receipt
188            .entry("request_id")
189            .or_insert_with(|| Value::String(request_id.to_string()));
190    }
191    receipt
192}
193
194const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
195const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
196    "Workflow task waiting for scheduled history.";
197const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
198const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
199const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
200const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
201const MAX_MEMO_ENTRIES: usize = 100;
202const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
203const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
204
205const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
206    "lease_expired",
207    "query_task_not_found",
208    "query_task_not_leased",
209    "query_task_timed_out",
210    "query_deadline_unavailable",
211    "lease_owner_mismatch",
212    "query_task_attempt_mismatch",
213];
214
215/// Manifest for the default service-worker profile.
216///
217/// Inline local execution is enabled separately by [`Worker::local_activities`].
218/// Local execution, sessions and caching require explicit Worker configuration.
219pub fn portable_worker_affinity_capability_manifest() -> Value {
220    json!({
221        "local_activities": {
222            "supported": false,
223            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
224            "reason": "rust_worker_does_not_execute_record_local_activity",
225        },
226        "worker_sessions": {
227            "supported": false,
228            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
229            "reason": "rust_worker_has_no_typed_session_lifecycle",
230        },
231        "sticky_execution": {
232            "supported": false,
233            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
234            "reason": "rust_worker_uses_complete_durable_history_replay",
235        },
236    })
237}
238
239/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
240pub const AVRO_VALUE_SCHEMA_JSON: &str =
241    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
242pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
243pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
244const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
245
246static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
247static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
248    OnceLock::new();
249
250#[derive(Clone, Copy)]
251enum RequestProtocol {
252    ControlPlane,
253    DefaultWorker,
254    Worker(&'static str),
255}
256
257pub type Result<T> = std::result::Result<T, Error>;
258
259pub use nexus::{
260    NexusOperationFailure, NexusOperationMode, NexusOperationResult, NexusServiceCall,
261    NexusServiceOptions, NexusWaitFor,
262};
263
264#[derive(Debug, Error)]
265#[non_exhaustive]
266pub enum Error {
267    #[error("transport error: {0}")]
268    Transport(#[from] reqwest::Error),
269    #[error(
270        "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"
271    )]
272    InvalidBaseUrl,
273    #[error("invalid additional root certificates: {0}")]
274    InvalidRootCertificates(String),
275    #[error(transparent)]
276    Testing(#[from] testing::TestingError),
277    #[error(transparent)]
278    Pagination(#[from] pagination::PaginationError),
279    #[error("json error: {0}")]
280    Json(#[from] serde_json::Error),
281    #[error("http {status}: {body}")]
282    Http {
283        status: reqwest::StatusCode,
284        body: String,
285    },
286    #[error("codec error: {0}")]
287    Codec(String),
288    #[error(transparent)]
289    QueryFailed(QueryFailure),
290    #[error(transparent)]
291    Protocol(ProtocolFailure),
292    #[error(transparent)]
293    NonDeterministicReplay(ReplayFailure),
294    #[error(transparent)]
295    ChildWorkflowFailed(ChildWorkflowFailure),
296    #[error(transparent)]
297    ActivityFailed(ActivityFailure),
298    #[error(transparent)]
299    ActivityError(#[from] ActivityError),
300    #[error(transparent)]
301    NexusOperationFailed(Box<NexusOperationFailure>),
302    #[error(transparent)]
303    ParallelFailed(ParallelFailure),
304    #[error(transparent)]
305    SagaCompensationFailed(SagaCompensationFailure),
306    #[error(transparent)]
307    InvalidParallelGroup(ParallelGroupError),
308    #[error(transparent)]
309    DurableOperationCancelled(DurableOperationCancelled),
310    #[error(transparent)]
311    WorkflowCancellationRequested(WorkflowCancellationRequested),
312    #[error(transparent)]
313    CooperativeCancellationRequested(CooperativeCancellationRequested),
314    #[error(transparent)]
315    CancellationScopeRequested(CancellationScopeRequested),
316    #[error(transparent)]
317    WorkflowCommandRejected(WorkflowCommandRejection),
318    #[error(transparent)]
319    WorkflowFailed(WorkflowTerminalOutcome),
320    #[error(transparent)]
321    WorkflowCancelled(WorkflowTerminalOutcome),
322    #[error(transparent)]
323    WorkflowTerminated(WorkflowTerminalOutcome),
324    #[error(transparent)]
325    WorkflowTimedOut(WorkflowTerminalOutcome),
326    #[error(transparent)]
327    ActivityTaskRejected(ActivityTaskRejection),
328    #[error("activity lease renewal unavailable: {0}")]
329    ActivityLeaseRenewalUnavailable(String),
330    #[error("workflow handler {0:?} is not registered")]
331    WorkflowNotRegistered(String),
332    #[error("activity handler {0:?} is not registered")]
333    ActivityNotRegistered(String),
334    #[error(
335        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
336    )]
337    HandlerType {
338        handler_kind: HandlerKind,
339        handler_name: String,
340        value_kind: HandlerValueKind,
341        rust_type: &'static str,
342        message: String,
343    },
344    #[error("workflow future yielded without emitting a durable command")]
345    WorkflowYieldedWithoutCommand,
346    #[error(
347        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
348    )]
349    MissingWorkflowCommandIdentity,
350    #[error("workflow state lock is poisoned")]
351    WorkflowStatePoisoned,
352    #[error("timer duration is too large for the worker protocol")]
353    TimerDurationOverflow,
354    #[error(transparent)]
355    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
356    #[error(transparent)]
357    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
358    #[error("operation timed out")]
359    Timeout,
360    #[error(
361        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
362    )]
363    MissingRoleCredentials {
364        role: &'static str,
365        opposite_role: &'static str,
366    },
367    #[error("worker loop error: {0}")]
368    WorkerLoop(String),
369    #[error(
370        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
371    )]
372    UnsupportedUpdateValidators { workflow_type: String },
373    #[error("{primary}; worker deregistration also failed: {deregistration}")]
374    WorkerShutdown {
375        primary: Box<Error>,
376        deregistration: Box<Error>,
377    },
378    #[error("invalid child workflow options: {0}")]
379    InvalidChildWorkflowOptions(String),
380    #[error("invalid workflow memo update: {0}")]
381    InvalidMemoUpdate(String),
382    #[error(
383        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
384    )]
385    WorkflowMemoUpdatesUnavailable,
386    #[error("cooperative cancellation is unavailable: {0}")]
387    CooperativeCancellationUnavailable(String),
388    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
389    CancellationScopeExecutionUnavailable,
390    #[error("invalid cooperative cancellation: {0}")]
391    InvalidCooperativeCancellation(String),
392    #[error("activity execution no longer owns its claim: {0}")]
393    ActivityExecutionAbandoned(String),
394    #[error(transparent)]
395    InvalidActivityOptions(ActivityOptionsError),
396    #[error(transparent)]
397    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
398    #[doc(hidden)]
399    #[error("workflow requested continue as new")]
400    ContinueAsNew(ContinueAsNewRequest),
401}
402
403impl Error {
404    /// The caller command key echoed by the Server in a refusal body.
405    ///
406    /// Signals and updates send their key as the `request_id` body field, and a
407    /// Server refusal such as `request_id_conflict` echoes it. Transport failures
408    /// and refusals without an echoed key return `None`: keep the key you passed
409    /// to a `*_with_request_id` method, or obtained from
410    /// [`Client::generate_signal_request_id`] or
411    /// [`Client::generate_update_request_id`], to retry the same logical command
412    /// after an uncertain outcome.
413    pub fn request_id(&self) -> Option<String> {
414        self.refusal_body()?
415            .get("request_id")
416            .and_then(Value::as_str)
417            .filter(|request_id| !request_id.is_empty())
418            .map(str::to_string)
419    }
420
421    /// Whether the Server refused a signal or update because its caller command
422    /// key is retained for a command with a different intent
423    /// (HTTP 409, `reason: "request_id_conflict"`).
424    pub fn is_request_id_conflict(&self) -> bool {
425        self.request_id_conflict().is_some()
426    }
427
428    /// The retained-command details of a `request_id_conflict` refusal.
429    pub fn request_id_conflict(&self) -> Option<RequestIdConflict> {
430        let status = match self {
431            Self::Http { status, .. } => status.as_u16(),
432            Self::WorkflowCommandRejected(rejection) => rejection.status,
433            _ => return None,
434        };
435        request_id_conflict(status, self.refusal_body()?)
436    }
437
438    fn refusal_body(&self) -> Option<Value> {
439        match self {
440            Self::Http { body, .. } => serde_json::from_str(body).ok(),
441            Self::WorkflowCommandRejected(rejection) => Some(rejection.body.clone()),
442            _ => None,
443        }
444    }
445}
446
447/// A refused signal or update whose caller command key is already retained for
448/// a command with a different intent.
449///
450/// Nothing was admitted or recorded, and the key stays bound to the retained
451/// command. Send a new key for a different command, or repeat the retained
452/// command's exact intent to receive its receipt. `conflict` lists the
453/// mismatched intent parts among `name`, `arguments` and `target`.
454#[derive(Clone, Debug, PartialEq)]
455#[non_exhaustive]
456pub struct RequestIdConflict {
457    pub status: u16,
458    pub request_id: String,
459    pub message: String,
460    pub retained_command_id: Option<String>,
461    pub retained_command_type: Option<String>,
462    pub retained_outcome: Option<String>,
463    pub conflict: Vec<String>,
464    pub body: Value,
465}
466
467fn request_id_conflict(status: u16, body: Value) -> Option<RequestIdConflict> {
468    if body.get("reason").and_then(Value::as_str) != Some(REQUEST_ID_CONFLICT_REASON) {
469        return None;
470    }
471    let string = |name: &str| body.get(name).and_then(Value::as_str).map(str::to_string);
472    Some(RequestIdConflict {
473        status,
474        request_id: string("request_id").unwrap_or_default(),
475        message: string("message")
476            .or_else(|| string("error"))
477            .unwrap_or_else(|| "request id is retained for a different command intent".to_string()),
478        retained_command_id: string("retained_command_id"),
479        retained_command_type: string("retained_command_type"),
480        retained_outcome: string("retained_outcome"),
481        conflict: body
482            .get("conflict")
483            .and_then(Value::as_array)
484            .map(|parts| {
485                parts
486                    .iter()
487                    .filter_map(Value::as_str)
488                    .map(str::to_string)
489                    .collect()
490            })
491            .unwrap_or_default(),
492        body,
493    })
494}
495
496/// Handler namespaces checked independently within a Worker.
497#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
498pub enum RegistrationKind {
499    Workflow,
500    Activity,
501    Query,
502    Update,
503}
504
505impl std::fmt::Display for RegistrationKind {
506    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
507        formatter.write_str(match self {
508            Self::Workflow => "workflow",
509            Self::Activity => "activity",
510            Self::Query => "query",
511            Self::Update => "update",
512        })
513    }
514}
515
516/// The authoring adapter and source location of a handler registration.
517#[derive(Clone, Debug, PartialEq, Eq)]
518pub struct HandlerRegistration {
519    pub method: &'static str,
520    pub handler_type: &'static str,
521    pub file: &'static str,
522    pub line: u32,
523    pub column: u32,
524}
525
526impl std::fmt::Display for HandlerRegistration {
527    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
528        write!(
529            formatter,
530            "{} at {}:{}:{} ({})",
531            self.method, self.file, self.line, self.column, self.handler_type
532        )
533    }
534}
535
536/// Ambiguous local configuration, rejected before contacting Server.
537#[derive(Clone, Debug, Error, PartialEq, Eq)]
538#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
539pub struct DuplicateRegistrationError {
540    pub handler_kind: RegistrationKind,
541    pub handler_name: String,
542    /// Query/update registrations are scoped to their owning workflow type.
543    pub workflow_type: Option<String>,
544    pub first_definition: HandlerRegistration,
545    pub second_definition: HandlerRegistration,
546}
547
548impl From<DuplicateRegistrationError> for Error {
549    fn from(error: DuplicateRegistrationError) -> Self {
550        Self::WorkerLoop(error.to_string())
551    }
552}
553
554/// Validation failure for a durable condition-wait definition.
555#[derive(Clone, Debug, Error, PartialEq, Eq)]
556pub enum ConditionWaitOptionsError {
557    #[error("condition_key must be non-empty")]
558    EmptyKey,
559    #[error("condition_definition_fingerprint must be non-empty")]
560    EmptyPredicateIdentity,
561    #[error("condition timeout is too large for the worker protocol")]
562    TimeoutOverflow,
563}
564
565/// Stable identity and optional durable timeout for a condition wait.
566///
567/// `predicate_identity` is recorded as the worker protocol's
568/// `condition_definition_fingerprint` and must change whenever predicate
569/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
570/// is written inline; it derives this identity from the predicate tokens.
571#[derive(Clone, Debug, PartialEq, Eq)]
572pub struct ConditionWaitOptions {
573    condition_key: String,
574    predicate_identity: String,
575    timeout: Option<Duration>,
576}
577
578impl ConditionWaitOptions {
579    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
580        Self {
581            condition_key: condition_key.into(),
582            predicate_identity: predicate_identity.into(),
583            timeout: None,
584        }
585    }
586
587    pub fn timeout(mut self, timeout: Duration) -> Self {
588        self.timeout = Some(timeout);
589        self
590    }
591
592    fn validate(
593        &self,
594    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
595        let condition_key = self.condition_key.trim();
596        if condition_key.is_empty() {
597            return Err(ConditionWaitOptionsError::EmptyKey);
598        }
599        let predicate_identity = self.predicate_identity.trim();
600        if predicate_identity.is_empty() {
601            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
602        }
603        let timeout_seconds = self
604            .timeout
605            .map(|timeout| {
606                timeout
607                    .as_secs()
608                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
609                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
610            })
611            .transpose()?;
612
613        Ok(ValidatedConditionWaitOptions {
614            condition_key: condition_key.to_string(),
615            predicate_identity: predicate_identity.to_string(),
616            timeout_seconds,
617        })
618    }
619}
620
621#[derive(Clone, Debug, PartialEq, Eq)]
622struct ValidatedConditionWaitOptions {
623    condition_key: String,
624    predicate_identity: String,
625    timeout_seconds: Option<u64>,
626}
627
628const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
629
630/// Unambiguous terminal result of a durable condition wait.
631#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
632#[serde(rename_all = "snake_case")]
633pub enum ConditionWaitResult {
634    Satisfied,
635    TimedOut,
636}
637
638impl ConditionWaitResult {
639    pub fn is_satisfied(self) -> bool {
640        self == Self::Satisfied
641    }
642
643    pub fn is_timed_out(self) -> bool {
644        self == Self::TimedOut
645    }
646}
647
648/// Build the stable condition definition identity used by [`wait_condition!`].
649#[doc(hidden)]
650pub fn __condition_definition_fingerprint(source: &str) -> String {
651    let mut digest = Sha256::new();
652    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
653    digest.update(source.as_bytes());
654    format!("sha256:{:x}", digest.finalize())
655}
656
657/// Create a durable condition wait whose predicate definition is fingerprinted
658/// from its inline Rust tokens.
659///
660/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
661/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
662#[macro_export]
663macro_rules! wait_condition {
664    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
665        $ctx.wait_condition(
666            $crate::ConditionWaitOptions::new(
667                $key,
668                $crate::__condition_definition_fingerprint(concat!(
669                    module_path!(),
670                    "\0",
671                    stringify!($predicate)
672                )),
673            )
674            .timeout($timeout),
675            $predicate,
676        )
677    }};
678    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
679        $ctx.wait_condition(
680            $crate::ConditionWaitOptions::new(
681                $key,
682                $crate::__condition_definition_fingerprint(concat!(
683                    module_path!(),
684                    "\0",
685                    stringify!($predicate)
686                )),
687            ),
688            $predicate,
689        )
690    }};
691}
692
693const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
694const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
695const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
696const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
697const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
698
699/// Validation failure for a typed workflow search-attribute update.
700#[derive(Clone, Debug, Error, PartialEq, Eq)]
701pub enum SearchAttributeUpdateError {
702    #[error("search-attribute update requires at least one attribute")]
703    Empty,
704    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
705    InvalidKey(String),
706    #[error("search-attribute update exceeds the limit of 100 attributes")]
707    TooManyAttributes,
708    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
709    ValueTooLong {
710        key: String,
711        kind: &'static str,
712        limit: usize,
713    },
714    #[error(
715        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
716    )]
717    EmptyString(String),
718    #[error("search attribute {0:?} has a non-finite float value")]
719    NonFiniteFloat(String),
720    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
721    InvalidDateTime(String),
722    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
723    PayloadTooLarge,
724}
725
726/// One public typed search-attribute value.
727#[derive(Clone, Debug, PartialEq)]
728pub enum SearchAttributeValue {
729    String(String),
730    Keyword(String),
731    KeywordList(Vec<String>),
732    Int(i64),
733    Float(f64),
734    Bool(bool),
735    DateTime(String),
736    Delete,
737}
738
739impl SearchAttributeValue {
740    fn type_name(&self) -> Option<&'static str> {
741        match self {
742            Self::String(_) => Some("string"),
743            Self::Keyword(_) => Some("keyword"),
744            Self::KeywordList(_) => Some("keyword_list"),
745            Self::Int(_) => Some("int"),
746            Self::Float(_) => Some("float"),
747            Self::Bool(_) => Some("bool"),
748            Self::DateTime(_) => Some("datetime"),
749            Self::Delete => None,
750        }
751    }
752
753    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
754        let normalize_string = |value: String, kind: &'static str, limit: usize| {
755            let value = value.trim().to_string();
756            if value.is_empty() {
757                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
758            }
759            if value.len() > limit {
760                return Err(SearchAttributeUpdateError::ValueTooLong {
761                    key: key.to_string(),
762                    kind,
763                    limit,
764                });
765            }
766            Ok(value)
767        };
768
769        match self {
770            Self::String(value) => Ok(Self::String(normalize_string(
771                value,
772                "string",
773                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
774            )?)),
775            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
776                value,
777                "keyword",
778                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
779            )?)),
780            Self::KeywordList(values) => {
781                let values = values
782                    .into_iter()
783                    .map(|value| {
784                        let value = value.trim().to_string();
785                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
786                            return Err(SearchAttributeUpdateError::ValueTooLong {
787                                key: key.to_string(),
788                                kind: "keyword-list entry",
789                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
790                            });
791                        }
792                        Ok(value)
793                    })
794                    .collect::<std::result::Result<Vec<_>, _>>()?;
795                Ok(Self::KeywordList(values))
796            }
797            Self::Float(value) if !value.is_finite() => {
798                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
799            }
800            Self::DateTime(value) => {
801                let value =
802                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
803                if DateTime::parse_from_rfc3339(&value).is_err() {
804                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
805                }
806                Ok(Self::DateTime(value))
807            }
808            value => Ok(value),
809        }
810    }
811
812    fn into_json(self) -> Value {
813        match self {
814            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
815                Value::String(value)
816            }
817            Self::KeywordList(values) => {
818                Value::Array(values.into_iter().map(Value::String).collect())
819            }
820            Self::Int(value) => json!(value),
821            Self::Float(value) => json!(value),
822            Self::Bool(value) => json!(value),
823            Self::Delete => Value::Null,
824        }
825    }
826}
827
828/// Validated typed workflow-side search-attribute mutation.
829#[derive(Clone, Debug, Default, PartialEq)]
830pub struct SearchAttributeUpdate {
831    attributes: BTreeMap<String, SearchAttributeValue>,
832}
833
834impl SearchAttributeUpdate {
835    pub fn new() -> Self {
836        Self::default()
837    }
838
839    pub fn set(
840        mut self,
841        key: impl Into<String>,
842        value: SearchAttributeValue,
843    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
844        let key = key.into();
845        validate_search_attribute_key(&key)?;
846        if !self.attributes.contains_key(&key)
847            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
848        {
849            return Err(SearchAttributeUpdateError::TooManyAttributes);
850        }
851        self.attributes.insert(key.clone(), value.normalized(&key)?);
852        self.validate_size()?;
853        Ok(self)
854    }
855
856    pub fn string(
857        self,
858        key: impl Into<String>,
859        value: impl Into<String>,
860    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
861        self.set(key, SearchAttributeValue::String(value.into()))
862    }
863
864    pub fn keyword(
865        self,
866        key: impl Into<String>,
867        value: impl Into<String>,
868    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
869        self.set(key, SearchAttributeValue::Keyword(value.into()))
870    }
871
872    pub fn keyword_list<I, V>(
873        self,
874        key: impl Into<String>,
875        values: I,
876    ) -> std::result::Result<Self, SearchAttributeUpdateError>
877    where
878        I: IntoIterator<Item = V>,
879        V: Into<String>,
880    {
881        self.set(
882            key,
883            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
884        )
885    }
886
887    pub fn int(
888        self,
889        key: impl Into<String>,
890        value: i64,
891    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
892        self.set(key, SearchAttributeValue::Int(value))
893    }
894
895    pub fn float(
896        self,
897        key: impl Into<String>,
898        value: f64,
899    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
900        self.set(key, SearchAttributeValue::Float(value))
901    }
902
903    pub fn bool(
904        self,
905        key: impl Into<String>,
906        value: bool,
907    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
908        self.set(key, SearchAttributeValue::Bool(value))
909    }
910
911    pub fn datetime(
912        self,
913        key: impl Into<String>,
914        value: impl Into<String>,
915    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
916        self.set(key, SearchAttributeValue::DateTime(value.into()))
917    }
918
919    pub fn delete(
920        self,
921        key: impl Into<String>,
922    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
923        self.set(key, SearchAttributeValue::Delete)
924    }
925
926    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
927        let (attributes, _) = self.clone().into_wire_parts();
928        if serde_json::to_vec(&attributes)
929            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
930            .unwrap_or(true)
931        {
932            return Err(SearchAttributeUpdateError::PayloadTooLarge);
933        }
934        Ok(())
935    }
936
937    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
938        let mut attributes = serde_json::Map::new();
939        let mut attribute_types = BTreeMap::new();
940        for (key, value) in self.attributes {
941            if let Some(type_name) = value.type_name() {
942                attribute_types.insert(key.clone(), type_name.to_string());
943            }
944            attributes.insert(key, value.into_json());
945        }
946        (Value::Object(attributes), attribute_types)
947    }
948
949    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
950        if self.attributes.is_empty() {
951            return Err(SearchAttributeUpdateError::Empty);
952        }
953        self.validate_size()
954    }
955}
956
957fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
958    let valid = !key.is_empty()
959        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
960        && key
961            .bytes()
962            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
963    if valid {
964        Ok(())
965    } else {
966        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
967    }
968}
969
970/// The registered handler family reported by [`Error::HandlerType`].
971#[derive(Clone, Copy, Debug, PartialEq, Eq)]
972pub enum HandlerKind {
973    Workflow,
974    Activity,
975}
976
977impl std::fmt::Display for HandlerKind {
978    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
979        formatter.write_str(match self {
980            Self::Workflow => "workflow",
981            Self::Activity => "activity",
982        })
983    }
984}
985
986/// Whether a typed handler failed to adapt its input or result.
987#[derive(Clone, Copy, Debug, PartialEq, Eq)]
988pub enum HandlerValueKind {
989    Input,
990    Result,
991}
992
993impl std::fmt::Display for HandlerValueKind {
994    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
995        formatter.write_str(match self {
996            Self::Input => "input",
997            Self::Result => "result",
998        })
999    }
1000}
1001
1002/// The lifecycle command sent to a workflow execution.
1003#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1004pub enum WorkflowCommandKind {
1005    Cancel,
1006    Terminate,
1007}
1008
1009impl WorkflowCommandKind {
1010    fn as_str(self) -> &'static str {
1011        match self {
1012            Self::Cancel => "cancel",
1013            Self::Terminate => "terminate",
1014        }
1015    }
1016}
1017
1018/// Optional structured fields for a cancellation or termination request.
1019#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
1020pub struct WorkflowCommandOptions {
1021    #[serde(skip_serializing_if = "Option::is_none")]
1022    pub reason: Option<String>,
1023    #[serde(skip_serializing_if = "Option::is_none")]
1024    pub request_id: Option<String>,
1025}
1026
1027/// Server-enforced timeout policy for a workflow start.
1028///
1029/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
1030/// only bounds how long the caller waits. A server deadline produces a terminal
1031/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
1032/// `run_timeout`.
1033#[derive(Clone, Debug, PartialEq, Eq)]
1034pub struct WorkflowStartOptions {
1035    pub execution_timeout_seconds: u64,
1036    pub run_timeout_seconds: u64,
1037}
1038
1039impl Default for WorkflowStartOptions {
1040    fn default() -> Self {
1041        Self {
1042            execution_timeout_seconds: 3600,
1043            run_timeout_seconds: 600,
1044        }
1045    }
1046}
1047
1048impl WorkflowStartOptions {
1049    pub fn new() -> Self {
1050        Self::default()
1051    }
1052
1053    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1054        self.execution_timeout_seconds = seconds;
1055        self
1056    }
1057
1058    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1059        self.run_timeout_seconds = seconds;
1060        self
1061    }
1062
1063    fn validate(&self) -> Result<()> {
1064        if self.execution_timeout_seconds == 0 {
1065            return Err(Error::Codec(
1066                "execution_timeout_seconds must be at least 1".to_string(),
1067            ));
1068        }
1069        if self.run_timeout_seconds == 0 {
1070            return Err(Error::Codec(
1071                "run_timeout_seconds must be at least 1".to_string(),
1072            ));
1073        }
1074        if self.run_timeout_seconds > self.execution_timeout_seconds {
1075            return Err(Error::Codec(
1076                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
1077            ));
1078        }
1079
1080        Ok(())
1081    }
1082}
1083
1084/// Optional routing overrides for a continue-as-new transition.
1085///
1086/// Omitted values retain the current workflow type and task queue. Server-owned
1087/// instance metadata is not accepted here and is carried by the server.
1088#[derive(Clone, Debug, Default, PartialEq, Eq)]
1089pub struct ContinueAsNewOptions {
1090    pub workflow_type: Option<String>,
1091    pub task_queue: Option<String>,
1092}
1093
1094impl ContinueAsNewOptions {
1095    pub fn new() -> Self {
1096        Self::default()
1097    }
1098
1099    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
1100        self.workflow_type = Some(workflow_type.into());
1101        self
1102    }
1103
1104    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1105        self.task_queue = Some(task_queue.into());
1106        self
1107    }
1108
1109    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
1110        for (field, value) in [
1111            ("workflow_type", self.workflow_type.as_deref()),
1112            ("task_queue", self.task_queue.as_deref()),
1113        ] {
1114            if value.is_some_and(|value| value.trim().is_empty()) {
1115                return Err(ContinueAsNewOptionsError {
1116                    field,
1117                    message: format!("{field} must not be empty"),
1118                });
1119            }
1120        }
1121        Ok(())
1122    }
1123}
1124
1125/// A stable validation error raised before a continue-as-new command is emitted.
1126#[derive(Clone, Debug, Error, PartialEq, Eq)]
1127#[error("invalid continue-as-new option {field}: {message}")]
1128pub struct ContinueAsNewOptionsError {
1129    pub field: &'static str,
1130    pub message: String,
1131}
1132
1133/// Public history-budget information attached to the current workflow task.
1134#[derive(Clone, Debug, Default, PartialEq, Eq)]
1135pub struct WorkflowHistoryBudget {
1136    pub event_count: u64,
1137    pub size_bytes: Option<u64>,
1138    pub continue_as_new_recommended: bool,
1139    pub pressure: Option<String>,
1140}
1141
1142#[doc(hidden)]
1143#[derive(Clone, Debug)]
1144pub struct ContinueAsNewRequest {
1145    arguments: AvroValue,
1146    options: ContinueAsNewOptions,
1147}
1148
1149impl WorkflowCommandOptions {
1150    pub fn new() -> Self {
1151        Self::default()
1152    }
1153
1154    pub fn reason(mut self, reason: impl Into<String>) -> Self {
1155        self.reason = Some(reason.into());
1156        self
1157    }
1158
1159    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
1160        self.request_id = Some(request_id.into());
1161        self
1162    }
1163}
1164
1165/// The accepted, machine-readable result of a lifecycle command.
1166#[derive(Clone, Debug, PartialEq)]
1167pub struct WorkflowCommandResult {
1168    pub command: WorkflowCommandKind,
1169    pub workflow_id: String,
1170    pub run_id: Option<String>,
1171    pub outcome: Option<String>,
1172    pub reason: Option<String>,
1173    pub command_status: Option<String>,
1174    pub raw: Value,
1175}
1176
1177/// A new run continuing a failed run from its recorded activity boundary.
1178#[derive(Clone, Debug, PartialEq)]
1179pub struct WorkflowRedriveResult {
1180    pub workflow_id: String,
1181    pub source_run_id: String,
1182    pub run_id: String,
1183    pub resume_step_sequence: u64,
1184    pub raw: Value,
1185}
1186
1187/// A stable rejection returned by instance- or selected-run lifecycle commands.
1188#[derive(Clone, Debug, Error)]
1189#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1190pub struct WorkflowCommandRejection {
1191    pub command: WorkflowCommandKind,
1192    pub status: u16,
1193    pub reason: String,
1194    pub message: String,
1195    pub workflow_id: String,
1196    pub run_id: Option<String>,
1197    pub target_scope: Option<String>,
1198    pub body: Value,
1199}
1200
1201/// Stable terminal categories returned by [`WorkflowHandle::result`].
1202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1203pub enum WorkflowTerminalKind {
1204    Failed,
1205    Cancelled,
1206    Terminated,
1207    TimedOut,
1208}
1209
1210/// A typed terminal workflow outcome with durable identity and failure metadata.
1211///
1212/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1213/// of parsing its display representation. Fields remain `None` when an older
1214/// server did not publish that metadata.
1215#[derive(Clone, Debug, Error)]
1216#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1217pub struct WorkflowTerminalOutcome {
1218    pub kind: WorkflowTerminalKind,
1219    pub workflow_id: String,
1220    pub run_id: Option<String>,
1221    pub reason: String,
1222    pub failure_category: Option<String>,
1223    pub failure_id: Option<String>,
1224    pub exception_type: Option<String>,
1225    pub exception_class: Option<String>,
1226    pub non_retryable: Option<bool>,
1227    pub message: Option<String>,
1228    pub exception: Option<Value>,
1229    pub raw: Value,
1230}
1231
1232/// A worker-side activity settlement or heartbeat rejected by durable state.
1233#[derive(Clone, Debug, Error)]
1234#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1235pub struct ActivityTaskRejection {
1236    pub operation: String,
1237    pub status: u16,
1238    pub reason: String,
1239    pub task_id: String,
1240    pub activity_attempt_id: String,
1241    pub cancel_requested: bool,
1242    pub can_continue: Option<bool>,
1243    pub run_closed_reason: Option<String>,
1244    pub body: Value,
1245}
1246
1247/// Stable validation categories for [`ActivityOptions`].
1248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1249pub enum ActivityOptionsErrorKind {
1250    EmptyTaskQueue,
1251    EmptyRetryPolicy,
1252    InvalidMaxAttempts,
1253    BackoffWithoutRetryBudget,
1254    TooManyBackoffIntervals,
1255    InvalidBackoffCoefficient,
1256    BackoffGenerationTooLarge,
1257    BackoffOverflow,
1258    EmptyNonRetryableErrorType,
1259    TimeoutNotPositive,
1260    MissingTotalTimeout,
1261    TimeoutOverflow,
1262    TimeoutOrder,
1263}
1264
1265/// A machine-readable activity-options validation failure.
1266#[derive(Clone, Debug, Error, PartialEq, Eq)]
1267#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1268pub struct ActivityOptionsError {
1269    pub kind: ActivityOptionsErrorKind,
1270    pub field: Option<&'static str>,
1271    pub message: String,
1272}
1273
1274impl ActivityOptionsError {
1275    fn new(
1276        kind: ActivityOptionsErrorKind,
1277        field: Option<&'static str>,
1278        message: impl Into<String>,
1279    ) -> Self {
1280        Self {
1281            kind,
1282            field,
1283            message: message.into(),
1284        }
1285    }
1286}
1287
1288/// Stable terminal categories returned when an awaited activity does not succeed.
1289#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1290pub enum ActivityFailureKind {
1291    Failed,
1292    Cancelled,
1293    TimedOut,
1294}
1295
1296/// A stable, machine-readable terminal activity failure.
1297///
1298/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1299/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1300#[derive(Clone, Debug, Error, PartialEq)]
1301#[error("activity failed ({reason}): {message}")]
1302pub struct ActivityFailure {
1303    pub kind: ActivityFailureKind,
1304    pub reason: String,
1305    pub message: String,
1306    pub activity_execution_id: Option<String>,
1307    pub activity_attempt_id: Option<String>,
1308    pub activity_type: Option<String>,
1309    pub activity_class: Option<String>,
1310    pub attempt_number: Option<u64>,
1311    pub failure_id: Option<String>,
1312    pub failure_category: Option<String>,
1313    pub timeout_kind: Option<String>,
1314    pub non_retryable: bool,
1315    pub exception_type: Option<String>,
1316    pub exception_class: Option<String>,
1317    pub code: Option<Value>,
1318    pub exception: Option<Value>,
1319}
1320
1321/// Stable terminal categories returned when an awaited child does not succeed.
1322#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1323pub enum ChildWorkflowFailureKind {
1324    Failed,
1325    Cancelled,
1326    Terminated,
1327}
1328
1329/// A stable, machine-readable child workflow failure delivered to its parent.
1330///
1331/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1332/// of parsing the display message. Child and parent identifiers retain the
1333/// relationship recorded in durable history across worker restarts.
1334#[derive(Clone, Debug, Error)]
1335#[error("child workflow failed ({reason}): {message}")]
1336pub struct ChildWorkflowFailure {
1337    pub kind: ChildWorkflowFailureKind,
1338    pub reason: String,
1339    pub message: String,
1340    pub parent_workflow_id: Option<String>,
1341    pub parent_workflow_run_id: Option<String>,
1342    pub child_workflow_id: Option<String>,
1343    pub child_workflow_run_id: Option<String>,
1344    pub child_workflow_type: Option<String>,
1345    pub failure_id: Option<String>,
1346    pub failure_category: Option<String>,
1347    pub exception_type: Option<String>,
1348    pub exception_class: Option<String>,
1349    pub non_retryable: bool,
1350    pub code: Option<Value>,
1351    pub exception: Option<Value>,
1352}
1353
1354/// The identity of one durable workflow execution.
1355#[derive(Clone, Debug, PartialEq, Eq)]
1356pub struct WorkflowIdentity {
1357    pub workflow_id: Option<String>,
1358    pub run_id: Option<String>,
1359}
1360
1361/// A successful child result together with its durable parent-child identity.
1362#[derive(Clone, Debug, PartialEq)]
1363pub struct ChildWorkflowResult {
1364    pub parent: WorkflowIdentity,
1365    pub child: WorkflowIdentity,
1366    pub child_workflow_type: Option<String>,
1367    pub result: Value,
1368}
1369
1370/// Lossless successful child result for fixed Avro Value workflows.
1371#[derive(Clone, Debug, PartialEq)]
1372pub struct ChildWorkflowAvroResult {
1373    pub parent: WorkflowIdentity,
1374    pub child: WorkflowIdentity,
1375    pub child_workflow_type: Option<String>,
1376    pub result: AvroValue,
1377}
1378
1379/// Stable user-facing identity for one member of a durable selection group.
1380#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1381#[serde(untagged)]
1382pub enum SelectionKey {
1383    Index(usize),
1384    Name(String),
1385}
1386
1387impl From<usize> for SelectionKey {
1388    fn from(value: usize) -> Self {
1389        Self::Index(value)
1390    }
1391}
1392
1393impl From<String> for SelectionKey {
1394    fn from(value: String) -> Self {
1395        Self::Name(value)
1396    }
1397}
1398
1399impl From<&str> for SelectionKey {
1400    fn from(value: &str) -> Self {
1401        Self::Name(value.to_string())
1402    }
1403}
1404
1405/// Typed result of explicitly awaiting a cancelled non-winning operation.
1406#[derive(Clone, Debug, Error, PartialEq, Eq)]
1407#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1408pub struct DurableOperationCancelled {
1409    pub selection_group_id: String,
1410    pub member_key: SelectionKey,
1411    pub member_index: usize,
1412    pub operation_kind: String,
1413    pub operation_identity: String,
1414}
1415
1416/// Stable identity for one enclosing deterministic parallel group.
1417///
1418/// The same fields are attached to every ordinary activity, timer, or child
1419/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1420/// no Rust-specific wire command is introduced.
1421#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1422pub struct ParallelGroupMetadata {
1423    pub parallel_group_id: String,
1424    pub parallel_group_kind: String,
1425    pub parallel_group_base_sequence: u64,
1426    pub parallel_group_size: usize,
1427    pub parallel_group_index: usize,
1428    #[serde(default, skip_serializing_if = "Option::is_none")]
1429    pub parallel_group_mode: Option<String>,
1430    #[serde(default, skip_serializing_if = "Option::is_none")]
1431    pub selection_member_key: Option<SelectionKey>,
1432    #[serde(default, skip_serializing_if = "Option::is_none")]
1433    pub selection_member_index: Option<usize>,
1434    #[serde(default, skip_serializing_if = "Option::is_none")]
1435    pub selection_member_base_sequence: Option<u64>,
1436    #[serde(default, skip_serializing_if = "Option::is_none")]
1437    pub selection_member_size: Option<usize>,
1438    #[serde(default, skip_serializing_if = "Option::is_none")]
1439    pub selection_member_kind: Option<String>,
1440}
1441
1442/// One input-ordered result returned by [`WorkflowContext::parallel`].
1443#[derive(Clone, Debug, PartialEq)]
1444pub enum ParallelResult {
1445    Activity(Value),
1446    ChildWorkflow(ChildWorkflowResult),
1447    Timer,
1448    Signal(Vec<Value>),
1449    Condition(ConditionWaitResult),
1450    Group(Vec<ParallelResult>),
1451}
1452
1453/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1454#[derive(Clone, Debug, PartialEq)]
1455pub enum ParallelAvroResult {
1456    Activity(AvroValue),
1457    ChildWorkflow(ChildWorkflowAvroResult),
1458    Timer,
1459    Signal(Vec<AvroValue>),
1460    Condition(ConditionWaitResult),
1461    Group(Vec<ParallelAvroResult>),
1462}
1463
1464impl ParallelAvroResult {
1465    fn into_json_result(self) -> Result<ParallelResult> {
1466        match self {
1467            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1468            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1469                parent: result.parent,
1470                child: result.child,
1471                child_workflow_type: result.child_workflow_type,
1472                result: result.result.into_json()?,
1473            })),
1474            Self::Timer => Ok(ParallelResult::Timer),
1475            Self::Signal(values) => Ok(ParallelResult::Signal(
1476                values
1477                    .into_iter()
1478                    .map(AvroValue::into_json)
1479                    .collect::<Result<Vec<_>>>()?,
1480            )),
1481            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1482            Self::Group(results) => Ok(ParallelResult::Group(
1483                results
1484                    .into_iter()
1485                    .map(Self::into_json_result)
1486                    .collect::<Result<Vec<_>>>()?,
1487            )),
1488        }
1489    }
1490}
1491
1492/// One successful leaf retained when another parallel member failed.
1493#[derive(Clone, Debug, PartialEq)]
1494pub struct ParallelCompletion {
1495    pub member_path: Vec<usize>,
1496    pub result: ParallelResult,
1497}
1498
1499/// A deterministic join failed after some siblings had already completed.
1500///
1501/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1502/// error. `completed` is declaration ordered and contains only durable
1503/// successes observed in the same replay. Late sibling completions can add
1504/// entries on a later replay without changing `member_path` or the selected
1505/// positional failure.
1506#[derive(Debug, Error)]
1507#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1508pub struct ParallelFailure {
1509    pub group_id: String,
1510    pub member_path: Vec<usize>,
1511    pub group_path: Vec<ParallelGroupMetadata>,
1512    pub completed: Vec<ParallelCompletion>,
1513    #[source]
1514    pub cause: Box<Error>,
1515}
1516
1517/// Stable validation error returned before an invalid group emits commands.
1518#[derive(Clone, Debug, Error, PartialEq, Eq)]
1519#[error("invalid deterministic parallel group ({reason}): {message}")]
1520pub struct ParallelGroupError {
1521    pub reason: &'static str,
1522    pub member_path: Vec<usize>,
1523    pub message: String,
1524}
1525
1526/// Cooperative workflow cancellation observed at an author-controlled point.
1527#[derive(Clone, Debug, Error, PartialEq, Eq)]
1528#[error("workflow cancellation was requested")]
1529pub struct WorkflowCancellationRequested;
1530
1531/// A forward saga failure followed by a terminal compensation failure.
1532#[derive(Debug, Error)]
1533#[error(
1534    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1535)]
1536pub struct SagaCompensationFailure {
1537    pub initiating_failure: Box<Error>,
1538    pub compensation_failure: Box<Error>,
1539    pub compensation_activity_type: String,
1540    pub compensation_registration_order: usize,
1541}
1542
1543/// Server behavior when a parent closes while its child is still open.
1544#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1545pub enum ParentClosePolicy {
1546    #[default]
1547    Abandon,
1548    /// Legacy terminal cancellation without cooperative cleanup.
1549    RequestCancel,
1550    /// Request cooperative cleanup with the original lineage and deadline.
1551    RequestCancellation,
1552    Terminate,
1553}
1554
1555impl ParentClosePolicy {
1556    fn as_str(self) -> &'static str {
1557        match self {
1558            Self::Abandon => "abandon",
1559            Self::RequestCancel => "request_cancel",
1560            Self::RequestCancellation => "request_cancellation",
1561            Self::Terminate => "terminate",
1562        }
1563    }
1564}
1565
1566/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1567#[non_exhaustive]
1568#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1569pub enum CancellationPolicy {
1570    /// Request cancellation and continue without waiting. Historical Activity default.
1571    TryCancel,
1572    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1573    WaitCancellationCompleted,
1574    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1575    #[default]
1576    Abandon,
1577}
1578
1579impl CancellationPolicy {
1580    fn as_str(self) -> &'static str {
1581        match self {
1582            Self::TryCancel => "try_cancel",
1583            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1584            Self::Abandon => "abandon",
1585        }
1586    }
1587}
1588
1589/// Durable retry policy for one child workflow invocation.
1590#[derive(Clone, Debug, Default, PartialEq, Eq)]
1591pub struct ChildWorkflowRetryPolicy {
1592    pub max_attempts: Option<u32>,
1593    pub backoff_seconds: Vec<u64>,
1594    pub non_retryable_error_types: Vec<String>,
1595}
1596
1597/// Options recorded with a child-workflow command.
1598///
1599/// The task queue is mandatory so routing is explicit and replay-stable.
1600#[derive(Clone, Debug, PartialEq, Eq)]
1601pub struct ChildWorkflowOptions {
1602    pub task_queue: String,
1603    pub parent_close_policy: ParentClosePolicy,
1604    pub cancellation_policy: CancellationPolicy,
1605    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1606    pub execution_timeout_seconds: Option<u64>,
1607    pub run_timeout_seconds: Option<u64>,
1608}
1609
1610impl ChildWorkflowOptions {
1611    pub fn new(task_queue: impl Into<String>) -> Self {
1612        Self {
1613            task_queue: task_queue.into(),
1614            parent_close_policy: ParentClosePolicy::Abandon,
1615            cancellation_policy: CancellationPolicy::Abandon,
1616            retry_policy: None,
1617            execution_timeout_seconds: None,
1618            run_timeout_seconds: None,
1619        }
1620    }
1621
1622    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1623        self.parent_close_policy = policy;
1624        self
1625    }
1626
1627    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1628        self.cancellation_policy = policy;
1629        self
1630    }
1631
1632    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1633        self.retry_policy = Some(policy);
1634        self
1635    }
1636
1637    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1638        self.execution_timeout_seconds = Some(seconds);
1639        self
1640    }
1641
1642    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1643        self.run_timeout_seconds = Some(seconds);
1644        self
1645    }
1646}
1647
1648/// Backoff intervals for one durable activity retry policy.
1649#[derive(Clone, Debug, PartialEq, Eq)]
1650pub enum ActivityBackoff {
1651    /// Use these intervals between attempts. The server repeats the final
1652    /// interval if the retry budget contains more attempts than entries.
1653    /// All entries are retained, including those beyond the retry budget.
1654    Explicit(Vec<Duration>),
1655    /// Generate one interval for every retry using integer exponential growth.
1656    Exponential {
1657        initial_interval: Duration,
1658        coefficient: u32,
1659        maximum_interval: Option<Duration>,
1660    },
1661}
1662
1663/// Durable server-side retry policy for one activity execution.
1664#[derive(Clone, Debug, Default, PartialEq, Eq)]
1665pub struct ActivityRetryPolicy {
1666    pub max_attempts: Option<u32>,
1667    pub backoff: Option<ActivityBackoff>,
1668    pub non_retryable_error_types: Vec<String>,
1669}
1670
1671impl ActivityRetryPolicy {
1672    /// Start a policy with a finite attempt budget, including the first attempt.
1673    pub fn new(max_attempts: u32) -> Self {
1674        Self {
1675            max_attempts: Some(max_attempts),
1676            ..Self::default()
1677        }
1678    }
1679
1680    /// Preserve the complete explicit list independently of the attempt budget.
1681    /// Unused entries remain part of the policy compared during replay.
1682    /// Set explicit durable retry intervals. Each positive fractional second
1683    /// is rounded up when encoded: `Duration::from_millis(100)` becomes one
1684    /// second. Zero stays zero. Queue latency can delay the next attempt further.
1685    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1686        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1687        self
1688    }
1689
1690    /// Generate durable retry intervals from `initial_interval` and `coefficient`.
1691    /// Each interval is capped by `maximum_interval`, when present, then rounded
1692    /// up to whole seconds. A 100 ms interval or cap therefore encodes one second.
1693    /// Zero stays zero. This policy is separate from HTTP transport retries.
1694    pub fn exponential_backoff(
1695        mut self,
1696        initial_interval: Duration,
1697        coefficient: u32,
1698        maximum_interval: Option<Duration>,
1699    ) -> Self {
1700        self.backoff = Some(ActivityBackoff::Exponential {
1701            initial_interval,
1702            coefficient,
1703            maximum_interval,
1704        });
1705        self
1706    }
1707
1708    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1709        self.non_retryable_error_types.push(error_type.into());
1710        self
1711    }
1712
1713    pub fn non_retryable_error_types(
1714        mut self,
1715        error_types: impl IntoIterator<Item = impl Into<String>>,
1716    ) -> Self {
1717        self.non_retryable_error_types
1718            .extend(error_types.into_iter().map(Into::into));
1719        self
1720    }
1721}
1722
1723/// Options recorded atomically on one deterministic `schedule_activity` command.
1724///
1725/// Durations are rounded up to whole seconds when encoded, so the server never
1726/// receives a shorter timeout or backoff than the caller requested.
1727#[derive(Clone, Debug, Default, PartialEq, Eq)]
1728pub struct ActivityOptions {
1729    pub task_queue: Option<String>,
1730    pub retry_policy: Option<ActivityRetryPolicy>,
1731    pub start_to_close_timeout: Option<Duration>,
1732    pub schedule_to_start_timeout: Option<Duration>,
1733    pub schedule_to_close_timeout: Option<Duration>,
1734    pub heartbeat_timeout: Option<Duration>,
1735    pub cancellation_policy: Option<CancellationPolicy>,
1736}
1737
1738impl ActivityOptions {
1739    pub fn new() -> Self {
1740        Self::default()
1741    }
1742
1743    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1744        self.task_queue = Some(task_queue.into());
1745        self
1746    }
1747
1748    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1749        self.retry_policy = Some(policy);
1750        self
1751    }
1752
1753    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1754        self.start_to_close_timeout = Some(timeout);
1755        self
1756    }
1757
1758    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1759        self.schedule_to_start_timeout = Some(timeout);
1760        self
1761    }
1762
1763    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1764        self.schedule_to_close_timeout = Some(timeout);
1765        self
1766    }
1767
1768    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1769        self.heartbeat_timeout = Some(timeout);
1770        self
1771    }
1772
1773    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1774        self.cancellation_policy = Some(policy);
1775        self
1776    }
1777
1778    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1779        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1780            && self.schedule_to_close_timeout.is_none()
1781        {
1782            return Err(ActivityOptionsError::new(
1783                ActivityOptionsErrorKind::MissingTotalTimeout,
1784                Some("schedule_to_close_timeout"),
1785                "remote Activity Abandon requires a finite positive total timeout",
1786            ));
1787        }
1788        if self
1789            .task_queue
1790            .as_deref()
1791            .is_some_and(|queue| queue.trim().is_empty())
1792        {
1793            return Err(ActivityOptionsError::new(
1794                ActivityOptionsErrorKind::EmptyTaskQueue,
1795                Some("task_queue"),
1796                "task_queue must not be empty",
1797            ));
1798        }
1799
1800        for (field, value) in [
1801            ("start_to_close_timeout", self.start_to_close_timeout),
1802            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1803            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1804            ("heartbeat_timeout", self.heartbeat_timeout),
1805        ] {
1806            if value.is_some_and(|value| value.is_zero()) {
1807                return Err(ActivityOptionsError::new(
1808                    ActivityOptionsErrorKind::TimeoutNotPositive,
1809                    Some(field),
1810                    format!("{field} must be positive"),
1811                ));
1812            }
1813        }
1814
1815        validate_timeout_order(
1816            "heartbeat_timeout",
1817            self.heartbeat_timeout,
1818            "start_to_close_timeout",
1819            self.start_to_close_timeout,
1820        )?;
1821        validate_timeout_order(
1822            "start_to_close_timeout",
1823            self.start_to_close_timeout,
1824            "schedule_to_close_timeout",
1825            self.schedule_to_close_timeout,
1826        )?;
1827        validate_timeout_order(
1828            "schedule_to_start_timeout",
1829            self.schedule_to_start_timeout,
1830            "schedule_to_close_timeout",
1831            self.schedule_to_close_timeout,
1832        )?;
1833
1834        Ok(ValidatedActivityOptions {
1835            task_queue: self.task_queue.clone(),
1836            retry_policy: self
1837                .retry_policy
1838                .as_ref()
1839                .map(validate_activity_retry_policy)
1840                .transpose()?,
1841            start_to_close_timeout: timeout_seconds(
1842                "start_to_close_timeout",
1843                self.start_to_close_timeout,
1844            )?,
1845            schedule_to_start_timeout: timeout_seconds(
1846                "schedule_to_start_timeout",
1847                self.schedule_to_start_timeout,
1848            )?,
1849            schedule_to_close_timeout: timeout_seconds(
1850                "schedule_to_close_timeout",
1851                self.schedule_to_close_timeout,
1852            )?,
1853            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
1854            cancellation_policy: self.cancellation_policy,
1855        })
1856    }
1857}
1858
1859/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
1860///
1861/// Constructors capture arguments but perform no I/O. The join validates the
1862/// complete tree, attaches the existing parallel-group metadata to every
1863/// ordinary command, schedules all leaves, and then suspends.
1864pub enum ParallelOperation {
1865    Activity {
1866        activity_type: String,
1867        options: ActivityOptions,
1868        arguments: Result<AvroValue>,
1869    },
1870    ChildWorkflow {
1871        workflow_type: String,
1872        options: ChildWorkflowOptions,
1873        arguments: Result<AvroValue>,
1874    },
1875    Timer(Duration),
1876    Signal(String),
1877    Condition {
1878        options: ConditionWaitOptions,
1879        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
1880    },
1881    Group(Vec<ParallelOperation>),
1882}
1883
1884impl ParallelOperation {
1885    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
1886        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
1887    }
1888
1889    pub fn activity_with_options<T: Serialize>(
1890        activity_type: impl Into<String>,
1891        options: ActivityOptions,
1892        args: T,
1893    ) -> Self {
1894        Self::Activity {
1895            activity_type: activity_type.into(),
1896            options,
1897            arguments: AvroValue::from_serialize(&args),
1898        }
1899    }
1900
1901    pub fn child_workflow<T: Serialize>(
1902        workflow_type: impl Into<String>,
1903        options: ChildWorkflowOptions,
1904        args: T,
1905    ) -> Self {
1906        Self::ChildWorkflow {
1907            workflow_type: workflow_type.into(),
1908            options,
1909            arguments: AvroValue::from_serialize(&args),
1910        }
1911    }
1912
1913    pub fn timer(duration: Duration) -> Self {
1914        Self::Timer(duration)
1915    }
1916
1917    pub fn signal(signal_name: impl Into<String>) -> Self {
1918        Self::Signal(signal_name.into())
1919    }
1920
1921    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
1922    where
1923        F: Fn() -> Result<bool> + Send + 'static,
1924    {
1925        Self::Condition {
1926            options,
1927            predicate: Box::new(predicate),
1928        }
1929    }
1930
1931    pub fn group(operations: Vec<ParallelOperation>) -> Self {
1932        Self::Group(operations)
1933    }
1934}
1935
1936#[derive(Clone, Debug)]
1937struct ValidatedActivityOptions {
1938    task_queue: Option<String>,
1939    retry_policy: Option<Value>,
1940    start_to_close_timeout: Option<u64>,
1941    schedule_to_start_timeout: Option<u64>,
1942    schedule_to_close_timeout: Option<u64>,
1943    heartbeat_timeout: Option<u64>,
1944    cancellation_policy: Option<CancellationPolicy>,
1945}
1946
1947fn validate_timeout_order(
1948    smaller_name: &'static str,
1949    smaller: Option<Duration>,
1950    larger_name: &'static str,
1951    larger: Option<Duration>,
1952) -> std::result::Result<(), ActivityOptionsError> {
1953    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
1954        return Err(ActivityOptionsError::new(
1955            ActivityOptionsErrorKind::TimeoutOrder,
1956            Some(smaller_name),
1957            format!("{smaller_name} must be <= {larger_name}"),
1958        ));
1959    }
1960    Ok(())
1961}
1962
1963fn timeout_seconds(
1964    field: &'static str,
1965    value: Option<Duration>,
1966) -> std::result::Result<Option<u64>, ActivityOptionsError> {
1967    value
1968        .map(|value| {
1969            activity_protocol_seconds(value).ok_or_else(|| {
1970                ActivityOptionsError::new(
1971                    ActivityOptionsErrorKind::TimeoutOverflow,
1972                    Some(field),
1973                    format!("{field} is too large for the worker protocol"),
1974                )
1975            })
1976        })
1977        .transpose()
1978}
1979
1980fn duration_seconds_ceil(value: Duration) -> Option<u64> {
1981    value
1982        .as_secs()
1983        .checked_add(u64::from(value.subsec_nanos() > 0))
1984}
1985
1986fn activity_protocol_seconds(value: Duration) -> Option<u64> {
1987    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
1988}
1989
1990fn validate_activity_retry_policy(
1991    policy: &ActivityRetryPolicy,
1992) -> std::result::Result<Value, ActivityOptionsError> {
1993    if policy.max_attempts.is_none()
1994        && policy.backoff.is_none()
1995        && policy.non_retryable_error_types.is_empty()
1996    {
1997        return Err(ActivityOptionsError::new(
1998            ActivityOptionsErrorKind::EmptyRetryPolicy,
1999            Some("retry_policy"),
2000            "retry_policy must configure at least one field",
2001        ));
2002    }
2003    if policy.max_attempts == Some(0) {
2004        return Err(ActivityOptionsError::new(
2005            ActivityOptionsErrorKind::InvalidMaxAttempts,
2006            Some("retry_policy.max_attempts"),
2007            "max_attempts must be >= 1",
2008        ));
2009    }
2010    if policy
2011        .non_retryable_error_types
2012        .iter()
2013        .any(|error_type| error_type.trim().is_empty())
2014    {
2015        return Err(ActivityOptionsError::new(
2016            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
2017            Some("retry_policy.non_retryable_error_types"),
2018            "non_retryable_error_types must not contain empty values",
2019        ));
2020    }
2021
2022    let backoff_seconds = match &policy.backoff {
2023        None => None,
2024        Some(backoff) => {
2025            let max_attempts = policy.max_attempts.ok_or_else(|| {
2026                ActivityOptionsError::new(
2027                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
2028                    Some("retry_policy.backoff"),
2029                    "backoff requires max_attempts",
2030                )
2031            })?;
2032            let retry_count = max_attempts.saturating_sub(1) as usize;
2033            let intervals = match backoff {
2034                ActivityBackoff::Explicit(intervals) => intervals.clone(),
2035                ActivityBackoff::Exponential {
2036                    initial_interval,
2037                    coefficient,
2038                    maximum_interval,
2039                } => {
2040                    if *coefficient < 1 {
2041                        return Err(ActivityOptionsError::new(
2042                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
2043                            Some("retry_policy.backoff.coefficient"),
2044                            "backoff coefficient must be >= 1",
2045                        ));
2046                    }
2047                    if retry_count > 10_000 {
2048                        return Err(ActivityOptionsError::new(
2049                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
2050                            Some("retry_policy.max_attempts"),
2051                            "generated backoff supports at most 10000 retry intervals",
2052                        ));
2053                    }
2054                    let mut current = *initial_interval;
2055                    let mut intervals = Vec::with_capacity(retry_count);
2056                    for _ in 0..retry_count {
2057                        let interval = maximum_interval
2058                            .map(|maximum| current.min(maximum))
2059                            .unwrap_or(current);
2060                        intervals.push(interval);
2061                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
2062                            break;
2063                        }
2064                        current = current.checked_mul(*coefficient).ok_or_else(|| {
2065                            ActivityOptionsError::new(
2066                                ActivityOptionsErrorKind::BackoffOverflow,
2067                                Some("retry_policy.backoff"),
2068                                "generated backoff interval overflowed",
2069                            )
2070                        })?;
2071                    }
2072                    intervals
2073                }
2074            };
2075            Some(
2076                intervals
2077                    .into_iter()
2078                    .map(|interval| {
2079                        activity_protocol_seconds(interval).ok_or_else(|| {
2080                            ActivityOptionsError::new(
2081                                ActivityOptionsErrorKind::BackoffOverflow,
2082                                Some("retry_policy.backoff"),
2083                                "backoff interval is too large for the worker protocol",
2084                            )
2085                        })
2086                    })
2087                    .collect::<std::result::Result<Vec<_>, _>>()?,
2088            )
2089        }
2090    };
2091
2092    let mut encoded = serde_json::Map::new();
2093    if let Some(max_attempts) = policy.max_attempts {
2094        encoded.insert("max_attempts".to_string(), json!(max_attempts));
2095    }
2096    if let Some(backoff_seconds) = backoff_seconds {
2097        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
2098    }
2099    if !policy.non_retryable_error_types.is_empty() {
2100        let mut canonical_error_types = Vec::new();
2101        for error_type in policy
2102            .non_retryable_error_types
2103            .iter()
2104            .map(|error_type| error_type.trim())
2105        {
2106            if !canonical_error_types.contains(&error_type) {
2107                canonical_error_types.push(error_type);
2108            }
2109        }
2110        encoded.insert(
2111            "non_retryable_error_types".to_string(),
2112            json!(canonical_error_types),
2113        );
2114    }
2115    Ok(Value::Object(encoded))
2116}
2117
2118/// A stable, machine-readable failure raised when workflow code no longer
2119/// reconstructs the durable command stream recorded in history.
2120#[derive(Clone, Debug, Error)]
2121#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
2122pub struct ReplayFailure {
2123    pub reason: String,
2124    pub sequence: Option<u64>,
2125    pub expected: Option<String>,
2126    pub actual: Option<String>,
2127    pub message: String,
2128}
2129
2130impl ReplayFailure {
2131    fn new(
2132        reason: impl Into<String>,
2133        sequence: Option<u64>,
2134        expected: Option<String>,
2135        actual: Option<String>,
2136        message: impl Into<String>,
2137    ) -> Self {
2138        Self {
2139            reason: reason.into(),
2140            sequence,
2141            expected,
2142            actual,
2143            message: message.into(),
2144        }
2145    }
2146}
2147
2148/// A stable, machine-readable workflow query or query-task settlement failure.
2149#[derive(Clone, Debug, Error)]
2150#[error("query failed ({reason}, HTTP {status}): {message}")]
2151pub struct QueryFailure {
2152    pub status: u16,
2153    pub reason: String,
2154    pub message: String,
2155    pub body: Value,
2156}
2157
2158/// A stable failure returned when a server rejects an SDK protocol version.
2159#[derive(Clone, Debug, Error)]
2160#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
2161pub struct ProtocolFailure {
2162    pub status: u16,
2163    pub reason: String,
2164    pub message: String,
2165    pub supported_version: Option<String>,
2166    pub requested_version: Option<String>,
2167    pub body: Value,
2168}
2169
2170#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2171pub struct PayloadEnvelope {
2172    pub codec: String,
2173    pub blob: String,
2174}
2175
2176impl PayloadEnvelope {
2177    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2178        encode_payload(value, DEFAULT_CODEC)
2179    }
2180
2181    /// Encode an explicit typed value, including the bytes branch that JSON
2182    /// serialization cannot represent.
2183    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2184        encode_avro_value(value)
2185    }
2186}
2187
2188/// Native adapter for the fixed language-neutral Avro Value schema.
2189#[derive(Clone, Debug)]
2190pub enum AvroValue {
2191    Null,
2192    Boolean(bool),
2193    Long(i64),
2194    Double(f64),
2195    Bytes(Vec<u8>),
2196    String(String),
2197    Array(Vec<AvroValue>),
2198    Map(BTreeMap<String, AvroValue>),
2199}
2200
2201impl PartialEq for AvroValue {
2202    fn eq(&self, other: &Self) -> bool {
2203        match (self, other) {
2204            (Self::Null, Self::Null) => true,
2205            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2206            (Self::Long(left), Self::Long(right)) => left == right,
2207            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2208            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2209            (Self::String(left), Self::String(right)) => left == right,
2210            (Self::Array(left), Self::Array(right)) => left == right,
2211            (Self::Map(left), Self::Map(right)) => left == right,
2212            _ => false,
2213        }
2214    }
2215}
2216
2217impl AvroValue {
2218    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2219        Self::from_serde_value(
2220            serde_value::to_value(value).map_err(|error| {
2221                Error::Codec(format!("could not adapt value for Avro: {error}"))
2222            })?,
2223        )
2224    }
2225
2226    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2227        use serde_value::Value as SerdeValue;
2228
2229        match value {
2230            SerdeValue::Unit => Ok(Self::Null),
2231            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2232            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2233            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2234            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2235            SerdeValue::I64(value) => Ok(Self::Long(value)),
2236            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2237            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2238            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2239            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2240                Error::Codec(
2241                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2242                        .to_string(),
2243                )
2244            }),
2245            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2246            SerdeValue::F64(value) => Self::finite_double(value),
2247            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2248            SerdeValue::String(value) => Ok(Self::String(value)),
2249            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2250            SerdeValue::Option(None) => Ok(Self::Null),
2251            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2252                Self::from_serde_value(*value)
2253            }
2254            SerdeValue::Seq(values) => values
2255                .into_iter()
2256                .map(Self::from_serde_value)
2257                .collect::<Result<Vec<_>>>()
2258                .map(Self::Array),
2259            SerdeValue::Map(values) => values
2260                .into_iter()
2261                .map(|(key, value)| {
2262                    let SerdeValue::String(key) = key else {
2263                        return Err(Error::Codec(
2264                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2265                        ));
2266                    };
2267
2268                    Ok((key, Self::from_serde_value(value)?))
2269                })
2270                .collect::<Result<BTreeMap<_, _>>>()
2271                .map(Self::Map),
2272        }
2273    }
2274
2275    fn finite_double(value: f64) -> Result<Self> {
2276        if !value.is_finite() {
2277            return Err(Error::Codec(
2278                "non_finite_float: Avro Value doubles must be finite".to_string(),
2279            ));
2280        }
2281
2282        Ok(Self::Double(value))
2283    }
2284
2285    fn into_json(self) -> Result<Value> {
2286        match self {
2287            Self::Null => Ok(Value::Null),
2288            Self::Boolean(value) => Ok(Value::Bool(value)),
2289            Self::Long(value) => Ok(Value::Number(value.into())),
2290            Self::Double(value) => serde_json::Number::from_f64(value)
2291                .map(Value::Number)
2292                .ok_or_else(|| {
2293                    Error::Codec(
2294                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2295                    )
2296                }),
2297            Self::Bytes(value) => Ok(json!({
2298                "$type": "bytes",
2299                "base64": BASE64.encode(value),
2300            })),
2301            Self::String(value) => Ok(Value::String(value)),
2302            Self::Array(values) => values
2303                .into_iter()
2304                .map(Self::into_json)
2305                .collect::<Result<Vec<_>>>()
2306                .map(Value::Array),
2307            Self::Map(values) => values
2308                .into_iter()
2309                .map(|(key, value)| Ok((key, value.into_json()?)))
2310                .collect::<Result<serde_json::Map<_, _>>>()
2311                .map(Value::Object),
2312        }
2313    }
2314
2315    fn into_serde_value(self) -> serde_value::Value {
2316        use serde_value::Value as SerdeValue;
2317
2318        match self {
2319            Self::Null => SerdeValue::Unit,
2320            Self::Boolean(value) => SerdeValue::Bool(value),
2321            Self::Long(value) => SerdeValue::I64(value),
2322            Self::Double(value) => SerdeValue::F64(value),
2323            Self::Bytes(value) => SerdeValue::Bytes(value),
2324            Self::String(value) => SerdeValue::String(value),
2325            Self::Array(values) => {
2326                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2327            }
2328            Self::Map(values) => SerdeValue::Map(
2329                values
2330                    .into_iter()
2331                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2332                    .collect(),
2333            ),
2334        }
2335    }
2336
2337    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2338        self.into_serde_value().deserialize_into().map_err(|error| {
2339            Error::Codec(format!(
2340                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2341            ))
2342        })
2343    }
2344}
2345
2346impl Serialize for AvroValue {
2347    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2348    where
2349        S: Serializer,
2350    {
2351        match self {
2352            Self::Null => serializer.serialize_unit(),
2353            Self::Boolean(value) => serializer.serialize_bool(*value),
2354            Self::Long(value) => serializer.serialize_i64(*value),
2355            Self::Double(value) => serializer.serialize_f64(*value),
2356            Self::Bytes(value) => serializer.serialize_bytes(value),
2357            Self::String(value) => serializer.serialize_str(value),
2358            Self::Array(values) => {
2359                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2360                for value in values {
2361                    sequence.serialize_element(value)?;
2362                }
2363                sequence.end()
2364            }
2365            Self::Map(values) => {
2366                let mut map = serializer.serialize_map(Some(values.len()))?;
2367                for (key, value) in values {
2368                    map.serialize_entry(key, value)?;
2369                }
2370                map.end()
2371            }
2372        }
2373    }
2374}
2375
2376pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2377    let datum = avro_value_to_datum(value)?;
2378    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2379        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2380    let mut bytes = Vec::with_capacity(datum.len() + 10);
2381    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2382    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2383    bytes.extend_from_slice(&datum);
2384    Ok(PayloadEnvelope {
2385        codec: DEFAULT_CODEC.to_string(),
2386        blob: BASE64.encode(bytes),
2387    })
2388}
2389
2390pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2391    if envelope.codec != DEFAULT_CODEC {
2392        return Err(unsupported_payload_codec(&envelope.codec));
2393    }
2394    decode_avro_value_blob(&envelope.blob)
2395}
2396
2397pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2398    let blob = match codec {
2399        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2400        other => return Err(unsupported_payload_codec(other)),
2401    };
2402
2403    Ok(PayloadEnvelope {
2404        codec: codec.to_string(),
2405        blob,
2406    })
2407}
2408
2409pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2410    match envelope.codec.as_str() {
2411        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2412        other => Err(unsupported_payload_codec(other)),
2413    }
2414}
2415
2416fn handler_type_error<T>(
2417    handler_kind: HandlerKind,
2418    handler_name: &str,
2419    value_kind: HandlerValueKind,
2420    message: impl Into<String>,
2421) -> Error {
2422    Error::HandlerType {
2423        handler_kind,
2424        handler_name: handler_name.to_string(),
2425        value_kind,
2426        rust_type: type_name::<T>(),
2427        message: message.into(),
2428    }
2429}
2430
2431fn decode_handler_input<T: DeserializeOwned>(
2432    arguments: AvroValue,
2433    handler_kind: HandlerKind,
2434    handler_name: &str,
2435) -> Result<T> {
2436    let argument = match arguments {
2437        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2438            arguments.pop().expect("one typed handler argument")
2439        }
2440        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2441        AvroValue::Array(arguments) => {
2442            return Err(handler_type_error::<T>(
2443                handler_kind,
2444                handler_name,
2445                HandlerValueKind::Input,
2446                format!(
2447                    "typed handlers accept one request value, but the task carried {} arguments",
2448                    arguments.len()
2449                ),
2450            ));
2451        }
2452        argument => argument,
2453    };
2454
2455    argument.deserialize().map_err(|error| {
2456        handler_type_error::<T>(
2457            handler_kind,
2458            handler_name,
2459            HandlerValueKind::Input,
2460            error.to_string(),
2461        )
2462    })
2463}
2464
2465fn decode_workflow_entry<T: DeserializeOwned>(
2466    arguments: AvroValue,
2467    workflow_type: &str,
2468) -> Result<T> {
2469    decode_handler_input(arguments, HandlerKind::Workflow, workflow_type).map_err(|_| {
2470        // Serde errors may contain recorded values. The entry refusal exposes
2471        // only the registered workflow and expected Rust type.
2472        handler_type_error::<T>(
2473            HandlerKind::Workflow,
2474            workflow_type,
2475            HandlerValueKind::Input,
2476            "workflow_entry_arguments_mismatch: restore compatible entry code before retrying the original task",
2477        )
2478    })
2479}
2480
2481fn encode_handler_result<T: Serialize>(
2482    result: &T,
2483    handler_kind: HandlerKind,
2484    handler_name: &str,
2485) -> Result<AvroValue> {
2486    AvroValue::from_serialize(result).map_err(|error| {
2487        handler_type_error::<T>(
2488            handler_kind,
2489            handler_name,
2490            HandlerValueKind::Result,
2491            error.to_string(),
2492        )
2493    })
2494}
2495
2496fn decode_handler_result<T: DeserializeOwned>(
2497    result: AvroValue,
2498    handler_kind: HandlerKind,
2499    handler_name: &str,
2500) -> Result<T> {
2501    result.deserialize().map_err(|error| {
2502        handler_type_error::<T>(
2503            handler_kind,
2504            handler_name,
2505            HandlerValueKind::Result,
2506            error.to_string(),
2507        )
2508    })
2509}
2510
2511#[cfg(test)]
2512fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2513    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2514}
2515
2516fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2517    validate_payload_codec(fallback_codec)?;
2518
2519    if value.is_null() {
2520        return Ok(Value::Null);
2521    }
2522
2523    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2524        return decode_blob(blob, codec);
2525    }
2526
2527    if let Some(blob) = value.as_str() {
2528        return decode_blob(blob, fallback_codec);
2529    }
2530
2531    Err(untagged_payload_value())
2532}
2533
2534fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2535    let envelope = match codec {
2536        DEFAULT_CODEC => encode_avro_value(value)?,
2537        other => return Err(unsupported_payload_codec(other)),
2538    };
2539    Ok(serde_json::to_value(envelope)?)
2540}
2541
2542fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2543    validate_payload_codec(fallback_codec)?;
2544
2545    if value.is_null() {
2546        return Ok(AvroValue::Null);
2547    }
2548
2549    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2550        validate_payload_codec(codec)?;
2551        return decode_avro_value_blob(blob);
2552    }
2553
2554    if let Some(blob) = value.as_str() {
2555        return match fallback_codec {
2556            DEFAULT_CODEC => decode_avro_value_blob(blob),
2557            other => Err(unsupported_payload_codec(other)),
2558        };
2559    }
2560
2561    Err(untagged_payload_value())
2562}
2563
2564fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2565    match value {
2566        AvroValue::Null => AvroValue::Array(Vec::new()),
2567        AvroValue::Array(_) => value,
2568        other => AvroValue::Array(vec![other]),
2569    }
2570}
2571
2572fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2573    match codec {
2574        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2575        other => Err(unsupported_payload_codec(other)),
2576    }
2577}
2578
2579fn validate_payload_codec(codec: &str) -> Result<()> {
2580    match codec {
2581        DEFAULT_CODEC => Ok(()),
2582        MISSING_TASK_PAYLOAD_CODEC => {
2583            Err(invalid_task_payload_codec("task payload_codec is missing"))
2584        }
2585        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2586        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2587            "task payload_codec must be a string",
2588        )),
2589        other => Err(unsupported_payload_codec(other)),
2590    }
2591}
2592
2593fn invalid_task_payload_codec(reason: &str) -> Error {
2594    Error::Codec(format!(
2595        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2596    ))
2597}
2598
2599fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2600    let Some(object) = value.as_object() else {
2601        return Ok(None);
2602    };
2603    if !object.contains_key("codec") && !object.contains_key("blob") {
2604        return Ok(None);
2605    }
2606
2607    let codec = object
2608        .get("codec")
2609        .and_then(Value::as_str)
2610        .ok_or_else(invalid_payload_envelope)?;
2611    validate_payload_codec(codec)?;
2612    let blob = object
2613        .get("blob")
2614        .and_then(Value::as_str)
2615        .ok_or_else(invalid_payload_envelope)?;
2616    Ok(Some((codec, blob)))
2617}
2618
2619fn invalid_payload_envelope() -> Error {
2620    Error::Codec(
2621        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2622            .to_string(),
2623    )
2624}
2625
2626fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2627    for command in commands {
2628        let Some(command) = command.as_object() else {
2629            continue;
2630        };
2631        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2632            continue;
2633        };
2634        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2635            continue;
2636        };
2637
2638        if let Some(codec) = command.get("payload_codec") {
2639            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2640            validate_payload_codec(codec)?;
2641        }
2642
2643        let payload = command
2644            .get(payload_field)
2645            .ok_or_else(invalid_payload_envelope)?;
2646        if runtime_payloads::Reference::parse(payload)?.is_none() {
2647            validate_outbound_payload_envelope(payload)?;
2648        }
2649    }
2650    Ok(())
2651}
2652
2653fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2654    if commands.iter().any(|command| {
2655        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2656            && command
2657                .get("condition_wait_occurrence_id")
2658                .and_then(Value::as_str)
2659                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2660    }) {
2661        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2662    } else if commands.iter().any(|command| {
2663        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2664            && command.get("attribute_types").is_some()
2665    }) {
2666        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2667    } else if commands
2668        .iter()
2669        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2670    {
2671        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2672    } else if commands
2673        .iter()
2674        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2675    {
2676        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2677    } else if commands.iter().any(|command| {
2678        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2679    }) {
2680        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2681    } else {
2682        MINIMUM_WORKER_PROTOCOL_VERSION
2683    }
2684}
2685
2686fn workflow_completion_protocol_version_with_message_streams(
2687    commands: &[Value],
2688    has_message_stream_metadata: bool,
2689) -> &'static str {
2690    let command_protocol = workflow_completion_protocol_version(commands);
2691    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2692        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2693    } else {
2694        command_protocol
2695    }
2696}
2697
2698fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2699    match command_type {
2700        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2701        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2702        "start_service_operation" => Some("request_payload"),
2703        "upsert_memo" => Some("entries"),
2704        _ => None,
2705    }
2706}
2707
2708fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2709    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2710        return Err(untagged_payload_value());
2711    };
2712    validate_payload_codec(codec)?;
2713    decode_avro_value_blob(blob)?;
2714    Ok(())
2715}
2716
2717fn unsupported_payload_codec(codec: &str) -> Error {
2718    Error::Codec(format!(
2719        "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"
2720    ))
2721}
2722
2723fn untagged_payload_value() -> Error {
2724    Error::Codec(
2725        "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"
2726            .to_string(),
2727    )
2728}
2729
2730fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2731    let bytes = BASE64.decode(blob).map_err(|err| {
2732        Error::Codec(format!(
2733            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2734        ))
2735    })?;
2736
2737    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2738        return Err(unsupported_payload_codec("json"));
2739    }
2740
2741    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2742        return Err(Error::Codec(
2743            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2744        ));
2745    }
2746
2747    let fingerprint: [u8; 8] = bytes[2..10]
2748        .try_into()
2749        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2750    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2751        return Err(Error::Codec(format!(
2752            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2753            fingerprint
2754                .iter()
2755                .map(|byte| format!("{byte:02x}"))
2756                .collect::<String>()
2757        )));
2758    }
2759
2760    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2761    // The current fingerprint selects the current immutable schema, so reader
2762    // resolution would only re-walk the same recursive union. Future retained
2763    // writer fingerprints supply a distinct reader schema in this branch.
2764    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2765    if datum_reader.truncated {
2766        return Err(Error::Codec(
2767            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2768        ));
2769    }
2770    let datum = datum.map_err(|err| {
2771        Error::Codec(format!(
2772            "invalid_payload_framing: malformed Avro Value datum: {err}"
2773        ))
2774    })?;
2775    if datum_reader.remaining() != 0 {
2776        return Err(Error::Codec(format!(
2777            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2778            datum_reader.remaining()
2779        )));
2780    }
2781    avro_value_from_datum(datum)
2782}
2783
2784struct StrictAvroDatumReader<'a> {
2785    bytes: &'a [u8],
2786    offset: usize,
2787    truncated: bool,
2788}
2789
2790impl<'a> StrictAvroDatumReader<'a> {
2791    fn new(bytes: &'a [u8]) -> Self {
2792        Self {
2793            bytes,
2794            offset: 0,
2795            truncated: false,
2796        }
2797    }
2798
2799    fn remaining(&self) -> usize {
2800        self.bytes.len() - self.offset
2801    }
2802}
2803
2804impl Read for StrictAvroDatumReader<'_> {
2805    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
2806        let count = buffer.len().min(self.remaining());
2807        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
2808        self.offset += count;
2809        if count < buffer.len() {
2810            self.truncated = true;
2811        }
2812
2813        Ok(count)
2814    }
2815}
2816
2817fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
2818    let branch = match value {
2819        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
2820        AvroValue::Boolean(value) => AvroDatum::Union(
2821            1,
2822            Box::new(AvroDatum::Record(vec![(
2823                "boolean".to_string(),
2824                AvroDatum::Boolean(*value),
2825            )])),
2826        ),
2827        AvroValue::Long(value) => AvroDatum::Union(
2828            2,
2829            Box::new(AvroDatum::Record(vec![(
2830                "long".to_string(),
2831                AvroDatum::Long(*value),
2832            )])),
2833        ),
2834        AvroValue::Double(value) => {
2835            if !value.is_finite() {
2836                return Err(Error::Codec(
2837                    "non_finite_float: Avro Value doubles must be finite".to_string(),
2838                ));
2839            }
2840            AvroDatum::Union(
2841                3,
2842                Box::new(AvroDatum::Record(vec![(
2843                    "double".to_string(),
2844                    AvroDatum::Double(*value),
2845                )])),
2846            )
2847        }
2848        AvroValue::Bytes(value) => AvroDatum::Union(
2849            4,
2850            Box::new(AvroDatum::Record(vec![(
2851                "bytes".to_string(),
2852                AvroDatum::Bytes(value.clone()),
2853            )])),
2854        ),
2855        AvroValue::String(value) => AvroDatum::Union(
2856            5,
2857            Box::new(AvroDatum::Record(vec![(
2858                "string".to_string(),
2859                AvroDatum::String(value.clone()),
2860            )])),
2861        ),
2862        AvroValue::Array(values) => AvroDatum::Union(
2863            6,
2864            Box::new(AvroDatum::Record(vec![(
2865                "items".to_string(),
2866                AvroDatum::Array(
2867                    values
2868                        .iter()
2869                        .map(avro_value_to_datum)
2870                        .collect::<Result<Vec<_>>>()?,
2871                ),
2872            )])),
2873        ),
2874        AvroValue::Map(values) => AvroDatum::Union(
2875            7,
2876            Box::new(AvroDatum::Record(vec![(
2877                "entries".to_string(),
2878                AvroDatum::Array(
2879                    values
2880                        .iter()
2881                        .map(|(key, value)| {
2882                            Ok(AvroDatum::Record(vec![
2883                                ("key".to_string(), AvroDatum::String(key.clone())),
2884                                ("value".to_string(), avro_value_to_datum(value)?),
2885                            ]))
2886                        })
2887                        .collect::<Result<Vec<_>>>()?,
2888                ),
2889            )])),
2890        ),
2891    };
2892    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
2893}
2894
2895fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
2896    let AvroDatum::Record(mut outer) = datum else {
2897        return Err(Error::Codec(
2898            "invalid_payload_framing: datum is not a Value record".to_string(),
2899        ));
2900    };
2901    let (_, branch) = outer
2902        .pop()
2903        .filter(|(name, _)| name == "value")
2904        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
2905    let AvroDatum::Union(_, branch) = branch else {
2906        return Err(Error::Codec(
2907            "invalid_payload_framing: invalid Value union".to_string(),
2908        ));
2909    };
2910    match *branch {
2911        AvroDatum::Null => Ok(AvroValue::Null),
2912        AvroDatum::Record(mut fields) => {
2913            let (name, value) = fields.pop().ok_or_else(|| {
2914                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
2915            })?;
2916            match (name.as_str(), value) {
2917                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
2918                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
2919                ("double", AvroDatum::Double(value)) if value.is_finite() => {
2920                    Ok(AvroValue::Double(value))
2921                }
2922                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
2923                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
2924                ("items", AvroDatum::Array(values)) => values
2925                    .into_iter()
2926                    .map(avro_value_from_datum)
2927                    .collect::<Result<Vec<_>>>()
2928                    .map(AvroValue::Array),
2929                ("entries", AvroDatum::Map(values)) => values
2930                    .into_iter()
2931                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
2932                    .collect::<Result<BTreeMap<_, _>>>()
2933                    .map(AvroValue::Map),
2934                _ => Err(Error::Codec(
2935                    "invalid_payload_framing: unknown Value branch".to_string(),
2936                )),
2937            }
2938        }
2939        _ => Err(Error::Codec(
2940            "invalid_payload_framing: invalid Value branch".to_string(),
2941        )),
2942    }
2943}
2944
2945fn avro_value_schema() -> Result<&'static Schema> {
2946    match AVRO_VALUE_SCHEMA.get_or_init(|| {
2947        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
2948            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
2949    }) {
2950        Ok(schema) => Ok(schema),
2951        Err(message) => Err(Error::Codec(message.clone())),
2952    }
2953}
2954
2955fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
2956    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
2957        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
2958        // have the same block representation when each ordered array record
2959        // contains the map key followed by its value, so this encoding-only
2960        // adaptation lets the official encoder retain BTreeMap wire order.
2961        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
2962            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
2963        let entries_schema = schema
2964            .pointer_mut("/fields/0/type/7/fields/0/type")
2965            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
2966        if *entries_schema != json!({"type": "map", "values": "Value"}) {
2967            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
2968        }
2969        *entries_schema = json!({
2970            "type": "array",
2971            "items": {
2972                "type": "record",
2973                "name": "MapEntry",
2974                "fields": [
2975                    {"name": "key", "type": "string"},
2976                    {"name": "value", "type": "Value"}
2977                ]
2978            }
2979        });
2980        Schema::parse_str(&schema.to_string())
2981            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
2982    }) {
2983        Ok(schema) => Ok(schema),
2984        Err(message) => Err(Error::Codec(message.clone())),
2985    }
2986}
2987
2988#[derive(Clone, Debug)]
2989pub struct Client {
2990    metrics: metrics::Metrics,
2991    http: reqwest::Client,
2992    hydration_timeout: Duration,
2993    base_url: String,
2994    token: Option<String>,
2995    control_token: Option<String>,
2996    worker_token: Option<String>,
2997    namespace: String,
2998    max_external_payload_bytes: usize,
2999    worker_storage_admission: Option<WorkerStorageAdmission>,
3000    worker_task_slot: Option<Arc<worker_capacity::TaskSlotMarker>>,
3001    cooperative_worker_protocol: bool,
3002    worker_protocol_version: WorkerProtocolVersion,
3003    local_activities_enabled: bool,
3004    worker_sessions_enabled: bool,
3005    max_concurrent_worker_sessions: usize,
3006    worker_build_id: Option<String>,
3007    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
3008    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
3009    activity_lease_renewal_supported: Arc<AtomicBool>,
3010    activity_lease_authority: Option<Arc<activity_lease::authority::Authority>>,
3011    #[cfg(feature = "telemetry")]
3012    execution_telemetry: Option<telemetry::ExecutionTelemetry>,
3013    #[cfg(feature = "telemetry")]
3014    observability_context_supported: Arc<AtomicBool>,
3015}
3016
3017impl Client {
3018    /// Configure optional propagation. Actual cluster discovery must advertise
3019    /// the exact supported capability before any command carries context.
3020    #[cfg(feature = "telemetry")]
3021    pub fn with_telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
3022        self.execution_telemetry = Some(telemetry);
3023        self
3024    }
3025
3026    #[cfg(feature = "telemetry")]
3027    fn with_observability_context(&self, mut body: Value) -> Value {
3028        if self.observability_context_supported.load(Ordering::SeqCst) {
3029            if let Some(context) = self
3030                .execution_telemetry
3031                .as_ref()
3032                .and_then(|telemetry| telemetry.capture())
3033            {
3034                body["observability_context"] = context;
3035            }
3036        }
3037        body
3038    }
3039
3040    #[cfg(not(feature = "telemetry"))]
3041    fn with_observability_context(&self, body: Value) -> Value {
3042        body
3043    }
3044
3045    pub fn new(base_url: impl Into<String>) -> Result<Self> {
3046        Self::builder(base_url).build()
3047    }
3048
3049    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
3050        ClientBuilder {
3051            base_url: base_url.into(),
3052            token: None,
3053            control_token: None,
3054            worker_token: None,
3055            namespace: "default".to_string(),
3056            timeout: Duration::from_secs(60),
3057            max_external_payload_bytes: 64 * 1024 * 1024,
3058            worker_protocol_version: WorkerProtocolVersion::default(),
3059            additional_root_certificates: Vec::new(),
3060            metrics: metrics::Metrics::default(),
3061        }
3062    }
3063
3064    pub async fn health(&self) -> Result<Value> {
3065        self.request_json(
3066            reqwest::Method::GET,
3067            "/health",
3068            RequestProtocol::ControlPlane,
3069            Option::<&Value>::None,
3070        )
3071        .await
3072    }
3073
3074    pub async fn cluster_info(&self) -> Result<Value> {
3075        let discovery: Value = self
3076            .request_json(
3077                reqwest::Method::GET,
3078                "/cluster/info",
3079                RequestProtocol::ControlPlane,
3080                Option::<&Value>::None,
3081            )
3082            .await?;
3083        self.observe_activity_lease_capabilities(
3084            &discovery["worker_protocol"]["server_capabilities"],
3085        );
3086        Ok(discovery)
3087    }
3088
3089    pub async fn start_workflow<T: Serialize>(
3090        &self,
3091        workflow_type: &str,
3092        task_queue: &str,
3093        workflow_id: &str,
3094        input: T,
3095    ) -> Result<WorkflowHandle> {
3096        self.start_workflow_with_options(
3097            workflow_type,
3098            task_queue,
3099            workflow_id,
3100            WorkflowStartOptions::default(),
3101            input,
3102        )
3103        .await
3104    }
3105
3106    /// Start a workflow with explicit server-enforced execution and run
3107    /// deadlines.
3108    pub async fn start_workflow_with_options<T: Serialize>(
3109        &self,
3110        workflow_type: &str,
3111        task_queue: &str,
3112        workflow_id: &str,
3113        options: WorkflowStartOptions,
3114        input: T,
3115    ) -> Result<WorkflowHandle> {
3116        options.validate()?;
3117        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3118        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3119        let body = self.with_observability_context(json!({
3120            "workflow_id": workflow_id,
3121            "workflow_type": workflow_type,
3122            "task_queue": task_queue,
3123            "input": input_envelope,
3124            "execution_timeout_seconds": options.execution_timeout_seconds,
3125            "run_timeout_seconds": options.run_timeout_seconds
3126        }));
3127
3128        let data: Value = self
3129            .request_json(
3130                reqwest::Method::POST,
3131                "/workflows",
3132                RequestProtocol::ControlPlane,
3133                Some(&body),
3134            )
3135            .await?;
3136
3137        Ok(WorkflowHandle {
3138            client: self.clone(),
3139            workflow_id: data
3140                .get("workflow_id")
3141                .and_then(Value::as_str)
3142                .unwrap_or(workflow_id)
3143                .to_string(),
3144            run_id: data
3145                .get("run_id")
3146                .and_then(Value::as_str)
3147                .map(str::to_string),
3148            workflow_type: data
3149                .get("workflow_type")
3150                .and_then(Value::as_str)
3151                .unwrap_or(workflow_type)
3152                .to_string(),
3153        })
3154    }
3155
3156    /// Send a signal with an SDK-generated caller command key.
3157    ///
3158    /// The key is sent as the `request_id` body field and is present in the
3159    /// returned receipt's `request_id`. A Server that already retains the key
3160    /// for the same signal intent returns the original receipt with
3161    /// `retained: true`; a different intent is refused with
3162    /// [`Error::is_request_id_conflict`]. Choose the key yourself with
3163    /// [`Client::signal_workflow_with_request_id`] when the application must be
3164    /// able to retry the same logical signal after a transport failure.
3165    pub async fn signal_workflow<T: Serialize>(
3166        &self,
3167        workflow_id: &str,
3168        signal_name: &str,
3169        input: T,
3170    ) -> Result<Value> {
3171        let request_id = Self::generate_signal_request_id();
3172        self.signal_workflow_target(workflow_id, None, signal_name, input, &request_id)
3173            .await
3174    }
3175
3176    /// Send a signal with an explicit caller command key (1 to 255 Unicode characters).
3177    ///
3178    /// Resend the identical signal with the same key after an uncertain
3179    /// outcome: the Server returns the retained receipt instead of admitting a
3180    /// second signal, for as long as the retained run's details are kept.
3181    pub async fn signal_workflow_with_request_id<T: Serialize>(
3182        &self,
3183        workflow_id: &str,
3184        signal_name: &str,
3185        input: T,
3186        request_id: &str,
3187    ) -> Result<Value> {
3188        self.signal_workflow_target(workflow_id, None, signal_name, input, request_id)
3189            .await
3190    }
3191
3192    /// A fresh caller command key for one logical signal (`sdk-rust-signal-<uuid>`).
3193    ///
3194    /// Methods without an explicit key generate one of these per call. Obtain it
3195    /// up front and pass it to [`Client::signal_workflow_with_request_id`] so a
3196    /// transport failure does not lose the key needed for a safe retry.
3197    pub fn generate_signal_request_id() -> String {
3198        generated_request_id("signal")
3199    }
3200
3201    /// A fresh caller command key for one logical update (`sdk-rust-update-<uuid>`).
3202    ///
3203    /// [`Client::update_workflow`] generates one of these when `request_id` is
3204    /// `None`. Obtain it up front and pass it explicitly so a transport failure
3205    /// does not lose the key needed for a safe retry.
3206    pub fn generate_update_request_id() -> String {
3207        generated_request_id("update")
3208    }
3209
3210    /// Append one idempotently identified item to an instance-scoped input stream.
3211    pub async fn append_message_stream<T: Serialize>(
3212        &self,
3213        workflow_id: &str,
3214        stream_name: &str,
3215        message_id: &str,
3216        input: T,
3217    ) -> Result<Value> {
3218        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3219        let body = json!({
3220            "message_id": message_id,
3221            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
3222        });
3223        self.request_json(
3224            reqwest::Method::POST,
3225            &format!("/workflows/{workflow_id}/message-streams/{stream_name}/messages"),
3226            RequestProtocol::ControlPlane,
3227            Some(&body),
3228        )
3229        .await
3230    }
3231
3232    /// Signal only if `run_id` is still the current run for this instance,
3233    /// with an SDK-generated caller command key.
3234    pub async fn signal_workflow_run<T: Serialize>(
3235        &self,
3236        workflow_id: &str,
3237        run_id: &str,
3238        signal_name: &str,
3239        input: T,
3240    ) -> Result<Value> {
3241        let request_id = Self::generate_signal_request_id();
3242        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, &request_id)
3243            .await
3244    }
3245
3246    /// Signal only if `run_id` is still the current run for this instance,
3247    /// with an explicit caller command key (1 to 255 Unicode characters).
3248    ///
3249    /// The selected run is part of the signal's intent: retrying with the same
3250    /// key and a different run target is a `request_id_conflict` refusal.
3251    pub async fn signal_workflow_run_with_request_id<T: Serialize>(
3252        &self,
3253        workflow_id: &str,
3254        run_id: &str,
3255        signal_name: &str,
3256        input: T,
3257        request_id: &str,
3258    ) -> Result<Value> {
3259        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, request_id)
3260            .await
3261    }
3262
3263    async fn signal_workflow_target<T: Serialize>(
3264        &self,
3265        workflow_id: &str,
3266        run_id: Option<&str>,
3267        signal_name: &str,
3268        input: T,
3269        request_id: &str,
3270    ) -> Result<Value> {
3271        validate_user_signal_name(signal_name)?;
3272        validate_request_id(request_id)?;
3273        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3274        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3275        let body = self.with_observability_context(json!({
3276            "input": input_envelope,
3277            "request_id": request_id,
3278        }));
3279        let path = match run_id {
3280            Some(run_id) => {
3281                format!("/workflows/{workflow_id}/runs/{run_id}/signal/{signal_name}")
3282            }
3283            None => format!("/workflows/{workflow_id}/signal/{signal_name}"),
3284        };
3285        let receipt = self
3286            .request_json(
3287                reqwest::Method::POST,
3288                &path,
3289                RequestProtocol::ControlPlane,
3290                Some(&body),
3291            )
3292            .await?;
3293        Ok(with_request_id(receipt, request_id))
3294    }
3295
3296    /// Close the current run as cancelled immediately.
3297    ///
3298    /// Server revokes open tasks and timers without resuming workflow code for
3299    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3300    /// request on a supporting runtime and opted-in worker.
3301    pub async fn cancel_workflow(
3302        &self,
3303        workflow_id: &str,
3304        options: WorkflowCommandOptions,
3305    ) -> Result<WorkflowCommandResult> {
3306        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3307            .await
3308    }
3309
3310    /// Close the selected run as cancelled, only if `run_id` is still current.
3311    pub async fn cancel_workflow_run(
3312        &self,
3313        workflow_id: &str,
3314        run_id: &str,
3315        options: WorkflowCommandOptions,
3316    ) -> Result<WorkflowCommandResult> {
3317        self.workflow_command(
3318            workflow_id,
3319            Some(run_id),
3320            WorkflowCommandKind::Cancel,
3321            options,
3322        )
3323        .await
3324    }
3325
3326    /// Forcefully terminate the current run for an instance.
3327    pub async fn terminate_workflow(
3328        &self,
3329        workflow_id: &str,
3330        options: WorkflowCommandOptions,
3331    ) -> Result<WorkflowCommandResult> {
3332        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3333            .await
3334    }
3335
3336    /// Forcefully terminate only if `run_id` is still current.
3337    pub async fn terminate_workflow_run(
3338        &self,
3339        workflow_id: &str,
3340        run_id: &str,
3341        options: WorkflowCommandOptions,
3342    ) -> Result<WorkflowCommandResult> {
3343        self.workflow_command(
3344            workflow_id,
3345            Some(run_id),
3346            WorkflowCommandKind::Terminate,
3347            options,
3348        )
3349        .await
3350    }
3351
3352    /// Continue a failed run from its recorded activity failure boundary.
3353    pub async fn redrive_workflow_run(
3354        &self,
3355        workflow_id: &str,
3356        failed_run_id: &str,
3357        request_id: Option<&str>,
3358    ) -> Result<WorkflowRedriveResult> {
3359        let body = request_id
3360            .map(|id| json!({"request_id": id}))
3361            .unwrap_or_else(|| json!({}));
3362        let data: Value = self
3363            .request_json(
3364                reqwest::Method::POST,
3365                &format!("/workflows/{workflow_id}/runs/{failed_run_id}/redrive"),
3366                RequestProtocol::ControlPlane,
3367                Some(&body),
3368            )
3369            .await?;
3370        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3371            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3372        {
3373            return Err(Error::Codec(
3374                "redrive response was not accepted".to_string(),
3375            ));
3376        }
3377        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3378            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3379        {
3380            return Err(Error::Codec(
3381                "redrive response does not match the requested source run".to_string(),
3382            ));
3383        }
3384        let run_id = data
3385            .get("run_id")
3386            .and_then(Value::as_str)
3387            .filter(|id| !id.is_empty() && *id != failed_run_id)
3388            .ok_or_else(|| {
3389                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3390            })?;
3391        let resume_step_sequence = data
3392            .get("resume_step_sequence")
3393            .and_then(Value::as_u64)
3394            .filter(|sequence| *sequence > 0)
3395            .ok_or_else(|| {
3396                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3397            })?;
3398        Ok(WorkflowRedriveResult {
3399            workflow_id: workflow_id.to_string(),
3400            source_run_id: failed_run_id.to_string(),
3401            run_id: run_id.to_string(),
3402            resume_step_sequence,
3403            raw: data,
3404        })
3405    }
3406
3407    async fn workflow_command(
3408        &self,
3409        workflow_id: &str,
3410        run_id: Option<&str>,
3411        command: WorkflowCommandKind,
3412        options: WorkflowCommandOptions,
3413    ) -> Result<WorkflowCommandResult> {
3414        #[cfg(feature = "telemetry")]
3415        let body = if command == WorkflowCommandKind::Cancel {
3416            self.with_observability_context(serde_json::to_value(&options)?)
3417        } else {
3418            serde_json::to_value(&options)?
3419        };
3420        #[cfg(not(feature = "telemetry"))]
3421        let body = &options;
3422        let path = match run_id {
3423            Some(run_id) => format!(
3424                "/workflows/{workflow_id}/runs/{run_id}/{}",
3425                command.as_str()
3426            ),
3427            None => format!("/workflows/{workflow_id}/{}", command.as_str()),
3428        };
3429        let data = match self
3430            .request_json(
3431                reqwest::Method::POST,
3432                &path,
3433                RequestProtocol::ControlPlane,
3434                Some(&body),
3435            )
3436            .await
3437        {
3438            Ok(data) => data,
3439            Err(Error::Http { status, body }) => {
3440                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3441                    command,
3442                    status,
3443                    body,
3444                    workflow_id,
3445                    run_id,
3446                )));
3447            }
3448            Err(error) => return Err(error),
3449        };
3450
3451        Ok(workflow_command_result(command, data, workflow_id, run_id))
3452    }
3453
3454    /// Execute a named, read-only query against a running or completed workflow.
3455    ///
3456    /// Arguments and results use the platform payload envelope. Server and
3457    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3458    /// reason, HTTP status, and original response body.
3459    pub async fn query_workflow<T: Serialize>(
3460        &self,
3461        workflow_id: &str,
3462        query_name: &str,
3463        input: T,
3464    ) -> Result<Value> {
3465        self.query_workflow_target(workflow_id, None, query_name, input)
3466            .await
3467    }
3468
3469    /// Query only if `run_id` is still current, preventing accidental retargeting.
3470    pub async fn query_workflow_run<T: Serialize>(
3471        &self,
3472        workflow_id: &str,
3473        run_id: &str,
3474        query_name: &str,
3475        input: T,
3476    ) -> Result<Value> {
3477        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3478            .await
3479    }
3480
3481    /// Query a workflow and return the lossless fixed Avro Value result.
3482    pub async fn query_workflow_avro_value<T: Serialize>(
3483        &self,
3484        workflow_id: &str,
3485        query_name: &str,
3486        input: T,
3487    ) -> Result<AvroValue> {
3488        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3489            .await
3490    }
3491
3492    /// Query a selected run and return the lossless fixed Avro Value result.
3493    pub async fn query_workflow_run_avro_value<T: Serialize>(
3494        &self,
3495        workflow_id: &str,
3496        run_id: &str,
3497        query_name: &str,
3498        input: T,
3499    ) -> Result<AvroValue> {
3500        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3501            .await
3502    }
3503
3504    async fn query_workflow_avro_value_target<T: Serialize>(
3505        &self,
3506        workflow_id: &str,
3507        run_id: Option<&str>,
3508        query_name: &str,
3509        input: T,
3510    ) -> Result<AvroValue> {
3511        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3512        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3513        let path = match run_id {
3514            Some(run_id) => {
3515                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3516            }
3517            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3518        };
3519        let response: Value = match self
3520            .request_json(
3521                reqwest::Method::POST,
3522                &path,
3523                RequestProtocol::ControlPlane,
3524                Some(&body),
3525            )
3526            .await
3527        {
3528            Ok(response) => response,
3529            Err(Error::Http { status, body }) => {
3530                return Err(Error::QueryFailed(query_failure(status, body)));
3531            }
3532            Err(error) => return Err(error),
3533        };
3534
3535        let envelope = response
3536            .get("result_envelope")
3537            .filter(|envelope| !envelope.is_null())
3538            .ok_or_else(|| {
3539                Error::Codec(
3540                    "missing_payload_envelope: typed query result requires result_envelope"
3541                        .to_string(),
3542                )
3543            })?;
3544        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3545    }
3546
3547    async fn query_workflow_target<T: Serialize>(
3548        &self,
3549        workflow_id: &str,
3550        run_id: Option<&str>,
3551        query_name: &str,
3552        input: T,
3553    ) -> Result<Value> {
3554        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3555        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3556        let body = json!({
3557            "input": input_envelope
3558        });
3559        let path = match run_id {
3560            Some(run_id) => {
3561                format!("/workflows/{workflow_id}/runs/{run_id}/query/{query_name}")
3562            }
3563            None => format!("/workflows/{workflow_id}/query/{query_name}"),
3564        };
3565        let response: Value = match self
3566            .request_json(
3567                reqwest::Method::POST,
3568                &path,
3569                RequestProtocol::ControlPlane,
3570                Some(&body),
3571            )
3572            .await
3573        {
3574            Ok(response) => response,
3575            Err(Error::Http { status, body }) => {
3576                return Err(Error::QueryFailed(query_failure(status, body)));
3577            }
3578            Err(error) => return Err(error),
3579        };
3580
3581        if let Some(envelope) = response
3582            .get("result_envelope")
3583            .filter(|envelope| !envelope.is_null())
3584        {
3585            return decode_wire_value(envelope, DEFAULT_CODEC);
3586        }
3587
3588        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3589    }
3590
3591    /// Send a synchronous update using fixed Avro Value arguments.
3592    ///
3593    /// `request_id` is the caller command key (1 to 255 Unicode characters), sent as the
3594    /// `request_id` body field; `None` generates one with
3595    /// [`Client::generate_update_request_id`]. A Server that already retains the
3596    /// key for the same update intent returns the original update's receipt and
3597    /// result instead of admitting a second update; a different intent is
3598    /// refused with [`Error::is_request_id_conflict`].
3599    pub async fn update_workflow<T: Serialize>(
3600        &self,
3601        workflow_id: &str,
3602        update_name: &str,
3603        input: T,
3604        request_id: Option<&str>,
3605    ) -> Result<Value> {
3606        let response = self
3607            .update_workflow_response(workflow_id, update_name, input, request_id)
3608            .await?;
3609        if let Some(envelope) = response
3610            .get("result_envelope")
3611            .filter(|envelope| !envelope.is_null())
3612        {
3613            return decode_wire_value(envelope, DEFAULT_CODEC);
3614        }
3615        Ok(response.get("result").cloned().unwrap_or(response))
3616    }
3617
3618    /// Send a synchronous update and retain a bytes-capable Avro result.
3619    pub async fn update_workflow_avro_value<T: Serialize>(
3620        &self,
3621        workflow_id: &str,
3622        update_name: &str,
3623        input: T,
3624        request_id: Option<&str>,
3625    ) -> Result<AvroValue> {
3626        let response = self
3627            .update_workflow_response(workflow_id, update_name, input, request_id)
3628            .await?;
3629        let envelope = response
3630            .get("result_envelope")
3631            .filter(|envelope| !envelope.is_null())
3632            .ok_or_else(|| {
3633                Error::Codec(
3634                    "missing_payload_envelope: typed update result requires result_envelope"
3635                        .to_string(),
3636                )
3637            })?;
3638        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3639    }
3640
3641    async fn update_workflow_response<T: Serialize>(
3642        &self,
3643        workflow_id: &str,
3644        update_name: &str,
3645        input: T,
3646        request_id: Option<&str>,
3647    ) -> Result<Value> {
3648        let request_id = match request_id {
3649            Some(request_id) => {
3650                validate_request_id(request_id)?;
3651                request_id.to_string()
3652            }
3653            None => Self::generate_update_request_id(),
3654        };
3655        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3656        let body = self.with_observability_context(json!({
3657            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3658            "wait_for": "completed",
3659            "request_id": request_id,
3660        }));
3661        let receipt = self
3662            .request_json(
3663                reqwest::Method::POST,
3664                &format!("/workflows/{workflow_id}/update/{update_name}"),
3665                RequestProtocol::ControlPlane,
3666                Some(&body),
3667            )
3668            .await?;
3669        Ok(with_request_id(receipt, &request_id))
3670    }
3671
3672    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3673        let path = format!("/workflows/{workflow_id}");
3674        let mut data: WorkflowDescription = self
3675            .request_json(
3676                reqwest::Method::GET,
3677                &path,
3678                RequestProtocol::ControlPlane,
3679                Option::<&Value>::None,
3680            )
3681            .await?;
3682        data.decode_payloads()?;
3683        Ok(data)
3684    }
3685
3686    /// Describe one selected run, including historical terminal runs.
3687    pub async fn describe_workflow_run(
3688        &self,
3689        workflow_id: &str,
3690        run_id: &str,
3691    ) -> Result<WorkflowDescription> {
3692        let path = format!("/workflows/{workflow_id}/runs/{run_id}");
3693        let mut data: WorkflowDescription = self
3694            .request_json(
3695                reqwest::Method::GET,
3696                &path,
3697                RequestProtocol::ControlPlane,
3698                Option::<&Value>::None,
3699            )
3700            .await?;
3701        data.decode_payloads()?;
3702        Ok(data)
3703    }
3704
3705    fn workflow_stream_path(workflow_id: &str, run_id: &str, stream_name: Option<&str>) -> String {
3706        let mut path = format!(
3707            "/workflows/{}/runs/{}/streams",
3708            percent_encode_path_segment(workflow_id),
3709            percent_encode_path_segment(run_id),
3710        );
3711        if let Some(stream_name) = stream_name {
3712            path.push('/');
3713            path.push_str(&percent_encode_path_segment(stream_name));
3714        }
3715        path
3716    }
3717
3718    /// List the run-scoped output streams already opened by a workflow.
3719    pub async fn list_workflow_streams(
3720        &self,
3721        workflow_id: &str,
3722        run_id: &str,
3723    ) -> Result<Vec<WorkflowStreamDescription>> {
3724        let response: WorkflowStreamListResponse = self
3725            .request_json(
3726                reqwest::Method::GET,
3727                &Self::workflow_stream_path(workflow_id, run_id, None),
3728                RequestProtocol::ControlPlane,
3729                Option::<&Value>::None,
3730            )
3731            .await?;
3732        Ok(response.streams)
3733    }
3734
3735    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3736    pub async fn describe_workflow_stream(
3737        &self,
3738        workflow_id: &str,
3739        run_id: &str,
3740        stream_name: &str,
3741    ) -> Result<WorkflowStreamDescription> {
3742        let response: WorkflowStreamDescriptionResponse = self
3743            .request_json(
3744                reqwest::Method::GET,
3745                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3746                RequestProtocol::ControlPlane,
3747                Option::<&Value>::None,
3748            )
3749            .await?;
3750        Ok(response.stream)
3751    }
3752
3753    /// Read one bounded page beginning at a zero-based offset.
3754    ///
3755    /// Delivery is at least once: persist `next_offset` only after processing
3756    /// the page. The future is cancellation-safe; dropping it cancels the
3757    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3758    /// service contract.
3759    pub async fn subscribe_workflow_stream(
3760        &self,
3761        workflow_id: &str,
3762        run_id: &str,
3763        stream_name: &str,
3764        from_offset: u64,
3765        max_items: usize,
3766        wait: Duration,
3767    ) -> Result<WorkflowStreamPage> {
3768        let max_items = max_items.clamp(1, 500);
3769        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
3770        let path = format!(
3771            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
3772            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3773        );
3774        let response: WorkflowStreamPageResponse = self
3775            .request_json_with_timeout(
3776                reqwest::Method::GET,
3777                &path,
3778                RequestProtocol::ControlPlane,
3779                Option::<&Value>::None,
3780                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
3781            )
3782            .await?;
3783
3784        let items = response
3785            .items
3786            .into_iter()
3787            .map(|raw| {
3788                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
3789                let envelope = raw.get("payload").cloned();
3790                let payload = envelope
3791                    .as_ref()
3792                    .filter(|value| value.get("blob").is_some())
3793                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
3794                    .transpose()?
3795                    .map(AvroValue::into_json)
3796                    .transpose()?;
3797                Ok(WorkflowStreamItem {
3798                    offset,
3799                    payload,
3800                    payload_envelope: envelope,
3801                    payload_reference: raw
3802                        .get("payload_reference")
3803                        .and_then(Value::as_str)
3804                        .map(str::to_string),
3805                    payload_codec: raw
3806                        .get("payload_codec")
3807                        .and_then(Value::as_str)
3808                        .map(str::to_string),
3809                    idempotency_key: raw
3810                        .get("idempotency_key")
3811                        .and_then(Value::as_str)
3812                        .map(str::to_string),
3813                    item_type: raw
3814                        .get("item_type")
3815                        .and_then(Value::as_str)
3816                        .map(str::to_string),
3817                    content_type: raw
3818                        .get("content_type")
3819                        .and_then(Value::as_str)
3820                        .map(str::to_string),
3821                    origin: raw
3822                        .get("origin")
3823                        .and_then(Value::as_str)
3824                        .map(str::to_string),
3825                    origin_reference: raw
3826                        .get("origin_reference")
3827                        .and_then(Value::as_str)
3828                        .map(str::to_string),
3829                    emitted_at: raw
3830                        .get("emitted_at")
3831                        .and_then(Value::as_str)
3832                        .map(str::to_string),
3833                    raw,
3834                })
3835            })
3836            .collect::<Result<Vec<_>>>()?;
3837        Ok(WorkflowStreamPage {
3838            stream: response.stream,
3839            items,
3840            next_offset: response.next_offset,
3841            terminal: response.terminal,
3842        })
3843    }
3844
3845    /// Append inline Avro envelopes or opaque external payload references.
3846    pub async fn append_workflow_stream(
3847        &self,
3848        workflow_id: &str,
3849        run_id: &str,
3850        stream_name: &str,
3851        items: &[WorkflowStreamAppendItem],
3852        max_pending_items: Option<u64>,
3853    ) -> Result<WorkflowStreamAppendResult> {
3854        if items.is_empty() {
3855            return Err(Error::Codec(
3856                "workflow_stream_items_empty: append requires at least one item".to_string(),
3857            ));
3858        }
3859        let mut body = json!({
3860            "items": items
3861                .iter()
3862                .map(|item| item.wire_value(None))
3863                .collect::<Vec<_>>(),
3864        });
3865        if let Some(max_pending_items) = max_pending_items {
3866            if max_pending_items == 0 {
3867                return Err(Error::Codec(
3868                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
3869                        .to_string(),
3870                ));
3871            }
3872            body["max_pending_items"] = json!(max_pending_items);
3873        }
3874        let response: WorkflowStreamAppendResponse = self
3875            .request_json(
3876                reqwest::Method::POST,
3877                &format!(
3878                    "{}/items",
3879                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3880                ),
3881                RequestProtocol::ControlPlane,
3882                Some(&body),
3883            )
3884            .await?;
3885        Ok(WorkflowStreamAppendResult {
3886            stream: response.stream,
3887            accepted_offsets: response.accepted_offsets,
3888            accepted: response.accepted,
3889            deduped: response.deduped,
3890        })
3891    }
3892
3893    /// Close a stream, or mark it errored when `error_reason` is supplied.
3894    pub async fn close_workflow_stream(
3895        &self,
3896        workflow_id: &str,
3897        run_id: &str,
3898        stream_name: &str,
3899        error_reason: Option<&str>,
3900        retention_seconds: Option<u64>,
3901    ) -> Result<WorkflowStreamDescription> {
3902        let mut body = json!({});
3903        if let Some(error_reason) = error_reason {
3904            body["error_reason"] = json!(error_reason);
3905        }
3906        if let Some(retention_seconds) = retention_seconds {
3907            if retention_seconds == 0 {
3908                return Err(Error::Codec(
3909                    "workflow_stream_retention_invalid: retention_seconds must be positive"
3910                        .to_string(),
3911                ));
3912            }
3913            body["retention_seconds"] = json!(retention_seconds);
3914        }
3915        let response: WorkflowStreamDescriptionResponse = self
3916            .request_json(
3917                reqwest::Method::POST,
3918                &format!(
3919                    "{}/close",
3920                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name)),
3921                ),
3922                RequestProtocol::ControlPlane,
3923                Some(&body),
3924            )
3925            .await?;
3926        Ok(response.stream)
3927    }
3928
3929    pub async fn register_worker(
3930        &self,
3931        worker_id: &str,
3932        task_queue: &str,
3933        supported_workflow_types: Vec<String>,
3934        supported_activity_types: Vec<String>,
3935        max_concurrent_workflow_tasks: usize,
3936        max_concurrent_activity_tasks: usize,
3937    ) -> Result<RegisterWorkerResponse> {
3938        self.register_worker_with_capabilities(
3939            worker_id,
3940            task_queue,
3941            supported_workflow_types,
3942            supported_activity_types,
3943            max_concurrent_workflow_tasks,
3944            max_concurrent_activity_tasks,
3945            Vec::new(),
3946        )
3947        .await
3948    }
3949
3950    /// Register a worker and explicitly advertise additive worker capabilities.
3951    pub async fn register_worker_with_capabilities(
3952        &self,
3953        worker_id: &str,
3954        task_queue: &str,
3955        supported_workflow_types: Vec<String>,
3956        supported_activity_types: Vec<String>,
3957        max_concurrent_workflow_tasks: usize,
3958        max_concurrent_activity_tasks: usize,
3959        capabilities: Vec<String>,
3960    ) -> Result<RegisterWorkerResponse> {
3961        self.register_worker_with_command_contracts(
3962            worker_id,
3963            task_queue,
3964            supported_workflow_types,
3965            supported_activity_types,
3966            max_concurrent_workflow_tasks,
3967            max_concurrent_activity_tasks,
3968            capabilities,
3969            Value::Object(serde_json::Map::new()),
3970        )
3971        .await
3972    }
3973
3974    /// Register a worker and advertise its named query and update handlers.
3975    ///
3976    /// This Rust SDK cannot execute synchronous pre-accept update validation,
3977    /// so a workflow contract with a non-empty or malformed
3978    /// `update_validators` declaration returns
3979    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
3980    #[allow(clippy::too_many_arguments)]
3981    pub async fn register_worker_with_command_contracts(
3982        &self,
3983        worker_id: &str,
3984        task_queue: &str,
3985        supported_workflow_types: Vec<String>,
3986        supported_activity_types: Vec<String>,
3987        max_concurrent_workflow_tasks: usize,
3988        max_concurrent_activity_tasks: usize,
3989        capabilities: Vec<String>,
3990        workflow_command_contracts: Value,
3991    ) -> Result<RegisterWorkerResponse> {
3992        self.register_worker_with_definition_fingerprints(
3993            worker_id,
3994            task_queue,
3995            supported_workflow_types,
3996            supported_activity_types,
3997            max_concurrent_workflow_tasks,
3998            max_concurrent_activity_tasks,
3999            capabilities,
4000            workflow_command_contracts,
4001            None,
4002        )
4003        .await
4004    }
4005
4006    #[allow(clippy::too_many_arguments)]
4007    async fn register_worker_with_definition_fingerprints(
4008        &self,
4009        worker_id: &str,
4010        task_queue: &str,
4011        supported_workflow_types: Vec<String>,
4012        supported_activity_types: Vec<String>,
4013        max_concurrent_workflow_tasks: usize,
4014        max_concurrent_activity_tasks: usize,
4015        capabilities: Vec<String>,
4016        workflow_command_contracts: Value,
4017        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
4018    ) -> Result<RegisterWorkerResponse> {
4019        if let Some(contracts) = workflow_command_contracts.as_object() {
4020            for (workflow_type, contract) in contracts {
4021                let Some(update_validators) = contract.get("update_validators") else {
4022                    continue;
4023                };
4024                if !update_validators
4025                    .as_array()
4026                    .is_some_and(|validators| validators.is_empty())
4027                {
4028                    return Err(Error::UnsupportedUpdateValidators {
4029                        workflow_type: workflow_type.clone(),
4030                    });
4031                }
4032            }
4033        }
4034
4035        let mut body = json!({
4036            "worker_id": worker_id,
4037            "task_queue": task_queue,
4038            "runtime": "rust",
4039            "sdk_version": SDK_VERSION,
4040            "supported_workflow_types": supported_workflow_types,
4041            "supported_activity_types": supported_activity_types,
4042            "capabilities": capabilities,
4043            "capability_manifest": portable_worker_affinity_capability_manifest(),
4044            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
4045            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
4046        });
4047        if capabilities
4048            .iter()
4049            .any(|capability| capability == "nexus_cooperative_cancellation")
4050        {
4051            body["capability_manifest"]["nexus_cooperative_cancellation"] = json!({
4052                "supported":true, "minimum_protocol_version":"1.20",
4053                "implementation":"owned_workflow_run_canonical_delivery", "binding_kinds":["workflow_run"],
4054            });
4055        }
4056        if let Some(build_id) = &self.worker_build_id {
4057            if build_id.is_empty() || build_id.len() > 255 {
4058                return Err(Error::WorkerLoop(
4059                    "worker build ID must contain 1 to 255 bytes".into(),
4060                ));
4061            }
4062            body["build_id"] = json!(build_id);
4063        }
4064        if self.sticky_cache.is_some() {
4065            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
4066                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
4067                "implementation":"bounded_durable_history_cache"});
4068        }
4069        if self.local_activities_enabled {
4070            body["capability_manifest"]["local_activities"] = json!({"supported":true,
4071                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4072        }
4073        if self.worker_sessions_enabled {
4074            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
4075                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4076            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
4077        }
4078        if workflow_command_contracts
4079            .as_object()
4080            .is_some_and(|contracts| !contracts.is_empty())
4081        {
4082            body["workflow_command_contracts"] = workflow_command_contracts;
4083        }
4084        if let Some(fingerprints) = workflow_definition_fingerprints {
4085            body["workflow_definition_fingerprints"] = json!(fingerprints);
4086        }
4087
4088        let response: Value = self
4089            .request_json(
4090                reqwest::Method::POST,
4091                "/worker/register",
4092                RequestProtocol::DefaultWorker,
4093                Some(&body),
4094            )
4095            .await?;
4096        if response["registered"] == true && response["worker_id"].as_str() == Some(worker_id) {
4097            self.observe_activity_lease_capabilities(&response["server_capabilities"]);
4098        }
4099        if self.sticky_cache.is_some() {
4100            self.confirm_sticky_registration(&response, worker_id, task_queue)
4101                .await?;
4102        }
4103        if self.local_activities_enabled || self.worker_sessions_enabled {
4104            let compatible = response["registered"].as_bool() == Some(true)
4105                && response["worker_id"].as_str() == Some(worker_id)
4106                && response["namespace"].as_str() == Some(self.namespace.as_str())
4107                && response["task_queue"].as_str() == Some(task_queue)
4108                && response["protocol_version"]
4109                    .as_str()
4110                    .and_then(|version| version.strip_prefix("1."))
4111                    .and_then(|minor| minor.parse::<u64>().ok())
4112                    .is_some_and(|minor| minor >= 18)
4113                && (!self.local_activities_enabled
4114                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
4115                        == Some(true))
4116                && (!self.worker_sessions_enabled
4117                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
4118                        == Some(true)
4119                        && response["capabilities"].as_array().is_some_and(|accepted| {
4120                            capabilities.iter().all(|capability| {
4121                                accepted
4122                                    .iter()
4123                                    .any(|value| value.as_str() == Some(capability.as_str()))
4124                            })
4125                        })));
4126            if !compatible {
4127                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
4128                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
4129                } else {
4130                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
4131                });
4132                if response["registered"] == true
4133                    && response["worker_id"].as_str() == Some(worker_id)
4134                {
4135                    if let Err(deregistration) =
4136                        self.deregister_worker_registration(worker_id).await
4137                    {
4138                        return Err(Error::WorkerShutdown {
4139                            primary: Box::new(error),
4140                            deregistration: Box::new(deregistration),
4141                        });
4142                    }
4143                }
4144                return Err(error);
4145            }
4146        }
4147        if self.cooperative_worker_protocol {
4148            let compatible = response["registered"].as_bool() == Some(true)
4149                && response["worker_id"].as_str() == Some(worker_id)
4150                && response["namespace"].as_str() == Some(self.namespace.as_str())
4151                && response["task_queue"].as_str() == Some(task_queue)
4152                && response["protocol_version"]
4153                    .as_str()
4154                    .is_some_and(cooperative_cancellation::supports_protocol)
4155                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
4156                    == Some(true)
4157                && (!capabilities
4158                    .iter()
4159                    .any(|capability| capability == "nexus_cooperative_cancellation")
4160                    || nexus::installed_cooperation(&response["server_capabilities"]))
4161                && response["capabilities"].as_array().is_some_and(|accepted| {
4162                    capabilities.iter().all(|capability| {
4163                        accepted
4164                            .iter()
4165                            .any(|value| value.as_str() == Some(capability.as_str()))
4166                    })
4167                });
4168            if !compatible {
4169                let error = Error::CooperativeCancellationUnavailable(
4170                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
4171                );
4172                if response["registered"].as_bool() == Some(true)
4173                    && response["worker_id"].as_str() == Some(worker_id)
4174                {
4175                    if let Err(deregistration) =
4176                        self.deregister_worker_registration(worker_id).await
4177                    {
4178                        return Err(Error::WorkerShutdown {
4179                            primary: Box::new(error),
4180                            deregistration: Box::new(deregistration),
4181                        });
4182                    }
4183                }
4184                return Err(error);
4185            }
4186        }
4187        Ok(serde_json::from_value(response)?)
4188    }
4189
4190    /// Gracefully remove one worker's registration through the worker plane.
4191    ///
4192    /// This operation is separate from operator-facing worker management. It
4193    /// uses worker-protocol authentication and returns the server's lease
4194    /// recovery result.
4195    pub async fn deregister_worker_registration(
4196        &self,
4197        worker_id: &str,
4198    ) -> Result<WorkerDeregistrationEnvelope> {
4199        let path = format!(
4200            "/worker/registrations/{}",
4201            percent_encode_path_segment(worker_id)
4202        );
4203        self.request_json(
4204            reqwest::Method::DELETE,
4205            &path,
4206            RequestProtocol::DefaultWorker,
4207            Option::<&Value>::None,
4208        )
4209        .await
4210    }
4211
4212    /// Long-poll for an ephemeral, read-only workflow query task.
4213    pub async fn poll_query_task(
4214        &self,
4215        worker_id: &str,
4216        task_queue: &str,
4217        timeout: Duration,
4218    ) -> Result<Option<QueryTask>> {
4219        Ok(self
4220            .poll_query_task_response(worker_id, task_queue, timeout)
4221            .await?
4222            .task)
4223    }
4224
4225    /// Poll a query task while preserving server stop and drain metadata.
4226    pub async fn poll_query_task_response(
4227        &self,
4228        worker_id: &str,
4229        task_queue: &str,
4230        timeout: Duration,
4231    ) -> Result<PollQueryTaskResponse> {
4232        let poll_request_id = unique_request_id("rust-query-poll");
4233        self.poll_query_task_response_with_request_id(
4234            worker_id,
4235            task_queue,
4236            timeout,
4237            &poll_request_id,
4238            1,
4239        )
4240        .await
4241    }
4242
4243    async fn poll_query_task_response_with_request_id(
4244        &self,
4245        worker_id: &str,
4246        task_queue: &str,
4247        timeout: Duration,
4248        poll_request_id: &str,
4249        transport_retries: usize,
4250    ) -> Result<PollQueryTaskResponse> {
4251        let timeout_seconds = long_poll_timeout_seconds(timeout);
4252        let body = json!({
4253            "worker_id": worker_id,
4254            "task_queue": task_queue,
4255            "poll_request_id": poll_request_id,
4256            "timeout_seconds": timeout_seconds,
4257        });
4258        self.poll_request_json(
4259            "/worker/query-tasks/poll",
4260            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4261            &body,
4262            timeout + Duration::from_secs(5),
4263            transport_retries,
4264        )
4265        .await
4266    }
4267
4268    /// Complete a query task without appending workflow history.
4269    pub async fn complete_query_task<T: Serialize>(
4270        &self,
4271        query_task_id: &str,
4272        lease_owner: &str,
4273        query_task_attempt: u64,
4274        result: T,
4275        codec: &str,
4276    ) -> Result<Value> {
4277        let typed_result = AvroValue::from_serialize(&result)?;
4278        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
4279        self.complete_query_task_with_envelope(
4280            query_task_id,
4281            lease_owner,
4282            query_task_attempt,
4283            typed_result.into_json()?,
4284            result_envelope,
4285        )
4286        .await
4287    }
4288
4289    async fn complete_query_task_with_envelope(
4290        &self,
4291        query_task_id: &str,
4292        lease_owner: &str,
4293        query_task_attempt: u64,
4294        result: Value,
4295        result_envelope: Value,
4296    ) -> Result<Value> {
4297        let body = json!({
4298            "lease_owner": lease_owner,
4299            "query_task_attempt": query_task_attempt,
4300            "result": result,
4301            "result_envelope": result_envelope,
4302        });
4303        let path = format!("/worker/query-tasks/{query_task_id}/complete");
4304        let response = self
4305            .request_json(
4306                reqwest::Method::POST,
4307                &path,
4308                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4309                Some(&body),
4310            )
4311            .await;
4312        query_task_response(response)
4313    }
4314
4315    /// Report a stable machine-readable query-task failure.
4316    pub async fn fail_query_task(
4317        &self,
4318        query_task_id: &str,
4319        lease_owner: &str,
4320        query_task_attempt: u64,
4321        message: impl Into<String>,
4322        reason: impl Into<String>,
4323        failure_type: impl Into<String>,
4324    ) -> Result<Value> {
4325        let body = json!({
4326            "lease_owner": lease_owner,
4327            "query_task_attempt": query_task_attempt,
4328            "failure": {
4329                "message": message.into(),
4330                "reason": reason.into(),
4331                "type": failure_type.into(),
4332            }
4333        });
4334        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4335        let response = self
4336            .request_json(
4337                reqwest::Method::POST,
4338                &path,
4339                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4340                Some(&body),
4341            )
4342            .await;
4343        query_task_response(response)
4344    }
4345
4346    pub async fn heartbeat_worker(
4347        &self,
4348        worker_id: &str,
4349        workflow_available: usize,
4350        activity_available: usize,
4351    ) -> Result<Value> {
4352        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4353            .await
4354    }
4355
4356    async fn heartbeat_worker_with_sessions(
4357        &self,
4358        worker_id: &str,
4359        workflow_available: usize,
4360        activity_available: usize,
4361        session_available: Option<usize>,
4362    ) -> Result<Value> {
4363        let mut body = json!({
4364            "worker_id": worker_id,
4365            "task_slots": {
4366                "workflow_available": workflow_available,
4367                "activity_available": activity_available
4368            },
4369            "process_metrics": {
4370                "process_id": std::process::id(),
4371                "process_uptime_seconds": 0
4372            }
4373        });
4374
4375        if let Some(available) = session_available {
4376            body["task_slots"]["session_available"] = json!(available);
4377        }
4378
4379        self.request_json(
4380            reqwest::Method::POST,
4381            "/worker/heartbeat",
4382            RequestProtocol::DefaultWorker,
4383            Some(&body),
4384        )
4385        .await
4386    }
4387
4388    pub async fn poll_workflow_task(
4389        &self,
4390        worker_id: &str,
4391        task_queue: &str,
4392        timeout: Duration,
4393    ) -> Result<Option<WorkflowTask>> {
4394        Ok(self
4395            .poll_workflow_task_response(worker_id, task_queue, timeout)
4396            .await?
4397            .task)
4398    }
4399
4400    pub async fn poll_workflow_task_response(
4401        &self,
4402        worker_id: &str,
4403        task_queue: &str,
4404        timeout: Duration,
4405    ) -> Result<PollWorkflowTaskResponse> {
4406        let poll_request_id = unique_request_id("rust-workflow-poll");
4407        self.poll_workflow_task_response_with_request_id(
4408            worker_id,
4409            task_queue,
4410            timeout,
4411            &poll_request_id,
4412            1,
4413        )
4414        .await
4415    }
4416
4417    async fn poll_workflow_task_response_with_request_id(
4418        &self,
4419        worker_id: &str,
4420        task_queue: &str,
4421        timeout: Duration,
4422        poll_request_id: &str,
4423        transport_retries: usize,
4424    ) -> Result<PollWorkflowTaskResponse> {
4425        let body = json!({
4426            "worker_id": worker_id,
4427            "task_queue": task_queue,
4428            "poll_request_id": poll_request_id,
4429            "timeout_seconds": long_poll_timeout_seconds(timeout),
4430            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4431        });
4432        let mut wire: Value = self
4433            .poll_request_json_unresolved(
4434                "/worker/workflow-tasks/poll",
4435                RequestProtocol::DefaultWorker,
4436                &body,
4437                timeout + Duration::from_secs(5),
4438                transport_retries,
4439            )
4440            .await?;
4441        let claim =
4442            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4443        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4444            self.resolve_runtime_payloads(
4445                &mut wire,
4446                "/worker/workflow-tasks/poll",
4447                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4448            )
4449            .await?;
4450            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4451            if let Some(task) = data.task.as_mut() {
4452                self.fetch_remaining_workflow_history(worker_id, task)
4453                    .await?;
4454            }
4455            Ok(data)
4456        })
4457        .await?;
4458        Ok(data)
4459    }
4460
4461    async fn fetch_remaining_workflow_history(
4462        &self,
4463        worker_id: &str,
4464        task: &mut WorkflowTask,
4465    ) -> Result<()> {
4466        let mut next_token = task.next_history_page_token.clone();
4467        let mut seen = BTreeSet::new();
4468
4469        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4470            if seen.len() >= 128 || !seen.insert(token.clone()) {
4471                return Err(Error::Codec(
4472                    "workflow history pagination exceeded its page bound or repeated a token"
4473                        .into(),
4474                ));
4475            }
4476            let lease_owner = task
4477                .lease_owner
4478                .clone()
4479                .unwrap_or_else(|| worker_id.to_string());
4480            let page = self
4481                .workflow_task_history_page(
4482                    &task.task_id,
4483                    &lease_owner,
4484                    task.workflow_task_attempt,
4485                    &token,
4486                )
4487                .await?;
4488
4489            task.append_history_page(page);
4490
4491            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4492                return Err(Error::Codec(
4493                    "workflow history pagination returned the same page token".to_string(),
4494                ));
4495            }
4496
4497            next_token = task.next_history_page_token.clone();
4498        }
4499
4500        Ok(())
4501    }
4502
4503    async fn workflow_task_history_page(
4504        &self,
4505        task_id: &str,
4506        lease_owner: &str,
4507        workflow_task_attempt: u64,
4508        next_history_page_token: &str,
4509    ) -> Result<WorkflowTaskHistoryPage> {
4510        let body = json!({
4511            "lease_owner": lease_owner,
4512            "workflow_task_attempt": workflow_task_attempt,
4513            "next_history_page_token": next_history_page_token
4514        });
4515        let path = format!("/worker/workflow-tasks/{task_id}/history");
4516
4517        self.request_json(
4518            reqwest::Method::POST,
4519            &path,
4520            RequestProtocol::DefaultWorker,
4521            Some(&body),
4522        )
4523        .await
4524    }
4525
4526    pub async fn complete_workflow_task(
4527        &self,
4528        task_id: &str,
4529        lease_owner: &str,
4530        workflow_task_attempt: u64,
4531        commands: Vec<Value>,
4532    ) -> Result<Value> {
4533        self.complete_workflow_task_with_message_streams(
4534            task_id,
4535            lease_owner,
4536            workflow_task_attempt,
4537            commands,
4538            Vec::new(),
4539            Vec::new(),
4540            None,
4541        )
4542        .await
4543    }
4544
4545    #[allow(clippy::too_many_arguments)]
4546    async fn complete_workflow_task_with_message_streams(
4547        &self,
4548        task_id: &str,
4549        lease_owner: &str,
4550        workflow_task_attempt: u64,
4551        commands: Vec<Value>,
4552        message_stream_cursors: Vec<Value>,
4553        message_stream_waits: Vec<Value>,
4554        sticky_cache: Option<Value>,
4555    ) -> Result<Value> {
4556        validate_workflow_task_commands(&commands)?;
4557        let has_message_stream_metadata =
4558            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4559        if has_message_stream_metadata
4560            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4561        {
4562            return Err(Error::Codec(
4563                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4564                    .to_string(),
4565            ));
4566        }
4567        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4568            &commands,
4569            has_message_stream_metadata,
4570        );
4571        let protocol_version = if sticky_cache.is_some()
4572            && protocol_version
4573                .strip_prefix("1.")
4574                .and_then(|minor| minor.parse::<u64>().ok())
4575                .is_some_and(|minor| minor < 18)
4576        {
4577            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4578        } else {
4579            protocol_version
4580        };
4581        let mut body = json!({
4582            "lease_owner": lease_owner,
4583            "workflow_task_attempt": workflow_task_attempt,
4584            "commands": commands
4585        });
4586        #[cfg(feature = "telemetry")]
4587        if self.observability_context_supported.load(Ordering::SeqCst)
4588            && opentelemetry::Context::current()
4589                .get::<telemetry::ExecutionFields>()
4590                .is_some()
4591        {
4592            if let Some(commands) = body["commands"].as_array_mut() {
4593                for command in commands {
4594                    if command.get("observability_context").is_none()
4595                        && matches!(
4596                            command["type"].as_str(),
4597                            Some("start_child_workflow" | "continue_as_new")
4598                        )
4599                    {
4600                        *command = self.with_observability_context(command.take());
4601                    }
4602                }
4603            }
4604        }
4605        if !message_stream_cursors.is_empty() {
4606            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4607        }
4608        if !message_stream_waits.is_empty() {
4609            body["message_stream_waits"] = Value::Array(message_stream_waits);
4610        }
4611        if let Some(claim) = sticky_cache {
4612            body["sticky_cache"] = claim;
4613        }
4614        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4615        self.request_json(
4616            reqwest::Method::POST,
4617            &path,
4618            RequestProtocol::Worker(protocol_version),
4619            Some(&body),
4620        )
4621        .await
4622    }
4623
4624    pub async fn fail_workflow_task(
4625        &self,
4626        task_id: &str,
4627        lease_owner: &str,
4628        workflow_task_attempt: u64,
4629        message: impl Into<String>,
4630    ) -> Result<Value> {
4631        self.fail_workflow_task_with_type(
4632            task_id,
4633            lease_owner,
4634            workflow_task_attempt,
4635            message,
4636            "RustWorkflowTaskFailure",
4637        )
4638        .await
4639    }
4640
4641    async fn fail_workflow_task_with_type(
4642        &self,
4643        task_id: &str,
4644        lease_owner: &str,
4645        workflow_task_attempt: u64,
4646        message: impl Into<String>,
4647        failure_type: &str,
4648    ) -> Result<Value> {
4649        self.fail_workflow_task_with_failure(
4650            task_id,
4651            lease_owner,
4652            workflow_task_attempt,
4653            json!({"message": message.into(), "type": failure_type}),
4654        )
4655        .await
4656    }
4657
4658    async fn fail_workflow_task_with_failure(
4659        &self,
4660        task_id: &str,
4661        lease_owner: &str,
4662        workflow_task_attempt: u64,
4663        failure: Value,
4664    ) -> Result<Value> {
4665        let body = json!({
4666            "lease_owner": lease_owner,
4667            "workflow_task_attempt": workflow_task_attempt,
4668            "failure": failure,
4669        });
4670        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4671        self.request_json(
4672            reqwest::Method::POST,
4673            &path,
4674            RequestProtocol::DefaultWorker,
4675            Some(&body),
4676        )
4677        .await
4678    }
4679
4680    pub async fn poll_activity_task(
4681        &self,
4682        worker_id: &str,
4683        task_queue: &str,
4684        timeout: Duration,
4685    ) -> Result<Option<ActivityTask>> {
4686        Ok(self
4687            .poll_activity_task_response(worker_id, task_queue, timeout)
4688            .await?
4689            .task)
4690    }
4691
4692    /// Poll an activity task while preserving server stop and drain metadata.
4693    pub async fn poll_activity_task_response(
4694        &self,
4695        worker_id: &str,
4696        task_queue: &str,
4697        timeout: Duration,
4698    ) -> Result<PollActivityTaskResponse> {
4699        let poll_request_id = unique_request_id("rust-activity-poll");
4700        self.poll_activity_task_response_with_request_id(
4701            worker_id,
4702            task_queue,
4703            timeout,
4704            &poll_request_id,
4705            1,
4706        )
4707        .await
4708        .map(worker_session::SessionPollResponse::ordinary)
4709    }
4710
4711    async fn poll_activity_task_response_with_request_id(
4712        &self,
4713        worker_id: &str,
4714        task_queue: &str,
4715        timeout: Duration,
4716        poll_request_id: &str,
4717        transport_retries: usize,
4718    ) -> Result<worker_session::SessionPollResponse> {
4719        let body = json!({
4720            "worker_id": worker_id,
4721            "task_queue": task_queue,
4722            "poll_request_id": poll_request_id,
4723            "timeout_seconds": long_poll_timeout_seconds(timeout),
4724        });
4725        let mut wire: Value = self
4726            .poll_request_json_unresolved(
4727                "/worker/activity-tasks/poll",
4728                RequestProtocol::DefaultWorker,
4729                &body,
4730                timeout + Duration::from_secs(5),
4731                transport_retries,
4732            )
4733            .await?;
4734        let lease =
4735            activity_lease::authority::Lease::confirm(self, &wire, worker_id, task_queue).await?;
4736        let observed = self.with_activity_lease_authority(
4737            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
4738        );
4739        let claim = if lease.is_none() {
4740            activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?
4741        } else {
4742            None
4743        };
4744        let loading = async {
4745            observed
4746                .resolve_runtime_payloads(
4747                    &mut wire,
4748                    "/worker/activity-tasks/poll",
4749                    RequestProtocol::DefaultWorker,
4750                )
4751                .await?;
4752            if let Some(lease) = &lease {
4753                lease
4754                    .authority
4755                    .refresh_delivery_session(&mut wire["task"])?;
4756            }
4757            Ok(serde_json::from_value(wire)?)
4758        };
4759        let mut data: worker_session::SessionPollResponse = match lease.as_ref() {
4760            Some(lease) => lease.authority.protect(loading).await?,
4761            None => {
4762                activity_hydration::HydrationClaim::protect(claim.as_ref(), self, loading).await?
4763            }
4764        };
4765        if let Some(task) = data.task.as_mut() {
4766            task.hydration_claim = claim;
4767            task.activity_lease = lease;
4768        }
4769        Ok(data)
4770    }
4771
4772    pub async fn complete_activity_task<T: Serialize>(
4773        &self,
4774        task_id: &str,
4775        activity_attempt_id: &str,
4776        lease_owner: &str,
4777        result: T,
4778        codec: &str,
4779    ) -> Result<Value> {
4780        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
4781        let body = json!({
4782            "activity_attempt_id": activity_attempt_id,
4783            "lease_owner": lease_owner,
4784            "result": result
4785        });
4786        let path = format!("/worker/activity-tasks/{task_id}/complete");
4787        activity_task_response(
4788            self.request_json(
4789                reqwest::Method::POST,
4790                &path,
4791                RequestProtocol::DefaultWorker,
4792                Some(&body),
4793            )
4794            .await,
4795            "complete",
4796            task_id,
4797            activity_attempt_id,
4798        )
4799    }
4800
4801    pub async fn fail_activity_task(
4802        &self,
4803        task_id: &str,
4804        activity_attempt_id: &str,
4805        lease_owner: &str,
4806        message: impl Into<String>,
4807        non_retryable: bool,
4808    ) -> Result<Value> {
4809        self.fail_activity_task_with_error(
4810            task_id,
4811            activity_attempt_id,
4812            lease_owner,
4813            &ActivityError::new("RustActivityFailure", message).non_retryable(non_retryable),
4814        )
4815        .await
4816    }
4817
4818    /// Report an activity's application-defined failure type and retry marker.
4819    pub async fn fail_activity_task_with_error(
4820        &self,
4821        task_id: &str,
4822        activity_attempt_id: &str,
4823        lease_owner: &str,
4824        error: &ActivityError,
4825    ) -> Result<Value> {
4826        let error = error.validated();
4827        let body = json!({
4828            "activity_attempt_id": activity_attempt_id,
4829            "lease_owner": lease_owner,
4830            "failure": {
4831                "message": error.message,
4832                "type": error.exception_type,
4833                "non_retryable": error.non_retryable
4834            }
4835        });
4836        let path = format!("/worker/activity-tasks/{task_id}/fail");
4837        activity_task_response(
4838            self.request_json(
4839                reqwest::Method::POST,
4840                &path,
4841                RequestProtocol::DefaultWorker,
4842                Some(&body),
4843            )
4844            .await,
4845            "fail",
4846            task_id,
4847            activity_attempt_id,
4848        )
4849    }
4850
4851    /// Record a flat map of scalar/null activity progress metadata.
4852    ///
4853    /// Heartbeat details use the Server's bounded JSON progress contract.
4854    /// They are not workflow payload envelopes.
4855    pub async fn heartbeat_activity_task<T: Serialize>(
4856        &self,
4857        task_id: &str,
4858        activity_attempt_id: &str,
4859        lease_owner: &str,
4860        details: T,
4861    ) -> Result<ActivityHeartbeatResponse> {
4862        serde_json::from_value(
4863            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
4864                .await?,
4865        )
4866        .map_err(Error::from)
4867    }
4868
4869    async fn heartbeat_activity_task_value<T: Serialize>(
4870        &self,
4871        task_id: &str,
4872        activity_attempt_id: &str,
4873        lease_owner: &str,
4874        details: T,
4875    ) -> Result<Value> {
4876        let details = AvroValue::from_serialize(&details)?.into_json()?;
4877        let body = json!({
4878            "activity_attempt_id": activity_attempt_id,
4879            "lease_owner": lease_owner,
4880            "details": details
4881        });
4882        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
4883        let started = tokio::time::Instant::now();
4884        let response = activity_task_response(
4885            self.request_json(
4886                reqwest::Method::POST,
4887                &path,
4888                RequestProtocol::DefaultWorker,
4889                Some(&body),
4890            )
4891            .await,
4892            "heartbeat",
4893            task_id,
4894            activity_attempt_id,
4895        )?;
4896        if let Some(authority) = &self.activity_lease_authority {
4897            authority.progress(&response, started)?;
4898        }
4899        Ok(response)
4900    }
4901
4902    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
4903        &self,
4904        method: reqwest::Method,
4905        path: &str,
4906        protocol: RequestProtocol,
4907        body: Option<&B>,
4908    ) -> Result<T> {
4909        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
4910            .await
4911    }
4912
4913    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4914        &self,
4915        method: reqwest::Method,
4916        path: &str,
4917        protocol: RequestProtocol,
4918        body: Option<&B>,
4919        timeout: Duration,
4920    ) -> Result<T> {
4921        self.metrics_request(method, path, protocol, body, timeout, true)
4922            .await
4923    }
4924
4925    fn worker_request_protocol(&self, protocol: RequestProtocol) -> Result<RequestProtocol> {
4926        Ok(match protocol {
4927            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
4928                let selected = self.worker_protocol_version.as_str();
4929                if self.cooperative_worker_protocol
4930                    && !cooperative_cancellation::supports_protocol(selected)
4931                {
4932                    return Err(Error::CooperativeCancellationUnavailable(
4933                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
4934                    ));
4935                }
4936                if let RequestProtocol::Worker(minimum) = protocol {
4937                    let supported = minimum
4938                        .strip_prefix("1.")
4939                        .and_then(|minor| minor.parse::<u64>().ok())
4940                        .zip(
4941                            selected
4942                                .strip_prefix("1.")
4943                                .and_then(|minor| minor.parse::<u64>().ok()),
4944                        )
4945                        .is_some_and(|(minimum, selected)| selected >= minimum);
4946                    if !supported {
4947                        return Err(Error::WorkerLoop(format!(
4948                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
4949                        )));
4950                    }
4951                }
4952                RequestProtocol::Worker(selected)
4953            }
4954            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
4955        })
4956    }
4957
4958    fn check_activity_lease_request(&self, path: &str, body: Option<&Value>) -> Result<()> {
4959        match &self.activity_lease_authority {
4960            Some(authority) => authority.check(path, body),
4961            None => Ok(()),
4962        }
4963    }
4964
4965    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4966        &self,
4967        method: reqwest::Method,
4968        path: &str,
4969        protocol: RequestProtocol,
4970        body: Option<&B>,
4971        timeout: Duration,
4972    ) -> Result<T> {
4973        self.metrics_request(method, path, protocol, body, timeout, false)
4974            .await
4975    }
4976
4977    async fn send_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
4978        &self,
4979        method: reqwest::Method,
4980        path: &str,
4981        protocol: RequestProtocol,
4982        body: Option<&B>,
4983        timeout: Duration,
4984        observation: &metrics::ClientObservation,
4985    ) -> Result<T> {
4986        #[cfg(feature = "telemetry")]
4987        self.begin_observability_discovery(&method, path);
4988        let protocol = self.worker_request_protocol(protocol)?;
4989        let auth_token = self.auth_token(protocol)?;
4990        let mut request = self
4991            .http
4992            .request(method.clone(), format!("{}/api{}", self.base_url, path))
4993            .timeout(timeout)
4994            .header(reqwest::header::ACCEPT, "application/json")
4995            .header(reqwest::header::CONTENT_TYPE, "application/json")
4996            .header("X-Namespace", &self.namespace);
4997
4998        match protocol {
4999            RequestProtocol::DefaultWorker => {
5000                request = request.header(
5001                    "X-Durable-Workflow-Protocol-Version",
5002                    self.worker_protocol_version.as_str(),
5003                );
5004            }
5005            RequestProtocol::Worker(version) => {
5006                request = request.header("X-Durable-Workflow-Protocol-Version", version);
5007            }
5008            RequestProtocol::ControlPlane => {
5009                request = request.header(
5010                    "X-Durable-Workflow-Control-Plane-Version",
5011                    CONTROL_PLANE_VERSION,
5012                );
5013            }
5014        }
5015
5016        if let Some(token) = auth_token {
5017            request = request.bearer_auth(token);
5018        }
5019
5020        if let Some(body) = body {
5021            let mut body = serde_json::to_value(body)?;
5022            if matches!(
5023                method,
5024                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
5025            ) {
5026                self.check_activity_lease_request(path, Some(&body))?;
5027                self.externalize_runtime_payloads(&mut body, path, protocol)
5028                    .await?;
5029                self.check_activity_lease_request(path, Some(&body))?;
5030            }
5031            request = request.json(&body);
5032        }
5033
5034        let request = request.build()?;
5035        let request_body = request
5036            .body()
5037            .and_then(reqwest::Body::as_bytes)
5038            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
5039        let poll_request_id = path.ends_with("/poll").then(|| {
5040            request_body
5041                .as_ref()
5042                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
5043                .unwrap_or_default()
5044        });
5045        let mut storage_retries = 0_usize;
5046        let mut deferred_workflow_completion = false;
5047
5048        loop {
5049            // Keep the serialized body and lease/poll identity across admission pauses.
5050            self.check_activity_lease_request(path, request_body.as_ref())?;
5051            let receive = async {
5052                let response = self
5053                    .http
5054                    .execute(request.try_clone().ok_or_else(|| {
5055                        Error::WorkerLoop("worker request body cannot be retried".to_string())
5056                    })?)
5057                    .await?;
5058                let status = response.status();
5059                observation.status(status);
5060                Ok::<_, Error>((status, response.bytes().await?))
5061            };
5062            let retry_deadline = self
5063                .worker_storage_admission
5064                .as_ref()
5065                .and_then(|admission| admission.workflow_completion_retry_deadline);
5066            if deferred_workflow_completion
5067                && retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
5068            {
5069                return Err(Error::Timeout);
5070            }
5071            let received = async {
5072                match retry_deadline.filter(|_| deferred_workflow_completion) {
5073                    Some(deadline) => tokio::time::timeout_at(deadline, receive)
5074                        .await
5075                        .map_err(|_| Error::Timeout)?,
5076                    None => receive.await,
5077                }
5078            };
5079            let (status, bytes) = match self
5080                .activity_lease_authority
5081                .as_ref()
5082                .filter(|authority| authority.governs(path))
5083            {
5084                Some(authority) => authority.protect(received).await?,
5085                None => received.await?,
5086            };
5087
5088            if !status.is_success() {
5089                let body = String::from_utf8_lossy(&bytes).to_string();
5090                if let Some(protocol) = protocol_failure(status, &body) {
5091                    return Err(Error::Protocol(protocol));
5092                }
5093                let error = Error::Http { status, body };
5094                deferred_workflow_completion |= worker_deferred_workflow_completion_retry_after(
5095                    &error,
5096                    path,
5097                    request_body.as_ref(),
5098                )
5099                .is_some();
5100                if self
5101                    .wait_for_storage_admission(
5102                        &error,
5103                        protocol,
5104                        Some(path),
5105                        poll_request_id.as_deref(),
5106                        request_body.as_ref(),
5107                        &mut storage_retries,
5108                    )
5109                    .await
5110                {
5111                    continue;
5112                }
5113                return Err(error);
5114            }
5115
5116            if bytes.is_empty() {
5117                return Ok(serde_json::from_value(Value::Null)?);
5118            }
5119
5120            #[cfg(feature = "telemetry")]
5121            return self.decode_observability_response(
5122                &method,
5123                path,
5124                request_body.as_ref(),
5125                &bytes,
5126            );
5127
5128            #[cfg(not(feature = "telemetry"))]
5129            return Ok(serde_json::from_slice(&bytes)?);
5130        }
5131    }
5132
5133    #[cfg(feature = "telemetry")]
5134    fn begin_observability_discovery(&self, method: &reqwest::Method, path: &str) {
5135        if *method == reqwest::Method::GET && path == "/cluster/info" {
5136            self.observability_context_supported
5137                .store(false, Ordering::SeqCst);
5138        }
5139    }
5140
5141    #[cfg(feature = "telemetry")]
5142    fn decode_observability_response<T: DeserializeOwned>(
5143        &self,
5144        method: &reqwest::Method,
5145        path: &str,
5146        request_body: Option<&Value>,
5147        bytes: &[u8],
5148    ) -> Result<T> {
5149        if *method == reqwest::Method::POST
5150            && self.execution_telemetry.is_some()
5151            && matches!(
5152                path,
5153                "/worker/workflow-tasks/poll"
5154                    | "/worker/activity-tasks/poll"
5155                    | "/worker/query-tasks/poll"
5156            )
5157        {
5158            let mut wire: Value = serde_json::from_slice(bytes)?;
5159            telemetry::carrier::retain_poll_observations(
5160                &mut wire,
5161                request_body.unwrap_or(&Value::Null),
5162                path,
5163                &self.namespace,
5164            );
5165            return Ok(serde_json::from_value(wire)?);
5166        }
5167        if *method == reqwest::Method::GET && path == "/cluster/info" {
5168            let info: Value = serde_json::from_slice(bytes)?;
5169            self.observability_context_supported
5170                .store(telemetry::carrier::supported(&info), Ordering::SeqCst);
5171            return Ok(serde_json::from_value(info)?);
5172        }
5173        Ok(serde_json::from_slice(bytes)?)
5174    }
5175
5176    async fn wait_for_storage_admission(
5177        &self,
5178        error: &Error,
5179        protocol: RequestProtocol,
5180        path: Option<&str>,
5181        poll_request_id: Option<&str>,
5182        request_body: Option<&Value>,
5183        retries: &mut usize,
5184    ) -> bool {
5185        let Some(admission) = self
5186            .worker_storage_admission
5187            .as_ref()
5188            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
5189        else {
5190            return false;
5191        };
5192        let completion_deferred = path.and_then(|path| {
5193            worker_deferred_workflow_completion_retry_after(error, path, request_body)
5194        });
5195        let Some(advertised_delay) = completion_deferred
5196            .or_else(|| worker_storage_admission_retry_after(error, poll_request_id))
5197            .or_else(|| {
5198                path.and_then(|path| {
5199                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
5200                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
5201                })
5202            })
5203        else {
5204            return false;
5205        };
5206        *retries = retries.saturating_add(1);
5207        let delay = worker_retry_delay(admission.policy, *retries)
5208            .max(advertised_delay)
5209            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
5210        let delay = if completion_deferred.is_some() {
5211            delay.max(advertised_delay)
5212        } else {
5213            delay
5214        };
5215        let wait_deadline = tokio::time::Instant::now() + delay;
5216        loop {
5217            if admission.stop.load(Ordering::SeqCst) {
5218                return false;
5219            }
5220            let now = tokio::time::Instant::now();
5221            if admission
5222                .workflow_completion_retry_deadline
5223                .is_some_and(|deadline| now >= deadline)
5224            {
5225                return false;
5226            }
5227            let remaining = wait_deadline.saturating_duration_since(now);
5228            if remaining.is_zero() {
5229                return true;
5230            }
5231            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
5232        }
5233    }
5234
5235    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
5236        &self,
5237        path: &str,
5238        protocol: RequestProtocol,
5239        body: &B,
5240        timeout: Duration,
5241        max_retries: usize,
5242    ) -> Result<T> {
5243        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
5244            .await
5245    }
5246
5247    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
5248        &self,
5249        path: &str,
5250        protocol: RequestProtocol,
5251        body: &B,
5252        timeout: Duration,
5253        max_retries: usize,
5254    ) -> Result<T> {
5255        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
5256            .await
5257    }
5258
5259    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
5260        &self,
5261        path: &str,
5262        protocol: RequestProtocol,
5263        body: &B,
5264        timeout: Duration,
5265        max_retries: usize,
5266        resolve: bool,
5267    ) -> Result<T> {
5268        self.metrics_poll_request(path, protocol, body, timeout, max_retries, resolve)
5269            .await
5270    }
5271
5272    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
5273        match protocol {
5274            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
5275                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
5276                    return Ok(Some(token));
5277                }
5278                if self.control_token.is_some() {
5279                    return Err(Error::MissingRoleCredentials {
5280                        role: "worker",
5281                        opposite_role: "control",
5282                    });
5283                }
5284                Ok(None)
5285            }
5286            RequestProtocol::ControlPlane => {
5287                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
5288                    return Ok(Some(token));
5289                }
5290                if self.worker_token.is_some() {
5291                    return Err(Error::MissingRoleCredentials {
5292                        role: "control",
5293                        opposite_role: "worker",
5294                    });
5295                }
5296                Ok(None)
5297            }
5298        }
5299    }
5300}
5301
5302fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
5303    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
5304    let reason = body
5305        .get("reason")
5306        .and_then(Value::as_str)
5307        .unwrap_or("query_rejected")
5308        .to_string();
5309    let message = body
5310        .get("message")
5311        .or_else(|| body.get("error"))
5312        .and_then(Value::as_str)
5313        .unwrap_or("workflow query was rejected")
5314        .to_string();
5315
5316    QueryFailure {
5317        status: status.as_u16(),
5318        reason,
5319        message,
5320        body,
5321    }
5322}
5323
5324fn workflow_command_result(
5325    command: WorkflowCommandKind,
5326    data: Value,
5327    workflow_id: &str,
5328    run_id: Option<&str>,
5329) -> WorkflowCommandResult {
5330    WorkflowCommandResult {
5331        command,
5332        workflow_id: data
5333            .get("workflow_id")
5334            .and_then(Value::as_str)
5335            .unwrap_or(workflow_id)
5336            .to_string(),
5337        run_id: data
5338            .get("run_id")
5339            .and_then(Value::as_str)
5340            .or(run_id)
5341            .map(str::to_string),
5342        outcome: data
5343            .get("outcome")
5344            .and_then(Value::as_str)
5345            .map(str::to_string),
5346        reason: data
5347            .get("reason")
5348            .and_then(Value::as_str)
5349            .map(str::to_string),
5350        command_status: data
5351            .get("command_status")
5352            .and_then(Value::as_str)
5353            .map(str::to_string),
5354        raw: data,
5355    }
5356}
5357
5358fn workflow_command_rejection(
5359    command: WorkflowCommandKind,
5360    status: reqwest::StatusCode,
5361    raw_body: String,
5362    workflow_id: &str,
5363    run_id: Option<&str>,
5364) -> WorkflowCommandRejection {
5365    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
5366    WorkflowCommandRejection {
5367        command,
5368        status: status.as_u16(),
5369        reason: body
5370            .get("reason")
5371            .and_then(Value::as_str)
5372            .unwrap_or("workflow_command_rejected")
5373            .to_string(),
5374        message: body
5375            .get("message")
5376            .or_else(|| body.get("error"))
5377            .and_then(Value::as_str)
5378            .unwrap_or("workflow lifecycle command was rejected")
5379            .to_string(),
5380        workflow_id: body
5381            .get("workflow_id")
5382            .and_then(Value::as_str)
5383            .unwrap_or(workflow_id)
5384            .to_string(),
5385        run_id: body
5386            .get("run_id")
5387            .and_then(Value::as_str)
5388            .or(run_id)
5389            .map(str::to_string),
5390        target_scope: body
5391            .get("target_scope")
5392            .and_then(Value::as_str)
5393            .map(str::to_string),
5394        body,
5395    }
5396}
5397
5398fn query_task_response(response: Result<Value>) -> Result<Value> {
5399    match response {
5400        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
5401        response => response,
5402    }
5403}
5404
5405fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
5406    match response {
5407        Err(Error::Http { status, body })
5408            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
5409        {
5410            Ok(serde_json::from_str(&body)?)
5411        }
5412        response => response,
5413    }
5414}
5415
5416fn worker_poll_body_is_stop(body: &str) -> bool {
5417    serde_json::from_str::<Value>(body)
5418        .ok()
5419        .is_some_and(|body| {
5420            worker_poll_is_stop(
5421                body.get("poll_status").and_then(Value::as_str),
5422                body.get("reason").and_then(Value::as_str),
5423            )
5424        })
5425}
5426
5427fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
5428    matches!(poll_status, Some("draining" | "stopped"))
5429        || matches!(reason, Some("worker_draining" | "worker_stopped"))
5430}
5431
5432fn query_task_rejection_is_final(error: &Error) -> bool {
5433    matches!(
5434        error,
5435        Error::QueryFailed(failure)
5436            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
5437    )
5438}
5439
5440fn activity_task_response<T>(
5441    response: Result<T>,
5442    operation: &str,
5443    task_id: &str,
5444    activity_attempt_id: &str,
5445) -> Result<T> {
5446    match response {
5447        Err(Error::Http { status, body }) => {
5448            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
5449            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
5450                operation: operation.to_string(),
5451                status: status.as_u16(),
5452                reason: body
5453                    .get("reason")
5454                    .and_then(Value::as_str)
5455                    .unwrap_or("activity_task_rejected")
5456                    .to_string(),
5457                task_id: body
5458                    .get("task_id")
5459                    .and_then(Value::as_str)
5460                    .unwrap_or(task_id)
5461                    .to_string(),
5462                activity_attempt_id: body
5463                    .get("activity_attempt_id")
5464                    .and_then(Value::as_str)
5465                    .unwrap_or(activity_attempt_id)
5466                    .to_string(),
5467                cancel_requested: body
5468                    .get("cancel_requested")
5469                    .and_then(Value::as_bool)
5470                    .unwrap_or(false),
5471                can_continue: body.get("can_continue").and_then(Value::as_bool),
5472                run_closed_reason: body
5473                    .get("run_closed_reason")
5474                    .and_then(Value::as_str)
5475                    .map(str::to_string),
5476                body,
5477            }))
5478        }
5479        response => response,
5480    }
5481}
5482
5483fn activity_task_rejection_is_final(error: &Error) -> bool {
5484    matches!(
5485        error,
5486        Error::ActivityTaskRejected(rejection)
5487            if matches!(
5488                rejection.reason.as_str(),
5489                "run_cancelled"
5490                    | "run_terminated"
5491                    | "attempt_closed"
5492                    | "stale_attempt"
5493                    | "activity_cancelled"
5494                    | "task_cancelled"
5495                    | "run_closed"
5496                    | "activity_not_running"
5497                    | "attempt_not_found"
5498            )
5499    )
5500}
5501
5502fn workflow_task_completion_is_terminal_timeout(
5503    error: &Error,
5504    task_id: &str,
5505    workflow_task_attempt: u64,
5506    run_id: Option<&str>,
5507) -> bool {
5508    let Error::Http { status, body } = error else {
5509        return false;
5510    };
5511    if *status != reqwest::StatusCode::CONFLICT {
5512        return false;
5513    }
5514
5515    let Some(run_id) = run_id else {
5516        return false;
5517    };
5518    let Ok(body) = serde_json::from_str::<Value>(body) else {
5519        return false;
5520    };
5521
5522    body.get("recorded").and_then(Value::as_bool) == Some(false)
5523        && body.get("reason").and_then(Value::as_str) == Some("run_timed_out")
5524        && body.get("run_status").and_then(Value::as_str) == Some("failed")
5525        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5526        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5527        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5528}
5529
5530fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5531    let body: Value = serde_json::from_str(raw_body).ok()?;
5532    let reason = body.get("reason")?.as_str()?;
5533    if !matches!(
5534        reason,
5535        "missing_protocol_version"
5536            | "unsupported_protocol_version"
5537            | "missing_control_plane_version"
5538            | "unsupported_control_plane_version"
5539    ) {
5540        return None;
5541    }
5542
5543    Some(ProtocolFailure {
5544        status: status.as_u16(),
5545        reason: reason.to_string(),
5546        message: body
5547            .get("message")
5548            .or_else(|| body.get("error"))
5549            .and_then(Value::as_str)
5550            .unwrap_or("protocol version rejected")
5551            .to_string(),
5552        supported_version: body
5553            .get("supported_version")
5554            .and_then(Value::as_str)
5555            .map(str::to_string),
5556        requested_version: body
5557            .get("requested_version")
5558            .and_then(Value::as_str)
5559            .map(str::to_string),
5560        body,
5561    })
5562}
5563
5564fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5565    timeout
5566        .as_secs()
5567        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5568        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5569}
5570
5571fn worker_operation_is_retryable(error: &Error) -> bool {
5572    if worker_poll_capacity_retry_after(error).is_some()
5573        || worker_storage_admission_body(error).is_some()
5574        || worker_backend_unavailable_body(error).is_some()
5575        || worker_operation_is_explicitly_non_retryable(error)
5576    {
5577        return false;
5578    }
5579
5580    match error {
5581        Error::Transport(error) => {
5582            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5583        }
5584        Error::Http { status, .. } => {
5585            matches!(
5586                *status,
5587                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5588            ) || status.is_server_error()
5589        }
5590        _ => false,
5591    }
5592}
5593
5594fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5595    let body: Value = match error {
5596        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5597        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5598        _ => return None,
5599    };
5600    matches!(
5601        body.get("reason").and_then(Value::as_str),
5602        Some("storage_pressure" | "storage_admission_unavailable")
5603    )
5604    .then_some(body)
5605}
5606
5607fn worker_storage_admission_retry_after(
5608    error: &Error,
5609    poll_request_id: Option<&str>,
5610) -> Option<Duration> {
5611    let Error::Http { status, .. } = error else {
5612        return None;
5613    };
5614    let body = worker_storage_admission_body(error)?;
5615    let delay = body.get("retry_after_seconds")?.as_u64()?;
5616    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5617        || delay == 0
5618        || body.get("retryable") != Some(&Value::Bool(true))
5619        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5620        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5621        || body
5622            .get("request_admitted")
5623            .is_some_and(|admitted| admitted != &Value::Bool(false))
5624    {
5625        return None;
5626    }
5627    match poll_request_id {
5628        Some(id) => {
5629            if id.is_empty()
5630                || body.get("task") != Some(&Value::Null)
5631                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5632                || body.get("poll_status") != body.get("reason")
5633                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5634                || body.get("claim_admitted") != Some(&Value::Bool(false))
5635            {
5636                return None;
5637            }
5638        }
5639        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5640        None => {}
5641    }
5642    Some(Duration::from_secs(delay))
5643}
5644
5645fn worker_backend_unavailable_retry_after(
5646    error: &Error,
5647    path: &str,
5648    poll_request_id: Option<&str>,
5649) -> Option<Duration> {
5650    let operation = match path {
5651        "/worker/register" => "register_worker",
5652        "/worker/heartbeat" => "heartbeat_worker",
5653        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5654        "/worker/activity-tasks/poll" => "poll_activity_task",
5655        "/worker/query-tasks/poll" => "poll_query_task",
5656        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
5657        _ => return None,
5658    };
5659    let body = worker_backend_unavailable_body(error)?;
5660    let delay = body.get("retry_after_seconds")?.as_u64()?;
5661    if delay == 0
5662        || body.get("operation")?.as_str()? != operation
5663        || body.get("outcome")?.as_str()? != "unknown"
5664        || body.get("retryable") != Some(&Value::Bool(true))
5665        || body.get("worker_id")?.as_str()?.is_empty()
5666    {
5667        return None;
5668    }
5669    if let Some(id) = poll_request_id {
5670        if id.is_empty()
5671            || body.get("task") != Some(&Value::Null)
5672            || body.get("poll_status")?.as_str()? != "backend_unavailable"
5673            || body.get("poll_request_id")?.as_str()? != id
5674            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5675        {
5676            return None;
5677        }
5678    } else if path.ends_with("/poll") {
5679        return None;
5680    }
5681    Some(Duration::from_secs(delay))
5682}
5683
5684fn worker_fenced_completion_retry_after(
5685    error: &Error,
5686    path: &str,
5687    request_body: Option<&Value>,
5688) -> Option<Duration> {
5689    let (operation, task_id, attempt_field) = if let Some(task_id) = path
5690        .strip_prefix("/worker/workflow-tasks/")
5691        .and_then(|tail| tail.strip_suffix("/complete"))
5692    {
5693        ("complete_workflow_task", task_id, "workflow_task_attempt")
5694    } else if let Some(task_id) = path
5695        .strip_prefix("/worker/activity-tasks/")
5696        .and_then(|tail| tail.strip_suffix("/complete"))
5697    {
5698        ("complete_activity_task", task_id, "activity_attempt_id")
5699    } else {
5700        return None;
5701    };
5702    if task_id.is_empty() || task_id.contains('/') {
5703        return None;
5704    }
5705
5706    let request = request_body?.as_object()?;
5707    let lease_owner = request.get("lease_owner")?.as_str()?;
5708    if lease_owner.is_empty() {
5709        return None;
5710    }
5711    let attempt = request.get(attempt_field)?;
5712    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
5713        || (attempt_field == "activity_attempt_id"
5714            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
5715    {
5716        return None;
5717    }
5718
5719    let body = worker_backend_unavailable_body(error)?;
5720    let delay = body.get("retry_after_seconds")?.as_u64()?;
5721    if delay == 0
5722        || body.get("operation")?.as_str()? != operation
5723        || body.get("outcome")?.as_str()? != "unknown"
5724        || body.get("retryable") != Some(&Value::Bool(true))
5725        || body.get("worker_id")?.as_str()? != lease_owner
5726        || body.get("task_queue") != Some(&Value::Null)
5727        || body.get("task_id")?.as_str()? != task_id
5728        || body.get("lease_owner")?.as_str()? != lease_owner
5729        || body.get(attempt_field) != Some(attempt)
5730    {
5731        return None;
5732    }
5733
5734    Some(Duration::from_secs(delay))
5735}
5736
5737fn worker_deferred_workflow_completion_retry_after(
5738    error: &Error,
5739    path: &str,
5740    request_body: Option<&Value>,
5741) -> Option<Duration> {
5742    let task_id = path
5743        .strip_prefix("/worker/workflow-tasks/")?
5744        .strip_suffix("/complete")?;
5745    if task_id.is_empty() || task_id.contains('/') {
5746        return None;
5747    }
5748    let request = request_body?.as_object()?;
5749    let owner = request.get("lease_owner")?.as_str()?;
5750    let attempt = request.get("workflow_task_attempt")?;
5751    if owner.trim().is_empty() || attempt.as_u64().filter(|attempt| *attempt > 0).is_none() {
5752        return None;
5753    }
5754    let Error::Http { status, body } = error else {
5755        return None;
5756    };
5757    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5758        return None;
5759    }
5760    let body: Value = serde_json::from_str(body).ok()?;
5761    let delay = body.get("retry_after_seconds")?.as_u64()?;
5762    if !(1..=5).contains(&delay)
5763        || body.get("reason")?.as_str()? != "backend_lock_pressure"
5764        || body.get("operation")?.as_str()? != "complete_workflow_task"
5765        || body.get("outcome")?.as_str()? != "deferred"
5766        || body.get("recorded") != Some(&Value::Bool(false))
5767        || body.get("retryable") != Some(&Value::Bool(true))
5768        || body.get("task_id")?.as_str()? != task_id
5769        || body.get("lease_owner")?.as_str()? != owner
5770        || body.get("workflow_task_attempt") != Some(attempt)
5771        || body.get("backend")?.get("lock_pressure") != Some(&Value::Bool(true))
5772    {
5773        return None;
5774    }
5775    Some(Duration::from_secs(delay))
5776}
5777
5778fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
5779    let Error::Http { status, body } = error else {
5780        return None;
5781    };
5782    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
5783        return None;
5784    }
5785    let body: Value = serde_json::from_str(body).ok()?;
5786    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
5787}
5788
5789fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
5790    let Error::Http { body, .. } = error else {
5791        return false;
5792    };
5793
5794    serde_json::from_str::<Value>(body)
5795        .ok()
5796        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
5797        == Some(false)
5798}
5799
5800fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
5801    let Error::Http { status, body } = error else {
5802        return None;
5803    };
5804    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
5805        return None;
5806    }
5807
5808    let body = serde_json::from_str::<Value>(body).ok()?;
5809    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
5810        == Some("long_poll_capacity_exhausted")
5811        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
5812    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
5813        return None;
5814    }
5815
5816    Some(Duration::from_secs(
5817        body.get("retry_after_seconds")
5818            .and_then(Value::as_u64)
5819            .unwrap_or_default(),
5820    ))
5821}
5822
5823fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
5824    let exponent = retry.saturating_sub(1).min(31) as u32;
5825    policy
5826        .initial_backoff
5827        .saturating_mul(1_u32 << exponent)
5828        .min(policy.max_backoff)
5829}
5830
5831#[derive(Debug)]
5832pub struct ClientBuilder {
5833    metrics: metrics::Metrics,
5834    base_url: String,
5835    token: Option<String>,
5836    control_token: Option<String>,
5837    worker_token: Option<String>,
5838    namespace: String,
5839    timeout: Duration,
5840    max_external_payload_bytes: usize,
5841    worker_protocol_version: WorkerProtocolVersion,
5842    additional_root_certificates: Vec<reqwest::Certificate>,
5843}
5844
5845impl ClientBuilder {
5846    /// Configure stable request metrics. Newly constructed workers inherit this recorder.
5847    pub fn metrics_recorder(mut self, recorder: Arc<dyn metrics::MetricsRecorder>) -> Self {
5848        self.metrics = metrics::Metrics::new(recorder);
5849        self
5850    }
5851    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
5852    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
5853        self.worker_protocol_version = version;
5854        self
5855    }
5856
5857    pub fn token(mut self, token: Option<String>) -> Self {
5858        self.token = token;
5859        self
5860    }
5861
5862    pub fn control_token(mut self, token: Option<String>) -> Self {
5863        self.control_token = token;
5864        self
5865    }
5866
5867    pub fn worker_token(mut self, token: Option<String>) -> Self {
5868        self.worker_token = token;
5869        self
5870    }
5871
5872    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
5873        self.namespace = namespace.into();
5874        self
5875    }
5876
5877    pub fn timeout(mut self, timeout: Duration) -> Self {
5878        self.timeout = timeout;
5879        self
5880    }
5881
5882    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
5883    /// References are fetched only from this client's authenticated runtime.
5884    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
5885        self.max_external_payload_bytes = bytes;
5886        self
5887    }
5888
5889    pub fn build(self) -> Result<Client> {
5890        let base_url = self.base_url.trim_end_matches('/').to_string();
5891        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
5892            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
5893            .unwrap_or_else(|_| base_url.ends_with("/api"));
5894
5895        if has_sdk_api_suffix {
5896            return Err(Error::InvalidBaseUrl);
5897        }
5898
5899        let mut http = reqwest::Client::builder()
5900            .timeout(self.timeout)
5901            .redirect(reqwest::redirect::Policy::none());
5902        for certificate in self.additional_root_certificates {
5903            http = http.add_root_certificate(certificate);
5904        }
5905        Ok(Client {
5906            metrics: self.metrics,
5907            http: http.build()?,
5908            hydration_timeout: self.timeout,
5909            base_url,
5910            token: self.token,
5911            control_token: self.control_token,
5912            worker_token: self.worker_token,
5913            namespace: self.namespace,
5914            max_external_payload_bytes: self.max_external_payload_bytes,
5915            worker_storage_admission: None,
5916            worker_task_slot: None,
5917            cooperative_worker_protocol: false,
5918            worker_protocol_version: self.worker_protocol_version,
5919            local_activities_enabled: false,
5920            worker_sessions_enabled: false,
5921            max_concurrent_worker_sessions: 10,
5922            worker_build_id: None,
5923            sticky_cache: None,
5924            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
5925            activity_lease_renewal_supported: Arc::new(AtomicBool::new(false)),
5926            activity_lease_authority: None,
5927            #[cfg(feature = "telemetry")]
5928            execution_telemetry: None,
5929            #[cfg(feature = "telemetry")]
5930            observability_context_supported: Arc::new(AtomicBool::new(false)),
5931        })
5932    }
5933}
5934
5935#[derive(Clone, Debug)]
5936pub struct WorkflowHandle {
5937    client: Client,
5938    pub workflow_id: String,
5939    pub run_id: Option<String>,
5940    pub workflow_type: String,
5941}
5942
5943impl WorkflowHandle {
5944    /// Describe whichever run is current for this stable workflow instance.
5945    pub async fn describe(&self) -> Result<WorkflowDescription> {
5946        self.client.describe_workflow(&self.workflow_id).await
5947    }
5948
5949    /// Describe the run identity originally selected by this handle.
5950    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
5951        let run_id = self.run_id.as_deref().ok_or_else(|| {
5952            Error::Codec("run_id is required for selected-run description".to_string())
5953        })?;
5954        self.client
5955            .describe_workflow_run(&self.workflow_id, run_id)
5956            .await
5957    }
5958
5959    /// Signal this workflow with an SDK-generated caller command key.
5960    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
5961        self.client
5962            .signal_workflow(&self.workflow_id, signal_name, input)
5963            .await
5964    }
5965
5966    /// Signal this workflow with an explicit caller command key (1 to 255 Unicode characters).
5967    pub async fn signal_with_request_id<T: Serialize>(
5968        &self,
5969        signal_name: &str,
5970        input: T,
5971        request_id: &str,
5972    ) -> Result<Value> {
5973        self.client
5974            .signal_workflow_with_request_id(&self.workflow_id, signal_name, input, request_id)
5975            .await
5976    }
5977
5978    pub async fn append_message<T: Serialize>(
5979        &self,
5980        stream_name: &str,
5981        message_id: &str,
5982        input: T,
5983    ) -> Result<Value> {
5984        self.client
5985            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
5986            .await
5987    }
5988
5989    /// Signal only if this handle's selected run is still current, with an
5990    /// SDK-generated caller command key.
5991    pub async fn signal_selected_run<T: Serialize>(
5992        &self,
5993        signal_name: &str,
5994        input: T,
5995    ) -> Result<Value> {
5996        let run_id = self.run_id.as_deref().ok_or_else(|| {
5997            Error::Codec("run_id is required for selected-run signaling".to_string())
5998        })?;
5999        self.client
6000            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
6001            .await
6002    }
6003
6004    /// Signal only if this handle's selected run is still current, with an
6005    /// explicit caller command key (1 to 255 Unicode characters).
6006    pub async fn signal_selected_run_with_request_id<T: Serialize>(
6007        &self,
6008        signal_name: &str,
6009        input: T,
6010        request_id: &str,
6011    ) -> Result<Value> {
6012        let run_id = self.run_id.as_deref().ok_or_else(|| {
6013            Error::Codec("run_id is required for selected-run signaling".to_string())
6014        })?;
6015        self.client
6016            .signal_workflow_run_with_request_id(
6017                &self.workflow_id,
6018                run_id,
6019                signal_name,
6020                input,
6021                request_id,
6022            )
6023            .await
6024    }
6025
6026    /// Close whichever run is current as cancelled, without workflow cleanup.
6027    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
6028        self.client
6029            .cancel_workflow(&self.workflow_id, options)
6030            .await
6031    }
6032
6033    /// Request cancellation only if this handle's selected run is still current.
6034    pub async fn cancel_selected_run(
6035        &self,
6036        options: WorkflowCommandOptions,
6037    ) -> Result<WorkflowCommandResult> {
6038        let run_id = self.run_id.as_deref().ok_or_else(|| {
6039            Error::Codec("run_id is required for selected-run cancellation".to_string())
6040        })?;
6041        self.client
6042            .cancel_workflow_run(&self.workflow_id, run_id, options)
6043            .await
6044    }
6045
6046    /// Forcefully terminate whichever run is current.
6047    pub async fn terminate(
6048        &self,
6049        options: WorkflowCommandOptions,
6050    ) -> Result<WorkflowCommandResult> {
6051        self.client
6052            .terminate_workflow(&self.workflow_id, options)
6053            .await
6054    }
6055
6056    /// Terminate only if this handle's selected run is still current.
6057    pub async fn terminate_selected_run(
6058        &self,
6059        options: WorkflowCommandOptions,
6060    ) -> Result<WorkflowCommandResult> {
6061        let run_id = self.run_id.as_deref().ok_or_else(|| {
6062            Error::Codec("run_id is required for selected-run termination".to_string())
6063        })?;
6064        self.client
6065            .terminate_workflow_run(&self.workflow_id, run_id, options)
6066            .await
6067    }
6068
6069    /// Continue this handle's failed run without repeating completed activities.
6070    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
6071        let run_id = self
6072            .run_id
6073            .as_deref()
6074            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
6075        self.client
6076            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
6077            .await
6078    }
6079
6080    /// Execute a named, read-only query against this workflow.
6081    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
6082        self.client
6083            .query_workflow(&self.workflow_id, query_name, input)
6084            .await
6085    }
6086
6087    pub async fn query_avro_value<T: Serialize>(
6088        &self,
6089        query_name: &str,
6090        input: T,
6091    ) -> Result<AvroValue> {
6092        self.client
6093            .query_workflow_avro_value(&self.workflow_id, query_name, input)
6094            .await
6095    }
6096
6097    pub async fn update<T: Serialize>(
6098        &self,
6099        update_name: &str,
6100        input: T,
6101        request_id: Option<&str>,
6102    ) -> Result<Value> {
6103        self.client
6104            .update_workflow(&self.workflow_id, update_name, input, request_id)
6105            .await
6106    }
6107
6108    pub async fn update_avro_value<T: Serialize>(
6109        &self,
6110        update_name: &str,
6111        input: T,
6112        request_id: Option<&str>,
6113    ) -> Result<AvroValue> {
6114        self.client
6115            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
6116            .await
6117    }
6118
6119    /// Query only if this handle's selected run is still current.
6120    pub async fn query_selected_run<T: Serialize>(
6121        &self,
6122        query_name: &str,
6123        input: T,
6124    ) -> Result<Value> {
6125        let run_id = self
6126            .run_id
6127            .as_deref()
6128            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
6129        self.client
6130            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
6131            .await
6132    }
6133
6134    /// Await the final terminal outcome of the current continue-as-new chain.
6135    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
6136        self.result_target(options, None).await
6137    }
6138
6139    /// Await the final result without projecting Avro bytes through JSON.
6140    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
6141        self.result_avro_value_target(options, None).await
6142    }
6143
6144    /// Await the final result and decode it into a Serde application type.
6145    pub async fn result_typed<T: DeserializeOwned>(
6146        &self,
6147        options: WorkflowResultOptions,
6148    ) -> Result<T> {
6149        let result = self.result_avro_value(options).await?;
6150        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
6151    }
6152
6153    /// Await only the run identity originally selected by this handle.
6154    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
6155        let run_id = self.run_id.as_deref().ok_or_else(|| {
6156            Error::Codec("run_id is required for selected-run result".to_string())
6157        })?;
6158        self.result_target(options, Some(run_id)).await
6159    }
6160
6161    /// Await the selected run's result on the lossless Avro Value surface.
6162    pub async fn result_selected_run_avro_value(
6163        &self,
6164        options: WorkflowResultOptions,
6165    ) -> Result<AvroValue> {
6166        let run_id = self.run_id.as_deref().ok_or_else(|| {
6167            Error::Codec("run_id is required for selected-run result".to_string())
6168        })?;
6169        self.result_avro_value_target(options, Some(run_id)).await
6170    }
6171
6172    /// Await the selected run and decode its result into a Serde type.
6173    pub async fn result_selected_run_typed<T: DeserializeOwned>(
6174        &self,
6175        options: WorkflowResultOptions,
6176    ) -> Result<T> {
6177        let result = self.result_selected_run_avro_value(options).await?;
6178        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
6179    }
6180
6181    async fn result_avro_value_target(
6182        &self,
6183        options: WorkflowResultOptions,
6184        selected_run_id: Option<&str>,
6185    ) -> Result<AvroValue> {
6186        let started = Instant::now();
6187
6188        loop {
6189            let description = match selected_run_id {
6190                Some(run_id) => {
6191                    self.client
6192                        .describe_workflow_run(&self.workflow_id, run_id)
6193                        .await?
6194                }
6195                None => self.describe().await?,
6196            };
6197            if description.is_completed() {
6198                return description.output_avro_value.ok_or_else(|| {
6199                    Error::Codec(
6200                        "missing_payload_envelope: typed workflow result requires output_envelope"
6201                            .to_string(),
6202                    )
6203                });
6204            }
6205            if description.is_terminal() {
6206                let outcome =
6207                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
6208                return Err(match outcome.kind {
6209                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
6210                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
6211                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
6212                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
6213                });
6214            }
6215            if started.elapsed() >= options.timeout {
6216                return Err(Error::Timeout);
6217            }
6218            tokio::time::sleep(options.poll_interval).await;
6219        }
6220    }
6221
6222    async fn result_target(
6223        &self,
6224        options: WorkflowResultOptions,
6225        selected_run_id: Option<&str>,
6226    ) -> Result<Value> {
6227        let started = Instant::now();
6228
6229        loop {
6230            let description = match selected_run_id {
6231                Some(run_id) => {
6232                    self.client
6233                        .describe_workflow_run(&self.workflow_id, run_id)
6234                        .await?
6235                }
6236                None => self.describe().await?,
6237            };
6238            if description.is_completed() {
6239                return Ok(description.output.unwrap_or(Value::Null));
6240            }
6241
6242            if description.is_terminal() {
6243                let outcome =
6244                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
6245                return Err(match outcome.kind {
6246                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
6247                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
6248                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
6249                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
6250                });
6251            }
6252
6253            if started.elapsed() >= options.timeout {
6254                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
6255                    kind: WorkflowTerminalKind::TimedOut,
6256                    workflow_id: description
6257                        .workflow_id
6258                        .clone()
6259                        .unwrap_or_else(|| self.workflow_id.clone()),
6260                    run_id: description
6261                        .run_id
6262                        .clone()
6263                        .or_else(|| selected_run_id.map(str::to_string)),
6264                    reason: "result_wait_timeout".to_string(),
6265                    failure_category: Some("client_timeout".to_string()),
6266                    failure_id: None,
6267                    exception_type: None,
6268                    exception_class: None,
6269                    non_retryable: None,
6270                    message: Some(format!(
6271                        "workflow result was not terminal within {:?}",
6272                        options.timeout
6273                    )),
6274                    exception: None,
6275                    raw: description.raw_value(),
6276                }));
6277            }
6278
6279            tokio::time::sleep(options.poll_interval).await;
6280        }
6281    }
6282}
6283
6284#[derive(Clone, Copy, Debug)]
6285pub struct WorkflowResultOptions {
6286    pub poll_interval: Duration,
6287    pub timeout: Duration,
6288}
6289
6290impl Default for WorkflowResultOptions {
6291    fn default() -> Self {
6292        Self {
6293            poll_interval: Duration::from_millis(500),
6294            timeout: Duration::from_secs(30),
6295        }
6296    }
6297}
6298
6299#[derive(Clone, Debug, Deserialize)]
6300pub struct WorkflowDescription {
6301    pub workflow_id: Option<String>,
6302    pub run_id: Option<String>,
6303    pub workflow_type: Option<String>,
6304    pub status: Option<String>,
6305    #[serde(default)]
6306    pub closed_reason: Option<String>,
6307    #[serde(default)]
6308    pub error: Option<String>,
6309    #[serde(default)]
6310    pub failure: Option<Value>,
6311    #[serde(default)]
6312    pub exception: Option<Value>,
6313    #[serde(default)]
6314    pub failures: Vec<Value>,
6315    #[serde(default)]
6316    pub output: Option<Value>,
6317    #[serde(default)]
6318    pub output_envelope: Option<Value>,
6319    #[serde(skip)]
6320    pub output_avro_value: Option<AvroValue>,
6321    #[serde(flatten)]
6322    pub raw: HashMap<String, Value>,
6323}
6324
6325/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
6326#[derive(Clone, Debug, Deserialize)]
6327pub struct WorkflowStreamDescription {
6328    pub stream_name: String,
6329    pub status: String,
6330    pub last_offset: i64,
6331    pub total_items: u64,
6332    pub pending_items: u64,
6333    #[serde(default)]
6334    pub opened_at: Option<String>,
6335    #[serde(default)]
6336    pub last_appended_at: Option<String>,
6337    #[serde(default)]
6338    pub closed_at: Option<String>,
6339    #[serde(default)]
6340    pub error_reason: Option<String>,
6341    #[serde(default)]
6342    pub retention_seconds: Option<u64>,
6343    #[serde(flatten)]
6344    pub raw: HashMap<String, Value>,
6345}
6346
6347impl WorkflowStreamDescription {
6348    pub fn is_terminal(&self) -> bool {
6349        matches!(self.status.as_str(), "closed" | "errored")
6350    }
6351}
6352
6353/// One item for direct or replay-safe append.
6354#[derive(Clone, Debug, Default)]
6355pub struct WorkflowStreamAppendItem {
6356    pub payload_envelope: Option<Value>,
6357    pub payload_reference: Option<String>,
6358    pub item_type: Option<String>,
6359    pub content_type: Option<String>,
6360    pub idempotency_key: Option<String>,
6361}
6362
6363impl WorkflowStreamAppendItem {
6364    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
6365    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
6366        let value = AvroValue::from_serialize(&payload)?;
6367        Ok(Self {
6368            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
6369            ..Self::default()
6370        })
6371    }
6372
6373    /// Preserve an external payload URI as an opaque service-contract reference.
6374    pub fn from_reference(reference: impl Into<String>) -> Self {
6375        Self {
6376            payload_reference: Some(reference.into()),
6377            ..Self::default()
6378        }
6379    }
6380
6381    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
6382        self.item_type = Some(item_type.into());
6383        self
6384    }
6385
6386    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
6387        self.content_type = Some(content_type.into());
6388        self
6389    }
6390
6391    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
6392        self.idempotency_key = Some(idempotency_key.into());
6393        self
6394    }
6395
6396    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
6397        let mut item = serde_json::Map::new();
6398        if let Some(payload) = &self.payload_envelope {
6399            item.insert("payload".to_string(), payload.clone());
6400            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
6401        }
6402        if let Some(reference) = &self.payload_reference {
6403            item.insert("payload_reference".to_string(), json!(reference));
6404        }
6405        if let Some(item_type) = &self.item_type {
6406            item.insert("item_type".to_string(), json!(item_type));
6407        }
6408        if let Some(content_type) = &self.content_type {
6409            item.insert("content_type".to_string(), json!(content_type));
6410        }
6411        if let Some(key) = derived_idempotency_key
6412            .as_ref()
6413            .or(self.idempotency_key.as_ref())
6414        {
6415            item.insert("idempotency_key".to_string(), json!(key));
6416        }
6417        Value::Object(item)
6418    }
6419}
6420
6421/// One durable item at its stable zero-based offset.
6422#[derive(Clone, Debug)]
6423pub struct WorkflowStreamItem {
6424    pub offset: u64,
6425    pub payload: Option<Value>,
6426    pub payload_envelope: Option<Value>,
6427    pub payload_reference: Option<String>,
6428    pub payload_codec: Option<String>,
6429    pub idempotency_key: Option<String>,
6430    pub item_type: Option<String>,
6431    pub content_type: Option<String>,
6432    pub origin: Option<String>,
6433    pub origin_reference: Option<String>,
6434    pub emitted_at: Option<String>,
6435    pub raw: Value,
6436}
6437
6438/// One bounded at-least-once subscription page.
6439#[derive(Clone, Debug)]
6440pub struct WorkflowStreamPage {
6441    pub stream: WorkflowStreamDescription,
6442    pub items: Vec<WorkflowStreamItem>,
6443    pub next_offset: u64,
6444    pub terminal: bool,
6445}
6446
6447/// Durable acceptance and deduplication outcome for an append request.
6448#[derive(Clone, Debug)]
6449pub struct WorkflowStreamAppendResult {
6450    pub stream: WorkflowStreamDescription,
6451    pub accepted_offsets: Vec<u64>,
6452    pub accepted: u64,
6453    pub deduped: u64,
6454}
6455
6456#[derive(Deserialize)]
6457struct WorkflowStreamListResponse {
6458    #[serde(default)]
6459    streams: Vec<WorkflowStreamDescription>,
6460}
6461
6462#[derive(Deserialize)]
6463struct WorkflowStreamDescriptionResponse {
6464    stream: WorkflowStreamDescription,
6465}
6466
6467#[derive(Deserialize)]
6468struct WorkflowStreamPageResponse {
6469    stream: WorkflowStreamDescription,
6470    #[serde(default)]
6471    items: Vec<Value>,
6472    next_offset: u64,
6473    terminal: bool,
6474}
6475
6476#[derive(Deserialize)]
6477struct WorkflowStreamAppendResponse {
6478    stream: WorkflowStreamDescription,
6479    #[serde(default)]
6480    accepted_offsets: Vec<u64>,
6481    accepted: u64,
6482    deduped: u64,
6483}
6484
6485impl WorkflowDescription {
6486    pub fn is_completed(&self) -> bool {
6487        matches!(self.status.as_deref(), Some("completed" | "Completed"))
6488    }
6489
6490    pub fn is_terminal(&self) -> bool {
6491        matches!(
6492            self.status.as_deref(),
6493            Some(
6494                "completed"
6495                    | "Completed"
6496                    | "failed"
6497                    | "Failed"
6498                    | "cancelled"
6499                    | "Cancelled"
6500                    | "terminated"
6501                    | "Terminated"
6502                    | "timed_out"
6503                    | "TimedOut",
6504            )
6505        )
6506    }
6507
6508    fn decode_payloads(&mut self) -> Result<()> {
6509        if let Some(envelope) = &self.output_envelope {
6510            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
6511            self.output = Some(value.clone().into_json()?);
6512            self.output_avro_value = Some(value);
6513        }
6514
6515        Ok(())
6516    }
6517
6518    fn raw_value(&self) -> Value {
6519        let mut data = self.raw.clone();
6520        data.insert(
6521            "workflow_id".to_string(),
6522            self.workflow_id
6523                .clone()
6524                .map(Value::String)
6525                .unwrap_or(Value::Null),
6526        );
6527        data.insert(
6528            "run_id".to_string(),
6529            self.run_id
6530                .clone()
6531                .map(Value::String)
6532                .unwrap_or(Value::Null),
6533        );
6534        data.insert(
6535            "workflow_type".to_string(),
6536            self.workflow_type
6537                .clone()
6538                .map(Value::String)
6539                .unwrap_or(Value::Null),
6540        );
6541        data.insert(
6542            "status".to_string(),
6543            self.status
6544                .clone()
6545                .map(Value::String)
6546                .unwrap_or(Value::Null),
6547        );
6548        data.insert(
6549            "closed_reason".to_string(),
6550            self.closed_reason
6551                .clone()
6552                .map(Value::String)
6553                .unwrap_or(Value::Null),
6554        );
6555        if let Some(failure) = &self.failure {
6556            data.insert("failure".to_string(), failure.clone());
6557        }
6558        if let Some(exception) = &self.exception {
6559            data.insert("exception".to_string(), exception.clone());
6560        }
6561        Value::Object(data.into_iter().collect())
6562    }
6563}
6564
6565fn workflow_terminal_outcome(
6566    description: &WorkflowDescription,
6567    workflow_id: &str,
6568    run_id: Option<&str>,
6569) -> WorkflowTerminalOutcome {
6570    let terminal_kind = description
6571        .closed_reason
6572        .as_deref()
6573        .or(description.status.as_deref())
6574        .unwrap_or("failed")
6575        .to_ascii_lowercase();
6576    let kind = match terminal_kind.as_str() {
6577        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
6578        "terminated" => WorkflowTerminalKind::Terminated,
6579        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
6580        _ => WorkflowTerminalKind::Failed,
6581    };
6582    let default_reason = match kind {
6583        WorkflowTerminalKind::Failed => "workflow_failed",
6584        WorkflowTerminalKind::Cancelled => "cancelled",
6585        WorkflowTerminalKind::Terminated => "terminated",
6586        WorkflowTerminalKind::TimedOut => "timed_out",
6587    };
6588    let failure = description
6589        .failure
6590        .as_ref()
6591        .filter(|value| value.is_object());
6592    let nested_failure = failure
6593        .and_then(|value| value.get("failures"))
6594        .and_then(Value::as_array)
6595        .and_then(|failures| failures.last())
6596        .or_else(|| description.failures.last());
6597    let exception = description
6598        .exception
6599        .clone()
6600        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
6601        .or_else(|| {
6602            nested_failure
6603                .and_then(|value| value.get("exception_payload"))
6604                .cloned()
6605        });
6606    let string_field = |name: &str| {
6607        failure
6608            .and_then(|value| value.get(name))
6609            .and_then(Value::as_str)
6610            .or_else(|| {
6611                nested_failure
6612                    .and_then(|value| value.get(name))
6613                    .and_then(Value::as_str)
6614            })
6615            .map(str::to_string)
6616    };
6617    let exception_field = |name: &str| {
6618        exception
6619            .as_ref()
6620            .and_then(|value| value.get(name))
6621            .and_then(Value::as_str)
6622            .map(str::to_string)
6623    };
6624    let message = description
6625        .error
6626        .clone()
6627        .or_else(|| string_field("message"))
6628        .or_else(|| exception_field("message"));
6629    let reason = description
6630        .raw
6631        .get("reason")
6632        .and_then(Value::as_str)
6633        .map(str::to_string)
6634        .or_else(|| {
6635            failure
6636                .and_then(|value| value.get("reason"))
6637                .and_then(Value::as_str)
6638                .map(str::to_string)
6639        })
6640        .or_else(|| description.closed_reason.clone())
6641        .unwrap_or_else(|| default_reason.to_string());
6642    let failure_id = string_field("failure_id").or_else(|| {
6643        nested_failure
6644            .and_then(|value| value.get("id"))
6645            .and_then(Value::as_str)
6646            .map(str::to_string)
6647    });
6648
6649    WorkflowTerminalOutcome {
6650        kind,
6651        workflow_id: description
6652            .workflow_id
6653            .clone()
6654            .unwrap_or_else(|| workflow_id.to_string()),
6655        run_id: description
6656            .run_id
6657            .clone()
6658            .or_else(|| run_id.map(str::to_string)),
6659        reason,
6660        failure_category: string_field("failure_category")
6661            .or_else(|| Some(default_reason.to_string())),
6662        failure_id,
6663        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
6664        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
6665        non_retryable: failure
6666            .and_then(|value| value.get("non_retryable"))
6667            .and_then(Value::as_bool)
6668            .or_else(|| {
6669                nested_failure
6670                    .and_then(|value| value.get("non_retryable"))
6671                    .and_then(Value::as_bool)
6672            }),
6673        message,
6674        exception,
6675        raw: description.raw_value(),
6676    }
6677}
6678
6679#[derive(Clone, Debug, Deserialize)]
6680pub struct RegisterWorkerResponse {
6681    pub worker_id: String,
6682    pub registered: bool,
6683    #[serde(default)]
6684    pub heartbeat_interval_seconds: Option<u64>,
6685    #[serde(default)]
6686    pub protocol_version: Option<String>,
6687    #[serde(default)]
6688    pub server_capabilities: Option<Value>,
6689}
6690
6691/// Result of gracefully removing a worker-plane registration.
6692#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
6693pub struct WorkerDeregistrationEnvelope {
6694    pub worker_id: String,
6695    pub outcome: String,
6696    pub recovered_workflow_task_count: u64,
6697}
6698
6699#[derive(Clone, Debug, Deserialize)]
6700pub struct PollWorkflowTaskResponse {
6701    #[serde(default)]
6702    pub task: Option<WorkflowTask>,
6703    #[serde(default)]
6704    pub poll_status: Option<String>,
6705    #[serde(default)]
6706    pub reason: Option<String>,
6707    #[serde(default)]
6708    pub protocol_version: Option<String>,
6709    #[serde(default)]
6710    pub server_capabilities: Option<Value>,
6711}
6712
6713impl PollWorkflowTaskResponse {
6714    /// Classify this response without parsing server display text.
6715    pub fn outcome(&self) -> WorkerPollOutcome {
6716        worker_poll_outcome(
6717            self.task.is_some(),
6718            self.poll_status.as_deref(),
6719            self.reason.as_deref(),
6720        )
6721    }
6722}
6723
6724fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
6725    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
6726        return false;
6727    };
6728    let supported = capabilities
6729        .get("workflow_memo_updates")
6730        .and_then(Value::as_object)
6731        .and_then(|memo| memo.get("supported"))
6732        .and_then(Value::as_bool)
6733        == Some(true);
6734    let command_advertised = capabilities
6735        .get("supported_workflow_task_commands")
6736        .and_then(Value::as_array)
6737        .is_some_and(|commands| {
6738            commands
6739                .iter()
6740                .any(|command| command.as_str() == Some("upsert_memo"))
6741        });
6742    supported && command_advertised
6743}
6744
6745fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
6746    commands
6747        .iter()
6748        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
6749}
6750
6751#[derive(Clone, Debug, Deserialize)]
6752pub struct PollActivityTaskResponse {
6753    #[serde(default)]
6754    pub task: Option<ActivityTask>,
6755    #[serde(default)]
6756    pub poll_status: Option<String>,
6757    #[serde(default)]
6758    pub reason: Option<String>,
6759}
6760
6761impl PollActivityTaskResponse {
6762    /// Classify this response without parsing server display text.
6763    pub fn outcome(&self) -> WorkerPollOutcome {
6764        worker_poll_outcome(
6765            self.task.is_some(),
6766            self.poll_status.as_deref(),
6767            self.reason.as_deref(),
6768        )
6769    }
6770}
6771
6772#[derive(Clone, Debug, Deserialize)]
6773pub struct PollQueryTaskResponse {
6774    #[serde(default)]
6775    pub task: Option<QueryTask>,
6776    #[serde(default)]
6777    pub poll_status: Option<String>,
6778    #[serde(default)]
6779    pub reason: Option<String>,
6780}
6781
6782impl PollQueryTaskResponse {
6783    /// Classify this response without parsing server display text.
6784    pub fn outcome(&self) -> WorkerPollOutcome {
6785        worker_poll_outcome(
6786            self.task.is_some(),
6787            self.poll_status.as_deref(),
6788            self.reason.as_deref(),
6789        )
6790    }
6791}
6792
6793/// Stable classification for worker poll responses.
6794#[derive(Clone, Debug, PartialEq, Eq)]
6795pub enum WorkerPollOutcome {
6796    /// A task was leased and is available on the response.
6797    Task,
6798    /// No task was leased, but the worker should continue polling.
6799    Idle {
6800        poll_status: Option<String>,
6801        reason: Option<String>,
6802    },
6803    /// The server asked this worker to stop claiming new work.
6804    Stop {
6805        poll_status: Option<String>,
6806        reason: Option<String>,
6807    },
6808}
6809
6810impl WorkerPollOutcome {
6811    pub fn should_stop(&self) -> bool {
6812        matches!(self, Self::Stop { .. })
6813    }
6814}
6815
6816fn worker_poll_outcome(
6817    has_task: bool,
6818    poll_status: Option<&str>,
6819    reason: Option<&str>,
6820) -> WorkerPollOutcome {
6821    if worker_poll_is_stop(poll_status, reason) {
6822        return WorkerPollOutcome::Stop {
6823            poll_status: poll_status.map(str::to_string),
6824            reason: reason.map(str::to_string),
6825        };
6826    }
6827
6828    if has_task {
6829        WorkerPollOutcome::Task
6830    } else {
6831        WorkerPollOutcome::Idle {
6832            poll_status: poll_status.map(str::to_string),
6833            reason: reason.map(str::to_string),
6834        }
6835    }
6836}
6837
6838/// An ephemeral server-routed query task.
6839#[derive(Clone, Debug, Deserialize)]
6840pub struct QueryTask {
6841    pub query_task_id: String,
6842    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6843    #[serde(default)]
6844    pub observability_context: Option<Value>,
6845    #[serde(default)]
6846    pub dispatch_observability_context: Option<Value>,
6847    #[serde(default)]
6848    pub observability_links: Option<Value>,
6849    #[serde(default = "default_workflow_task_attempt")]
6850    pub query_task_attempt: u64,
6851    #[serde(default)]
6852    pub lease_owner: Option<String>,
6853    #[serde(default)]
6854    pub workflow_id: Option<String>,
6855    #[serde(default)]
6856    pub run_id: Option<String>,
6857    pub workflow_type: String,
6858    pub query_name: String,
6859    #[serde(
6860        default = "missing_task_payload_codec",
6861        deserialize_with = "deserialize_task_payload_codec"
6862    )]
6863    pub payload_codec: String,
6864    #[serde(default)]
6865    pub workflow_arguments: Option<Value>,
6866    #[serde(default)]
6867    pub query_arguments: Option<Value>,
6868    #[serde(default)]
6869    pub history_events: Vec<HistoryEvent>,
6870    #[serde(default)]
6871    pub history_export: Option<Value>,
6872    #[serde(default)]
6873    pub run_status: Option<String>,
6874}
6875
6876#[derive(Clone, Debug, Deserialize)]
6877pub struct WorkflowTask {
6878    pub task_id: String,
6879    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6880    #[serde(default)]
6881    pub observability_context: Option<Value>,
6882    #[serde(default)]
6883    pub dispatch_observability_context: Option<Value>,
6884    #[serde(default)]
6885    pub observability_links: Option<Value>,
6886    #[serde(default)]
6887    pub workflow_command_id: Option<String>,
6888    #[serde(default)]
6889    pub workflow_id: Option<String>,
6890    #[serde(default)]
6891    pub run_id: Option<String>,
6892    pub workflow_type: String,
6893    #[serde(default)]
6894    pub cancel_requested: bool,
6895    #[serde(
6896        default = "missing_task_payload_codec",
6897        deserialize_with = "deserialize_task_payload_codec"
6898    )]
6899    pub payload_codec: String,
6900    #[serde(default)]
6901    pub arguments: Option<Value>,
6902    #[serde(default)]
6903    pub history_events: Vec<HistoryEvent>,
6904    #[serde(default)]
6905    pub total_history_events: Option<u64>,
6906    #[serde(default)]
6907    pub history_size_bytes: Option<u64>,
6908    #[serde(default)]
6909    pub continue_as_new_recommended: Option<bool>,
6910    #[serde(default)]
6911    pub history_budget_pressure: Option<String>,
6912    #[serde(default)]
6913    pub next_history_page_token: Option<String>,
6914    #[serde(default = "default_workflow_task_attempt")]
6915    pub workflow_task_attempt: u64,
6916    #[serde(default)]
6917    pub workflow_signal_id: Option<String>,
6918    #[serde(default)]
6919    pub signal_name: Option<String>,
6920    #[serde(default)]
6921    pub signal_arguments: Option<Value>,
6922    #[serde(default)]
6923    pub workflow_update_id: Option<String>,
6924    #[serde(default)]
6925    pub update_name: Option<String>,
6926    #[serde(default)]
6927    pub lease_owner: Option<String>,
6928}
6929
6930impl WorkflowTask {
6931    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
6932        self.history_events.extend(page.history_events);
6933
6934        if page.total_history_events.is_some() {
6935            self.total_history_events = page.total_history_events;
6936        }
6937
6938        self.next_history_page_token = page
6939            .next_history_page_token
6940            .filter(|token| !token.is_empty());
6941    }
6942}
6943
6944#[derive(Clone, Debug, Deserialize)]
6945struct WorkflowTaskHistoryPage {
6946    #[serde(default)]
6947    history_events: Vec<HistoryEvent>,
6948    #[serde(default)]
6949    total_history_events: Option<u64>,
6950    #[serde(default)]
6951    next_history_page_token: Option<String>,
6952}
6953
6954#[derive(Clone, Debug, Deserialize)]
6955pub struct ActivityTask {
6956    pub task_id: String,
6957    #[serde(default)]
6958    pub workflow_id: Option<String>,
6959    #[serde(default)]
6960    pub run_id: Option<String>,
6961    #[serde(default)]
6962    pub activity_execution_id: Option<String>,
6963    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
6964    #[serde(default)]
6965    pub observability_context: Option<Value>,
6966    #[serde(default)]
6967    pub dispatch_observability_context: Option<Value>,
6968    #[serde(default)]
6969    pub observability_links: Option<Value>,
6970    #[serde(default)]
6971    pub activity_attempt_id: Option<String>,
6972    #[serde(default)]
6973    pub attempt_id: Option<String>,
6974    pub activity_type: String,
6975    #[serde(
6976        default = "missing_task_payload_codec",
6977        deserialize_with = "deserialize_task_payload_codec"
6978    )]
6979    pub payload_codec: String,
6980    #[serde(default)]
6981    pub arguments: Option<Value>,
6982    #[serde(default = "default_attempt_number")]
6983    pub attempt_number: u64,
6984    #[serde(default)]
6985    pub lease_owner: Option<String>,
6986}
6987
6988#[derive(Clone, Debug, Serialize, Deserialize)]
6989pub struct HistoryEvent {
6990    #[serde(alias = "type")]
6991    pub event_type: String,
6992    #[serde(default)]
6993    pub payload: Value,
6994    #[serde(flatten)]
6995    pub raw: HashMap<String, Value>,
6996}
6997
6998/// One decoded signal in the committed workflow-history snapshot.
6999#[derive(Clone, Debug, PartialEq)]
7000pub struct QuerySignal {
7001    pub id: Option<String>,
7002    pub name: String,
7003    pub arguments: Vec<Value>,
7004    avro_arguments: Vec<AvroValue>,
7005    pub workflow_sequence: Option<u64>,
7006}
7007
7008impl QuerySignal {
7009    /// Lossless fixed Avro Value arguments for this committed signal.
7010    pub fn arguments_avro_value(&self) -> &[AvroValue] {
7011        &self.avro_arguments
7012    }
7013}
7014
7015/// Immutable state supplied to a registered query handler.
7016///
7017/// This context intentionally exposes no activity, signal-wait, or command
7018/// APIs. Query handlers inspect committed history and return a value; query
7019/// completion does not append an event or advance deterministic execution.
7020#[derive(Clone, Debug)]
7021pub struct QueryContext {
7022    pub workflow_id: Option<String>,
7023    pub run_id: Option<String>,
7024    pub workflow_type: String,
7025    pub run_status: Option<String>,
7026    workflow_input: Value,
7027    workflow_input_avro_value: AvroValue,
7028    history_events: Arc<Vec<HistoryEvent>>,
7029    signal_events: Arc<Vec<QuerySignal>>,
7030}
7031
7032impl QueryContext {
7033    /// The normalized argument list used to start the workflow.
7034    pub fn workflow_input(&self) -> &Value {
7035        &self.workflow_input
7036    }
7037
7038    /// The lossless fixed Avro Value argument list used to start the workflow.
7039    pub fn workflow_input_avro_value(&self) -> &AvroValue {
7040        &self.workflow_input_avro_value
7041    }
7042
7043    /// The immutable committed history used for this query snapshot.
7044    pub fn history_events(&self) -> &[HistoryEvent] {
7045        self.history_events.as_slice()
7046    }
7047
7048    /// All decoded signals in committed workflow order.
7049    pub fn signal_events(&self) -> &[QuerySignal] {
7050        self.signal_events.as_slice()
7051    }
7052
7053    /// Decoded argument lists for each committed signal with `signal_name`.
7054    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
7055        self.signal_events
7056            .iter()
7057            .filter(|signal| signal.name == signal_name)
7058            .map(|signal| signal.arguments.clone())
7059            .collect()
7060    }
7061
7062    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
7063    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
7064        self.signal_events
7065            .iter()
7066            .filter(|signal| signal.name == signal_name)
7067            .map(|signal| signal.avro_arguments.clone())
7068            .collect()
7069    }
7070}
7071
7072#[derive(Clone, Debug, Deserialize)]
7073pub struct ActivityHeartbeatResponse {
7074    #[serde(default)]
7075    pub cancel_requested: bool,
7076    #[serde(default)]
7077    pub heartbeat_recorded: bool,
7078    #[serde(default)]
7079    pub can_continue: Option<bool>,
7080    #[serde(default)]
7081    pub reason: Option<String>,
7082    #[serde(default)]
7083    pub run_closed_reason: Option<String>,
7084    #[serde(default)]
7085    pub run_closed_at: Option<String>,
7086    #[serde(default)]
7087    pub lease_expires_at: Option<String>,
7088    #[serde(default)]
7089    pub last_heartbeat_at: Option<String>,
7090}
7091
7092impl ActivityHeartbeatResponse {
7093    /// Whether the activity should stop instead of attempting completion.
7094    pub fn should_stop(&self) -> bool {
7095        self.cancel_requested || self.can_continue == Some(false)
7096    }
7097}
7098
7099fn missing_task_payload_codec() -> String {
7100    MISSING_TASK_PAYLOAD_CODEC.to_string()
7101}
7102
7103fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
7104where
7105    D: Deserializer<'de>,
7106{
7107    Ok(match Value::deserialize(deserializer)? {
7108        Value::String(codec) => codec,
7109        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
7110        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
7111    })
7112}
7113
7114fn default_workflow_task_attempt() -> u64 {
7115    1
7116}
7117
7118fn default_attempt_number() -> u64 {
7119    1
7120}
7121
7122type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7123type WorkflowHandler =
7124    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<WorkflowFuture> + Send + Sync>;
7125type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
7126type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
7127type ReplayedWorkflowHandler =
7128    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<ReplayedWorkflowInvocation> + Send + Sync>;
7129type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7130type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
7131type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7132type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
7133type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
7134type ReplayedQueryHandler = Arc<
7135    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
7136        + Send
7137        + Sync,
7138>;
7139type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
7140
7141struct ReplayedWorkflowInvocation {
7142    future: WorkflowFuture,
7143    snapshot: WorkflowStateSnapshot,
7144}
7145
7146#[derive(Clone)]
7147struct RegisteredWorkflow {
7148    execute: WorkflowHandler,
7149    replay: Option<ReplayedWorkflowHandler>,
7150    state_type: Option<TypeId>,
7151    definition_fingerprint: Option<String>,
7152}
7153
7154fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
7155    names
7156        .iter()
7157        .map(|name| {
7158            json!({
7159                "name": name,
7160                "parameters": [{
7161                    "name": "args",
7162                    "position": 0,
7163                    "required": false,
7164                    "variadic": true,
7165                    "type": null,
7166                    "allows_null": true,
7167                    "default_available": false,
7168                    "default": null,
7169                }],
7170            })
7171        })
7172        .collect()
7173}
7174
7175#[derive(Debug)]
7176struct WorkflowTaskDecision {
7177    commands: Vec<Value>,
7178    message_stream_cursors: Vec<Value>,
7179    message_stream_waits: Vec<Value>,
7180    cancellation_delivery: Option<CancellationDelivery>,
7181    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
7182    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
7183}
7184
7185enum PreparedWorkflowTask {
7186    Decision(WorkflowTaskDecision),
7187    Execution {
7188        task: WorkflowTask,
7189        context: WorkflowContext,
7190        future: WorkflowFuture,
7191    },
7192}
7193
7194impl WorkflowTaskDecision {
7195    fn without_message_streams(commands: Vec<Value>) -> Self {
7196        Self {
7197            commands,
7198            message_stream_cursors: Vec::new(),
7199            message_stream_waits: Vec::new(),
7200            cancellation_delivery: None,
7201            cancellation_scope_opening: None,
7202            cancellation_scope_delivery: None,
7203        }
7204    }
7205}
7206
7207#[derive(Clone)]
7208enum RegisteredQuery {
7209    Snapshot(QueryHandler),
7210    Replayed {
7211        state_type: TypeId,
7212        handler: ReplayedQueryHandler,
7213    },
7214}
7215
7216#[derive(Clone, Debug)]
7217pub struct WorkerHeartbeatObservation {
7218    pub worker_id: String,
7219    pub task_queue: String,
7220    pub acknowledged_at_unix_millis: u64,
7221    pub acknowledgement: Value,
7222}
7223
7224/// Bounded retry policy for worker poll acquisition and worker heartbeats.
7225///
7226/// Expected empty long polls and explicit Server capacity backpressure are
7227/// normal worker states. Capacity backpressure honors the advertised retry
7228/// delay without consuming this retry budget. Other transport failures,
7229/// retryable HTTP 408/429 responses, and server errors are retried with capped
7230/// exponential backoff. Authentication, protocol, codec, and handler failures
7231/// are never retried by the worker.
7232/// Explicit storage admission pauses also preserve the already-serialized worker
7233/// request without consuming this budget or rerunning its handler. The delay is
7234/// capped by `max_backoff`, except an explicit completion deferral must honor
7235/// the Server's minimum delay. Shutdown interrupts storage waits; cooperative
7236/// completion retries remain bounded by the original cleanup deadline.
7237/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
7238/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
7239/// and `max_retries = 0` disables ordinary retries in either mode.
7240#[derive(Clone, Copy, Debug)]
7241pub struct WorkerRetryPolicy {
7242    /// Number of retries after the initial request fails.
7243    pub max_retries: usize,
7244    /// Delay before the first retry.
7245    pub initial_backoff: Duration,
7246    /// Maximum delay between retries.
7247    pub max_backoff: Duration,
7248}
7249
7250impl Default for WorkerRetryPolicy {
7251    fn default() -> Self {
7252        Self {
7253            max_retries: 5,
7254            initial_backoff: Duration::from_millis(100),
7255            max_backoff: Duration::from_secs(5),
7256        }
7257    }
7258}
7259
7260#[derive(Clone, Debug)]
7261struct WorkerStorageAdmission {
7262    policy: WorkerRetryPolicy,
7263    stop: Arc<AtomicBool>,
7264    workflow_completion_retry_deadline: Option<tokio::time::Instant>,
7265}
7266
7267struct StopWorkerOnDrop(Arc<AtomicBool>);
7268
7269impl Drop for StopWorkerOnDrop {
7270    fn drop(&mut self) {
7271        self.0.store(true, Ordering::SeqCst);
7272    }
7273}
7274
7275async fn wait_for_worker_stop(stop: &AtomicBool) {
7276    while !stop.load(Ordering::SeqCst) {
7277        tokio::time::sleep(Duration::from_millis(100)).await;
7278    }
7279}
7280
7281#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7282enum ManagedPollOutcome {
7283    Idle,
7284    Handled,
7285    Stop,
7286}
7287
7288#[derive(Clone)]
7289pub struct Worker {
7290    metrics: metrics::Metrics,
7291    #[cfg(feature = "telemetry")]
7292    telemetry: Option<telemetry::ExecutionTelemetry>,
7293    client: Client,
7294    worker_id: String,
7295    task_queue: String,
7296    workflows: HashMap<String, RegisteredWorkflow>,
7297    activities: HashMap<String, ActivityHandler>,
7298    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
7299    signals: HashMap<String, Vec<String>>,
7300    updates: HashMap<String, HashMap<String, UpdateHandler>>,
7301    registration_definitions:
7302        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
7303    registration_error: Option<DuplicateRegistrationError>,
7304    max_concurrent_workflow_tasks: usize,
7305    max_concurrent_activity_tasks: usize,
7306    workflow_capacity: Arc<worker_capacity::TaskCapacity>,
7307    activity_capacity: Arc<worker_capacity::TaskCapacity>,
7308    poll_timeout: Duration,
7309    heartbeat_interval: Duration,
7310    retry_policy: WorkerRetryPolicy,
7311    recover_transient_outages: bool,
7312    run_stop: Option<Arc<AtomicBool>>,
7313    heartbeat_observer: Option<WorkerHeartbeatObserver>,
7314    cooperative_cancellation_enabled: bool,
7315    nexus_cooperative_cancellation_enabled: bool,
7316    allow_cancellation_scope_authoring: bool,
7317    allow_cancellation_scope_delivery: bool,
7318    cooperative_registration_confirmed: Arc<AtomicBool>,
7319    nexus_registration_confirmed: Arc<AtomicBool>,
7320    local_registration_confirmed: Arc<AtomicBool>,
7321    session_registration_confirmed: Arc<AtomicBool>,
7322    sticky_registration_confirmed: Arc<AtomicBool>,
7323    require_query_task_authority: bool,
7324    query_authority_confirmed: Arc<AtomicBool>,
7325    resource_capabilities: Vec<String>,
7326    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
7327}
7328
7329impl Worker {
7330    /// Override worker poll/task metrics; client request metrics retain their client's recorder.
7331    pub fn metrics_recorder(mut self, recorder: Arc<dyn metrics::MetricsRecorder>) -> Self {
7332        self.metrics = metrics::Metrics::new(recorder);
7333        self
7334    }
7335    pub fn new(client: Client, task_queue: impl Into<String>) -> Self {
7336        Self {
7337            metrics: client.metrics.clone(),
7338            #[cfg(feature = "telemetry")]
7339            telemetry: None,
7340            client,
7341            worker_id: default_worker_id(),
7342            task_queue: task_queue.into(),
7343            workflows: HashMap::new(),
7344            activities: HashMap::new(),
7345            queries: HashMap::new(),
7346            signals: HashMap::new(),
7347            updates: HashMap::new(),
7348            registration_definitions: HashMap::new(),
7349            registration_error: None,
7350            max_concurrent_workflow_tasks: 10,
7351            max_concurrent_activity_tasks: 10,
7352            workflow_capacity: worker_capacity::TaskCapacity::new(10),
7353            activity_capacity: worker_capacity::TaskCapacity::new(10),
7354            poll_timeout: Duration::from_secs(30),
7355            heartbeat_interval: Duration::from_secs(60),
7356            retry_policy: WorkerRetryPolicy::default(),
7357            recover_transient_outages: false,
7358            run_stop: None,
7359            heartbeat_observer: None,
7360            cooperative_cancellation_enabled: false,
7361            nexus_cooperative_cancellation_enabled: false,
7362            allow_cancellation_scope_authoring: false,
7363            allow_cancellation_scope_delivery: false,
7364            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
7365            nexus_registration_confirmed: Arc::new(AtomicBool::new(false)),
7366            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
7367            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
7368            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
7369            require_query_task_authority: false,
7370            query_authority_confirmed: Arc::new(AtomicBool::new(false)),
7371            resource_capabilities: Vec::new(),
7372            sessions: Arc::new(Mutex::new(HashMap::new())),
7373        }
7374    }
7375
7376    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
7377        self.worker_id = worker_id.into();
7378        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
7379        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7380        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
7381        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
7382        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
7383        self.query_authority_confirmed = Arc::new(AtomicBool::new(false));
7384        self.client.reset_sticky_cache();
7385        self.sessions = Arc::new(Mutex::new(HashMap::new()));
7386        self
7387    }
7388
7389    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
7390        self.poll_timeout = timeout;
7391        self
7392    }
7393
7394    /// Opt in to execution spans using application-owned OpenTelemetry providers.
7395    /// No exporter, logging bridge, global provider or Server carrier is installed.
7396    #[cfg(feature = "telemetry")]
7397    pub fn telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
7398        self.client.execution_telemetry = Some(telemetry.clone());
7399        self.telemetry = Some(telemetry);
7400        self
7401    }
7402
7403    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
7404        self.heartbeat_interval = interval;
7405        self
7406    }
7407
7408    /// Require original query timing and non-renewing runtime observation.
7409    ///
7410    /// Registration refuses before creating a Worker unless protocol 1.20 and
7411    /// the runtime's `query_task_authority` capability are available. By default,
7412    /// older Servers retain their weaker, disclosed local-timing behavior.
7413    pub fn require_query_task_authority(mut self, required: bool) -> Self {
7414        self.require_query_task_authority = required;
7415        self
7416    }
7417
7418    /// Explicitly enable inline local activities in this workflow worker.
7419    ///
7420    /// The worker advertises the capability to Server only when enabled.
7421    /// These callbacks must yield to Tokio and have idempotent side effects.
7422    /// Cooperative prepared local supervision is a separate capability.
7423    pub fn local_activities(mut self, enabled: bool) -> Self {
7424        self.client.local_activities_enabled = enabled;
7425        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
7426        self
7427    }
7428
7429    /// Opt in to separate cooperative workflow cancellation requests.
7430    ///
7431    /// Registration requires the Server to acknowledge this exact worker,
7432    /// namespace, queue and capabilities with compatible protocol 1.20. Task
7433    /// processing uses canonical delivery and activity ownership fences.
7434    /// Existing terminal cancel and terminate operations remain terminal.
7435    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
7436    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
7437    /// and [`Worker::run_until`] register automatically.
7438    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
7439        self.cooperative_cancellation_enabled = enabled;
7440        self.client.cooperative_worker_protocol = enabled;
7441        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
7442        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7443        if !enabled {
7444            self.nexus_cooperative_cancellation_enabled = false;
7445        }
7446        self
7447    }
7448
7449    /// Opt in to cooperative Nexus completion waits on an installed workflow binding.
7450    ///
7451    /// This also enables ordinary cooperative cancellation. Registration checks
7452    /// protocol 1.20 and Server's installed `workflow_run` bridge before advertising.
7453    pub fn nexus_cooperative_cancellation(self, enabled: bool) -> Self {
7454        let mut worker = if enabled {
7455            self.cooperative_cancellation(true)
7456        } else {
7457            self
7458        };
7459        worker.nexus_cooperative_cancellation_enabled = enabled;
7460        worker.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7461        worker
7462    }
7463
7464    /// Enable candidate scope authoring without advertising scoped execution.
7465    #[doc(hidden)]
7466    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
7467        self.allow_cancellation_scope_authoring = enabled;
7468        self
7469    }
7470
7471    /// Enable the candidate scoped call consumer with canonical authoring.
7472    #[doc(hidden)]
7473    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
7474        self.allow_cancellation_scope_delivery = enabled;
7475        self
7476    }
7477
7478    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
7479    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
7480        self.retry_policy = policy;
7481        self
7482    }
7483
7484    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
7485    ///
7486    /// Retries preserve the poll request identity and use capped exponential
7487    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
7488    /// An in-flight poll is allowed to finish so leased work is not discarded.
7489    /// Authentication, protocol, codec, handler and task settlement failures
7490    /// remain errors. Registration and deregistration are not retried here.
7491    ///
7492    /// The default is disabled, preserving the bounded retry contract.
7493    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
7494    /// even when this option is enabled.
7495    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
7496        self.recover_transient_outages = enabled;
7497        self
7498    }
7499
7500    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
7501    where
7502        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
7503    {
7504        self.heartbeat_observer = Some(Arc::new(observer));
7505        self
7506    }
7507
7508    /// Bound simultaneous claimed workflow tasks, including loading and settlement.
7509    /// Defaults to 10. Use 1 for serial workflow-task execution.
7510    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
7511        self.max_concurrent_workflow_tasks = count.clamp(1, tokio::sync::Semaphore::MAX_PERMITS);
7512        self.workflow_capacity =
7513            worker_capacity::TaskCapacity::new(self.max_concurrent_workflow_tasks);
7514        self
7515    }
7516
7517    /// Bound simultaneous remote activity tasks, including loading and settlement.
7518    /// Defaults to 10. Use 1 for serial activity-task execution.
7519    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
7520        self.max_concurrent_activity_tasks = count.clamp(1, tokio::sync::Semaphore::MAX_PERMITS);
7521        self.activity_capacity =
7522            worker_capacity::TaskCapacity::new(self.max_concurrent_activity_tasks);
7523        self
7524    }
7525
7526    /// Validate local handler admission without making a Server request.
7527    ///
7528    /// Registration methods retain their existing signatures. A duplicate keeps
7529    /// the original handler and makes this Worker invalid, including its clones.
7530    /// `register`, `run`, `run_until` and `run_once` enforce this check before
7531    /// any network request. Build a new Worker to correct an invalid configuration.
7532    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
7533        match &self.registration_error {
7534            Some(error) => Err(error.clone()),
7535            None => Ok(()),
7536        }
7537    }
7538
7539    #[track_caller]
7540    fn admit_registration<F>(
7541        &mut self,
7542        handler_kind: RegistrationKind,
7543        workflow_type: Option<&str>,
7544        handler_name: &str,
7545        method: &'static str,
7546    ) -> bool {
7547        let location = std::panic::Location::caller();
7548        let definition = HandlerRegistration {
7549            method,
7550            handler_type: type_name::<F>(),
7551            file: location.file(),
7552            line: location.line(),
7553            column: location.column(),
7554        };
7555        let key = (
7556            handler_kind,
7557            workflow_type.map(str::to_owned),
7558            handler_name.to_owned(),
7559        );
7560        if let Some(first_definition) = self.registration_definitions.get(&key) {
7561            if self.registration_error.is_none() {
7562                self.registration_error = Some(DuplicateRegistrationError {
7563                    handler_kind,
7564                    workflow_type: key.1.clone(),
7565                    handler_name: key.2.clone(),
7566                    first_definition: first_definition.clone(),
7567                    second_definition: definition,
7568                });
7569            }
7570            return false;
7571        }
7572        self.registration_definitions.insert(key, definition);
7573        true
7574    }
7575
7576    /// Register a workflow handler.
7577    ///
7578    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
7579    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
7580    /// while acquiring or decoding a worker task remain worker-operation
7581    /// failures and do not get converted into workflow outcomes.
7582    #[track_caller]
7583    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
7584    where
7585        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
7586        Fut: Future<Output = Result<Value>> + Send + 'static,
7587    {
7588        let workflow_type = workflow_type.into();
7589        if !self.admit_registration::<F>(
7590            RegistrationKind::Workflow,
7591            None,
7592            &workflow_type,
7593            "register_workflow",
7594        ) {
7595            return;
7596        }
7597        let handler = Arc::new(handler);
7598        self.workflows.insert(
7599            workflow_type,
7600            RegisteredWorkflow {
7601                execute: Arc::new(move |ctx, input| {
7602                    let handler = Arc::clone(&handler);
7603                    Ok(Box::pin(async move {
7604                        let result = handler(ctx, input.into_json()?).await?;
7605                        AvroValue::from_serialize(&result)
7606                    }))
7607                }),
7608                replay: None,
7609                state_type: None,
7610                definition_fingerprint: None,
7611            },
7612        );
7613    }
7614
7615    /// Register a workflow with one Serde request value and a Serde result.
7616    ///
7617    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
7618    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
7619    /// workflow-specific schema. A task must contain zero arguments for a unit
7620    /// request or exactly one argument for every other request type.
7621    ///
7622    /// See the runnable
7623    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
7624    /// for typed workflow and activity contracts with retry and timeout policy.
7625    #[track_caller]
7626    pub fn register_typed_workflow<I, O, F, Fut>(
7627        &mut self,
7628        workflow_type: impl Into<String>,
7629        handler: F,
7630    ) where
7631        I: DeserializeOwned + Send + 'static,
7632        O: Serialize + Send + 'static,
7633        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
7634        Fut: Future<Output = Result<O>> + Send + 'static,
7635    {
7636        let workflow_type = workflow_type.into();
7637        if !self.admit_registration::<F>(
7638            RegistrationKind::Workflow,
7639            None,
7640            &workflow_type,
7641            "register_typed_workflow",
7642        ) {
7643            return;
7644        }
7645        let handler_name = workflow_type.clone();
7646        let handler = Arc::new(handler);
7647        self.workflows.insert(
7648            workflow_type,
7649            RegisteredWorkflow {
7650                execute: Arc::new(move |ctx, input| {
7651                    let input = decode_workflow_entry::<I>(input, &handler_name)?;
7652                    let handler = Arc::clone(&handler);
7653                    let handler_name = handler_name.clone();
7654                    Ok(Box::pin(async move {
7655                        let result = handler(ctx, input).await?;
7656                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7657                    }))
7658                }),
7659                replay: None,
7660                state_type: None,
7661                definition_fingerprint: None,
7662            },
7663        );
7664    }
7665
7666    /// Register a workflow on the lossless fixed Avro Value surface.
7667    #[track_caller]
7668    pub fn register_workflow_avro_value<F, Fut>(
7669        &mut self,
7670        workflow_type: impl Into<String>,
7671        handler: F,
7672    ) where
7673        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
7674        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7675    {
7676        let workflow_type = workflow_type.into();
7677        if !self.admit_registration::<F>(
7678            RegistrationKind::Workflow,
7679            None,
7680            &workflow_type,
7681            "register_workflow_avro_value",
7682        ) {
7683            return;
7684        }
7685        self.workflows.insert(
7686            workflow_type,
7687            RegisteredWorkflow {
7688                execute: Arc::new(move |ctx, input| Ok(Box::pin(handler(ctx, input)))),
7689                replay: None,
7690                state_type: None,
7691                definition_fingerprint: None,
7692            },
7693        );
7694    }
7695
7696    /// Register a workflow whose typed instance state can be reconstructed for queries.
7697    ///
7698    /// `state_factory` creates a fresh instance for every normal workflow task and
7699    /// query replay. The workflow handler is the single source of truth for state
7700    /// transitions: it updates [`WorkflowInstance`] after activities and signals
7701    /// resolve. Query replay runs this same handler over committed history and
7702    /// discards any commands it would emit.
7703    #[track_caller]
7704    pub fn register_replayed_workflow<S, Factory, F, Fut>(
7705        &mut self,
7706        workflow_type: impl Into<String>,
7707        state_factory: Factory,
7708        handler: F,
7709    ) where
7710        S: Clone + Send + Sync + 'static,
7711        Factory: Fn() -> S + Send + Sync + 'static,
7712        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7713        Fut: Future<Output = Result<Value>> + Send + 'static,
7714    {
7715        let workflow_type = workflow_type.into();
7716        if !self.admit_registration::<F>(
7717            RegistrationKind::Workflow,
7718            None,
7719            &workflow_type,
7720            "register_replayed_workflow",
7721        ) {
7722            return;
7723        }
7724        let state_factory = Arc::new(state_factory);
7725        let handler = Arc::new(handler);
7726
7727        let execute_factory = Arc::clone(&state_factory);
7728        let execute_handler = Arc::clone(&handler);
7729        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7730            let state = WorkflowInstance::new(execute_factory());
7731            let handler = Arc::clone(&execute_handler);
7732            Ok(Box::pin(async move {
7733                let result = handler(ctx, input.into_json()?, state).await?;
7734                AvroValue::from_serialize(&result)
7735            }) as WorkflowFuture)
7736        });
7737
7738        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7739            let state = WorkflowInstance::new(state_factory());
7740            let snapshot_state = state.clone();
7741            let snapshot: WorkflowStateSnapshot =
7742                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7743            let replay_handler = Arc::clone(&handler);
7744            let future = async move {
7745                let result = replay_handler(ctx, input.into_json()?, state).await?;
7746                AvroValue::from_serialize(&result)
7747            };
7748            Ok(ReplayedWorkflowInvocation {
7749                future: Box::pin(future),
7750                snapshot,
7751            })
7752        });
7753
7754        self.workflows.insert(
7755            workflow_type,
7756            RegisteredWorkflow {
7757                execute,
7758                replay: Some(replay),
7759                state_type: Some(TypeId::of::<S>()),
7760                definition_fingerprint: None,
7761            },
7762        );
7763    }
7764
7765    /// Register a replayable workflow with one Serde request value and result.
7766    ///
7767    /// Normal task execution and instance-state query replay both decode and
7768    /// encode through the fixed Avro Value codec. The state factory and handler
7769    /// otherwise follow [`Worker::register_replayed_workflow`].
7770    #[track_caller]
7771    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
7772        &mut self,
7773        workflow_type: impl Into<String>,
7774        state_factory: Factory,
7775        handler: F,
7776    ) where
7777        I: DeserializeOwned + Send + 'static,
7778        O: Serialize + Send + 'static,
7779        S: Clone + Send + Sync + 'static,
7780        Factory: Fn() -> S + Send + Sync + 'static,
7781        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7782        Fut: Future<Output = Result<O>> + Send + 'static,
7783    {
7784        let workflow_type = workflow_type.into();
7785        if !self.admit_registration::<F>(
7786            RegistrationKind::Workflow,
7787            None,
7788            &workflow_type,
7789            "register_typed_replayed_workflow",
7790        ) {
7791            return;
7792        }
7793        let state_factory = Arc::new(state_factory);
7794        let handler = Arc::new(handler);
7795
7796        let execute_name = workflow_type.clone();
7797        let execute_factory = Arc::clone(&state_factory);
7798        let execute_handler = Arc::clone(&handler);
7799        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7800            let input = decode_workflow_entry::<I>(input, &execute_name)?;
7801            let state = WorkflowInstance::new(execute_factory());
7802            let handler = Arc::clone(&execute_handler);
7803            let handler_name = execute_name.clone();
7804            Ok(Box::pin(async move {
7805                let result = handler(ctx, input, state).await?;
7806                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7807            }) as WorkflowFuture)
7808        });
7809
7810        let replay_name = workflow_type.clone();
7811        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7812            let input = decode_workflow_entry::<I>(input, &replay_name)?;
7813            let state = WorkflowInstance::new(state_factory());
7814            let snapshot_state = state.clone();
7815            let snapshot: WorkflowStateSnapshot =
7816                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7817            let handler = Arc::clone(&handler);
7818            let handler_name = replay_name.clone();
7819            let future = async move {
7820                let result = handler(ctx, input, state).await?;
7821                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
7822            };
7823            Ok(ReplayedWorkflowInvocation {
7824                future: Box::pin(future),
7825                snapshot,
7826            })
7827        });
7828
7829        self.workflows.insert(
7830            workflow_type,
7831            RegisteredWorkflow {
7832                execute,
7833                replay: Some(replay),
7834                state_type: Some(TypeId::of::<S>()),
7835                definition_fingerprint: None,
7836            },
7837        );
7838    }
7839
7840    /// Declare the signal names consumed by a registered workflow.
7841    ///
7842    /// Call this after registering the workflow and before starting the worker.
7843    /// Names read through `wait_signal` or `signals` need a declaration for
7844    /// Server command admission. Arguments remain arbitrary positional values,
7845    /// including lossless Avro values. This replaces the previous declaration;
7846    /// an empty slice declares no signals. Names are sorted and deduplicated.
7847    /// Existing runs retain the declarations captured when they started.
7848    pub fn declare_workflow_signals(
7849        &mut self,
7850        workflow_type: &str,
7851        signal_names: &[&str],
7852    ) -> Result<()> {
7853        if !self.workflows.contains_key(workflow_type) {
7854            return Err(Error::Codec(format!(
7855                "workflow type {workflow_type:?} is not registered"
7856            )));
7857        }
7858        if signal_names
7859            .iter()
7860            .any(|name| name.is_empty() || *name != name.trim())
7861        {
7862            return Err(Error::Codec(
7863                "signal names must be non-empty and have no surrounding whitespace".into(),
7864            ));
7865        }
7866        let mut names = signal_names
7867            .iter()
7868            .map(|name| (*name).to_string())
7869            .collect::<Vec<_>>();
7870        names.sort();
7871        names.dedup();
7872        self.signals.insert(workflow_type.to_string(), names);
7873        Ok(())
7874    }
7875
7876    /// Bind a registered workflow to compile-time embedded source for safe redrive.
7877    ///
7878    /// Supply `include_str!` values for the workflow body and every helper whose
7879    /// behavior can affect replay. Register the workflow once, then set its
7880    /// identity before starting the worker. Duplicate registrations are invalid. The server
7881    /// rejects reusing a worker ID when its prior fingerprint disappears.
7882    /// Workflows without source identity remain runnable but cannot be safely redriven.
7883    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
7884    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
7885    pub fn set_workflow_definition_sources(
7886        &mut self,
7887        workflow_type: &str,
7888        sources: &[&str],
7889    ) -> Result<()> {
7890        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
7891            return Err(Error::Codec(
7892                "workflow definition sources must be non-empty".to_string(),
7893            ));
7894        }
7895        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
7896            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
7897        })?;
7898        let mut hasher = Sha256::new();
7899        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
7900        hasher.update((workflow_type.len() as u64).to_be_bytes());
7901        hasher.update(workflow_type.as_bytes());
7902        for source in sources {
7903            hasher.update((source.len() as u64).to_be_bytes());
7904            hasher.update(source.as_bytes());
7905        }
7906        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
7907        Ok(())
7908    }
7909
7910    /// Register a replayable workflow on the lossless fixed Avro Value surface.
7911    #[track_caller]
7912    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
7913        &mut self,
7914        workflow_type: impl Into<String>,
7915        state_factory: Factory,
7916        handler: F,
7917    ) where
7918        S: Clone + Send + Sync + 'static,
7919        Factory: Fn() -> S + Send + Sync + 'static,
7920        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
7921        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
7922    {
7923        let workflow_type = workflow_type.into();
7924        if !self.admit_registration::<F>(
7925            RegistrationKind::Workflow,
7926            None,
7927            &workflow_type,
7928            "register_replayed_workflow_avro_value",
7929        ) {
7930            return;
7931        }
7932        let state_factory = Arc::new(state_factory);
7933        let handler = Arc::new(handler);
7934
7935        let execute_factory = Arc::clone(&state_factory);
7936        let execute_handler = Arc::clone(&handler);
7937        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7938            let state = WorkflowInstance::new(execute_factory());
7939            Ok(Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture)
7940        });
7941
7942        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
7943            let state = WorkflowInstance::new(state_factory());
7944            let snapshot_state = state.clone();
7945            let snapshot: WorkflowStateSnapshot =
7946                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
7947            Ok(ReplayedWorkflowInvocation {
7948                future: Box::pin(handler(ctx, input, state)),
7949                snapshot,
7950            })
7951        });
7952
7953        self.workflows.insert(
7954            workflow_type,
7955            RegisteredWorkflow {
7956                execute,
7957                replay: Some(replay),
7958                state_type: Some(TypeId::of::<S>()),
7959                definition_fingerprint: None,
7960            },
7961        );
7962    }
7963
7964    #[track_caller]
7965    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
7966    where
7967        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
7968        Fut: Future<Output = Result<Value>> + Send + 'static,
7969    {
7970        let activity_type = activity_type.into();
7971        if !self.admit_registration::<F>(
7972            RegistrationKind::Activity,
7973            None,
7974            &activity_type,
7975            "register_activity",
7976        ) {
7977            return;
7978        }
7979        let handler = Arc::new(handler);
7980        self.activities.insert(
7981            activity_type,
7982            Arc::new(move |ctx, args| {
7983                let handler = Arc::clone(&handler);
7984                Box::pin(async move {
7985                    let result = handler(ctx, args.into_json()?).await?;
7986                    AvroValue::from_serialize(&result)
7987                })
7988            }),
7989        );
7990    }
7991
7992    /// Register an activity with one Serde request value and a Serde result.
7993    ///
7994    /// Inputs and results use the platform's fixed Avro Value schema. Shape
7995    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
7996    /// with the activity name and Rust type.
7997    #[track_caller]
7998    pub fn register_typed_activity<I, O, F, Fut>(
7999        &mut self,
8000        activity_type: impl Into<String>,
8001        handler: F,
8002    ) where
8003        I: DeserializeOwned + Send + 'static,
8004        O: Serialize + Send + 'static,
8005        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
8006        Fut: Future<Output = Result<O>> + Send + 'static,
8007    {
8008        let activity_type = activity_type.into();
8009        if !self.admit_registration::<F>(
8010            RegistrationKind::Activity,
8011            None,
8012            &activity_type,
8013            "register_typed_activity",
8014        ) {
8015            return;
8016        }
8017        let handler_name = activity_type.clone();
8018        let handler = Arc::new(handler);
8019        self.activities.insert(
8020            activity_type,
8021            Arc::new(move |ctx, input| {
8022                let handler = Arc::clone(&handler);
8023                let handler_name = handler_name.clone();
8024                Box::pin(async move {
8025                    let input =
8026                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
8027                    let result = handler(ctx, input).await?;
8028                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
8029                })
8030            }),
8031        );
8032    }
8033
8034    /// Register an activity on the lossless fixed Avro Value surface.
8035    #[track_caller]
8036    pub fn register_activity_avro_value<F, Fut>(
8037        &mut self,
8038        activity_type: impl Into<String>,
8039        handler: F,
8040    ) where
8041        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
8042        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8043    {
8044        let activity_type = activity_type.into();
8045        if !self.admit_registration::<F>(
8046            RegistrationKind::Activity,
8047            None,
8048            &activity_type,
8049            "register_activity_avro_value",
8050        ) {
8051            return;
8052        }
8053        self.activities.insert(
8054            activity_type,
8055            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
8056        );
8057    }
8058
8059    /// Register a named, read-only query handler for a workflow type.
8060    ///
8061    /// The workflow type must also be registered with [`Worker::register_workflow`]
8062    /// before the worker runs. The handler receives only an immutable committed
8063    /// state snapshot and normalized query arguments.
8064    #[track_caller]
8065    pub fn register_query<F, Fut>(
8066        &mut self,
8067        workflow_type: impl Into<String>,
8068        query_name: impl Into<String>,
8069        handler: F,
8070    ) where
8071        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
8072        Fut: Future<Output = Result<Value>> + Send + 'static,
8073    {
8074        let workflow_type = workflow_type.into();
8075        let query_name = query_name.into();
8076        if !self.admit_registration::<F>(
8077            RegistrationKind::Query,
8078            Some(&workflow_type),
8079            &query_name,
8080            "register_query",
8081        ) {
8082            return;
8083        }
8084        let handler = Arc::new(handler);
8085        self.queries.entry(workflow_type).or_default().insert(
8086            query_name,
8087            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
8088                let handler = Arc::clone(&handler);
8089                Box::pin(async move {
8090                    let result = handler(ctx, args.into_json()?).await?;
8091                    AvroValue::from_serialize(&result)
8092                })
8093            })),
8094        );
8095    }
8096
8097    /// Register a query handler on the lossless fixed Avro Value surface.
8098    #[track_caller]
8099    pub fn register_query_avro_value<F, Fut>(
8100        &mut self,
8101        workflow_type: impl Into<String>,
8102        query_name: impl Into<String>,
8103        handler: F,
8104    ) where
8105        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
8106        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8107    {
8108        let workflow_type = workflow_type.into();
8109        let query_name = query_name.into();
8110        if !self.admit_registration::<F>(
8111            RegistrationKind::Query,
8112            Some(&workflow_type),
8113            &query_name,
8114            "register_query_avro_value",
8115        ) {
8116            return;
8117        }
8118        self.queries.entry(workflow_type).or_default().insert(
8119            query_name,
8120            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
8121        );
8122    }
8123
8124    /// Register a named query against deterministically replayed instance state.
8125    ///
8126    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
8127    /// same state type `S`. The handler receives an immutable, detached state
8128    /// clone, so successful and failed queries cannot affect workflow execution
8129    /// or the state reconstructed by a later query.
8130    #[track_caller]
8131    pub fn register_replayed_query<S, F, Fut>(
8132        &mut self,
8133        workflow_type: impl Into<String>,
8134        query_name: impl Into<String>,
8135        handler: F,
8136    ) where
8137        S: Clone + Send + Sync + 'static,
8138        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
8139        Fut: Future<Output = Result<Value>> + Send + 'static,
8140    {
8141        let workflow_type = workflow_type.into();
8142        let query_name = query_name.into();
8143        if !self.admit_registration::<F>(
8144            RegistrationKind::Query,
8145            Some(&workflow_type),
8146            &query_name,
8147            "register_replayed_query",
8148        ) {
8149            return;
8150        }
8151        let handler = Arc::new(handler);
8152        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
8153            let state = state.downcast::<S>().map_err(|_| {
8154                "registered query state type does not match the replayed workflow state".to_string()
8155            })?;
8156            let handler = Arc::clone(&handler);
8157            Ok(Box::pin(async move {
8158                let result = handler(ctx, state, args.into_json()?).await?;
8159                AvroValue::from_serialize(&result)
8160            }))
8161        });
8162
8163        self.queries.entry(workflow_type).or_default().insert(
8164            query_name,
8165            RegisteredQuery::Replayed {
8166                state_type: TypeId::of::<S>(),
8167                handler: erased_handler,
8168            },
8169        );
8170    }
8171
8172    /// Register a replayed-state query on the lossless fixed Avro Value surface.
8173    #[track_caller]
8174    pub fn register_replayed_query_avro_value<S, F, Fut>(
8175        &mut self,
8176        workflow_type: impl Into<String>,
8177        query_name: impl Into<String>,
8178        handler: F,
8179    ) where
8180        S: Clone + Send + Sync + 'static,
8181        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
8182        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8183    {
8184        let workflow_type = workflow_type.into();
8185        let query_name = query_name.into();
8186        if !self.admit_registration::<F>(
8187            RegistrationKind::Query,
8188            Some(&workflow_type),
8189            &query_name,
8190            "register_replayed_query_avro_value",
8191        ) {
8192            return;
8193        }
8194        let handler = Arc::new(handler);
8195        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
8196            let state = state.downcast::<S>().map_err(|_| {
8197                "registered query state type does not match the replayed workflow state".to_string()
8198            })?;
8199            Ok(Box::pin(handler(ctx, state, args)))
8200        });
8201
8202        self.queries.entry(workflow_type).or_default().insert(
8203            query_name,
8204            RegisteredQuery::Replayed {
8205                state_type: TypeId::of::<S>(),
8206                handler: erased_handler,
8207            },
8208        );
8209    }
8210
8211    /// Register a synchronous workflow update handler.
8212    #[track_caller]
8213    pub fn register_update<F, Fut>(
8214        &mut self,
8215        workflow_type: impl Into<String>,
8216        update_name: impl Into<String>,
8217        handler: F,
8218    ) where
8219        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
8220        Fut: Future<Output = Result<Value>> + Send + 'static,
8221    {
8222        let workflow_type = workflow_type.into();
8223        let update_name = update_name.into();
8224        if !self.admit_registration::<F>(
8225            RegistrationKind::Update,
8226            Some(&workflow_type),
8227            &update_name,
8228            "register_update",
8229        ) {
8230            return;
8231        }
8232        let handler = Arc::new(handler);
8233        self.updates.entry(workflow_type).or_default().insert(
8234            update_name,
8235            Arc::new(move |ctx, args| {
8236                let handler = Arc::clone(&handler);
8237                Box::pin(async move {
8238                    let result = handler(ctx, args.into_json()?).await?;
8239                    AvroValue::from_serialize(&result)
8240                })
8241            }),
8242        );
8243    }
8244
8245    /// Register an update handler on the lossless fixed Avro Value surface.
8246    #[track_caller]
8247    pub fn register_update_avro_value<F, Fut>(
8248        &mut self,
8249        workflow_type: impl Into<String>,
8250        update_name: impl Into<String>,
8251        handler: F,
8252    ) where
8253        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
8254        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8255    {
8256        let workflow_type = workflow_type.into();
8257        let update_name = update_name.into();
8258        if !self.admit_registration::<F>(
8259            RegistrationKind::Update,
8260            Some(&workflow_type),
8261            &update_name,
8262            "register_update_avro_value",
8263        ) {
8264            return;
8265        }
8266        self.updates.entry(workflow_type).or_default().insert(
8267            update_name,
8268            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
8269        );
8270    }
8271
8272    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
8273        self.validate_registration()?;
8274        self.nexus_registration_confirmed
8275            .store(false, Ordering::SeqCst);
8276        self.query_authority_confirmed
8277            .store(false, Ordering::SeqCst);
8278        if self.nexus_cooperative_cancellation_enabled {
8279            let info: Value = self
8280                .client
8281                .request_json(
8282                    reqwest::Method::GET,
8283                    "/cluster/info",
8284                    RequestProtocol::Worker("1.20"),
8285                    Option::<&Value>::None,
8286                )
8287                .await?;
8288            if !nexus::installed_cooperation(&info["worker_protocol"]["server_capabilities"]) {
8289                return Err(Error::CooperativeCancellationUnavailable(
8290                    "nexus_cooperative_cancellation_not_supported: Server must advertise the installed workflow_run bridge".into(),
8291                ));
8292            }
8293        }
8294        if self.require_query_task_authority {
8295            if self.client.worker_protocol_version != WorkerProtocolVersion::V120 {
8296                return Err(Error::WorkerLoop(
8297                    "query authority requires worker protocol 1.20".into(),
8298                ));
8299            }
8300            // Discovery uses the Worker credential, including worker-only Clients.
8301            let discovery: Value = self
8302                .client
8303                .request_json_unresolved_with_timeout::<Value, Value>(
8304                    reqwest::Method::GET,
8305                    "/cluster/info",
8306                    RequestProtocol::Worker("1.20"),
8307                    None,
8308                    Duration::from_secs(5),
8309                )
8310                .await?;
8311            if discovery["worker_protocol"]["server_capabilities"]["query_task_authority"] != true {
8312                return Err(Error::WorkerLoop(
8313                    "runtime does not advertise query_task_authority".into(),
8314                ));
8315            }
8316        }
8317        self.sticky_registration_confirmed
8318            .store(false, Ordering::SeqCst);
8319        self.session_registration_confirmed
8320            .store(false, Ordering::SeqCst);
8321        for capability in &self.resource_capabilities {
8322            worker_session::validate_resource_capability(capability)?;
8323        }
8324        self.local_registration_confirmed
8325            .store(false, Ordering::SeqCst);
8326        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
8327            return Err(Error::CooperativeCancellationUnavailable(
8328                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
8329            ));
8330        }
8331        let mut command_contracts = serde_json::Map::new();
8332        for workflow_type in self.workflows.keys() {
8333            let mut queries = self
8334                .queries
8335                .get(workflow_type)
8336                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
8337                .unwrap_or_default();
8338            queries.sort();
8339            let mut updates = self
8340                .updates
8341                .get(workflow_type)
8342                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
8343                .unwrap_or_default();
8344            updates.sort();
8345            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
8346            command_contracts.insert(
8347                workflow_type.clone(),
8348                json!({
8349                    "queries": queries,
8350                    "query_contracts": argument_vector_contracts(&queries),
8351                    "signals": signals,
8352                    "signal_contracts": argument_vector_contracts(&signals),
8353                    "updates": updates,
8354                    "update_contracts": argument_vector_contracts(&updates),
8355                    "update_validators": [],
8356                }),
8357            );
8358        }
8359
8360        self.cooperative_registration_confirmed
8361            .store(false, Ordering::SeqCst);
8362        #[cfg(feature = "telemetry")]
8363        if self
8364            .telemetry
8365            .as_ref()
8366            .is_some_and(telemetry::ExecutionTelemetry::is_enabled)
8367            && !self
8368                .client
8369                .observability_context_supported
8370                .load(Ordering::SeqCst)
8371        {
8372            // Optional startup discovery is bounded and cached. Its failure
8373            // cannot refuse registration or add retries to a business command.
8374            let _ = self
8375                .client
8376                .request_json_unresolved_with_timeout::<Value, Value>(
8377                    reqwest::Method::GET,
8378                    "/cluster/info",
8379                    RequestProtocol::DefaultWorker,
8380                    None,
8381                    Duration::from_secs(5),
8382                )
8383                .await;
8384        }
8385        let response = self
8386            .client
8387            .register_worker_with_definition_fingerprints(
8388                &self.worker_id,
8389                &self.task_queue,
8390                self.workflows.keys().cloned().collect(),
8391                self.activities.keys().cloned().collect(),
8392                self.max_concurrent_workflow_tasks,
8393                self.max_concurrent_activity_tasks,
8394                [
8395                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
8396                    Some("workflow_entry_arguments_validation".to_string()),
8397                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
8398                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
8399                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
8400                    self.client
8401                        .local_activities_enabled
8402                        .then(|| "local_activities".to_string()),
8403                    self.client
8404                        .worker_sessions_enabled
8405                        .then(|| "worker_sessions".to_string()),
8406                    self.client
8407                        .sticky_cache
8408                        .is_some()
8409                        .then(|| "sticky_execution".to_string()),
8410                    self.cooperative_cancellation_enabled
8411                        .then(|| "cooperative_cancellation".to_string()),
8412                    self.nexus_cooperative_cancellation_enabled
8413                        .then(|| "nexus_cooperative_cancellation".to_string()),
8414                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
8415                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
8416                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
8417                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
8418                ]
8419                .into_iter()
8420                .flatten()
8421                .chain(self.resource_capabilities.iter().cloned())
8422                .collect(),
8423                Value::Object(command_contracts),
8424                Some(
8425                    self.workflows
8426                        .iter()
8427                        .filter_map(|(workflow_type, workflow)| {
8428                            workflow
8429                                .definition_fingerprint
8430                                .as_ref()
8431                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
8432                        })
8433                        .collect(),
8434                ),
8435            )
8436            .await?;
8437        if self.cooperative_cancellation_enabled && response.registered {
8438            self.cooperative_registration_confirmed
8439                .store(true, Ordering::SeqCst);
8440        }
8441        if self.nexus_cooperative_cancellation_enabled && response.registered {
8442            self.nexus_registration_confirmed
8443                .store(true, Ordering::SeqCst);
8444        }
8445        if self.client.local_activities_enabled && response.registered {
8446            self.local_registration_confirmed
8447                .store(true, Ordering::SeqCst);
8448        }
8449        if self.client.worker_sessions_enabled && response.registered {
8450            self.session_registration_confirmed
8451                .store(true, Ordering::SeqCst);
8452        }
8453        if self.client.sticky_cache.is_some() && response.registered {
8454            self.sticky_registration_confirmed
8455                .store(true, Ordering::SeqCst);
8456        }
8457        self.query_authority_confirmed.store(
8458            response.registered
8459                && self.client.worker_protocol_version == WorkerProtocolVersion::V120
8460                && response
8461                    .server_capabilities
8462                    .as_ref()
8463                    .is_some_and(|capabilities| capabilities["query_task_authority"] == true),
8464            Ordering::SeqCst,
8465        );
8466        Ok(response)
8467    }
8468
8469    /// Run until shutdown or a terminal worker error occurs.
8470    ///
8471    /// Empty long-poll expirations do not stop the worker. Retryable poll and
8472    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
8473    /// authentication, protocol, and other non-retryable failures are returned.
8474    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
8475    /// poll and heartbeat outages beyond the ordinary retry budget.
8476    pub async fn run(&self) -> Result<()> {
8477        self.run_until(std::future::pending::<()>()).await
8478    }
8479
8480    /// Run until `shutdown` resolves or a terminal worker error occurs.
8481    ///
8482    /// This has the same liveness and terminal-error contract as [`Worker::run`].
8483    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
8484    where
8485        F: Future<Output = ()>,
8486    {
8487        let _clear_cache_on_drop =
8488            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
8489        let stop = Arc::new(AtomicBool::new(false));
8490        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
8491        let mut worker = self.with_storage_admission(Arc::clone(&stop));
8492        worker.run_stop = Some(Arc::clone(&stop));
8493        let run = worker.run_with_storage_admission(Arc::clone(&stop));
8494        tokio::pin!(run);
8495        tokio::pin!(shutdown);
8496        tokio::select! {
8497            result = &mut run => result,
8498            _ = &mut shutdown => {
8499                stop.store(true, Ordering::SeqCst);
8500                run.await
8501            }
8502        }
8503    }
8504
8505    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
8506        let mut worker = self.clone();
8507        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
8508            policy: self.retry_policy,
8509            stop,
8510            workflow_completion_retry_deadline: None,
8511        });
8512        worker
8513    }
8514
8515    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
8516        let registration = self.register().await?;
8517        if !registration.registered {
8518            return Err(Error::WorkerLoop(format!(
8519                "worker registration for {:?} was not accepted",
8520                self.worker_id
8521            )));
8522        }
8523        let registered_worker_id = registration.worker_id.clone();
8524        let primary = self.run_registered_until(stop, registration).await;
8525        let primary = match (primary, self.close_worker_sessions().await) {
8526            (Ok(()), result) => result,
8527            (Err(error), Ok(())) => Err(error),
8528            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
8529                primary: Box::new(primary),
8530                deregistration: Box::new(close),
8531            }),
8532        };
8533        self.session_registration_confirmed
8534            .store(false, Ordering::SeqCst);
8535        self.cooperative_registration_confirmed
8536            .store(false, Ordering::SeqCst);
8537        self.local_registration_confirmed
8538            .store(false, Ordering::SeqCst);
8539        let deregistration = self
8540            .client
8541            .deregister_worker_registration(&registered_worker_id)
8542            .await;
8543        self.sticky_registration_confirmed
8544            .store(false, Ordering::SeqCst);
8545        self.client.clear_sticky_cache()?;
8546
8547        match (primary, deregistration) {
8548            (Ok(()), Ok(_)) => Ok(()),
8549            (Ok(()), Err(deregistration)) => Err(deregistration),
8550            (Err(primary), Ok(_)) => Err(primary),
8551            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
8552                primary: Box::new(primary),
8553                deregistration: Box::new(deregistration),
8554            }),
8555        }
8556    }
8557
8558    async fn run_registered_until(
8559        &self,
8560        stop: Arc<AtomicBool>,
8561        registration: RegisterWorkerResponse,
8562    ) -> Result<()> {
8563        if self.require_query_task_authority
8564            && !self.query_authority_confirmed.load(Ordering::SeqCst)
8565        {
8566            return Err(Error::WorkerLoop(
8567                "registration did not confirm query_task_authority".into(),
8568            ));
8569        }
8570        let heartbeat_interval = Duration::from_secs(
8571            registration
8572                .heartbeat_interval_seconds
8573                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
8574        );
8575        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
8576        // from the completion of the preceding attempt, including its bounded
8577        // retries. A fixed-epoch interval can leave an already-due tick queued
8578        // while an acknowledgement is slow, producing a catch-up heartbeat as
8579        // soon as that request completes.
8580        let heartbeat = tokio::time::sleep(Duration::ZERO);
8581        tokio::pin!(heartbeat);
8582        // Poll responses may already have leased server-side work by the time
8583        // they become ready, so each poller owns its responses through
8584        // completion or failure instead of racing raw polls in this select.
8585        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
8586            let worker = self.clone();
8587            let stop = Arc::clone(&stop);
8588            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
8589        });
8590        let mut activity_poller = (!self.activities.is_empty()).then(|| {
8591            let worker = self.clone();
8592            let stop = Arc::clone(&stop);
8593            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
8594        });
8595        let mut query_poller = (!self.queries.is_empty()).then(|| {
8596            let worker = self.clone();
8597            let stop = Arc::clone(&stop);
8598            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
8599        });
8600
8601        loop {
8602            tokio::select! {
8603                _ = wait_for_worker_stop(&stop) => {
8604                    stop.store(true, Ordering::SeqCst);
8605                    break;
8606                }
8607                _ = &mut heartbeat => {
8608                    let result = self.retry_worker_operation(|| {
8609                        self.client.heartbeat_worker_with_sessions(
8610                            &self.worker_id,
8611                            self.workflow_capacity.available(),
8612                            self.activity_capacity.available(),
8613                            self.client.worker_sessions_enabled.then(|| self.session_available()),
8614                        )
8615                    }).await;
8616                    heartbeat
8617                        .as_mut()
8618                        .reset(tokio::time::Instant::now() + heartbeat_interval);
8619                    match result {
8620                        Ok(Some(acknowledgement)) => {
8621                            if let Some(observer) = &self.heartbeat_observer {
8622                                observer(&WorkerHeartbeatObservation {
8623                                    worker_id: self.worker_id.clone(),
8624                                    task_queue: self.task_queue.clone(),
8625                                    acknowledged_at_unix_millis: SystemTime::now()
8626                                        .duration_since(UNIX_EPOCH)
8627                                        .unwrap_or_default()
8628                                        .as_millis()
8629                                        .min(u64::MAX as u128)
8630                                        as u64,
8631                                    acknowledgement,
8632                                });
8633                            }
8634                        }
8635                        Ok(None) => break,
8636                        Err(error) => {
8637                            stop.store(true, Ordering::SeqCst);
8638                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
8639                            return Err(error);
8640                        }
8641                    }
8642                }
8643                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
8644                    workflow_poller = None;
8645                    let stopped_by_server = stop.load(Ordering::SeqCst);
8646                    stop.store(true, Ordering::SeqCst);
8647                    let poller_result = optional_poller_result("workflow", result);
8648                    let join_result =
8649                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8650                    poller_result?;
8651                    join_result?;
8652                    if stopped_by_server {
8653                        return Ok(());
8654                    }
8655                    return Err(Error::WorkerLoop(
8656                        "workflow poller stopped unexpectedly".to_string(),
8657                    ));
8658                }
8659                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
8660                    activity_poller = None;
8661                    let stopped_by_server = stop.load(Ordering::SeqCst);
8662                    stop.store(true, Ordering::SeqCst);
8663                    let poller_result = optional_poller_result("activity", result);
8664                    let join_result =
8665                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8666                    poller_result?;
8667                    join_result?;
8668                    if stopped_by_server {
8669                        return Ok(());
8670                    }
8671                    return Err(Error::WorkerLoop(
8672                        "activity poller stopped unexpectedly".to_string(),
8673                    ));
8674                }
8675                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
8676                    query_poller = None;
8677                    let stopped_by_server = stop.load(Ordering::SeqCst);
8678                    stop.store(true, Ordering::SeqCst);
8679                    let poller_result = optional_poller_result("query", result);
8680                    let join_result =
8681                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
8682                    poller_result?;
8683                    join_result?;
8684                    if stopped_by_server {
8685                        return Ok(());
8686                    }
8687                    return Err(Error::WorkerLoop(
8688                        "query poller stopped unexpectedly".to_string(),
8689                    ));
8690                }
8691            }
8692        }
8693
8694        join_pollers(
8695            workflow_poller.take(),
8696            activity_poller.take(),
8697            query_poller.take(),
8698        )
8699        .await
8700    }
8701
8702    /// Poll and settle at most one task from each enabled task family.
8703    ///
8704    /// A workflow may reach its server-enforced run deadline while this worker
8705    /// holds a task. When the completion endpoint authoritatively rejects that
8706    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
8707    /// terminal `run_status=failed`, the workflow tick is considered settled:
8708    /// the late command was not recorded and cannot replace the terminal run.
8709    /// Every other completion rejection remains an error. This worker-level
8710    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
8711    /// only bounds how long a client waits for a result.
8712    ///
8713    /// Direct callers of [`Client::complete_workflow_task`] continue to receive
8714    /// the original [`Error::Http`] status and response body.
8715    pub async fn run_once(&self) -> Result<usize> {
8716        self.validate_registration()?;
8717        if self.client.worker_sessions_enabled {
8718            self.require_session_registration()?;
8719        }
8720        if self.cooperative_cancellation_enabled
8721            && !self
8722                .cooperative_registration_confirmed
8723                .load(Ordering::SeqCst)
8724        {
8725            return Err(Error::CooperativeCancellationUnavailable(
8726                "register this cooperative worker before polling tasks".into(),
8727            ));
8728        }
8729        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
8730        let mut handled = 0;
8731        match worker.poll_workflow_once().await? {
8732            ManagedPollOutcome::Handled => handled += 1,
8733            ManagedPollOutcome::Stop => return Ok(handled),
8734            ManagedPollOutcome::Idle => {}
8735        }
8736        match worker.poll_activity_once().await? {
8737            ManagedPollOutcome::Handled => handled += 1,
8738            ManagedPollOutcome::Stop => return Ok(handled),
8739            ManagedPollOutcome::Idle => {}
8740        }
8741        if !self.queries.is_empty() {
8742            match worker.poll_query_once().await? {
8743                ManagedPollOutcome::Handled => handled += 1,
8744                ManagedPollOutcome::Stop => return Ok(handled),
8745                ManagedPollOutcome::Idle => {}
8746            }
8747        }
8748        Ok(handled)
8749    }
8750
8751    async fn poll_workflow_once_reserved(&self) -> Result<ManagedPollOutcome> {
8752        if self.client.sticky_cache.is_some()
8753            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
8754        {
8755            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
8756        }
8757        if self.client.local_activities_enabled
8758            && !self.local_registration_confirmed.load(Ordering::SeqCst)
8759        {
8760            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
8761        }
8762        if self.cooperative_cancellation_enabled {
8763            return self.poll_cooperative_workflow_once().await;
8764        }
8765        let mut poll_metrics = self.metrics.worker(false, "workflow", &self.task_queue);
8766        let poll_request_id = unique_request_id("rust-workflow-poll");
8767        let response = self
8768            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
8769            .await;
8770        poll_metrics.poll(&response, |value| value.0.outcome());
8771        drop(poll_metrics);
8772        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
8773            return Ok(ManagedPollOutcome::Idle);
8774        };
8775        if response.outcome().should_stop() {
8776            return Ok(ManagedPollOutcome::Stop);
8777        }
8778        let memo_updates_supported =
8779            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
8780        let Some(task) = response.task else {
8781            return Ok(ManagedPollOutcome::Idle);
8782        };
8783
8784        let mut task_metrics = self.metrics.worker(true, "workflow", &self.task_queue);
8785        task_metrics.outcome("failed");
8786        let task_id = task.task_id.clone();
8787        let attempt = task.workflow_task_attempt;
8788        let run_id = task.run_id.clone();
8789        let lease_owner = task
8790            .lease_owner
8791            .clone()
8792            .unwrap_or_else(|| self.worker_id.clone());
8793
8794        let decision = match self.execute_workflow_with_local_activities(task).await {
8795            Ok(Some(decision)) => Ok(decision),
8796            Ok(None) => {
8797                task_metrics.outcome("expired");
8798                return Ok(ManagedPollOutcome::Handled);
8799            }
8800            Err(error) => Err(error),
8801        };
8802        let task_outcome = metrics::workflow_task_outcome(decision.as_ref().ok());
8803        let settled = self
8804            .settle_workflow_task_decision(
8805                &task_id,
8806                &lease_owner,
8807                attempt,
8808                run_id.as_deref(),
8809                decision,
8810                memo_updates_supported,
8811                snapshot,
8812            )
8813            .await;
8814        if settled.is_ok() {
8815            task_metrics.outcome(task_outcome);
8816        }
8817        settled
8818    }
8819
8820    #[allow(clippy::too_many_arguments)]
8821    async fn settle_workflow_task_decision(
8822        &self,
8823        task_id: &str,
8824        lease_owner: &str,
8825        attempt: u64,
8826        run_id: Option<&str>,
8827        decision: Result<WorkflowTaskDecision>,
8828        memo_updates_supported: bool,
8829        snapshot: Option<sticky_worker::StickySnapshot>,
8830    ) -> Result<ManagedPollOutcome> {
8831        match decision {
8832            Ok(decision)
8833                if decision.cancellation_delivery.is_some()
8834                    || decision.cancellation_scope_delivery.is_some()
8835                    || decision.cancellation_scope_opening.is_some() =>
8836            {
8837                return Err(Error::CooperativeCancellationUnavailable(
8838                    "worker cancellation delivery has not been negotiated".into(),
8839                ));
8840            }
8841            Ok(decision)
8842                if commands_use_workflow_memo_updates(&decision.commands)
8843                    && !memo_updates_supported =>
8844            {
8845                self.client
8846                    .fail_workflow_task(
8847                        task_id,
8848                        lease_owner,
8849                        attempt,
8850                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
8851                    )
8852                    .await?;
8853            }
8854            Ok(decision) if decision.commands.is_empty() => {
8855                // A replay can consume a recorded pending durable command
8856                // without producing a new command. The standalone protocol
8857                // acknowledges that state through the typed waiting outcome;
8858                // an empty completion is rejected by servers that require at
8859                // least one executable command.
8860                self.client
8861                    .fail_workflow_task_with_type(
8862                        task_id,
8863                        lease_owner,
8864                        attempt,
8865                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
8866                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
8867                    )
8868                    .await?;
8869            }
8870            Ok(decision) => {
8871                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
8872                let completion = self
8873                    .client
8874                    .complete_workflow_task_with_message_streams(
8875                        task_id,
8876                        lease_owner,
8877                        attempt,
8878                        decision.commands,
8879                        decision.message_stream_cursors,
8880                        decision.message_stream_waits,
8881                        sticky_claim,
8882                    )
8883                    .await;
8884                if let Err(error) = completion {
8885                    self.discard_sticky_snapshot(snapshot.as_ref())?;
8886                    if !workflow_task_completion_is_terminal_timeout(
8887                        &error, task_id, attempt, run_id,
8888                    ) {
8889                        return Err(error);
8890                    }
8891                }
8892            }
8893            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
8894            Err(error) => {
8895                self.discard_sticky_snapshot(snapshot.as_ref())?;
8896                if matches!(
8897                    error,
8898                    Error::HandlerType {
8899                        handler_kind: HandlerKind::Workflow,
8900                        value_kind: HandlerValueKind::Input,
8901                        ..
8902                    }
8903                ) {
8904                    self.client
8905                        .fail_workflow_task_with_failure(
8906                            task_id,
8907                            lease_owner,
8908                            attempt,
8909                            json!({
8910                                "message": error.to_string(),
8911                                "type": "WorkflowEntryArgumentsMismatch",
8912                                "reason": "workflow_entry_arguments_mismatch",
8913                            }),
8914                        )
8915                        .await?;
8916                } else {
8917                    self.client
8918                        .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
8919                        .await?;
8920                }
8921            }
8922        }
8923
8924        Ok(ManagedPollOutcome::Handled)
8925    }
8926
8927    async fn poll_activity_once_reserved(&self) -> Result<ManagedPollOutcome> {
8928        if self.client.worker_sessions_enabled {
8929            self.require_session_registration()?;
8930        }
8931        let mut poll_metrics = self.metrics.worker(false, "activity", &self.task_queue);
8932        let poll_request_id = unique_request_id("rust-activity-poll");
8933        let response = self
8934            .retry_worker_operation(|| {
8935                self.client.poll_activity_task_response_with_request_id(
8936                    &self.worker_id,
8937                    &self.task_queue,
8938                    self.poll_timeout,
8939                    &poll_request_id,
8940                    0,
8941                )
8942            })
8943            .await;
8944        poll_metrics.poll(&response, |value| value.outcome());
8945        drop(poll_metrics);
8946        let response = match response {
8947            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
8948            response => response,
8949        };
8950        let Some(response) = self.settle_worker_poll_response(response).await? else {
8951            return Ok(ManagedPollOutcome::Idle);
8952        };
8953        if response.outcome().should_stop() {
8954            return Ok(ManagedPollOutcome::Stop);
8955        }
8956        let Some(task) = response.task else {
8957            return Ok(ManagedPollOutcome::Idle);
8958        };
8959
8960        self.settle_polled_activity(task).await
8961    }
8962
8963    async fn settle_polled_activity(
8964        &self,
8965        task: worker_session::SessionActivityTask,
8966    ) -> Result<ManagedPollOutcome> {
8967        let mut task_metrics = self.metrics.worker(true, "activity", &self.task_queue);
8968        task_metrics.outcome("failed");
8969        let lease = task.activity_lease.clone();
8970        let mut worker = self.clone();
8971        worker.client = self.client.with_activity_lease_authority(
8972            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
8973        );
8974        let operation = worker.execute_polled_activity(task, &mut task_metrics);
8975        let result = match lease.as_ref() {
8976            Some(lease) => lease.authority.protect(operation).await,
8977            None => operation.await,
8978        };
8979        match result {
8980            Err(Error::ActivityExecutionAbandoned(_)) => {
8981                task_metrics.outcome("expired");
8982                Ok(ManagedPollOutcome::Handled)
8983            }
8984            result => result,
8985        }
8986    }
8987
8988    async fn execute_polled_activity(
8989        &self,
8990        task: worker_session::SessionActivityTask,
8991        task_metrics: &mut metrics::WorkerObservation,
8992    ) -> Result<ManagedPollOutcome> {
8993        if self.cooperative_cancellation_enabled {
8994            return self.settle_cooperative_activity(task, task_metrics).await;
8995        }
8996        let session = self.track_session_task(task.worker_session.as_ref())?;
8997        let invocation = task.invocation(session);
8998        let task = task.task;
8999
9000        let task_id = task.task_id.clone();
9001        let attempt_id = task
9002            .activity_attempt_id
9003            .clone()
9004            .or(task.attempt_id.clone())
9005            .unwrap_or_default();
9006        let lease_owner = task
9007            .lease_owner
9008            .clone()
9009            .unwrap_or_else(|| self.worker_id.clone());
9010        let codec = task.payload_codec.clone();
9011        let result = self.execute_session_activity_task(task, invocation).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        let invocation = worker_session::ActivityInvocation::unknown(task.attempt_number);
9980        self.execute_session_activity_task(task, invocation).await
9981    }
9982
9983    async fn execute_session_activity_task(
9984        &self,
9985        task: ActivityTask,
9986        invocation: worker_session::ActivityInvocation,
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, invocation),
10001                )
10002                .await;
10003        }
10004        self.execute_session_activity_task_inner(task, invocation)
10005            .await
10006    }
10007
10008    async fn execute_session_activity_task_inner(
10009        &self,
10010        task: ActivityTask,
10011        invocation: worker_session::ActivityInvocation,
10012    ) -> Result<AvroValue> {
10013        let worker_session::ActivityInvocation {
10014            worker_session,
10015            hydration_claim,
10016            retry_info,
10017        } = invocation;
10018        validate_activity_task_payloads(&task)?;
10019        if worker_session.is_some() {
10020            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
10021                || task
10022                    .activity_attempt_id
10023                    .as_deref()
10024                    .or(task.attempt_id.as_deref())
10025                    .is_none_or(str::is_empty)
10026                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
10027            {
10028                return Err(Error::ActivityExecutionAbandoned(
10029                    "session activity requires this worker's exact immutable claim".into(),
10030                ));
10031            }
10032        }
10033
10034        let handler = self
10035            .activities
10036            .get(&task.activity_type)
10037            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
10038        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
10039        let attempt_id = task
10040            .activity_attempt_id
10041            .clone()
10042            .or(task.attempt_id.clone())
10043            .unwrap_or_default();
10044        let lease_owner = task
10045            .lease_owner
10046            .clone()
10047            .unwrap_or_else(|| self.worker_id.clone());
10048        let session = worker_session.clone();
10049        if let Some(claim) = &hydration_claim {
10050            claim.confirm(&self.client).await?;
10051        }
10052        #[cfg(feature = "telemetry")]
10053        let observations = self.activity_observations(&task);
10054        #[cfg(feature = "telemetry")]
10055        let fields = self.activity_telemetry_fields(&task);
10056        let ctx = ActivityContext {
10057            client: self.client.clone(),
10058            task_id: task.task_id,
10059            activity_attempt_id: attempt_id,
10060            lease_owner,
10061            activity_type: task.activity_type,
10062            attempt_number: task.attempt_number,
10063            retry_info,
10064            activity_execution_id: task.activity_execution_id,
10065            workflow_id: task.workflow_id,
10066            run_id: task.run_id,
10067            task_queue: self.task_queue.clone(),
10068            worker_id: self.worker_id.clone(),
10069            claim_guard: None,
10070            local_heartbeats: None,
10071            worker_session,
10072        };
10073
10074        let operation = async {
10075            let callback = self.activity_callback(handler, ctx, args, false);
10076            if let Some(session) = session {
10077                tokio::select! {
10078                    biased;
10079                    _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
10080                    result = callback => if session.active() { result } else {
10081                        Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
10082                    },
10083                }
10084            } else {
10085                callback.await
10086            }
10087        };
10088        #[cfg(feature = "telemetry")]
10089        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
10090            self.client
10091                .observability_context_supported
10092                .load(Ordering::SeqCst)
10093        }) {
10094            return telemetry
10095                .run_observed(
10096                    "durable.activity.task",
10097                    fields,
10098                    false,
10099                    observations,
10100                    operation,
10101                )
10102                .await;
10103        }
10104        operation.await
10105    }
10106
10107    fn activity_callback(
10108        &self,
10109        handler: &ActivityHandler,
10110        context: ActivityContext,
10111        args: AvroValue,
10112        local: bool,
10113    ) -> ActivityFuture {
10114        #[cfg(feature = "telemetry")]
10115        if let Some(telemetry) = &self.telemetry {
10116            let telemetry = telemetry.clone();
10117            let fields = self.callback_telemetry_fields(&context, local);
10118            let handler = handler.clone();
10119            let name = if local {
10120                "durable.local_activity.attempt"
10121            } else {
10122                "durable.activity.attempt"
10123            };
10124            return Box::pin(async move {
10125                telemetry
10126                    .run(
10127                        name,
10128                        fields,
10129                        true,
10130                        async move { handler(context, args).await },
10131                    )
10132                    .await
10133            });
10134        }
10135        #[cfg(not(feature = "telemetry"))]
10136        let _ = local;
10137        handler(context, args)
10138    }
10139}
10140
10141fn poller_result(
10142    kind: &str,
10143    result: std::result::Result<Result<()>, tokio::task::JoinError>,
10144) -> Result<()> {
10145    match result {
10146        Ok(result) => result,
10147        Err(error) => Err(Error::WorkerLoop(format!(
10148            "{kind} poller join error: {error}"
10149        ))),
10150    }
10151}
10152
10153fn optional_poller_result(
10154    kind: &str,
10155    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
10156) -> Result<()> {
10157    match result {
10158        Some(result) => poller_result(kind, result),
10159        None => Ok(()),
10160    }
10161}
10162
10163async fn join_pollers(
10164    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10165    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10166    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10167) -> Result<()> {
10168    let mut first_error = None;
10169
10170    if let Some(handle) = workflow_poller {
10171        if let Err(error) = poller_result("workflow", handle.await) {
10172            first_error.get_or_insert(error);
10173        }
10174    }
10175
10176    if let Some(handle) = activity_poller {
10177        if let Err(error) = poller_result("activity", handle.await) {
10178            first_error.get_or_insert(error);
10179        }
10180    }
10181
10182    if let Some(handle) = query_poller {
10183        if let Err(error) = poller_result("query", handle.await) {
10184            first_error.get_or_insert(error);
10185        }
10186    }
10187
10188    if let Some(error) = first_error {
10189        Err(error)
10190    } else {
10191        Ok(())
10192    }
10193}
10194
10195fn default_worker_id() -> String {
10196    let millis = SystemTime::now()
10197        .duration_since(UNIX_EPOCH)
10198        .unwrap_or_default()
10199        .as_millis();
10200    format!("rust-worker-{}-{millis}", std::process::id())
10201}
10202
10203fn percent_encode_path_segment(segment: &str) -> String {
10204    const HEX: &[u8; 16] = b"0123456789ABCDEF";
10205    let mut encoded = String::with_capacity(segment.len());
10206
10207    for byte in segment.bytes() {
10208        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
10209            encoded.push(char::from(byte));
10210        } else {
10211            encoded.push('%');
10212            encoded.push(char::from(HEX[(byte >> 4) as usize]));
10213            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
10214        }
10215    }
10216
10217    encoded
10218}
10219
10220fn unique_request_id(prefix: &str) -> String {
10221    let nanos = SystemTime::now()
10222        .duration_since(UNIX_EPOCH)
10223        .unwrap_or_default()
10224        .as_nanos();
10225    format!("{prefix}-{}-{nanos}", std::process::id())
10226}
10227
10228#[derive(Debug)]
10229struct QueryTaskExecutionFailure {
10230    reason: String,
10231    message: String,
10232    failure_type: String,
10233}
10234
10235impl QueryTaskExecutionFailure {
10236    fn new(
10237        reason: impl Into<String>,
10238        message: impl Into<String>,
10239        failure_type: impl Into<String>,
10240    ) -> Self {
10241        Self {
10242            reason: reason.into(),
10243            message: message.into(),
10244            failure_type: failure_type.into(),
10245        }
10246    }
10247}
10248
10249/// Typed local state owned by one deterministic workflow invocation.
10250///
10251/// Use [`WorkflowInstance::update`] for the same state transitions during
10252/// ordinary execution and replay. A replayed query receives a detached
10253/// immutable `Arc<S>` rather than this mutation-capable handle.
10254#[derive(Clone, Debug)]
10255pub struct WorkflowInstance<S> {
10256    state: Arc<Mutex<S>>,
10257}
10258
10259impl<S> WorkflowInstance<S> {
10260    fn new(state: S) -> Self {
10261        Self {
10262            state: Arc::new(Mutex::new(state)),
10263        }
10264    }
10265
10266    /// Read the current workflow-instance state without changing it.
10267    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
10268        let state = self
10269            .state
10270            .lock()
10271            .map_err(|_| Error::WorkflowStatePoisoned)?;
10272        Ok(reader(&state))
10273    }
10274
10275    /// Apply one deterministic workflow-instance state transition.
10276    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
10277        let mut state = self
10278            .state
10279            .lock()
10280            .map_err(|_| Error::WorkflowStatePoisoned)?;
10281        Ok(transition(&mut state))
10282    }
10283}
10284
10285impl<S: Clone> WorkflowInstance<S> {
10286    fn snapshot(&self) -> Result<S> {
10287        self.read(Clone::clone)
10288    }
10289}
10290
10291#[derive(Clone, Debug, PartialEq)]
10292pub struct MessageStreamMessage {
10293    pub stream_name: String,
10294    pub message_id: String,
10295    pub position: u64,
10296    pub arguments: Vec<AvroValue>,
10297}
10298
10299#[derive(Clone, Debug)]
10300pub struct MessageStream {
10301    ctx: WorkflowContext,
10302    name: String,
10303}
10304
10305impl MessageStream {
10306    /// Wait for one message, then return a bounded currently-available batch.
10307    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
10308        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
10309            return Err(Error::Codec(format!(
10310                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
10311            )));
10312        }
10313        loop {
10314            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
10315                return Ok(batch);
10316            }
10317
10318            self.ctx.record_message_stream_wait(&self.name)?;
10319            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
10320            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
10321            self.ctx.buffer_message_stream_delivery(arguments)?;
10322            if let Some(sequence) = replay_wait_sequence {
10323                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
10324            }
10325        }
10326    }
10327
10328    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
10329        self.receive(1)
10330            .await?
10331            .into_iter()
10332            .next()
10333            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
10334    }
10335}
10336
10337#[derive(Clone, Debug)]
10338pub struct WorkflowContext {
10339    state: Arc<Mutex<WorkflowState>>,
10340    cancellation_scope_id: String,
10341}
10342
10343fn valid_memo_key(key: &str) -> bool {
10344    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
10345
10346    !key.is_empty()
10347        && key.len() <= 64
10348        && (numeric_candidate.is_empty()
10349            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
10350        && key
10351            .bytes()
10352            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
10353}
10354
10355fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
10356    BASE64
10357        .decode(encode_avro_value(value)?.blob)
10358        .map(|bytes| bytes.len())
10359        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
10360}
10361
10362fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
10363    let AvroValue::Map(entries) = value else {
10364        return Err(Error::InvalidMemoUpdate(
10365            "entries must serialize to an Avro string-keyed map".to_string(),
10366        ));
10367    };
10368    if require_entries && entries.is_empty() {
10369        return Err(Error::InvalidMemoUpdate(
10370            "at least one entry is required".to_string(),
10371        ));
10372    }
10373    if entries.len() > MAX_MEMO_ENTRIES {
10374        return Err(Error::InvalidMemoUpdate(format!(
10375            "at most {MAX_MEMO_ENTRIES} entries are allowed"
10376        )));
10377    }
10378
10379    for (key, value) in &entries {
10380        if !valid_memo_key(&key) {
10381            return Err(Error::InvalidMemoUpdate(
10382                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
10383            ));
10384        }
10385        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
10386            return Err(Error::InvalidMemoUpdate(format!(
10387                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
10388            )));
10389        }
10390    }
10391
10392    let value = AvroValue::Map(entries);
10393    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
10394        return Err(Error::InvalidMemoUpdate(format!(
10395            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
10396        )));
10397    }
10398    Ok(value)
10399}
10400
10401fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
10402    let object = envelope.as_object().ok_or_else(|| {
10403        Error::InvalidMemoUpdate(
10404            "history field must use the public {codec, blob} payload envelope".to_string(),
10405        )
10406    })?;
10407    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
10408        return Err(Error::InvalidMemoUpdate(
10409            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
10410        ));
10411    }
10412
10413    canonical_memo_entries(
10414        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
10415        require_entries,
10416    )
10417}
10418
10419impl WorkflowContext {
10420    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
10421        let name = name.into();
10422        if name.is_empty()
10423            || name.len() > 128
10424            || !name.bytes().all(|byte| {
10425                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
10426            })
10427        {
10428            return Err(Error::Codec(
10429                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
10430                    .to_string(),
10431            ));
10432        }
10433        Ok(MessageStream {
10434            ctx: self.clone(),
10435            name,
10436        })
10437    }
10438
10439    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
10440        let mut state = self
10441            .state
10442            .lock()
10443            .map_err(|_| Error::WorkflowStatePoisoned)?;
10444        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
10445        state
10446            .message_stream_waits
10447            .insert(name.to_string(), position);
10448        Ok(())
10449    }
10450
10451    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
10452        let mut state = self
10453            .state
10454            .lock()
10455            .map_err(|_| Error::WorkflowStatePoisoned)?;
10456        let cursor = state
10457            .message_stream_cursors
10458            .get(&message.stream_name)
10459            .copied()
10460            .unwrap_or(0);
10461        if message.position <= cursor {
10462            return Ok(());
10463        }
10464        let pending = state
10465            .message_stream_messages
10466            .entry(message.stream_name.clone())
10467            .or_default();
10468        if pending.iter().any(|candidate| {
10469            candidate.position == message.position || candidate.message_id == message.message_id
10470        }) {
10471            return Ok(());
10472        }
10473        pending.push(message);
10474        pending.sort_by_key(|candidate| candidate.position);
10475        Ok(())
10476    }
10477
10478    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
10479        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
10480            match delivery {
10481                MessageStreamDelivery::Message(message) => {
10482                    let stream_name = message.stream_name.clone();
10483                    self.buffer_message_stream(message)?;
10484                    return Ok(Some(stream_name));
10485                }
10486                MessageStreamDelivery::Cursor {
10487                    stream_name,
10488                    through_position,
10489                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
10490            }
10491        }
10492        Ok(None)
10493    }
10494
10495    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
10496        let state = self
10497            .state
10498            .lock()
10499            .map_err(|_| Error::WorkflowStatePoisoned)?;
10500        Ok(match state.recorded_commands.get(state.command_cursor) {
10501            Some(RecordedCommand::SignalWait {
10502                sequence,
10503                signal_name,
10504                ..
10505            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
10506            _ => None,
10507        })
10508    }
10509
10510    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
10511        let (history, payload_codec) = {
10512            let state = self
10513                .state
10514                .lock()
10515                .map_err(|_| Error::WorkflowStatePoisoned)?;
10516            (
10517                Arc::clone(&state.history_events),
10518                state.payload_codec.clone(),
10519            )
10520        };
10521
10522        let Some(opened_index) = history.iter().position(|event| {
10523            event.event_type == "SignalWaitOpened"
10524                && durable_event_sequence(event) == Some(wait_sequence)
10525                && event.payload.get("signal_name").and_then(Value::as_str)
10526                    == Some(MESSAGE_STREAM_SIGNAL)
10527        }) else {
10528            return Ok(());
10529        };
10530        let boundary_index = history
10531            .iter()
10532            .enumerate()
10533            .skip(opened_index + 1)
10534            .find_map(|(index, event)| {
10535                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
10536                    && is_authored_command_open_event(event))
10537                .then_some(index)
10538            })
10539            .unwrap_or(history.len());
10540
10541        for event in history[opened_index + 1..boundary_index]
10542            .iter()
10543            .filter(|event| {
10544                event.event_type == "SignalReceived"
10545                    && event.payload.get("signal_name").and_then(Value::as_str)
10546                        == Some(MESSAGE_STREAM_SIGNAL)
10547            })
10548        {
10549            let arguments = decode_signal_event_arguments(event, &payload_codec)?
10550                .into_iter()
10551                .map(AvroValue::into_json)
10552                .collect::<Result<Vec<_>>>()?;
10553            self.buffer_message_stream_delivery(arguments)?;
10554        }
10555        Ok(())
10556    }
10557
10558    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
10559        let mut state = self
10560            .state
10561            .lock()
10562            .map_err(|_| Error::WorkflowStatePoisoned)?;
10563        let cursor = state
10564            .message_stream_cursors
10565            .entry(name.to_string())
10566            .or_default();
10567        *cursor = (*cursor).max(through_position);
10568        if let Some(pending) = state.message_stream_messages.get_mut(name) {
10569            pending.retain(|message| message.position > through_position);
10570        }
10571        Ok(())
10572    }
10573
10574    fn take_message_stream_batch(
10575        &self,
10576        name: &str,
10577        max_items: usize,
10578    ) -> Result<Option<Vec<MessageStreamMessage>>> {
10579        let mut state = self
10580            .state
10581            .lock()
10582            .map_err(|_| Error::WorkflowStatePoisoned)?;
10583        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
10584        let pending = state
10585            .message_stream_messages
10586            .entry(name.to_string())
10587            .or_default();
10588        let count = contiguous_message_stream_count(pending, cursor, max_items);
10589        if count == 0 {
10590            return Ok(None);
10591        }
10592        let batch = pending.drain(..count).collect::<Vec<_>>();
10593        let position = batch.last().map(|message| message.position).unwrap_or(0);
10594        state
10595            .message_stream_cursors
10596            .insert(name.to_string(), position);
10597        state.message_stream_waits.remove(name);
10598        Ok(Some(batch))
10599    }
10600
10601    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
10602        let state = self
10603            .state
10604            .lock()
10605            .map_err(|_| Error::WorkflowStatePoisoned)?;
10606        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
10607        cursors.sort_by_key(|(name, _)| *name);
10608        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
10609        waits.sort_by_key(|(name, _)| *name);
10610        Ok((
10611            cursors
10612                .into_iter()
10613                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
10614                .collect(),
10615            waits
10616                .into_iter()
10617                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
10618                .collect(),
10619        ))
10620    }
10621    /// Identity of the parent workflow currently being replayed.
10622    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
10623        let state = self
10624            .state
10625            .lock()
10626            .map_err(|_| Error::WorkflowStatePoisoned)?;
10627        Ok(WorkflowIdentity {
10628            workflow_id: state.workflow_id.clone(),
10629            run_id: state.run_id.clone(),
10630        })
10631    }
10632
10633    /// Return the server-published history budget for this workflow task.
10634    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
10635        let state = self
10636            .state
10637            .lock()
10638            .map_err(|_| Error::WorkflowStatePoisoned)?;
10639        Ok(state.history_budget.clone())
10640    }
10641
10642    /// Continue this workflow instance as a fresh run with replacement arguments.
10643    ///
10644    /// Return this value directly from the workflow handler. The worker converts
10645    /// it to the terminal protocol command only after replay has consumed every
10646    /// recorded durable command.
10647    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
10648        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
10649    }
10650
10651    /// Continue as new with optional workflow-type and task-queue overrides.
10652    pub fn continue_as_new_with_options<T: Serialize>(
10653        &self,
10654        options: ContinueAsNewOptions,
10655        args: T,
10656    ) -> Result<Value> {
10657        options.validate()?;
10658        Err(Error::ContinueAsNew(ContinueAsNewRequest {
10659            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
10660            options,
10661        }))
10662    }
10663
10664    pub fn activity<T: Serialize>(
10665        &self,
10666        activity_type: impl Into<String>,
10667        args: T,
10668    ) -> ActivityCall {
10669        self.activity_with_options(activity_type, ActivityOptions::new(), args)
10670    }
10671
10672    pub fn activity_on_queue<T, Q>(
10673        &self,
10674        activity_type: impl Into<String>,
10675        task_queue: Option<Q>,
10676        args: T,
10677    ) -> ActivityCall
10678    where
10679        T: Serialize,
10680        Q: Into<String>,
10681    {
10682        let mut options = ActivityOptions::new();
10683        options.task_queue = task_queue.map(Into::into);
10684        self.activity_with_options(activity_type, options, args)
10685    }
10686
10687    /// Schedule one durable activity with retry, routing, and timeout options.
10688    ///
10689    /// Options are validated before the command is emitted. Once the command is
10690    /// recorded, replay consumes the same activity lifecycle at this command
10691    /// position and never emits a duplicate schedule.
10692    ///
10693    /// ```no_run
10694    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
10695    /// # use std::time::Duration;
10696    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
10697    /// let result = ctx
10698    ///     .activity_with_options(
10699    ///         "charge-card",
10700    ///         ActivityOptions::new()
10701    ///             .task_queue("payments")
10702    ///             .retry_policy(
10703    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
10704    ///                     Duration::from_secs(1),
10705    ///                     2,
10706    ///                     Some(Duration::from_secs(30)),
10707    ///                 ),
10708    ///             )
10709    ///             .start_to_close_timeout(Duration::from_secs(60))
10710    ///             .schedule_to_close_timeout(Duration::from_secs(180))
10711    ///             .heartbeat_timeout(Duration::from_secs(15)),
10712    ///         json!([{"order_id": "order-42"}]),
10713    ///     )
10714    ///     .await;
10715    /// match result {
10716    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
10717    ///         "reason": failure.reason,
10718    ///         "timeout_kind": failure.timeout_kind,
10719    ///     })),
10720    ///     other => other,
10721    /// }
10722    /// # }
10723    /// ```
10724    pub fn activity_with_options<T: Serialize>(
10725        &self,
10726        activity_type: impl Into<String>,
10727        options: ActivityOptions,
10728        args: T,
10729    ) -> ActivityCall {
10730        ActivityCall {
10731            ctx: self.clone(),
10732            activity_type: activity_type.into(),
10733            options,
10734            worker_session: None,
10735            args: Some(AvroValue::from_serialize(&args)),
10736            scheduled: false,
10737            local: false,
10738            local_result: None,
10739            parallel_group_path: Vec::new(),
10740        }
10741    }
10742
10743    pub async fn activity_avro_value<T: Serialize>(
10744        &self,
10745        activity_type: impl Into<String>,
10746        args: T,
10747    ) -> Result<AvroValue> {
10748        let mut call = self.activity(activity_type, args);
10749        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10750    }
10751
10752    pub async fn activity_avro_value_with_options<T: Serialize>(
10753        &self,
10754        activity_type: impl Into<String>,
10755        options: ActivityOptions,
10756        args: T,
10757    ) -> Result<AvroValue> {
10758        let mut call = self.activity_with_options(activity_type, options, args);
10759        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10760    }
10761
10762    /// Schedule an activity with a Serde request and decode its Serde result.
10763    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
10764    where
10765        I: Serialize,
10766        O: DeserializeOwned,
10767    {
10768        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
10769            .await
10770    }
10771
10772    /// Schedule an activity with options and decode its result into `O`.
10773    ///
10774    /// Both directions use the fixed Avro Value codec. In particular, this
10775    /// method does not deserialize the JSON-safe inspection projection returned
10776    /// by the dynamic [`ActivityCall`] future.
10777    pub async fn activity_typed_with_options<I, O>(
10778        &self,
10779        activity_type: impl Into<String>,
10780        options: ActivityOptions,
10781        args: I,
10782    ) -> Result<O>
10783    where
10784        I: Serialize,
10785        O: DeserializeOwned,
10786    {
10787        let activity_type = activity_type.into();
10788        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
10789            handler_type_error::<I>(
10790                HandlerKind::Activity,
10791                &activity_type,
10792                HandlerValueKind::Input,
10793                error.to_string(),
10794            )
10795        });
10796        let mut call = ActivityCall {
10797            ctx: self.clone(),
10798            activity_type: activity_type.clone(),
10799            options,
10800            worker_session: None,
10801            args: Some(encoded),
10802            scheduled: false,
10803            local: false,
10804            local_result: None,
10805            parallel_group_path: Vec::new(),
10806        };
10807        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
10808        decode_handler_result(result, HandlerKind::Activity, &activity_type)
10809    }
10810
10811    /// Schedule and join a deterministic activity/child/timer group.
10812    ///
10813    /// Nested groups retain their input shape. Every durable leaf is scheduled
10814    /// before this future yields, results are assembled by declaration order,
10815    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
10816    /// declaration path, stable group metadata, and completed siblings.
10817    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10818        ParallelCall::new(self.clone(), operations)
10819    }
10820
10821    /// Alias for [`WorkflowContext::parallel`].
10822    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10823        self.parallel(operations)
10824    }
10825
10826    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
10827    pub async fn parallel_avro_value(
10828        &self,
10829        operations: Vec<ParallelOperation>,
10830    ) -> Result<Vec<ParallelAvroResult>> {
10831        let mut call = self.parallel(operations);
10832        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10833    }
10834
10835    /// Start every durable operation and resume from the one winner persisted
10836    /// by Server. Non-winning operations continue and remain addressable.
10837    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
10838        let operations = operations
10839            .into_iter()
10840            .enumerate()
10841            .map(|(index, operation)| (SelectionKey::Index(index), operation))
10842            .collect();
10843        SelectCall::new(self.clone(), operations)
10844    }
10845
10846    /// Named-key variant of [`WorkflowContext::select`].
10847    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
10848    where
10849        K: Into<SelectionKey>,
10850    {
10851        SelectCall::new(
10852            self.clone(),
10853            operations
10854                .into_iter()
10855                .map(|(key, operation)| (key.into(), operation))
10856                .collect(),
10857        )
10858    }
10859
10860    /// Create a workflow-local deterministic compensation registry.
10861    pub fn saga(&self) -> Saga {
10862        Saga::new(self.clone())
10863    }
10864
10865    /// Whether cancellation has reached this replay's authored boundary.
10866    ///
10867    /// Server's current `/cancel` route is terminal and does not set this flag.
10868    /// A canonical service request remains pending until its committed delivery
10869    /// is consumed. Request observation alone does not authorize an exception.
10870    pub fn is_cancellation_requested(&self) -> Result<bool> {
10871        let state = self
10872            .state
10873            .lock()
10874            .map_err(|_| Error::WorkflowStatePoisoned)?;
10875        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10876            return Ok(state
10877                .scope_delivery
10878                .as_ref()
10879                .unwrap()
10880                .contexts
10881                .contains_key(&self.cancellation_scope_id));
10882        }
10883        Ok(state.cancel_requested
10884            || state
10885                .scope_delivery
10886                .as_ref()
10887                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
10888    }
10889
10890    /// Raise a typed cooperative cancellation at an author-controlled point.
10891    ///
10892    /// Passing this result to [`Saga::finish`] compensates already registered
10893    /// forward steps before the cancellation remains the initiating outcome.
10894    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
10895        let mut state = self
10896            .state
10897            .lock()
10898            .map_err(|_| Error::WorkflowStatePoisoned)?;
10899        if state.cancellation_shield_depth == 0 {
10900            if let Some(replay) = &state.scope_delivery {
10901                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
10902                    let delivered = replay
10903                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
10904                        .ok_or_else(|| {
10905                            Error::InvalidCooperativeCancellation(
10906                                "scoped request lacks its consumed original delivery".into(),
10907                            )
10908                        })?;
10909                    return Err(Error::CancellationScopeRequested(
10910                        CancellationScopeRequested {
10911                            context: context
10912                                .clone()
10913                                .with_replay(Some(Arc::downgrade(&self.state))),
10914                            delivery: delivered.boundary.clone(),
10915                        },
10916                    ));
10917                }
10918            }
10919        }
10920        if state.cancel_requested && state.cancellation_shield_depth == 0 {
10921            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10922                return Ok(());
10923            }
10924            return Err(state.cancellation_error());
10925        }
10926        Ok(())
10927    }
10928
10929    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10930        SignalCall {
10931            ctx: self.clone(),
10932            signal_name: signal_name.into(),
10933            runtime_reserved_allowed: false,
10934            opened_wait: false,
10935            matched_pending: false,
10936            parallel_group_path: Vec::new(),
10937        }
10938    }
10939
10940    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10941        SignalCall {
10942            ctx: self.clone(),
10943            signal_name: signal_name.into(),
10944            runtime_reserved_allowed: true,
10945            opened_wait: false,
10946            matched_pending: false,
10947            parallel_group_path: Vec::new(),
10948        }
10949    }
10950
10951    pub async fn wait_signal_avro_value(
10952        &self,
10953        signal_name: impl Into<String>,
10954    ) -> Result<Vec<AvroValue>> {
10955        let mut call = self.wait_signal(signal_name);
10956        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10957    }
10958
10959    /// Return every committed signal argument list with the given name.
10960    ///
10961    /// This history-backed view is deterministic and is intended for
10962    /// condition predicates that must be re-evaluated after a signal while the
10963    /// workflow is blocked on [`WorkflowContext::wait_condition`].
10964    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
10965        self.signals_avro_value(signal_name)?
10966            .into_iter()
10967            .map(|arguments| {
10968                arguments
10969                    .into_iter()
10970                    .map(AvroValue::into_json)
10971                    .collect::<Result<Vec<_>>>()
10972            })
10973            .collect()
10974    }
10975
10976    /// Lossless fixed Avro Value view of committed signals with the given name.
10977    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10978        let state = self
10979            .state
10980            .lock()
10981            .map_err(|_| Error::WorkflowStatePoisoned)?;
10982        state
10983            .history_events
10984            .iter()
10985            .filter(|event| {
10986                event.event_type == "SignalReceived"
10987                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
10988            })
10989            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
10990            .collect()
10991    }
10992
10993    /// Return every committed update argument list with the given name.
10994    ///
10995    /// Accepted and applied records for the same update ID are de-duplicated.
10996    /// A Server task created after an update therefore replays the workflow and
10997    /// re-evaluates an open condition without application polling.
10998    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
10999        self.updates_avro_value(update_name)?
11000            .into_iter()
11001            .map(|arguments| {
11002                arguments
11003                    .into_iter()
11004                    .map(AvroValue::into_json)
11005                    .collect::<Result<Vec<_>>>()
11006            })
11007            .collect()
11008    }
11009
11010    /// Lossless fixed Avro Value view of committed updates with the given name.
11011    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
11012        let state = self
11013            .state
11014            .lock()
11015            .map_err(|_| Error::WorkflowStatePoisoned)?;
11016        let mut seen = Vec::new();
11017        let mut updates = Vec::new();
11018        for event in state.history_events.iter() {
11019            if !matches!(
11020                event.event_type.as_str(),
11021                "UpdateAccepted" | "UpdateApplied"
11022            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
11023                || event.payload.get("arguments").is_none()
11024            {
11025                continue;
11026            }
11027            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
11028                if seen.iter().any(|recorded| recorded == update_id) {
11029                    continue;
11030                }
11031                seen.push(update_id.to_string());
11032            }
11033            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
11034        }
11035        Ok(updates)
11036    }
11037
11038    /// Wait for a deterministic predicate to become true or for its durable
11039    /// timeout to elapse.
11040    ///
11041    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
11042    /// predicate tokens automatically change the recorded definition
11043    /// fingerprint. Direct callers must provide an equally stable identity in
11044    /// [`ConditionWaitOptions`].
11045    pub fn wait_condition<F>(
11046        &self,
11047        options: ConditionWaitOptions,
11048        predicate: F,
11049    ) -> ConditionWaitCall
11050    where
11051        F: Fn() -> Result<bool> + Send + 'static,
11052    {
11053        ConditionWaitCall {
11054            ctx: self.clone(),
11055            options,
11056            predicate: Box::new(predicate),
11057            occurrence_id: None,
11058            opened_wait: false,
11059            parallel_group_path: Vec::new(),
11060        }
11061    }
11062
11063    /// Wait for server-backed durable time without blocking the worker executor.
11064    ///
11065    /// Polling this future emits one `start_timer` command and yields. The
11066    /// server records the deadline, so neither worker nor server restarts reset
11067    /// the wait. Replay resolves the future only from a `TimerScheduled` and
11068    /// `TimerFired` pair at the same position in the shared durable-command
11069    /// stream, with matching sequence, timer identity, and delay. Sub-second
11070    /// durations round up because protocol deadlines use whole seconds.
11071    ///
11072    /// ```no_run
11073    /// # use durable_workflow::{json, Client, Worker};
11074    /// # use std::time::Duration;
11075    /// # fn configure(client: Client) {
11076    /// let mut worker = Worker::new(client, "rust-workers");
11077    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
11078    ///     ctx.sleep(Duration::from_secs(5)).await?;
11079    ///     Ok(json!({"status": "timer fired"}))
11080    /// });
11081    /// # }
11082    /// ```
11083    pub fn sleep(&self, duration: Duration) -> TimerCall {
11084        let delay_seconds = duration
11085            .as_secs()
11086            .checked_add(u64::from(duration.subsec_nanos() > 0));
11087        TimerCall {
11088            ctx: self.clone(),
11089            delay_seconds,
11090            scheduled: false,
11091            matched_pending: false,
11092            parallel_group_path: Vec::new(),
11093        }
11094    }
11095
11096    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
11097    pub fn start_timer(&self, duration: Duration) -> TimerCall {
11098        self.sleep(duration)
11099    }
11100
11101    /// Evaluate a non-deterministic callback once and durably record its typed value.
11102    ///
11103    /// On replay the callback is not invoked: the value is decoded from the
11104    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
11105    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
11106    /// small values that must remain fixed for the lifetime of a workflow run.
11107    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
11108    where
11109        T: Serialize + DeserializeOwned,
11110        F: FnOnce() -> T,
11111    {
11112        {
11113            let mut state = self
11114                .state
11115                .lock()
11116                .map_err(|_| Error::WorkflowStatePoisoned)?;
11117            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11118                return match recorded {
11119                    RecordedCommand::SideEffect { sequence, value } => {
11120                        state.command_cursor += 1;
11121                        value.deserialize().map_err(|error| {
11122                            Error::NonDeterministicReplay(ReplayFailure::new(
11123                                "side_effect_type_mismatch",
11124                                Some(sequence),
11125                                Some(std::any::type_name::<T>().to_string()),
11126                                Some(error.to_string()),
11127                                "recorded side-effect value is incompatible with the requested Rust type",
11128                            ))
11129                        })
11130                    }
11131                    other => Err(command_mismatch(&other, "side effect")),
11132                };
11133            }
11134        }
11135
11136        let value = callback();
11137        let avro_value = AvroValue::from_serialize(&value)?;
11138        let mut state = self
11139            .state
11140            .lock()
11141            .map_err(|_| Error::WorkflowStatePoisoned)?;
11142        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
11143        state.commands.push(json!({
11144            "type": "record_side_effect",
11145            "result": result,
11146        }));
11147        Ok(value)
11148    }
11149
11150    /// Record or replay a lossless fixed Avro Value side effect.
11151    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
11152    where
11153        F: FnOnce() -> AvroValue,
11154    {
11155        {
11156            let mut state = self
11157                .state
11158                .lock()
11159                .map_err(|_| Error::WorkflowStatePoisoned)?;
11160            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11161                return match recorded {
11162                    RecordedCommand::SideEffect { value, .. } => {
11163                        state.command_cursor += 1;
11164                        Ok(value)
11165                    }
11166                    other => Err(command_mismatch(&other, "side effect")),
11167                };
11168            }
11169        }
11170
11171        let value = callback();
11172        let mut state = self
11173            .state
11174            .lock()
11175            .map_err(|_| Error::WorkflowStatePoisoned)?;
11176        let result = encode_typed_envelope(&value, &state.payload_codec)?;
11177        state.commands.push(json!({
11178            "type": "record_side_effect",
11179            "result": result,
11180        }));
11181        Ok(value)
11182    }
11183
11184    /// Append output items at a deterministic workflow command boundary.
11185    ///
11186    /// Stable idempotency keys are derived from the server-provided durable
11187    /// workflow command identity, command ordinal, and item index. Replay
11188    /// consumes the recorded side effect and never emits another append.
11189    pub fn append_workflow_stream(
11190        &self,
11191        stream_name: impl Into<String>,
11192        items: &[WorkflowStreamAppendItem],
11193        max_pending_items: Option<u64>,
11194    ) -> Result<()> {
11195        if items.is_empty() {
11196            return Err(Error::Codec(
11197                "workflow_stream_items_empty: append requires at least one item".to_string(),
11198            ));
11199        }
11200        if max_pending_items == Some(0) {
11201            return Err(Error::Codec(
11202                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
11203                    .to_string(),
11204            ));
11205        }
11206        let stream_name = stream_name.into();
11207        if stream_name.is_empty() {
11208            return Err(Error::Codec(
11209                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11210            ));
11211        }
11212
11213        let mut state = self
11214            .state
11215            .lock()
11216            .map_err(|_| Error::WorkflowStatePoisoned)?;
11217        let command_ordinal = state.workflow_stream_command_counter;
11218        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11219            state.workflow_stream_command_counter += 1;
11220            return match recorded {
11221                RecordedCommand::SideEffect { .. } => {
11222                    state.command_cursor += 1;
11223                    Ok(())
11224                }
11225                other => Err(command_mismatch(&other, "workflow stream append")),
11226            };
11227        }
11228
11229        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11230        state.workflow_stream_command_counter += 1;
11231        let wire_items = items
11232            .iter()
11233            .enumerate()
11234            .map(|(item_index, item)| {
11235                item.wire_value(Some(format!(
11236                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
11237                )))
11238            })
11239            .collect::<Vec<_>>();
11240        let mut directive = json!({
11241            "operation": "append",
11242            "stream_name": stream_name,
11243            "command_identity": identity,
11244            "command_ordinal": command_ordinal,
11245            "items": wire_items,
11246        });
11247        if let Some(max_pending_items) = max_pending_items {
11248            directive["max_pending_items"] = json!(max_pending_items);
11249        }
11250        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11251        state.commands.push(json!({
11252            "type": "record_side_effect",
11253            "result": result,
11254            "workflow_stream": directive,
11255        }));
11256        Ok(())
11257    }
11258
11259    /// Close a run-scoped output stream at a deterministic command boundary.
11260    pub fn close_workflow_stream(
11261        &self,
11262        stream_name: impl Into<String>,
11263        retention_seconds: Option<u64>,
11264    ) -> Result<()> {
11265        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
11266    }
11267
11268    /// Mark a run-scoped output stream errored at a deterministic command boundary.
11269    pub fn error_workflow_stream(
11270        &self,
11271        stream_name: impl Into<String>,
11272        error_reason: impl Into<String>,
11273        retention_seconds: Option<u64>,
11274    ) -> Result<()> {
11275        let error_reason = error_reason.into();
11276        if error_reason.is_empty() {
11277            return Err(Error::Codec(
11278                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
11279            ));
11280        }
11281        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
11282    }
11283
11284    fn finish_workflow_stream(
11285        &self,
11286        stream_name: String,
11287        error_reason: Option<String>,
11288        retention_seconds: Option<u64>,
11289    ) -> Result<()> {
11290        if stream_name.is_empty() {
11291            return Err(Error::Codec(
11292                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11293            ));
11294        }
11295        if retention_seconds == Some(0) {
11296            return Err(Error::Codec(
11297                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
11298            ));
11299        }
11300        let mut state = self
11301            .state
11302            .lock()
11303            .map_err(|_| Error::WorkflowStatePoisoned)?;
11304        let command_ordinal = state.workflow_stream_command_counter;
11305        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11306            state.workflow_stream_command_counter += 1;
11307            return match recorded {
11308                RecordedCommand::SideEffect { .. } => {
11309                    state.command_cursor += 1;
11310                    Ok(())
11311                }
11312                other => Err(command_mismatch(&other, "workflow stream close")),
11313            };
11314        }
11315        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11316        state.workflow_stream_command_counter += 1;
11317        let mut directive = json!({
11318            "operation": if error_reason.is_some() { "error" } else { "close" },
11319            "stream_name": stream_name,
11320            "command_identity": identity,
11321            "command_ordinal": command_ordinal,
11322        });
11323        if let Some(error_reason) = error_reason {
11324            directive["error_reason"] = json!(error_reason);
11325        }
11326        if let Some(retention_seconds) = retention_seconds {
11327            directive["retention_seconds"] = json!(retention_seconds);
11328        }
11329        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11330        state.commands.push(json!({
11331            "type": "record_side_effect",
11332            "result": result,
11333            "workflow_stream": directive,
11334        }));
11335        Ok(())
11336    }
11337
11338    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
11339        let identity = state.workflow_command_identity.as_str();
11340        if identity.is_empty() {
11341            return Err(Error::MissingWorkflowCommandIdentity);
11342        }
11343        Ok(identity)
11344    }
11345
11346    /// Validate, emit, or replay a typed workflow search-attribute update.
11347    ///
11348    /// The command is non-blocking within a workflow decision, but its
11349    /// `SearchAttributesUpserted` event occupies the same deterministic command
11350    /// stream as activities, timers, conditions, and other durable operations.
11351    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
11352        update.validate()?;
11353        let (attributes, attribute_types) = update.into_wire_parts();
11354        let mut state = self
11355            .state
11356            .lock()
11357            .map_err(|_| Error::WorkflowStatePoisoned)?;
11358
11359        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11360            return match recorded {
11361                RecordedCommand::SearchAttributes {
11362                    sequence,
11363                    attributes: recorded_attributes,
11364                    attribute_types: recorded_attribute_types,
11365                } => {
11366                    if recorded_attributes != attributes {
11367                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11368                            "search_attribute_value_mismatch",
11369                            Some(sequence),
11370                            Some(recorded_attributes.to_string()),
11371                            Some(attributes.to_string()),
11372                            "search-attribute values differ from the recorded durable command",
11373                        )));
11374                    }
11375                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
11376                        if recorded_types != attribute_types {
11377                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11378                                "search_attribute_type_mismatch",
11379                                Some(sequence),
11380                                Some(json!(recorded_types).to_string()),
11381                                Some(json!(attribute_types).to_string()),
11382                                "search-attribute declared types differ from the recorded durable command",
11383                            )));
11384                        }
11385                    }
11386                    state.command_cursor += 1;
11387                    Ok(())
11388                }
11389                other => Err(command_mismatch(&other, "search-attribute update")),
11390            };
11391        }
11392
11393        let mut command = serde_json::Map::from_iter([
11394            ("type".to_string(), json!("upsert_search_attributes")),
11395            ("attributes".to_string(), attributes),
11396        ]);
11397        if !attribute_types.is_empty() {
11398            command.insert("attribute_types".to_string(), json!(attribute_types));
11399        }
11400        state.commands.push(Value::Object(command));
11401        Ok(())
11402    }
11403
11404    /// Record a UUIDv4 once and return the same UUID on every replay.
11405    pub fn uuid_v4(&self) -> Result<Uuid> {
11406        self.side_effect(Uuid::new_v4)
11407    }
11408
11409    /// Select the newest supported version for a change, or replay the version
11410    /// already committed for that stable change ID.
11411    ///
11412    /// An unmarked old history that reached its next durable operation, or
11413    /// already completed, selects `-1` when that version is supported. This
11414    /// leaves the original operation available and writes no additional marker.
11415    /// Consistent markers written by older workers retain their original ordered
11416    /// positions. Repeated calls consume a matching marker at the current cursor.
11417    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
11418    pub fn get_version(
11419        &self,
11420        change_id: impl Into<String>,
11421        min_supported: i32,
11422        max_supported: i32,
11423    ) -> Result<i32> {
11424        let change_id = change_id.into();
11425        if change_id.trim().is_empty() {
11426            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11427                "version_change_id_invalid",
11428                None,
11429                Some("non-empty change ID".to_string()),
11430                Some(change_id),
11431                "version markers require a stable non-empty change ID",
11432            )));
11433        }
11434        if min_supported > max_supported {
11435            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11436                "version_range_invalid",
11437                None,
11438                Some("min_supported <= max_supported".to_string()),
11439                Some(format!("{min_supported}..={max_supported}")),
11440                "version marker supported range is invalid",
11441            )));
11442        }
11443
11444        let mut state = self
11445            .state
11446            .lock()
11447            .map_err(|_| Error::WorkflowStatePoisoned)?;
11448        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
11449            if let Some(RecordedCommand::VersionMarker {
11450                sequence: alias_sequence,
11451                change_id: alias_change_id,
11452                version: alias_version,
11453            }) = state.recorded_commands.get(state.command_cursor)
11454            {
11455                if alias_change_id == &change_id {
11456                    if *alias_version != version {
11457                        return Err(invalid_recorded_history(
11458                            "version_marker_conflict",
11459                            *alias_sequence,
11460                            &format!("selected version {version} for change ID {change_id:?}"),
11461                            &format!("recorded version {alias_version}"),
11462                            "recorded marker conflicts with the decision already selected during replay",
11463                        ));
11464                    }
11465                    ensure_version_supported(
11466                        &change_id,
11467                        version,
11468                        min_supported,
11469                        max_supported,
11470                        *alias_sequence,
11471                    )?;
11472                    // Older workers could record the same decision again. Keep
11473                    // each physical boundary without skipping intervening work.
11474                    state.command_cursor += 1;
11475                    return Ok(version);
11476                }
11477            }
11478            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
11479            return Ok(version);
11480        }
11481
11482        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11483            return match recorded {
11484                RecordedCommand::VersionMarker {
11485                    sequence,
11486                    change_id: recorded_change_id,
11487                    version,
11488                    ..
11489                } => {
11490                    if recorded_change_id != change_id {
11491                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11492                            "version_change_id_mismatch",
11493                            Some(sequence),
11494                            Some(recorded_change_id),
11495                            Some(change_id),
11496                            "recorded version marker change ID differs from current workflow code",
11497                        )));
11498                    }
11499                    ensure_version_supported(
11500                        &change_id,
11501                        version,
11502                        min_supported,
11503                        max_supported,
11504                        sequence,
11505                    )?;
11506                    state.command_cursor += 1;
11507                    state.version_markers.insert(change_id, (version, sequence));
11508                    Ok(version)
11509                }
11510                other => {
11511                    let version = -1;
11512                    let sequence = other.sequence();
11513                    ensure_version_supported(
11514                        &change_id,
11515                        version,
11516                        min_supported,
11517                        max_supported,
11518                        sequence,
11519                    )?;
11520                    // The existing operation proves this patch site was reached
11521                    // before its marker existed. Keep its original cursor.
11522                    state.version_markers.insert(change_id, (version, sequence));
11523                    Ok(version)
11524                }
11525            };
11526        }
11527
11528        if state
11529            .history_events
11530            .iter()
11531            .any(|event| event.event_type == "WorkflowCompleted")
11532        {
11533            let version = -1;
11534            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
11535            state.version_markers.insert(change_id, (version, 0));
11536            return Ok(version);
11537        }
11538
11539        let version = max_supported;
11540        state.commands.push(json!({
11541            "type": "record_version_marker",
11542            "change_id": change_id,
11543            "version": version,
11544            "min_supported": min_supported,
11545            "max_supported": max_supported,
11546        }));
11547        // Sequence numbers are assigned by the server. Zero identifies a marker
11548        // selected in this uncommitted decision batch for duplicate-call checks.
11549        state.version_markers.insert(change_id, (version, 0));
11550        Ok(version)
11551    }
11552
11553    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
11554    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
11555        Ok(self.get_version(change_id, -1, 1)? == 1)
11556    }
11557
11558    /// Keep a patch marker in history after the legacy branch has been removed.
11559    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
11560        self.get_version(change_id, -1, 1).map(|_| ())
11561    }
11562
11563    /// Merge non-indexed workflow memo metadata through durable history.
11564    ///
11565    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
11566    /// public Avro payload envelope consumed by Server and Cloud runtimes.
11567    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
11568        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
11569        let mut state = self
11570            .state
11571            .lock()
11572            .map_err(|_| Error::WorkflowStatePoisoned)?;
11573
11574        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11575            return match recorded {
11576                RecordedCommand::Memo {
11577                    sequence,
11578                    entries: recorded_entries,
11579                } => {
11580                    if recorded_entries != entries {
11581                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11582                            "memo_update_mismatch",
11583                            Some(sequence),
11584                            Some(format!("{recorded_entries:?}")),
11585                            Some(format!("{entries:?}")),
11586                            "recorded memo entries differ from the current workflow update",
11587                        )));
11588                    }
11589                    state.command_cursor += 1;
11590                    Ok(())
11591                }
11592                other => Err(command_mismatch(&other, "memo upsert")),
11593            };
11594        }
11595
11596        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
11597        state.commands.push(json!({
11598            "type": "upsert_memo",
11599            "entries": entries_envelope,
11600        }));
11601        Ok(())
11602    }
11603
11604    /// Start a named durable child on an explicit queue and await its result.
11605    ///
11606    /// The command is recorded in the parent's sequence-ordered durable command
11607    /// stream. Replay keeps a scheduled child pending without emitting another
11608    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
11609    /// values preserve the history payload codec and include both sides of the
11610    /// durable relationship; failures are returned as
11611    /// [`Error::ChildWorkflowFailed`].
11612    ///
11613    /// ```no_run
11614    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
11615    /// # fn configure(client: Client) {
11616    /// let mut worker = Worker::new(client, "parent-workers");
11617    /// worker.register_workflow("order-parent", |ctx, _input| async move {
11618    ///     let child = ctx
11619    ///         .start_child_workflow(
11620    ///             "fulfil-order",
11621    ///             ChildWorkflowOptions::new("fulfilment-workers")
11622    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
11623    ///             json!([{"order_id": "order-42"}]),
11624    ///         )
11625    ///         .await?;
11626    ///     Ok(child.result)
11627    /// });
11628    /// # }
11629    /// ```
11630    pub fn start_child_workflow<T: Serialize>(
11631        &self,
11632        workflow_type: impl Into<String>,
11633        options: ChildWorkflowOptions,
11634        args: T,
11635    ) -> ChildWorkflowCall {
11636        ChildWorkflowCall {
11637            ctx: self.clone(),
11638            workflow_type: workflow_type.into(),
11639            options,
11640            args: Some(AvroValue::from_serialize(&args)),
11641            scheduled: false,
11642            matched_pending: false,
11643            parallel_group_path: Vec::new(),
11644        }
11645    }
11646
11647    pub async fn start_child_workflow_avro_value<T: Serialize>(
11648        &self,
11649        workflow_type: impl Into<String>,
11650        options: ChildWorkflowOptions,
11651        args: T,
11652    ) -> Result<ChildWorkflowAvroResult> {
11653        let mut call = self.start_child_workflow(workflow_type, options, args);
11654        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
11655    }
11656
11657    fn take_commands(&self) -> Result<Vec<Value>> {
11658        let mut state = self
11659            .state
11660            .lock()
11661            .map_err(|_| Error::WorkflowStatePoisoned)?;
11662        Ok(std::mem::take(&mut state.commands))
11663    }
11664
11665    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
11666        let mut state = self
11667            .state
11668            .lock()
11669            .map_err(|_| Error::WorkflowStatePoisoned)?;
11670
11671        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11672            return Err(command_mismatch(&recorded, "continue as new"));
11673        }
11674        if state.recorded_continue_as_new_sequence.is_some() {
11675            state.continue_as_new_consumed = true;
11676            return Ok(None);
11677        }
11678
11679        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
11680        let mut command = serde_json::Map::from_iter([
11681            ("type".to_string(), json!("continue_as_new")),
11682            ("arguments".to_string(), arguments),
11683            ("queue".to_string(), json!(state.task_queue.clone())),
11684        ]);
11685        if let Some(workflow_type) = request.options.workflow_type {
11686            command.insert("workflow_type".to_string(), json!(workflow_type));
11687        }
11688        if let Some(task_queue) = request.options.task_queue {
11689            command.insert("queue".to_string(), json!(task_queue));
11690        }
11691        Ok(Some(Value::Object(command)))
11692    }
11693
11694    fn matched_recorded_pending(&self) -> Result<bool> {
11695        let state = self
11696            .state
11697            .lock()
11698            .map_err(|_| Error::WorkflowStatePoisoned)?;
11699        Ok(state.matched_recorded_pending)
11700    }
11701
11702    fn ensure_history_consumed(&self) -> Result<()> {
11703        let state = self
11704            .state
11705            .lock()
11706            .map_err(|_| Error::WorkflowStatePoisoned)?;
11707        if let Some(replay) = &state.scope_delivery {
11708            if let Some((&sequence, _)) = replay
11709                .canonical
11710                .deliveries
11711                .iter()
11712                .find(|(sequence, _)| !replay.consumed.contains(sequence))
11713            {
11714                return Err(invalid_recorded_history(
11715                    "cancellation_scope_delivery_unconsumed",
11716                    sequence,
11717                    "original scoped delivery",
11718                    "workflow completion",
11719                    "workflow completed without consuming its committed scope delivery",
11720                ));
11721            }
11722        }
11723        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
11724            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11725                "recorded_commands_unconsumed",
11726                Some(command.sequence()),
11727                Some(command.shape().to_string()),
11728                Some("workflow completion".to_string()),
11729                "workflow completed before consuming all recorded durable commands",
11730            )));
11731        }
11732        if let Some(delivery) = state
11733            .cancellation_history
11734            .delivery
11735            .as_ref()
11736            .filter(|_| !state.cancellation_consumed)
11737        {
11738            return Err(invalid_recorded_history(
11739                "cooperative_cancellation_unconsumed",
11740                delivery.sequence,
11741                "committed cancellation call",
11742                "workflow completion",
11743                "workflow completed without reaching its committed cancellation boundary",
11744            ));
11745        }
11746        if let Some(sequence) = state
11747            .recorded_continue_as_new_sequence
11748            .filter(|_| !state.continue_as_new_consumed)
11749        {
11750            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11751                "recorded_continue_as_new_unconsumed",
11752                Some(sequence),
11753                Some("continue as new".to_string()),
11754                Some("workflow completion".to_string()),
11755                "workflow completed without consuming its recorded continue-as-new transition",
11756            )));
11757        }
11758        Ok(())
11759    }
11760}
11761
11762fn contiguous_message_stream_count(
11763    pending: &[MessageStreamMessage],
11764    cursor: u64,
11765    max_items: usize,
11766) -> usize {
11767    pending
11768        .iter()
11769        .take(max_items)
11770        .enumerate()
11771        .take_while(|(offset, message)| {
11772            u64::try_from(*offset)
11773                .ok()
11774                .and_then(|offset| cursor.checked_add(offset + 1))
11775                == Some(message.position)
11776        })
11777        .count()
11778}
11779
11780fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
11781    matches!(
11782        event.event_type.as_str(),
11783        "ActivityScheduled"
11784            | "TimerScheduled"
11785            | "ChildWorkflowScheduled"
11786            | "SignalWaitOpened"
11787            | "ConditionWaitOpened"
11788            | "SearchAttributesUpserted"
11789            | "SideEffectRecorded"
11790            | "VersionMarkerRecorded"
11791            | "MemoUpserted"
11792            | "WorkflowContinuedAsNew"
11793    )
11794}
11795
11796#[derive(Debug)]
11797struct WorkflowState {
11798    workflow_id: Option<String>,
11799    run_id: Option<String>,
11800    task_queue: String,
11801    payload_codec: String,
11802    history_events: Arc<Vec<HistoryEvent>>,
11803    history_budget: WorkflowHistoryBudget,
11804    cancel_requested: bool,
11805    cancellation_history: CancellationHistory,
11806    cancellation_consumed: bool,
11807    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
11808    cancellation_shield_depth: u64,
11809    cancellation_delivery_enabled: bool,
11810    cancellation_delivery_intent: Option<CancellationDelivery>,
11811    cancellation_delivery_command_count: usize,
11812    allow_cancellation_scope_authoring: bool,
11813    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
11814    cancellation_scope_memberships: BTreeMap<u64, String>,
11815    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
11816    resume_signal: Option<ResumeSignal>,
11817    recorded_commands: Vec<RecordedCommand>,
11818    selection_markers: Vec<SelectionMarker>,
11819    selection_marker_cursor: usize,
11820    cancelled_selection_members: Vec<SelectionCancellation>,
11821    recorded_continue_as_new_sequence: Option<u64>,
11822    continue_as_new_consumed: bool,
11823    command_cursor: usize,
11824    condition_wait_occurrence_counter: u64,
11825    matched_recorded_pending: bool,
11826    version_markers: HashMap<String, (i32, u64)>,
11827    workflow_command_identity: String,
11828    workflow_stream_command_counter: u64,
11829    commands: Vec<Value>,
11830    local_activity_requests: Vec<local_activity::Request>,
11831    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
11832    message_stream_cursors: HashMap<String, u64>,
11833    message_stream_waits: HashMap<String, u64>,
11834}
11835
11836impl WorkflowState {
11837    #[cfg(test)]
11838    fn new(
11839        history: Vec<HistoryEvent>,
11840        task_queue: String,
11841        payload_codec: String,
11842        resume_signal: Option<ResumeSignal>,
11843    ) -> Result<Self> {
11844        Self::new_with_identity(
11845            history,
11846            None,
11847            None,
11848            task_queue,
11849            payload_codec,
11850            resume_signal,
11851        )
11852    }
11853
11854    fn new_with_identity(
11855        history: Vec<HistoryEvent>,
11856        workflow_id: Option<String>,
11857        run_id: Option<String>,
11858        task_queue: String,
11859        payload_codec: String,
11860        resume_signal: Option<ResumeSignal>,
11861    ) -> Result<Self> {
11862        Self::new_with_identity_and_scopes(
11863            history,
11864            workflow_id,
11865            run_id,
11866            task_queue,
11867            payload_codec,
11868            resume_signal,
11869            false,
11870        )
11871    }
11872
11873    fn new_with_identity_and_scopes(
11874        history: Vec<HistoryEvent>,
11875        workflow_id: Option<String>,
11876        run_id: Option<String>,
11877        task_queue: String,
11878        payload_codec: String,
11879        resume_signal: Option<ResumeSignal>,
11880        allow_cancellation_scope_authoring: bool,
11881    ) -> Result<Self> {
11882        Self::new_with_identity_and_scope_delivery(
11883            history,
11884            workflow_id,
11885            run_id,
11886            task_queue,
11887            payload_codec,
11888            resume_signal,
11889            allow_cancellation_scope_authoring,
11890            false,
11891        )
11892    }
11893
11894    fn new_with_identity_and_scope_delivery(
11895        history: Vec<HistoryEvent>,
11896        workflow_id: Option<String>,
11897        run_id: Option<String>,
11898        task_queue: String,
11899        payload_codec: String,
11900        resume_signal: Option<ResumeSignal>,
11901        allow_cancellation_scope_authoring: bool,
11902        allow_cancellation_scope_delivery: bool,
11903    ) -> Result<Self> {
11904        cooperative_cancellation::assert_cancellation_scope_replay_supported(
11905            &history,
11906            allow_cancellation_scope_authoring,
11907            allow_cancellation_scope_delivery,
11908        )?;
11909        let scopes = if allow_cancellation_scope_authoring {
11910            cancellation_scope::CancellationScopeHistory::read(
11911                &history,
11912                run_id.as_deref().unwrap_or_default(),
11913            )?
11914        } else {
11915            cancellation_scope::CancellationScopeHistory::default()
11916        };
11917        let cancellation_history = CancellationHistory::from_events(
11918            &history,
11919            run_id.as_deref().unwrap_or_default(),
11920            None,
11921        )?;
11922        if allow_cancellation_scope_authoring
11923            && cancellation_history.request.is_some()
11924            && !allow_cancellation_scope_delivery
11925        {
11926            return Err(Error::CancellationScopeExecutionUnavailable);
11927        }
11928        let scope_delivery = if allow_cancellation_scope_delivery {
11929            Some(cancellation_scope_replay::ScopeReplay::read(
11930                &history,
11931                &scopes,
11932                run_id.as_deref().unwrap_or_default(),
11933                workflow_id.as_deref().unwrap_or_default(),
11934            )?)
11935        } else {
11936            None
11937        };
11938        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
11939            &history,
11940            &payload_codec,
11941            WorkflowIdentity {
11942                workflow_id: workflow_id.clone(),
11943                run_id: run_id.clone(),
11944            },
11945        )?)?;
11946        for (sequence, opening) in &scopes.openings {
11947            if recorded_commands
11948                .iter()
11949                .any(|command| command.sequence() == *sequence)
11950            {
11951                return Err(invalid_recorded_history(
11952                    "invalid_cancellation_scope_history",
11953                    *sequence,
11954                    "distinct authored scope opening",
11955                    "operation collision",
11956                    "scope opening collides with a command",
11957                ));
11958            }
11959            recorded_commands.push(RecordedCommand::CancellationScope {
11960                sequence: *sequence,
11961                scope_id: opening.scope_id.clone(),
11962                parent_scope_id: opening.parent_scope_id.clone(),
11963                shield_parent: opening.shield_parent,
11964            });
11965        }
11966        recorded_commands.sort_by_key(RecordedCommand::sequence);
11967        if let Some(replay) = &scope_delivery {
11968            replay.bind_commands(&mut recorded_commands)?;
11969        }
11970        let selection_markers = recorded_selection_markers(&history)?;
11971        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
11972        let recorded_continue_as_new = history
11973            .iter()
11974            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
11975            .collect::<Vec<_>>();
11976        if recorded_continue_as_new.len() > 1 {
11977            return Err(invalid_recorded_history(
11978                "duplicate_continue_as_new_transition",
11979                recorded_continue_as_new
11980                    .last()
11981                    .and_then(|event| durable_event_sequence(event))
11982                    .unwrap_or(0),
11983                "one WorkflowContinuedAsNew event",
11984                &format!(
11985                    "{} WorkflowContinuedAsNew events",
11986                    recorded_continue_as_new.len()
11987                ),
11988                "workflow history records one continue-as-new transition more than once",
11989            ));
11990        }
11991        let recorded_continue_as_new_sequence = recorded_continue_as_new
11992            .first()
11993            .map(|event| {
11994                durable_event_sequence(event).ok_or_else(|| {
11995                    Error::NonDeterministicReplay(ReplayFailure::new(
11996                        "continue_as_new_sequence_missing",
11997                        None,
11998                        Some("recorded transition sequence".to_string()),
11999                        Some("missing sequence".to_string()),
12000                        "WorkflowContinuedAsNew history is missing its recorded sequence",
12001                    ))
12002                })
12003            })
12004            .transpose()?;
12005        let mut message_stream_cursors = HashMap::new();
12006        for event in &history {
12007            if !matches!(
12008                event.event_type.as_str(),
12009                "SignalReceived" | "SignalApplied"
12010            ) || event.payload.get("signal_name").and_then(Value::as_str)
12011                != Some(MESSAGE_STREAM_SIGNAL)
12012            {
12013                continue;
12014            }
12015            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
12016            if arguments.len() != 1 {
12017                continue;
12018            }
12019            let envelope = arguments[0].clone().into_json()?;
12020            let Some(envelope) = envelope.as_object() else {
12021                continue;
12022            };
12023            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
12024            {
12025                continue;
12026            }
12027            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
12028                continue;
12029            };
12030            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
12031            else {
12032                continue;
12033            };
12034            let cursor = message_stream_cursors
12035                .entry(stream_name.to_string())
12036                .or_insert(0);
12037            *cursor = (*cursor).max(through_position);
12038        }
12039        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
12040        let cancel_requested = history.iter().any(|event| {
12041            matches!(
12042                event.event_type.as_str(),
12043                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
12044            )
12045        });
12046        let cancellation_clock = cancellation_history
12047            .request
12048            .as_ref()
12049            .and_then(|request| request.context.as_ref())
12050            .map(|_| {
12051                cancellation_replay_clock::ReplayClock::new(
12052                    &history,
12053                    &recorded_commands,
12054                    cancellation_history.delivery_index,
12055                )
12056            })
12057            .or_else(|| {
12058                scope_delivery.as_ref().map(|_| {
12059                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
12060                })
12061            });
12062        Ok(Self {
12063            workflow_command_identity: String::new(),
12064            workflow_stream_command_counter: 0,
12065            workflow_id,
12066            run_id,
12067            task_queue,
12068            payload_codec,
12069            history_events: Arc::new(history),
12070            history_budget: WorkflowHistoryBudget {
12071                event_count,
12072                ..WorkflowHistoryBudget::default()
12073            },
12074            cancel_requested,
12075            cancellation_history,
12076            cancellation_consumed: false,
12077            cancellation_clock,
12078            cancellation_shield_depth: 0,
12079            cancellation_delivery_enabled: false,
12080            cancellation_delivery_intent: None,
12081            cancellation_delivery_command_count: 0,
12082            allow_cancellation_scope_authoring,
12083            cancellation_scope_opening: None,
12084            cancellation_scope_memberships: scopes.memberships,
12085            scope_delivery,
12086            resume_signal,
12087            recorded_commands,
12088            selection_markers,
12089            selection_marker_cursor: 0,
12090            cancelled_selection_members,
12091            recorded_continue_as_new_sequence,
12092            continue_as_new_consumed: false,
12093            command_cursor: 0,
12094            condition_wait_occurrence_counter: 0,
12095            matched_recorded_pending: false,
12096            version_markers: HashMap::new(),
12097            commands: Vec::new(),
12098            local_activity_requests: Vec::new(),
12099            message_stream_messages: HashMap::new(),
12100            message_stream_cursors,
12101            message_stream_waits: HashMap::new(),
12102        })
12103    }
12104}
12105
12106enum MessageStreamDelivery {
12107    Message(MessageStreamMessage),
12108    Cursor {
12109        stream_name: String,
12110        through_position: u64,
12111    },
12112}
12113
12114fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
12115    if arguments.len() != 1 {
12116        return Ok(None);
12117    }
12118    let envelope = arguments
12119        .into_iter()
12120        .next()
12121        .expect("one argument was checked");
12122    let Some(envelope) = envelope.as_object() else {
12123        return Ok(None);
12124    };
12125    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
12126        return Ok(None);
12127    };
12128    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
12129        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
12130        else {
12131            return Ok(None);
12132        };
12133        return Ok(Some(MessageStreamDelivery::Cursor {
12134            stream_name: stream_name.to_string(),
12135            through_position,
12136        }));
12137    }
12138    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
12139        return Ok(None);
12140    }
12141    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
12142        return Ok(None);
12143    };
12144    let Some(position) = envelope
12145        .get("position")
12146        .and_then(Value::as_u64)
12147        .filter(|value| *value > 0)
12148    else {
12149        return Ok(None);
12150    };
12151    let Some(payload_envelope) = envelope.get("payload_envelope") else {
12152        return Ok(None);
12153    };
12154    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
12155    else {
12156        return Ok(None);
12157    };
12158    let decoded = decode_avro_value(&payload_envelope)?;
12159    let AvroValue::Array(values) = decoded else {
12160        return Ok(None);
12161    };
12162    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
12163        stream_name: stream_name.to_string(),
12164        message_id: message_id.to_string(),
12165        position,
12166        arguments: values,
12167    })))
12168}
12169
12170#[derive(Clone, Debug)]
12171enum RecordedCommand {
12172    ServiceOperation {
12173        sequence: u64,
12174        call: nexus::RecordedServiceCall,
12175    },
12176    CancellationScope {
12177        sequence: u64,
12178        scope_id: String,
12179        parent_scope_id: String,
12180        shield_parent: bool,
12181    },
12182    CancellationGroup {
12183        sequence: u64,
12184        span: u64,
12185        original: Vec<RecordedCommand>,
12186    },
12187    CancellationBoundary {
12188        sequence: u64,
12189        call_kind: CancellationCallKind,
12190        original: Option<Box<RecordedCommand>>,
12191    },
12192    Activity {
12193        sequence: u64,
12194        activity_type: Option<String>,
12195        cancellation_policy: String,
12196        options: Option<RecordedActivityOptions>,
12197        outcome: Option<ActivityOutcome>,
12198        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12199    },
12200    Timer {
12201        sequence: u64,
12202        delay_seconds: u64,
12203        fired: bool,
12204        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12205    },
12206    ChildWorkflow {
12207        sequence: u64,
12208        workflow_type: Option<String>,
12209        policies: RecordedChildPolicies,
12210        outcome: Option<ChildWorkflowOutcome>,
12211        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12212    },
12213    SignalWait {
12214        sequence: u64,
12215        signal_name: String,
12216        value: Option<Vec<AvroValue>>,
12217        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12218    },
12219    ConditionWait {
12220        sequence: u64,
12221        occurrence_id: String,
12222        condition_key: Option<String>,
12223        predicate_identity: String,
12224        timeout_seconds: Option<u64>,
12225        result: Option<ConditionWaitResult>,
12226        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12227    },
12228    SearchAttributes {
12229        sequence: u64,
12230        attributes: Value,
12231        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
12232    },
12233    SideEffect {
12234        sequence: u64,
12235        value: AvroValue,
12236    },
12237    VersionMarker {
12238        sequence: u64,
12239        change_id: String,
12240        version: i32,
12241    },
12242    Memo {
12243        sequence: u64,
12244        entries: AvroValue,
12245    },
12246}
12247
12248#[derive(Clone, Debug, PartialEq, Eq)]
12249struct SelectionMarker {
12250    selection_group_id: String,
12251    selection_group_base_sequence: u64,
12252    selection_group_size: usize,
12253    member_key: SelectionKey,
12254    member_index: usize,
12255    member_base_sequence: u64,
12256    member_size: usize,
12257    operation_kind: String,
12258    operation_identity: String,
12259    outcome: String,
12260    resolution_event_id: String,
12261    resolution_event_type: String,
12262}
12263
12264#[derive(Clone, Debug, PartialEq, Eq)]
12265struct SelectionCancellation {
12266    selection_group_id: String,
12267    member_key: SelectionKey,
12268    member_index: usize,
12269    member_base_sequence: u64,
12270    member_size: usize,
12271    operation_kind: String,
12272    operation_identity: String,
12273}
12274
12275fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
12276    let mut markers: Vec<SelectionMarker> = Vec::new();
12277    for event in events
12278        .iter()
12279        .filter(|event| event.event_type == "SelectionResolved")
12280    {
12281        let payload = &event.payload;
12282        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
12283        let group_size = required_selection_usize(payload, "selection_group_size")?;
12284        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
12285        let member_size = required_selection_usize(payload, "member_size")?;
12286        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
12287        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
12288            invalid_recorded_history(
12289                "selection_marker_invalid",
12290                base_sequence,
12291                "non-empty selection_group_id",
12292                &payload.to_string(),
12293                "selection winner history is missing its durable group identity",
12294            )
12295        })?;
12296        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
12297        if group_id != expected_group_id {
12298            return Err(invalid_recorded_history(
12299                "selection_marker_invalid",
12300                base_sequence,
12301                &expected_group_id,
12302                &group_id,
12303                "selection winner history contains an incompatible group identity",
12304            ));
12305        }
12306        let group_end = base_sequence
12307            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
12308            .unwrap_or(u64::MAX);
12309        let member_end = member_base_sequence
12310            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
12311            .unwrap_or(u64::MAX);
12312        if member_index >= group_size
12313            || member_base_sequence < base_sequence
12314            || member_end > group_end
12315        {
12316            return Err(invalid_recorded_history(
12317                "selection_marker_invalid",
12318                base_sequence,
12319                "winner member within selection group bounds",
12320                &payload.to_string(),
12321                "selection winner history contains an invalid member range",
12322            ));
12323        }
12324        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
12325            invalid_recorded_history(
12326                "selection_marker_invalid",
12327                base_sequence,
12328                "selection operation kind",
12329                &payload.to_string(),
12330                "selection winner history is missing its operation kind",
12331            )
12332        })?;
12333        if !matches!(
12334            operation_kind.as_str(),
12335            "activity" | "child" | "timer" | "signal" | "condition" | "group"
12336        ) {
12337            return Err(invalid_recorded_history(
12338                "selection_marker_invalid",
12339                base_sequence,
12340                "activity, child, timer, signal, condition, or group",
12341                &operation_kind,
12342                "selection winner history contains an unsupported operation kind",
12343            ));
12344        }
12345        let operation_identity =
12346            payload_string(payload, "operation_identity").ok_or_else(|| {
12347                invalid_recorded_history(
12348                    "selection_marker_invalid",
12349                    base_sequence,
12350                    "non-empty operation identity",
12351                    &payload.to_string(),
12352                    "selection winner history is missing its durable operation identity",
12353                )
12354            })?;
12355        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
12356            invalid_recorded_history(
12357                "selection_marker_invalid",
12358                base_sequence,
12359                "completed or failed selection outcome",
12360                &payload.to_string(),
12361                "selection winner history is missing its outcome",
12362            )
12363        })?;
12364        if !matches!(outcome.as_str(), "completed" | "failed") {
12365            return Err(invalid_recorded_history(
12366                "selection_marker_invalid",
12367                base_sequence,
12368                "completed or failed selection outcome",
12369                &outcome,
12370                "selection winner history contains an unsupported outcome",
12371            ));
12372        }
12373        let marker = SelectionMarker {
12374            selection_group_id: group_id,
12375            selection_group_base_sequence: base_sequence,
12376            selection_group_size: group_size,
12377            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
12378            member_index,
12379            member_base_sequence,
12380            member_size,
12381            operation_kind,
12382            operation_identity,
12383            outcome,
12384            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
12385                || {
12386                    invalid_recorded_history(
12387                        "selection_marker_invalid",
12388                        base_sequence,
12389                        "durable resolution_event_id",
12390                        &payload.to_string(),
12391                        "selection winner history is missing its terminal event identity",
12392                    )
12393                },
12394            )?,
12395            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
12396                || {
12397                    invalid_recorded_history(
12398                        "selection_marker_invalid",
12399                        base_sequence,
12400                        "durable resolution_event_type",
12401                        &payload.to_string(),
12402                        "selection winner history is missing its terminal event type",
12403                    )
12404                },
12405            )?,
12406        };
12407        if let Some(existing) = markers
12408            .iter()
12409            .find(|existing| existing.selection_group_id == marker.selection_group_id)
12410        {
12411            if existing != &marker {
12412                return Err(invalid_recorded_history(
12413                    "selection_marker_conflict",
12414                    base_sequence,
12415                    &format!("one winner for {}", marker.selection_group_id),
12416                    &payload.to_string(),
12417                    "selection history records conflicting winners for one durable group",
12418                ));
12419            }
12420            continue;
12421        }
12422        markers.push(marker);
12423    }
12424    Ok(markers)
12425}
12426
12427fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
12428    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
12429    for event in events
12430        .iter()
12431        .filter(|event| event.event_type == "SelectionOperationCancelled")
12432    {
12433        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
12434            invalid_recorded_history(
12435                "selection_cancellation_invalid",
12436                0,
12437                "non-empty selection_group_id",
12438                &event.payload.to_string(),
12439                "selection cancellation history is missing its group identity",
12440            )
12441        })?;
12442        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
12443        let marker = SelectionCancellation {
12444            selection_group_id: group_id,
12445            member_key: selection_key_from_value(
12446                event.payload.get("member_key"),
12447                member_base_sequence,
12448            )?,
12449            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
12450            member_base_sequence,
12451            member_size: required_selection_usize(&event.payload, "member_size")?,
12452            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
12453                invalid_recorded_history(
12454                    "selection_cancellation_invalid",
12455                    member_base_sequence,
12456                    "selection operation kind",
12457                    &event.payload.to_string(),
12458                    "selection cancellation is missing its operation kind",
12459                )
12460            })?,
12461            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
12462                || {
12463                    invalid_recorded_history(
12464                        "selection_cancellation_invalid",
12465                        member_base_sequence,
12466                        "selection operation identity",
12467                        &event.payload.to_string(),
12468                        "selection cancellation is missing its operation identity",
12469                    )
12470                },
12471            )?,
12472        };
12473        if let Some(existing) = cancelled.iter().find(|recorded| {
12474            recorded.selection_group_id == marker.selection_group_id
12475                && recorded.member_base_sequence == marker.member_base_sequence
12476        }) {
12477            if existing != &marker {
12478                return Err(invalid_recorded_history(
12479                    "selection_cancellation_conflict",
12480                    member_base_sequence,
12481                    "one stable SelectionOperationCancelled marker",
12482                    &event.payload.to_string(),
12483                    "selection cancellation history contains conflicting member metadata",
12484                ));
12485            }
12486        } else {
12487            cancelled.push(marker);
12488        }
12489    }
12490    Ok(cancelled)
12491}
12492
12493fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
12494    payload
12495        .get(field)
12496        .and_then(value_as_u64)
12497        .filter(|value| *value > 0)
12498        .ok_or_else(|| {
12499            invalid_recorded_history(
12500                "selection_marker_invalid",
12501                0,
12502                &format!("positive integer {field}"),
12503                &payload.to_string(),
12504                "selection history contains invalid durable identity metadata",
12505            )
12506        })
12507}
12508
12509fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
12510    required_selection_usize_allow_zero(payload, field).and_then(|value| {
12511        if value > 0 {
12512            Ok(value)
12513        } else {
12514            Err(invalid_recorded_history(
12515                "selection_marker_invalid",
12516                0,
12517                &format!("positive integer {field}"),
12518                &payload.to_string(),
12519                "selection history contains invalid durable identity metadata",
12520            ))
12521        }
12522    })
12523}
12524
12525fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
12526    payload
12527        .get(field)
12528        .and_then(value_as_u64)
12529        .and_then(|value| usize::try_from(value).ok())
12530        .ok_or_else(|| {
12531            invalid_recorded_history(
12532                "selection_marker_invalid",
12533                0,
12534                &format!("non-negative integer {field}"),
12535                &payload.to_string(),
12536                "selection history contains invalid durable identity metadata",
12537            )
12538        })
12539}
12540
12541#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12542struct RecordedActivityOptions {
12543    task_queue: RecordedSnapshotValue<Option<String>>,
12544    execution_mode: RecordedSnapshotValue<Option<String>>,
12545    retry_policy: ActivityRetrySnapshot,
12546    worker_session: Option<Value>,
12547}
12548
12549#[derive(Clone, Debug)]
12550struct RecordedChildPolicies {
12551    parent_close_policy: String,
12552    cancellation_policy: String,
12553}
12554
12555fn recorded_activity_cancellation_policy(
12556    events: &[&HistoryEvent],
12557    sequence: u64,
12558) -> Result<String> {
12559    let mut policy: Option<String> = None;
12560    for event in events.iter().filter(|event| {
12561        matches!(
12562            event.event_type.as_str(),
12563            "ActivityScheduled"
12564                | "ActivityStarted"
12565                | "ActivityCompleted"
12566                | "ActivityFailed"
12567                | "ActivityTimedOut"
12568                | "ActivityCancelled"
12569        )
12570    }) {
12571        for source in [Some(&event.payload), event.payload.get("activity")]
12572            .into_iter()
12573            .flatten()
12574        {
12575            let Some(value) = source.get("cancellation_policy") else {
12576                continue;
12577            };
12578            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
12579                value.as_str()
12580            else {
12581                return Err(invalid_recorded_history(
12582                    "invalid_activity_cancellation_policy_history",
12583                    sequence,
12584                    "supported Activity cancellation policy",
12585                    &value.to_string(),
12586                    "Activity history contains an invalid cancellation policy",
12587                ));
12588            };
12589            if let Some(previous) = policy.as_deref() {
12590                if previous != incoming {
12591                    return Err(invalid_recorded_history(
12592                        "activity_cancellation_policy_history_conflict",
12593                        sequence,
12594                        previous,
12595                        incoming,
12596                        "Activity cancellation policy changed between history events",
12597                    ));
12598                }
12599            }
12600            policy = Some(incoming.to_string());
12601        }
12602        policy.get_or_insert_with(|| "try_cancel".to_string());
12603    }
12604    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
12605}
12606
12607fn recorded_child_policy_value<'a>(
12608    payload: &'a Value,
12609    field: &str,
12610    sequence: u64,
12611) -> Result<Option<&'a str>> {
12612    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
12613        return Ok(None);
12614    };
12615    let valid = match (field, value.as_str()) {
12616        (
12617            "parent_close_policy",
12618            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
12619        ) => true,
12620        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
12621            true
12622        }
12623        _ => false,
12624    };
12625    if !valid {
12626        return Err(invalid_recorded_history(
12627            "invalid_child_workflow_policy_history",
12628            sequence,
12629            "supported child workflow policy",
12630            &value.to_string(),
12631            "child workflow history contains an invalid policy",
12632        ));
12633    }
12634    Ok(value.as_str())
12635}
12636
12637fn recorded_child_policies(
12638    events: &[&HistoryEvent],
12639    scheduled: &HistoryEvent,
12640    sequence: u64,
12641) -> Result<RecordedChildPolicies> {
12642    let parent_close_policy =
12643        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
12644            .unwrap_or("abandon")
12645            .to_string();
12646    let cancellation_policy =
12647        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
12648            .unwrap_or("abandon")
12649            .to_string();
12650    for event in events {
12651        for (field, expected) in [
12652            ("parent_close_policy", parent_close_policy.as_str()),
12653            ("cancellation_policy", cancellation_policy.as_str()),
12654        ] {
12655            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
12656                if actual != expected {
12657                    return Err(invalid_recorded_history(
12658                        "child_workflow_policy_history_conflict",
12659                        sequence,
12660                        expected,
12661                        actual,
12662                        "child workflow policy changed between history events",
12663                    ));
12664                }
12665            }
12666        }
12667    }
12668    Ok(RecordedChildPolicies {
12669        parent_close_policy,
12670        cancellation_policy,
12671    })
12672}
12673
12674fn ensure_child_policies_match(
12675    sequence: u64,
12676    recorded: &RecordedChildPolicies,
12677    current: &ChildWorkflowOptions,
12678) -> Result<()> {
12679    for (field, expected, actual) in [
12680        (
12681            "parent_close_policy",
12682            recorded.parent_close_policy.as_str(),
12683            current.parent_close_policy.as_str(),
12684        ),
12685        (
12686            "cancellation_policy",
12687            recorded.cancellation_policy.as_str(),
12688            current.cancellation_policy.as_str(),
12689        ),
12690    ] {
12691        if expected != actual {
12692            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
12693                "child_workflow_policy_changed",
12694                Some(sequence),
12695                Some(expected.to_string()),
12696                Some(actual.to_string()),
12697                format!("child workflow {field} changed during replay"),
12698            )));
12699        }
12700    }
12701    Ok(())
12702}
12703
12704#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12705enum RecordedSnapshotValue<T> {
12706    /// Older history did not persist this field, so it cannot constrain replay.
12707    Unknown,
12708    Known(T),
12709}
12710
12711impl<T: PartialEq> RecordedSnapshotValue<T> {
12712    fn matches_current(&self, current: &Self) -> bool {
12713        match self {
12714            Self::Unknown => true,
12715            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
12716        }
12717    }
12718}
12719
12720#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12721struct ActivityRetrySnapshot {
12722    snapshot_version: RecordedSnapshotValue<Option<u64>>,
12723    max_attempts: RecordedSnapshotValue<Option<u64>>,
12724    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
12725    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12726    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
12727    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12728    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
12729    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
12730}
12731
12732impl ActivityRetrySnapshot {
12733    fn matches_current(&self, current: &Self) -> bool {
12734        self.snapshot_version
12735            .matches_current(&current.snapshot_version)
12736            && self.max_attempts.matches_current(&current.max_attempts)
12737            && self
12738                .backoff_seconds
12739                .matches_current(&current.backoff_seconds)
12740            && self
12741                .start_to_close_timeout
12742                .matches_current(&current.start_to_close_timeout)
12743            && self
12744                .schedule_to_start_timeout
12745                .matches_current(&current.schedule_to_start_timeout)
12746            && self
12747                .schedule_to_close_timeout
12748                .matches_current(&current.schedule_to_close_timeout)
12749            && self
12750                .heartbeat_timeout
12751                .matches_current(&current.heartbeat_timeout)
12752            && self
12753                .non_retryable_error_types
12754                .matches_current(&current.non_retryable_error_types)
12755    }
12756}
12757
12758fn recorded_optional_u64(
12759    object: Option<&serde_json::Map<String, Value>>,
12760    field: &str,
12761) -> RecordedSnapshotValue<Option<u64>> {
12762    match object.and_then(|object| object.get(field)) {
12763        None => RecordedSnapshotValue::Unknown,
12764        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12765        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
12766    }
12767}
12768
12769fn recorded_optional_string(
12770    object: &serde_json::Map<String, Value>,
12771    field: &str,
12772) -> RecordedSnapshotValue<Option<String>> {
12773    match object.get(field) {
12774        None => RecordedSnapshotValue::Unknown,
12775        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12776        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
12777    }
12778}
12779
12780fn recorded_activity_execution_mode(
12781    events: &[&HistoryEvent],
12782    sequence: u64,
12783) -> Result<RecordedSnapshotValue<Option<String>>> {
12784    let mut recorded = RecordedSnapshotValue::Unknown;
12785    for event in events {
12786        for object in [
12787            event.payload.as_object(),
12788            event.payload.get("activity").and_then(Value::as_object),
12789        ]
12790        .into_iter()
12791        .flatten()
12792        {
12793            let mode = match object.get("execution_mode") {
12794                None => None,
12795                Some(Value::Null) => Some(None),
12796                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
12797                Some(_) => {
12798                    return Err(invalid_recorded_history(
12799                        "activity_execution_mode_invalid",
12800                        sequence,
12801                        "null or a non-empty execution mode",
12802                        "invalid execution_mode",
12803                        "activity history contains an invalid execution mode",
12804                    ))
12805                }
12806            };
12807            let legacy_mode = match object.get("local_activity") {
12808                None => None,
12809                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
12810                Some(_) => {
12811                    return Err(invalid_recorded_history(
12812                        "activity_execution_mode_invalid",
12813                        sequence,
12814                        "boolean local_activity",
12815                        "invalid local_activity",
12816                        "activity history contains an invalid local-activity marker",
12817                    ))
12818                }
12819            };
12820            for mode in [mode, legacy_mode].into_iter().flatten() {
12821                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
12822                {
12823                    return Err(invalid_recorded_history(
12824                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
12825                        "activity lifecycle events at one workflow sequence disagree on execution mode",
12826                    ));
12827                }
12828                recorded = RecordedSnapshotValue::Known(mode);
12829            }
12830        }
12831    }
12832    Ok(recorded)
12833}
12834
12835fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
12836    let policy = policy.and_then(Value::as_object);
12837    let backoff_seconds = policy
12838        .and_then(|policy| policy.get("backoff_seconds"))
12839        .and_then(Value::as_array)
12840        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12841        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
12842    let mut non_retryable_error_types = Vec::new();
12843    for error_type in policy
12844        .and_then(|policy| policy.get("non_retryable_error_types"))
12845        .and_then(Value::as_array)
12846        .into_iter()
12847        .flatten()
12848        .filter_map(Value::as_str)
12849        .map(str::trim)
12850        .filter(|error_type| !error_type.is_empty())
12851    {
12852        if !non_retryable_error_types
12853            .iter()
12854            .any(|recorded| recorded == error_type)
12855        {
12856            non_retryable_error_types.push(error_type.to_string());
12857        }
12858    }
12859
12860    ActivityRetrySnapshot {
12861        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
12862        max_attempts: recorded_optional_u64(policy, "max_attempts"),
12863        backoff_seconds,
12864        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
12865        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
12866        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
12867        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
12868        non_retryable_error_types: if policy
12869            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
12870        {
12871            RecordedSnapshotValue::Known(non_retryable_error_types)
12872        } else {
12873            RecordedSnapshotValue::Unknown
12874        },
12875    }
12876}
12877
12878fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
12879    let policy = options.retry_policy.as_ref();
12880    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
12881        Some(Value::Null) => None,
12882        Some(value) => value_as_u64(value),
12883        None => Some(1),
12884    };
12885    let backoff_seconds = policy
12886        .and_then(|policy| policy.get("backoff_seconds"))
12887        .and_then(Value::as_array)
12888        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12889        .unwrap_or_default();
12890    let non_retryable_error_types = policy
12891        .and_then(|policy| policy.get("non_retryable_error_types"))
12892        .and_then(Value::as_array)
12893        .into_iter()
12894        .flatten()
12895        .filter_map(Value::as_str)
12896        .map(str::to_string)
12897        .collect();
12898
12899    ActivityRetrySnapshot {
12900        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
12901        max_attempts: RecordedSnapshotValue::Known(max_attempts),
12902        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
12903        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
12904        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
12905        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
12906        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
12907        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
12908    }
12909}
12910
12911fn activity_options_description(options: &RecordedActivityOptions) -> String {
12912    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
12913}
12914
12915impl RecordedCommand {
12916    fn sequence(&self) -> u64 {
12917        match self {
12918            Self::CancellationGroup { sequence, .. }
12919            | Self::CancellationScope { sequence, .. }
12920            | Self::CancellationBoundary { sequence, .. }
12921            | Self::Activity { sequence, .. }
12922            | Self::Timer { sequence, .. }
12923            | Self::ChildWorkflow { sequence, .. }
12924            | Self::SignalWait { sequence, .. }
12925            | Self::ConditionWait { sequence, .. }
12926            | Self::SearchAttributes { sequence, .. }
12927            | Self::SideEffect { sequence, .. }
12928            | Self::VersionMarker { sequence, .. }
12929            | Self::Memo { sequence, .. } => *sequence,
12930            Self::ServiceOperation { sequence, .. } => *sequence,
12931        }
12932    }
12933
12934    fn shape(&self) -> &'static str {
12935        match self {
12936            Self::CancellationScope { .. } => "cancellation scope",
12937            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
12938                "cooperative cancellation"
12939            }
12940            Self::Activity { .. } => "activity",
12941            Self::Timer { .. } => "timer",
12942            Self::ChildWorkflow { .. } => "child workflow",
12943            Self::SignalWait { .. } => "signal wait",
12944            Self::ConditionWait { .. } => "condition wait",
12945            Self::SearchAttributes { .. } => "search-attribute update",
12946            Self::SideEffect { .. } => "side effect",
12947            Self::VersionMarker { .. } => "version marker",
12948            Self::Memo { .. } => "memo upsert",
12949            Self::ServiceOperation { .. } => "service operation",
12950        }
12951    }
12952}
12953
12954fn ensure_version_supported(
12955    change_id: &str,
12956    version: i32,
12957    min_supported: i32,
12958    max_supported: i32,
12959    sequence: u64,
12960) -> Result<()> {
12961    if (min_supported..=max_supported).contains(&version) {
12962        return Ok(());
12963    }
12964    Err(Error::NonDeterministicReplay(ReplayFailure::new(
12965        "version_marker_incompatible_range",
12966        (sequence != 0).then_some(sequence),
12967        Some(format!("{min_supported}..={max_supported}")),
12968        Some(format!("{change_id}:{version}")),
12969        "recorded workflow version is outside the range supported by current code",
12970    )))
12971}
12972
12973#[derive(Clone, Debug)]
12974struct ResumeSignal {
12975    signal_name: String,
12976    arguments: Vec<AvroValue>,
12977}
12978
12979const MAX_PARALLEL_OPERATIONS: usize = 1000;
12980
12981fn parallel_group_prefix(kind: &str) -> &'static str {
12982    match kind {
12983        "activity" => "parallel-activities",
12984        "child" => "parallel-children",
12985        "timer" => "parallel-timers",
12986        _ => "parallel-calls",
12987    }
12988}
12989
12990fn parallel_group_entry(
12991    base_sequence: u64,
12992    size: usize,
12993    index: usize,
12994    kind: &str,
12995) -> ParallelGroupMetadata {
12996    ParallelGroupMetadata {
12997        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
12998        parallel_group_kind: kind.to_string(),
12999        parallel_group_base_sequence: base_sequence,
13000        parallel_group_size: size,
13001        parallel_group_index: index,
13002        parallel_group_mode: None,
13003        selection_member_key: None,
13004        selection_member_index: None,
13005        selection_member_base_sequence: None,
13006        selection_member_size: None,
13007        selection_member_kind: None,
13008    }
13009}
13010
13011struct SelectionMemberMetadata {
13012    key: SelectionKey,
13013    index: usize,
13014    base_sequence: u64,
13015    size: usize,
13016    kind: String,
13017}
13018
13019fn selection_group_entry(
13020    base_sequence: u64,
13021    size: usize,
13022    index: usize,
13023    kind: &str,
13024    member: &SelectionMemberMetadata,
13025) -> ParallelGroupMetadata {
13026    ParallelGroupMetadata {
13027        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
13028        parallel_group_kind: kind.to_string(),
13029        parallel_group_base_sequence: base_sequence,
13030        parallel_group_size: size,
13031        parallel_group_index: index,
13032        parallel_group_mode: Some("select".to_string()),
13033        selection_member_key: Some(member.key.clone()),
13034        selection_member_index: Some(member.index),
13035        selection_member_base_sequence: Some(member.base_sequence),
13036        selection_member_size: Some(member.size),
13037        selection_member_kind: Some(member.kind.clone()),
13038    }
13039}
13040
13041fn apply_parallel_group_path(
13042    command: &mut serde_json::Map<String, Value>,
13043    path: &[ParallelGroupMetadata],
13044) {
13045    let Some(inner) = path.last() else {
13046        return;
13047    };
13048    command.insert(
13049        "parallel_group_id".to_string(),
13050        json!(inner.parallel_group_id),
13051    );
13052    command.insert(
13053        "parallel_group_kind".to_string(),
13054        json!(inner.parallel_group_kind),
13055    );
13056    command.insert(
13057        "parallel_group_base_sequence".to_string(),
13058        json!(inner.parallel_group_base_sequence),
13059    );
13060    command.insert(
13061        "parallel_group_size".to_string(),
13062        json!(inner.parallel_group_size),
13063    );
13064    command.insert(
13065        "parallel_group_index".to_string(),
13066        json!(inner.parallel_group_index),
13067    );
13068    if let Some(mode) = &inner.parallel_group_mode {
13069        command.insert("parallel_group_mode".to_string(), json!(mode));
13070    }
13071    if let Some(key) = &inner.selection_member_key {
13072        command.insert("selection_member_key".to_string(), json!(key));
13073    }
13074    if let Some(index) = inner.selection_member_index {
13075        command.insert("selection_member_index".to_string(), json!(index));
13076    }
13077    if let Some(base_sequence) = inner.selection_member_base_sequence {
13078        command.insert(
13079            "selection_member_base_sequence".to_string(),
13080            json!(base_sequence),
13081        );
13082    }
13083    if let Some(size) = inner.selection_member_size {
13084        command.insert("selection_member_size".to_string(), json!(size));
13085    }
13086    if let Some(kind) = &inner.selection_member_kind {
13087        command.insert("selection_member_kind".to_string(), json!(kind));
13088    }
13089    command.insert("parallel_group_path".to_string(), json!(path));
13090}
13091
13092fn ensure_parallel_path_matches(
13093    sequence: u64,
13094    recorded: Option<&[ParallelGroupMetadata]>,
13095    expected: &[ParallelGroupMetadata],
13096) -> Result<()> {
13097    match (recorded, expected.is_empty()) {
13098        (None, true) => Ok(()),
13099        (Some(recorded), false) if recorded == expected => Ok(()),
13100        (None, false) => Err(invalid_recorded_history(
13101            "parallel_group_metadata_missing",
13102            sequence,
13103            &serde_json::to_string(expected).unwrap_or_default(),
13104            "<missing>",
13105            "recorded parallel member is missing its durable group path",
13106        )),
13107        (Some(recorded), true) => Err(invalid_recorded_history(
13108            "parallel_group_shape_mismatch",
13109            sequence,
13110            "sequential command",
13111            &serde_json::to_string(recorded).unwrap_or_default(),
13112            "recorded command belonged to a parallel group but current code schedules it sequentially",
13113        )),
13114        (Some(recorded), false) => Err(invalid_recorded_history(
13115            "parallel_group_shape_mismatch",
13116            sequence,
13117            &serde_json::to_string(recorded).unwrap_or_default(),
13118            &serde_json::to_string(expected).unwrap_or_default(),
13119            "recorded parallel-group identity or path changed during replay",
13120        )),
13121    }
13122}
13123
13124#[derive(Clone, Debug)]
13125enum ParallelShape {
13126    Leaf,
13127    Group(Vec<ParallelShape>),
13128}
13129
13130struct ParallelDescriptor {
13131    operation: ParallelOperation,
13132    offset: usize,
13133    member_path: Vec<usize>,
13134    group_path: Vec<ParallelGroupMetadata>,
13135}
13136
13137fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
13138    operations
13139        .iter()
13140        .map(|operation| match operation {
13141            ParallelOperation::Group(children) => parallel_leaf_count(children),
13142            _ => 1,
13143        })
13144        .sum()
13145}
13146
13147fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
13148    match operation {
13149        ParallelOperation::Activity { .. } => Some("activity"),
13150        ParallelOperation::ChildWorkflow { .. } => Some("child"),
13151        ParallelOperation::Timer(_) => Some("timer"),
13152        ParallelOperation::Signal(_) => Some("signal"),
13153        ParallelOperation::Condition { .. } => Some("condition"),
13154        ParallelOperation::Group(children) => parallel_group_kind(children),
13155    }
13156}
13157
13158fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
13159    let mut kind = None;
13160    for operation in operations {
13161        let Some(operation_kind) = parallel_operation_kind(operation) else {
13162            continue;
13163        };
13164        match kind {
13165            None => kind = Some(operation_kind),
13166            Some(current) if current == operation_kind => {}
13167            Some(_) => return Some("mixed"),
13168        }
13169    }
13170    kind
13171}
13172
13173fn validate_parallel_operations(
13174    operations: &[ParallelOperation],
13175    member_path: &mut Vec<usize>,
13176    root: bool,
13177) -> Result<()> {
13178    let leaves = parallel_leaf_count(operations);
13179    if leaves > MAX_PARALLEL_OPERATIONS {
13180        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13181            reason: "fan_out_limit_exceeded",
13182            member_path: member_path.clone(),
13183            message: format!(
13184                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13185            ),
13186        }));
13187    }
13188    if !root && operations.is_empty() {
13189        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13190            reason: "nested_group_empty",
13191            member_path: member_path.clone(),
13192            message: "a nested group must contain at least one durable leaf".to_string(),
13193        }));
13194    }
13195
13196    for (index, operation) in operations.iter().enumerate() {
13197        member_path.push(index);
13198        match operation {
13199            ParallelOperation::Activity {
13200                options, arguments, ..
13201            } => {
13202                options
13203                    .validate()
13204                    .map_err(|error| Error::InvalidActivityOptions(error))?;
13205                if let Err(error) = arguments {
13206                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13207                        reason: "arguments_invalid",
13208                        member_path: member_path.clone(),
13209                        message: error.to_string(),
13210                    }));
13211                }
13212            }
13213            ParallelOperation::ChildWorkflow {
13214                options, arguments, ..
13215            } => {
13216                validate_parallel_child_options(options)?;
13217                if let Err(error) = arguments {
13218                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13219                        reason: "arguments_invalid",
13220                        member_path: member_path.clone(),
13221                        message: error.to_string(),
13222                    }));
13223                }
13224            }
13225            ParallelOperation::Timer(duration)
13226                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
13227            {
13228                return Err(Error::TimerDurationOverflow);
13229            }
13230            ParallelOperation::Timer(_) => {}
13231            ParallelOperation::Signal(signal_name) => {
13232                validate_user_signal_name(signal_name)?;
13233                if signal_name.trim().is_empty() {
13234                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13235                        reason: "signal_name_empty",
13236                        member_path: member_path.clone(),
13237                        message: "signal wait name must not be empty".to_string(),
13238                    }));
13239                }
13240            }
13241            ParallelOperation::Condition { options, .. } => {
13242                options.validate()?;
13243            }
13244            ParallelOperation::Group(children) => {
13245                validate_parallel_operations(children, member_path, false)?;
13246            }
13247        }
13248        member_path.pop();
13249    }
13250    Ok(())
13251}
13252
13253fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
13254    if options.task_queue.trim().is_empty() {
13255        return Err(Error::InvalidChildWorkflowOptions(
13256            "task_queue must not be empty".to_string(),
13257        ));
13258    }
13259    for (name, value) in [
13260        (
13261            "execution_timeout_seconds",
13262            options.execution_timeout_seconds,
13263        ),
13264        ("run_timeout_seconds", options.run_timeout_seconds),
13265    ] {
13266        if value == Some(0) {
13267            return Err(Error::InvalidChildWorkflowOptions(format!(
13268                "{name} must be at least 1"
13269            )));
13270        }
13271    }
13272    if options
13273        .retry_policy
13274        .as_ref()
13275        .is_some_and(|policy| policy.max_attempts == Some(0))
13276    {
13277        return Err(Error::InvalidChildWorkflowOptions(
13278            "retry_policy.max_attempts must be at least 1".to_string(),
13279        ));
13280    }
13281    Ok(())
13282}
13283
13284fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
13285    ParallelShape::Group(
13286        operations
13287            .iter()
13288            .map(|operation| match operation {
13289                ParallelOperation::Group(children) => parallel_shape(children),
13290                _ => ParallelShape::Leaf,
13291            })
13292            .collect(),
13293    )
13294}
13295
13296fn parallel_descriptors(
13297    operations: Vec<ParallelOperation>,
13298    base_sequence: u64,
13299) -> Result<Vec<ParallelDescriptor>> {
13300    let size = parallel_leaf_count(&operations);
13301    let kind = parallel_group_kind(&operations).unwrap_or("activity");
13302    let mut descriptors = Vec::with_capacity(size);
13303    let mut cursor = 0;
13304
13305    for (index, operation) in operations.into_iter().enumerate() {
13306        match operation {
13307            ParallelOperation::Group(children) => {
13308                let child_base = base_sequence
13309                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13310                    .ok_or(Error::TimerDurationOverflow)?;
13311                for mut descriptor in parallel_descriptors(children, child_base)? {
13312                    let outer_index = cursor + descriptor.offset;
13313                    descriptor.group_path.insert(
13314                        0,
13315                        parallel_group_entry(base_sequence, size, outer_index, kind),
13316                    );
13317                    descriptor.member_path.insert(0, index);
13318                    descriptor.offset = outer_index;
13319                    descriptors.push(descriptor);
13320                }
13321                cursor = descriptors.len();
13322            }
13323            operation => {
13324                descriptors.push(ParallelDescriptor {
13325                    operation,
13326                    offset: cursor,
13327                    member_path: vec![index],
13328                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
13329                });
13330                cursor += 1;
13331            }
13332        }
13333    }
13334    Ok(descriptors)
13335}
13336
13337enum ParallelLeafCall {
13338    Activity(ActivityCall),
13339    ChildWorkflow(ChildWorkflowCall),
13340    Timer(TimerCall),
13341    Signal(SignalCall),
13342    Condition(ConditionWaitCall),
13343}
13344
13345fn parallel_leaf_call(
13346    ctx: &WorkflowContext,
13347    operation: ParallelOperation,
13348    parallel_group_path: Vec<ParallelGroupMetadata>,
13349) -> ParallelLeafCall {
13350    match operation {
13351        ParallelOperation::Activity {
13352            activity_type,
13353            options,
13354            arguments,
13355        } => ParallelLeafCall::Activity(ActivityCall {
13356            ctx: ctx.clone(),
13357            activity_type,
13358            options,
13359            worker_session: None,
13360            args: Some(arguments),
13361            scheduled: false,
13362            local: false,
13363            local_result: None,
13364            parallel_group_path,
13365        }),
13366        ParallelOperation::ChildWorkflow {
13367            workflow_type,
13368            options,
13369            arguments,
13370        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
13371            ctx: ctx.clone(),
13372            workflow_type,
13373            options,
13374            args: Some(arguments),
13375            scheduled: false,
13376            matched_pending: false,
13377            parallel_group_path,
13378        }),
13379        ParallelOperation::Timer(duration) => {
13380            let delay_seconds = duration
13381                .as_secs()
13382                .checked_add(u64::from(duration.subsec_nanos() > 0));
13383            ParallelLeafCall::Timer(TimerCall {
13384                ctx: ctx.clone(),
13385                delay_seconds,
13386                scheduled: false,
13387                matched_pending: false,
13388                parallel_group_path,
13389            })
13390        }
13391        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
13392            ctx: ctx.clone(),
13393            signal_name,
13394            runtime_reserved_allowed: false,
13395            opened_wait: false,
13396            matched_pending: false,
13397            parallel_group_path,
13398        }),
13399        ParallelOperation::Condition { options, predicate } => {
13400            ParallelLeafCall::Condition(ConditionWaitCall {
13401                ctx: ctx.clone(),
13402                options,
13403                predicate,
13404                occurrence_id: None,
13405                opened_wait: false,
13406                parallel_group_path,
13407            })
13408        }
13409        ParallelOperation::Group(_) => {
13410            unreachable!("parallel descriptors contain only durable leaves")
13411        }
13412    }
13413}
13414
13415impl ParallelLeafCall {
13416    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
13417        match self {
13418            Self::Activity(call) => Pin::new(call)
13419                .poll_avro_value(cx)
13420                .map_ok(ParallelAvroResult::Activity),
13421            Self::ChildWorkflow(call) => Pin::new(call)
13422                .poll_avro_value(cx)
13423                .map_ok(ParallelAvroResult::ChildWorkflow),
13424            Self::Timer(call) => Pin::new(call)
13425                .poll(cx)
13426                .map_ok(|()| ParallelAvroResult::Timer),
13427            Self::Signal(call) => Pin::new(call)
13428                .poll_avro_value(cx)
13429                .map_ok(ParallelAvroResult::Signal),
13430            Self::Condition(call) => Pin::new(call)
13431                .poll(cx)
13432                .map_ok(ParallelAvroResult::Condition),
13433        }
13434    }
13435}
13436
13437struct ParallelLeaf {
13438    call: ParallelLeafCall,
13439    sequence: u64,
13440    member_path: Vec<usize>,
13441    group_path: Vec<ParallelGroupMetadata>,
13442    result: Option<ParallelAvroResult>,
13443}
13444
13445/// Future returned by [`WorkflowContext::parallel`].
13446pub struct ParallelCall {
13447    ctx: WorkflowContext,
13448    operations: Option<Vec<ParallelOperation>>,
13449    shape: Option<ParallelShape>,
13450    leaves: Vec<ParallelLeaf>,
13451    pending_scope_delivery: bool,
13452    worker_session: Option<WorkerSessionOptions>,
13453}
13454
13455impl ParallelCall {
13456    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
13457        Self {
13458            ctx,
13459            operations: Some(operations),
13460            shape: None,
13461            leaves: Vec::new(),
13462            pending_scope_delivery: false,
13463            worker_session: None,
13464        }
13465    }
13466
13467    fn initialize(&mut self) -> Result<()> {
13468        if let Some(session) = &self.worker_session {
13469            session.to_wire()?;
13470        }
13471        let operations = self.operations.take().unwrap_or_default();
13472        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
13473        self.shape = Some(parallel_shape(&operations));
13474        if operations.is_empty() {
13475            return Ok(());
13476        }
13477
13478        let base_sequence = {
13479            let state = self
13480                .ctx
13481                .state
13482                .lock()
13483                .map_err(|_| Error::WorkflowStatePoisoned)?;
13484            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13485                recorded.sequence()
13486            } else {
13487                let last = state
13488                    .recorded_commands
13489                    .last()
13490                    .map(RecordedCommand::sequence)
13491                    .unwrap_or(0);
13492                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
13493                    .and_then(|sequence| sequence.checked_add(1))
13494                    .ok_or_else(|| {
13495                        Error::InvalidParallelGroup(ParallelGroupError {
13496                            reason: "sequence_overflow",
13497                            member_path: Vec::new(),
13498                            message: "parallel group sequence identity overflowed u64".to_string(),
13499                        })
13500                    })?
13501            }
13502        };
13503
13504        let descriptors = parallel_descriptors(operations, base_sequence)?;
13505        {
13506            let mut state = self
13507                .ctx
13508                .state
13509                .lock()
13510                .map_err(|_| Error::WorkflowStatePoisoned)?;
13511            let cursor = state.command_cursor;
13512            self.ctx.validate_scope_membership(&mut state, cursor)?;
13513            if state.prepare_parallel_scope_cancellation(&descriptors)? {
13514                self.pending_scope_delivery = true;
13515                return Ok(());
13516            }
13517            state.expand_cancellation_group(&descriptors)?;
13518            state.prepare_group_cancellation(&descriptors)?;
13519        }
13520        self.leaves = descriptors
13521            .into_iter()
13522            .map(|descriptor| {
13523                let mut call = parallel_leaf_call(
13524                    &self.ctx,
13525                    descriptor.operation,
13526                    descriptor.group_path.clone(),
13527                );
13528                if let (Some(session), ParallelLeafCall::Activity(activity)) =
13529                    (&self.worker_session, &mut call)
13530                {
13531                    activity.worker_session = Some(session.clone());
13532                }
13533                ParallelLeaf {
13534                    call,
13535                    sequence: base_sequence + descriptor.offset as u64,
13536                    member_path: descriptor.member_path,
13537                    group_path: descriptor.group_path,
13538                    result: None,
13539                }
13540            })
13541            .collect();
13542        Ok(())
13543    }
13544
13545    fn poll_avro_value(
13546        mut self: Pin<&mut Self>,
13547        cx: &mut TaskContext<'_>,
13548    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
13549        if self.operations.is_some() {
13550            if let Err(error) = self.initialize() {
13551                return Poll::Ready(Err(error));
13552            }
13553        }
13554        if self.pending_scope_delivery {
13555            return Poll::Pending;
13556        }
13557        if self.leaves.is_empty() {
13558            return Poll::Ready(Ok(Vec::new()));
13559        }
13560
13561        let mut failures = Vec::new();
13562        let mut pending = false;
13563        for (index, leaf) in self.leaves.iter_mut().enumerate() {
13564            if leaf.result.is_some() {
13565                continue;
13566            }
13567            match leaf.call.poll_avro_value(cx) {
13568                Poll::Ready(Ok(result)) => leaf.result = Some(result),
13569                Poll::Ready(Err(error)) => failures.push((index, error)),
13570                Poll::Pending => pending = true,
13571            }
13572        }
13573
13574        if !failures.is_empty() {
13575            if let Some(position) = failures
13576                .iter()
13577                .position(|(_, error)| workflow_task_integrity_error(error))
13578            {
13579                return Poll::Ready(Err(failures.remove(position).1));
13580            }
13581            if self
13582                .ctx
13583                .state
13584                .lock()
13585                .map_err(|_| Error::WorkflowStatePoisoned)?
13586                .cancellation_delivery_intent
13587                .is_some()
13588            {
13589                return Poll::Pending;
13590            }
13591            if let Some(position) = failures
13592                .iter()
13593                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
13594            {
13595                return Poll::Ready(Err(failures.remove(position).1));
13596            }
13597            failures.sort_by_key(|(index, _)| *index);
13598            let (failed_index, cause) = failures.remove(0);
13599            let failed = &self.leaves[failed_index];
13600            let completed = self
13601                .leaves
13602                .iter()
13603                .filter_map(|leaf| {
13604                    leaf.result
13605                        .clone()
13606                        .and_then(|result| result.into_json_result().ok())
13607                        .map(|result| ParallelCompletion {
13608                            member_path: leaf.member_path.clone(),
13609                            result,
13610                        })
13611                })
13612                .collect();
13613            let group_id = failed
13614                .group_path
13615                .first()
13616                .map(|entry| entry.parallel_group_id.clone())
13617                .unwrap_or_default();
13618            let sequences = self
13619                .leaves
13620                .iter()
13621                .map(|leaf| leaf.sequence)
13622                .collect::<Vec<_>>();
13623            self.ctx
13624                .state
13625                .lock()
13626                .map_err(|_| Error::WorkflowStatePoisoned)?
13627                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
13628            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
13629                group_id,
13630                member_path: failed.member_path.clone(),
13631                group_path: failed.group_path.clone(),
13632                completed,
13633                cause: Box::new(cause),
13634            })));
13635        }
13636        if pending
13637            || self
13638                .ctx
13639                .state
13640                .lock()
13641                .map_err(|_| Error::WorkflowStatePoisoned)?
13642                .cancellation_delivery_intent
13643                .is_some()
13644        {
13645            return Poll::Pending;
13646        }
13647
13648        let mut flat_results = self
13649            .leaves
13650            .iter_mut()
13651            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
13652            .collect::<Vec<_>>()
13653            .into_iter();
13654        let results = parallel_results_for_shape(
13655            self.shape.as_ref().expect("initialized parallel shape"),
13656            &mut flat_results,
13657        );
13658        let sequences = self
13659            .leaves
13660            .iter()
13661            .map(|leaf| leaf.sequence)
13662            .collect::<Vec<_>>();
13663        self.ctx
13664            .state
13665            .lock()
13666            .map_err(|_| Error::WorkflowStatePoisoned)?
13667            .advance_cancellation_sequences(&sequences, None);
13668        Poll::Ready(Ok(match results {
13669            ParallelAvroResult::Group(results) => results,
13670            ParallelAvroResult::Activity(_)
13671            | ParallelAvroResult::ChildWorkflow(_)
13672            | ParallelAvroResult::Timer
13673            | ParallelAvroResult::Signal(_)
13674            | ParallelAvroResult::Condition(_) => {
13675                unreachable!("root parallel shape is a group")
13676            }
13677        }))
13678    }
13679}
13680
13681fn parallel_results_for_shape(
13682    shape: &ParallelShape,
13683    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
13684) -> ParallelAvroResult {
13685    match shape {
13686        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
13687        ParallelShape::Group(children) => ParallelAvroResult::Group(
13688            children
13689                .iter()
13690                .map(|child| parallel_results_for_shape(child, flat_results))
13691                .collect(),
13692        ),
13693    }
13694}
13695
13696impl Future for ParallelCall {
13697    type Output = Result<Vec<ParallelResult>>;
13698
13699    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13700        self.poll_avro_value(cx)
13701            .map_ok(|results| {
13702                results
13703                    .into_iter()
13704                    .map(ParallelAvroResult::into_json_result)
13705                    .collect::<Result<Vec<_>>>()
13706            })
13707            .map_ok(|result| result)
13708            .flatten_result()
13709    }
13710}
13711
13712#[derive(Clone, Debug)]
13713struct SelectionMemberPlan {
13714    key: SelectionKey,
13715    index: usize,
13716    base_sequence: u64,
13717    size: usize,
13718    kind: String,
13719    shape: ParallelShape,
13720    leaf_start: usize,
13721}
13722
13723fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
13724    match operation {
13725        ParallelOperation::Activity { .. } => "activity",
13726        ParallelOperation::ChildWorkflow { .. } => "child",
13727        ParallelOperation::Timer(_) => "timer",
13728        ParallelOperation::Signal(_) => "signal",
13729        ParallelOperation::Condition { .. } => "condition",
13730        ParallelOperation::Group(_) => "group",
13731    }
13732}
13733
13734fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
13735    match operation {
13736        ParallelOperation::Group(children) => parallel_shape(children),
13737        _ => ParallelShape::Leaf,
13738    }
13739}
13740
13741fn selection_descriptors(
13742    operations: Vec<(SelectionKey, ParallelOperation)>,
13743    base_sequence: u64,
13744) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
13745    if operations.is_empty() {
13746        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13747            reason: "selection_empty",
13748            member_path: Vec::new(),
13749            message: "durable selection requires at least one operation".to_string(),
13750        }));
13751    }
13752    let operation_refs = operations
13753        .iter()
13754        .map(|(_, operation)| operation)
13755        .collect::<Vec<_>>();
13756    let total_size = operation_refs
13757        .iter()
13758        .map(|operation| match operation {
13759            ParallelOperation::Group(children) => parallel_leaf_count(children),
13760            _ => 1,
13761        })
13762        .sum::<usize>();
13763    if total_size > MAX_PARALLEL_OPERATIONS {
13764        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13765            reason: "fan_out_limit_exceeded",
13766            member_path: Vec::new(),
13767            message: format!(
13768                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13769            ),
13770        }));
13771    }
13772    let group_kind = {
13773        let mut kind = None;
13774        for operation in &operation_refs {
13775            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
13776            match kind {
13777                None => kind = Some(operation_kind),
13778                Some(current) if current == operation_kind => {}
13779                Some(_) => {
13780                    kind = Some("mixed");
13781                    break;
13782                }
13783            }
13784        }
13785        kind.unwrap_or("mixed")
13786    };
13787
13788    let mut descriptors = Vec::with_capacity(total_size);
13789    let mut members = Vec::with_capacity(operations.len());
13790    let mut cursor = 0usize;
13791    let mut seen_keys: Vec<SelectionKey> = Vec::new();
13792    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
13793        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
13794            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13795                reason: "selection_key_invalid",
13796                member_path: vec![member_index],
13797                message: "selection member keys must be non-empty strings or non-negative integers"
13798                    .to_string(),
13799            }));
13800        }
13801        if seen_keys.contains(&key) {
13802            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13803                reason: "selection_key_duplicate",
13804                member_path: vec![member_index],
13805                message: format!("selection member key {key:?} is duplicated"),
13806            }));
13807        }
13808        seen_keys.push(key.clone());
13809        let member_size = match &operation {
13810            ParallelOperation::Group(children) => parallel_leaf_count(children),
13811            _ => 1,
13812        };
13813        if member_size == 0 {
13814            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13815                reason: "selection_member_empty",
13816                member_path: vec![member_index],
13817                message: "a selection member must contain at least one durable leaf".to_string(),
13818            }));
13819        }
13820        let member_base = base_sequence
13821            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13822            .ok_or(Error::TimerDurationOverflow)?;
13823        let member_kind = selection_operation_kind(&operation).to_string();
13824        let member_shape = selection_operation_shape(&operation);
13825        let leaf_start = descriptors.len();
13826        match operation {
13827            ParallelOperation::Group(children) => {
13828                validate_parallel_operations(&children, &mut vec![member_index], false)?;
13829                for mut descriptor in parallel_descriptors(children, member_base)? {
13830                    let flat_index = cursor + descriptor.offset;
13831                    descriptor.group_path.insert(
13832                        0,
13833                        selection_group_entry(
13834                            base_sequence,
13835                            total_size,
13836                            flat_index,
13837                            group_kind,
13838                            &SelectionMemberMetadata {
13839                                key: key.clone(),
13840                                index: member_index,
13841                                base_sequence: member_base,
13842                                size: member_size,
13843                                kind: member_kind.clone(),
13844                            },
13845                        ),
13846                    );
13847                    descriptor.member_path.insert(0, member_index);
13848                    descriptor.offset = flat_index;
13849                    descriptors.push(descriptor);
13850                }
13851            }
13852            operation => {
13853                validate_parallel_operations(
13854                    std::slice::from_ref(&operation),
13855                    &mut Vec::new(),
13856                    true,
13857                )?;
13858                descriptors.push(ParallelDescriptor {
13859                    operation,
13860                    offset: cursor,
13861                    member_path: vec![member_index],
13862                    group_path: vec![selection_group_entry(
13863                        base_sequence,
13864                        total_size,
13865                        cursor,
13866                        group_kind,
13867                        &SelectionMemberMetadata {
13868                            key: key.clone(),
13869                            index: member_index,
13870                            base_sequence: member_base,
13871                            size: member_size,
13872                            kind: member_kind.clone(),
13873                        },
13874                    )],
13875                });
13876            }
13877        }
13878        members.push(SelectionMemberPlan {
13879            key,
13880            index: member_index,
13881            base_sequence: member_base,
13882            size: member_size,
13883            kind: member_kind,
13884            shape: member_shape,
13885            leaf_start,
13886        });
13887        cursor += member_size;
13888    }
13889    Ok((descriptors, members))
13890}
13891
13892struct SelectionLeaf {
13893    call: ParallelLeafCall,
13894    outcome: Option<Result<ParallelAvroResult>>,
13895}
13896
13897/// Stable reference to one member of a durable selection group.
13898#[derive(Clone)]
13899pub struct DurableOperationHandle {
13900    ctx: WorkflowContext,
13901    pub key: SelectionKey,
13902    pub index: usize,
13903    pub kind: String,
13904    pub identity: String,
13905    pub base_sequence: u64,
13906    pub size: usize,
13907    pub selection_group_id: String,
13908    shape: ParallelShape,
13909}
13910
13911impl std::fmt::Debug for DurableOperationHandle {
13912    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13913        formatter
13914            .debug_struct("DurableOperationHandle")
13915            .field("key", &self.key)
13916            .field("index", &self.index)
13917            .field("kind", &self.kind)
13918            .field("identity", &self.identity)
13919            .field("base_sequence", &self.base_sequence)
13920            .field("size", &self.size)
13921            .field("selection_group_id", &self.selection_group_id)
13922            .finish()
13923    }
13924}
13925
13926impl DurableOperationHandle {
13927    /// Await this member after another member has already won the selection.
13928    pub fn await_result(&self) -> DurableOperationAwaitCall {
13929        DurableOperationAwaitCall {
13930            handle: self.clone(),
13931        }
13932    }
13933
13934    /// Request cancellation without affecting siblings. The future resolves
13935    /// to unit; only `SelectionOperationCancelled` history proves cancellation
13936    /// beat a concurrently committed terminal result.
13937    pub fn cancel(&self) -> CancelDurableOperationCall {
13938        CancelDurableOperationCall {
13939            handle: self.clone(),
13940            emitted: false,
13941        }
13942    }
13943}
13944
13945/// The one winner committed for a durable selection group.
13946#[derive(Debug)]
13947pub struct SelectionResult {
13948    pub key: SelectionKey,
13949    pub index: usize,
13950    pub kind: String,
13951    pub identity: String,
13952    pub value: Option<ParallelResult>,
13953    pub failure: Option<Error>,
13954    pub winner: DurableOperationHandle,
13955    pub handles: Vec<DurableOperationHandle>,
13956}
13957
13958impl SelectionResult {
13959    pub fn succeeded(&self) -> bool {
13960        self.failure.is_none()
13961    }
13962
13963    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
13964        self.handles.iter().find(|handle| &handle.key == key)
13965    }
13966
13967    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
13968        self.handles
13969            .iter()
13970            .filter(|handle| handle.index != self.index)
13971            .collect()
13972    }
13973
13974    pub fn into_result(self) -> Result<ParallelResult> {
13975        match (self.value, self.failure) {
13976            (Some(value), None) => Ok(value),
13977            (_, Some(error)) => Err(error),
13978            _ => Err(Error::WorkerLoop(
13979                "selection result contained neither a value nor a failure".to_string(),
13980            )),
13981        }
13982    }
13983}
13984
13985/// Future returned by [`WorkflowContext::select`].
13986pub struct SelectCall {
13987    ctx: WorkflowContext,
13988    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
13989    members: Vec<SelectionMemberPlan>,
13990    leaves: Vec<SelectionLeaf>,
13991    group_id: Option<String>,
13992}
13993
13994impl SelectCall {
13995    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
13996        Self {
13997            ctx,
13998            operations: Some(operations),
13999            members: Vec::new(),
14000            leaves: Vec::new(),
14001            group_id: None,
14002        }
14003    }
14004
14005    fn initialize(&mut self) -> Result<()> {
14006        let operations = self.operations.take().unwrap_or_default();
14007        let base_sequence = {
14008            let state = self
14009                .ctx
14010                .state
14011                .lock()
14012                .map_err(|_| Error::WorkflowStatePoisoned)?;
14013            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
14014                state.recorded_commands.get(state.command_cursor)
14015            {
14016                *sequence
14017            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
14018            {
14019                marker.selection_group_base_sequence
14020            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
14021                recorded.sequence()
14022            } else {
14023                let last = state
14024                    .recorded_commands
14025                    .last()
14026                    .map(RecordedCommand::sequence)
14027                    .unwrap_or(0);
14028                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
14029                    .and_then(|sequence| sequence.checked_add(1))
14030                    .ok_or(Error::TimerDurationOverflow)?
14031            }
14032        };
14033        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
14034        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
14035        {
14036            let mut state = self
14037                .ctx
14038                .state
14039                .lock()
14040                .map_err(|_| Error::WorkflowStatePoisoned)?;
14041            state.expand_cancellation_group(&descriptors)?;
14042            state.prepare_group_cancellation(&descriptors)?;
14043        }
14044        self.leaves = descriptors
14045            .into_iter()
14046            .map(|descriptor| SelectionLeaf {
14047                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
14048                outcome: None,
14049            })
14050            .collect();
14051        self.members = members;
14052        self.group_id = Some(group_id);
14053        Ok(())
14054    }
14055}
14056
14057impl Future for SelectCall {
14058    type Output = Result<SelectionResult>;
14059
14060    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14061        if self.operations.is_some() {
14062            if let Err(error) = self.initialize() {
14063                return Poll::Ready(Err(error));
14064            }
14065        }
14066
14067        for leaf in &mut self.leaves {
14068            if leaf.outcome.is_some() {
14069                continue;
14070            }
14071            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
14072                if outcome
14073                    .as_ref()
14074                    .err()
14075                    .is_some_and(workflow_task_integrity_error)
14076                {
14077                    return Poll::Ready(outcome.map(|_| unreachable!()));
14078                }
14079                leaf.outcome = Some(outcome);
14080            }
14081        }
14082
14083        if self
14084            .ctx
14085            .state
14086            .lock()
14087            .map_err(|_| Error::WorkflowStatePoisoned)?
14088            .cancellation_delivery_intent
14089            .is_some()
14090        {
14091            return Poll::Pending;
14092        }
14093
14094        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
14095            matches!(
14096                leaf.outcome,
14097                Some(Err(Error::CooperativeCancellationRequested(_)))
14098            )
14099        }) {
14100            return Poll::Ready(
14101                leaf.outcome
14102                    .take()
14103                    .expect("matched cancellation")
14104                    .map(|_| unreachable!()),
14105            );
14106        }
14107
14108        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
14109        let selection_member_range = self
14110            .members
14111            .first()
14112            .map(|member| member.base_sequence)
14113            .zip(self.leaves.len().try_into().ok())
14114            .map(|(base_sequence, size): (u64, u64)| {
14115                base_sequence..base_sequence.saturating_add(size)
14116            });
14117        let marker = {
14118            let mut state = match self.ctx.state.lock() {
14119                Ok(state) => state,
14120                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14121            };
14122            let marker = state
14123                .selection_markers
14124                .get(state.selection_marker_cursor)
14125                .cloned();
14126            if marker.is_none()
14127                && all_members_terminal
14128                && selection_member_range.as_ref().is_some_and(|member_range| {
14129                    state
14130                        .recorded_commands
14131                        .iter()
14132                        .any(|command| member_range.contains(&command.sequence()))
14133                })
14134            {
14135                // Terminal member history can be committed before the server's
14136                // SelectionResolved marker becomes visible to this task. That
14137                // marker is the durable barrier the selection is still waiting
14138                // on, so an otherwise commandless replay remains legitimately
14139                // pending instead of failing as an untracked yield.
14140                state.matched_recorded_pending = true;
14141            }
14142            marker
14143        };
14144        let Some(marker) = marker else {
14145            return Poll::Pending;
14146        };
14147        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
14148            || marker.selection_group_size != self.leaves.len()
14149            || self.members.first().map(|member| member.base_sequence)
14150                != Some(marker.selection_group_base_sequence)
14151        {
14152            return Poll::Ready(Err(invalid_recorded_history(
14153                "selection_group_shape_mismatch",
14154                marker.selection_group_base_sequence,
14155                self.group_id
14156                    .as_deref()
14157                    .unwrap_or("initialized selection group"),
14158                &marker.selection_group_id,
14159                "recorded selection group differs from current workflow code",
14160            )));
14161        }
14162        let Some(member_position) = self.members.iter().position(|member| {
14163            member.key == marker.member_key
14164                && member.index == marker.member_index
14165                && member.base_sequence == marker.member_base_sequence
14166                && member.size == marker.member_size
14167                && member.kind == marker.operation_kind
14168        }) else {
14169            return Poll::Ready(Err(invalid_recorded_history(
14170                "selection_member_shape_mismatch",
14171                marker.member_base_sequence,
14172                "winner member matching current workflow code",
14173                &format!("{:?}", marker.member_key),
14174                "recorded selection winner differs from the authored member identity",
14175            )));
14176        };
14177        let member = self.members[member_position].clone();
14178        let (handles, resolution_sequence) = {
14179            let mut state = match self.ctx.state.lock() {
14180                Ok(state) => state,
14181                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14182            };
14183            let identities = self
14184                .members
14185                .iter()
14186                .map(|candidate| {
14187                    selection_operation_identity(
14188                        &state,
14189                        &candidate.kind,
14190                        candidate.base_sequence,
14191                        candidate.size,
14192                    )
14193                })
14194                .collect::<Vec<_>>();
14195            if let Some((position, missing)) = identities
14196                .iter()
14197                .enumerate()
14198                .find(|(_, identity)| identity.is_empty())
14199                .map(|(position, identity)| (position, identity.clone()))
14200            {
14201                let candidate = &self.members[position];
14202                return Poll::Ready(Err(invalid_recorded_history(
14203                    "selection_operation_identity_missing",
14204                    candidate.base_sequence,
14205                    &format!(
14206                        "durable {} resource identity from scheduled/open history",
14207                        candidate.kind
14208                    ),
14209                    &missing,
14210                    "selection member history is missing its canonical durable identity",
14211                )));
14212            }
14213            let expected_winner_identity = &identities[member_position];
14214            let resolution_sequence = match validated_selection_resolution_sequence(
14215                &state,
14216                &marker,
14217                &member,
14218                expected_winner_identity,
14219            ) {
14220                Ok(sequence) => sequence,
14221                Err(error) => return Poll::Ready(Err(error)),
14222            };
14223            let handles = self
14224                .members
14225                .iter()
14226                .zip(identities)
14227                .map(|(member, identity)| DurableOperationHandle {
14228                    ctx: self.ctx.clone(),
14229                    key: member.key.clone(),
14230                    index: member.index,
14231                    kind: member.kind.clone(),
14232                    identity,
14233                    base_sequence: member.base_sequence,
14234                    size: member.size,
14235                    selection_group_id: marker.selection_group_id.clone(),
14236                    shape: member.shape.clone(),
14237                })
14238                .collect::<Vec<_>>();
14239            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
14240                return Poll::Ready(Err(error));
14241            }
14242            state.selection_marker_cursor += 1;
14243            (handles, resolution_sequence)
14244        };
14245
14246        let mut winner_failure = None;
14247        let mut flat_results = Vec::with_capacity(member.size);
14248        if marker.outcome == "failed" {
14249            let resolution_offset = match resolution_sequence
14250                .checked_sub(member.base_sequence)
14251                .and_then(|offset| usize::try_from(offset).ok())
14252            {
14253                Some(offset) if offset < member.size => offset,
14254                _ => {
14255                    return Poll::Ready(Err(invalid_recorded_history(
14256                        "selection_resolution_event_mismatch",
14257                        member.base_sequence,
14258                        "failure event within selected member bounds",
14259                        &resolution_sequence.to_string(),
14260                        "selection failure event is outside the authored member",
14261                    )))
14262                }
14263            };
14264            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
14265            match leaf.outcome.take() {
14266                Some(Err(error)) => winner_failure = Some(error),
14267                _ => {
14268                    return Poll::Ready(Err(invalid_recorded_history(
14269                        "selection_winner_outcome_mismatch",
14270                        member.base_sequence,
14271                        "exact failed terminal history referenced by SelectionResolved",
14272                        "missing or successful resolution event",
14273                        "selection winner marker disagrees with terminal operation history",
14274                    )))
14275                }
14276            }
14277        } else {
14278            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
14279                match leaf.outcome.take() {
14280                    Some(Ok(result)) => flat_results.push(result),
14281                    Some(Err(_)) => {
14282                        return Poll::Ready(Err(invalid_recorded_history(
14283                            "selection_winner_outcome_mismatch",
14284                            member.base_sequence,
14285                            "fully completed nested selection member",
14286                            "failed durable leaf",
14287                            "completed selection winner contains a failed leaf",
14288                        )))
14289                    }
14290                    None => {
14291                        return Poll::Ready(Err(invalid_recorded_history(
14292                            "selection_winner_unresolved",
14293                            member.base_sequence,
14294                            "terminal history for every completed winner leaf",
14295                            "pending member history",
14296                            "completed SelectionResolved member has an unfinished durable barrier",
14297                        )))
14298                    }
14299                }
14300            }
14301        }
14302        let value = if winner_failure.is_none() {
14303            let mut flat_results = flat_results.into_iter();
14304            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
14305            match value.into_json_result() {
14306                Ok(value) => Some(value),
14307                Err(error) => return Poll::Ready(Err(error)),
14308            }
14309        } else {
14310            None
14311        };
14312        let winner = handles[member_position].clone();
14313        self.ctx
14314            .state
14315            .lock()
14316            .map_err(|_| Error::WorkflowStatePoisoned)?
14317            .advance_cancellation_selection(&marker.selection_group_id);
14318        Poll::Ready(Ok(SelectionResult {
14319            key: winner.key.clone(),
14320            index: winner.index,
14321            kind: winner.kind.clone(),
14322            identity: winner.identity.clone(),
14323            value,
14324            failure: winner_failure,
14325            winner,
14326            handles,
14327        }))
14328    }
14329}
14330
14331fn selection_operation_identity(
14332    state: &WorkflowState,
14333    kind: &str,
14334    base_sequence: u64,
14335    size: usize,
14336) -> String {
14337    if kind == "group" {
14338        return format!("group:{base_sequence}:{size}");
14339    }
14340    let fields: &[&str] = match kind {
14341        "activity" => &["activity_execution_id"],
14342        "child" => &["child_workflow_run_id"],
14343        "timer" => &["timer_id"],
14344        "signal" => &["signal_wait_id"],
14345        "condition" => &["condition_wait_id"],
14346        _ => &[],
14347    };
14348    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
14349        for event in state
14350            .history_events
14351            .iter()
14352            .filter(|event| durable_event_sequence(event) == Some(sequence))
14353        {
14354            for field in fields {
14355                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
14356                    if !identity.is_empty() {
14357                        return identity.to_string();
14358                    }
14359                }
14360            }
14361        }
14362    }
14363    String::new()
14364}
14365
14366fn validated_selection_resolution_sequence(
14367    state: &WorkflowState,
14368    marker: &SelectionMarker,
14369    member: &SelectionMemberPlan,
14370    expected_identity: &str,
14371) -> Result<u64> {
14372    if expected_identity.is_empty() {
14373        return Err(invalid_recorded_history(
14374            "selection_operation_identity_missing",
14375            member.base_sequence,
14376            &format!(
14377                "durable {} resource identity from scheduled/open history",
14378                member.kind
14379            ),
14380            "missing operation identity",
14381            "selection member history is missing its canonical durable identity",
14382        ));
14383    }
14384    if marker.operation_identity != expected_identity {
14385        return Err(invalid_recorded_history(
14386            "selection_operation_identity_mismatch",
14387            member.base_sequence,
14388            expected_identity,
14389            &marker.operation_identity,
14390            "selection winner identity does not match durable scheduled/open history",
14391        ));
14392    }
14393
14394    let failure_types = [
14395        "ActivityFailed",
14396        "ActivityCancelled",
14397        "ActivityTimedOut",
14398        "ChildRunFailed",
14399        "ChildRunCancelled",
14400        "ChildRunTerminated",
14401    ];
14402    let success_types = [
14403        "ActivityCompleted",
14404        "ChildRunCompleted",
14405        "TimerFired",
14406        "SignalApplied",
14407        "ConditionWaitSatisfied",
14408        "ConditionWaitTimedOut",
14409    ];
14410    let terminal_types: &[&str] = if marker.outcome == "failed" {
14411        &failure_types
14412    } else {
14413        &success_types
14414    };
14415    let mut candidates = Vec::new();
14416    let member_commands = (member.base_sequence
14417        ..member.base_sequence.saturating_add(member.size as u64))
14418        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
14419        .map(|command| (command.sequence(), command))
14420        .collect::<BTreeMap<_, _>>();
14421    let mut resolved_conditions = BTreeSet::new();
14422    for event in state.history_events.iter() {
14423        let Some(sequence) = durable_event_sequence(event) else {
14424            continue;
14425        };
14426        let Some(command) = member_commands.get(&sequence) else {
14427            continue;
14428        };
14429        if !terminal_types.contains(&event.event_type.as_str()) {
14430            continue;
14431        }
14432        if matches!(command, RecordedCommand::ConditionWait { .. }) {
14433            if !matches!(
14434                event.event_type.as_str(),
14435                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
14436            ) && !(event.event_type == "TimerFired"
14437                && event.payload.get("timer_kind").and_then(Value::as_str)
14438                    == Some("condition_timeout"))
14439            {
14440                continue;
14441            }
14442            if !resolved_conditions.insert(sequence) {
14443                continue;
14444            }
14445        }
14446        let event_id = event
14447            .raw
14448            .get("id")
14449            .or_else(|| event.raw.get("event_id"))
14450            .and_then(Value::as_str)
14451            .filter(|value| !value.is_empty())
14452            .ok_or_else(|| {
14453                invalid_recorded_history(
14454                    "selection_resolution_event_id_missing",
14455                    member.base_sequence,
14456                    "terminal selection history with a durable event id",
14457                    &event.payload.to_string(),
14458                    "selection terminal history cannot be bound to its winner marker",
14459                )
14460            })?;
14461        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
14462    }
14463    let resolution = if marker.outcome == "failed" {
14464        candidates.first()
14465    } else {
14466        candidates.last()
14467    };
14468    let Some((event_id, event_type, sequence)) = resolution else {
14469        return Err(invalid_recorded_history(
14470            "selection_resolution_event_missing",
14471            member.base_sequence,
14472            "terminal history for the selected member",
14473            &format!("{:?}", marker.member_key),
14474            "selection winner marker has no matching durable terminal event",
14475        ));
14476    };
14477    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
14478        return Err(invalid_recorded_history(
14479            "selection_resolution_event_mismatch",
14480            member.base_sequence,
14481            &format!("{event_type}:{event_id}"),
14482            &format!(
14483                "{}:{}",
14484                marker.resolution_event_type, marker.resolution_event_id
14485            ),
14486            "selection winner marker does not reference the event that made its member terminal",
14487        ));
14488    }
14489    Ok(*sequence)
14490}
14491
14492fn selection_member_recorded_command(
14493    state: &WorkflowState,
14494    authored_sequence: u64,
14495) -> Option<&RecordedCommand> {
14496    let original = state
14497        .recorded_commands
14498        .iter()
14499        .find(|command| command.sequence() == authored_sequence)?;
14500    let RecordedCommand::ConditionWait {
14501        occurrence_id,
14502        parallel_group_path: Some(_),
14503        ..
14504    } = original
14505    else {
14506        return Some(original);
14507    };
14508    // Decoding proves each physical reopen has the same authored identity and
14509    // group path after a satisfied predecessor. Only its latest wait can make
14510    // this logical member terminal.
14511    state
14512        .recorded_commands
14513        .iter()
14514        .filter(|command| {
14515            matches!(command, RecordedCommand::ConditionWait {
14516                occurrence_id: candidate, ..
14517            } if candidate == occurrence_id)
14518        })
14519        .max_by_key(|command| command.sequence())
14520}
14521
14522fn recorded_selection_member_outcome(
14523    state: &WorkflowState,
14524    handle: &DurableOperationHandle,
14525) -> Result<Option<ParallelResult>> {
14526    for event in state.history_events.iter() {
14527        let Some(sequence) = durable_event_sequence(event) else {
14528            continue;
14529        };
14530        if sequence < handle.base_sequence
14531            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
14532            || !matches!(
14533                event.event_type.as_str(),
14534                "ActivityFailed"
14535                    | "ActivityCancelled"
14536                    | "ActivityTimedOut"
14537                    | "ChildRunFailed"
14538                    | "ChildRunCancelled"
14539                    | "ChildRunTerminated"
14540            )
14541        {
14542            continue;
14543        }
14544        let Some(command) = state
14545            .recorded_commands
14546            .iter()
14547            .find(|command| command.sequence() == sequence)
14548        else {
14549            continue;
14550        };
14551        match command {
14552            RecordedCommand::Activity {
14553                outcome: Some(Err(failure)),
14554                ..
14555            } => return Err(Error::ActivityFailed(failure.clone())),
14556            RecordedCommand::ChildWorkflow {
14557                outcome: Some(Err(failure)),
14558                ..
14559            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
14560            _ => {}
14561        }
14562    }
14563
14564    let mut results = Vec::with_capacity(handle.size);
14565    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
14566        let Some(command) = selection_member_recorded_command(state, sequence) else {
14567            return Ok(None);
14568        };
14569        let result = match command {
14570            RecordedCommand::Activity { outcome, .. } => match outcome {
14571                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
14572                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
14573                None => return Ok(None),
14574            },
14575            RecordedCommand::Timer { fired, .. } => {
14576                if !fired {
14577                    return Ok(None);
14578                }
14579                ParallelAvroResult::Timer
14580            }
14581            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
14582                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
14583                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
14584                None => return Ok(None),
14585            },
14586            RecordedCommand::SignalWait { value, .. } => match value {
14587                Some(value) => ParallelAvroResult::Signal(value.clone()),
14588                None => return Ok(None),
14589            },
14590            RecordedCommand::ConditionWait { result, .. } => match result {
14591                Some(result) => ParallelAvroResult::Condition(*result),
14592                None => return Ok(None),
14593            },
14594            other => {
14595                return Err(command_mismatch(
14596                    other,
14597                    format!("selected {} member", handle.kind),
14598                ))
14599            }
14600        };
14601        results.push(result);
14602    }
14603    let mut results = results.into_iter();
14604    parallel_results_for_shape(&handle.shape, &mut results)
14605        .into_json_result()
14606        .map(Some)
14607}
14608
14609fn recorded_selection_member_is_terminal(
14610    state: &WorkflowState,
14611    handle: &DurableOperationHandle,
14612) -> bool {
14613    let mut completed = 0usize;
14614    let mut all_completed = true;
14615    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
14616        let Some(command) = selection_member_recorded_command(state, sequence) else {
14617            all_completed = false;
14618            continue;
14619        };
14620        let terminal = match command {
14621            RecordedCommand::Activity {
14622                outcome: Some(Err(_)),
14623                ..
14624            }
14625            | RecordedCommand::ChildWorkflow {
14626                outcome: Some(Err(_)),
14627                ..
14628            } => return true,
14629            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
14630            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
14631            RecordedCommand::Timer { fired, .. } => *fired,
14632            RecordedCommand::SignalWait { value, .. } => value.is_some(),
14633            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
14634            RecordedCommand::SearchAttributes { .. }
14635            | RecordedCommand::CancellationScope { .. }
14636            | RecordedCommand::SideEffect { .. }
14637            | RecordedCommand::VersionMarker { .. }
14638            | RecordedCommand::Memo { .. }
14639            | RecordedCommand::CancellationBoundary { .. }
14640            | RecordedCommand::CancellationGroup { .. } => false,
14641            RecordedCommand::ServiceOperation { .. } => false,
14642        };
14643        if !terminal {
14644            all_completed = false;
14645            continue;
14646        }
14647        completed += 1;
14648    }
14649    all_completed && completed == handle.size
14650}
14651
14652fn selection_cancellation_for_handle(
14653    state: &WorkflowState,
14654    handle: &DurableOperationHandle,
14655) -> Result<bool> {
14656    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
14657        recorded.selection_group_id == handle.selection_group_id
14658            && recorded.member_base_sequence == handle.base_sequence
14659    }) else {
14660        return Ok(false);
14661    };
14662    validate_selection_cancellation_marker(marker, handle)?;
14663    Ok(true)
14664}
14665
14666fn validate_selection_cancellations_for_handles(
14667    state: &WorkflowState,
14668    handles: &[DurableOperationHandle],
14669) -> Result<()> {
14670    let Some(group_id) = handles
14671        .first()
14672        .map(|handle| handle.selection_group_id.as_str())
14673    else {
14674        return Ok(());
14675    };
14676    for marker in state
14677        .cancelled_selection_members
14678        .iter()
14679        .filter(|marker| marker.selection_group_id == group_id)
14680    {
14681        let Some(handle) = handles
14682            .iter()
14683            .find(|handle| handle.base_sequence == marker.member_base_sequence)
14684        else {
14685            return Err(invalid_recorded_history(
14686                "selection_cancellation_member_mismatch",
14687                marker.member_base_sequence,
14688                "SelectionOperationCancelled matching an authored selection handle",
14689                &format!("{marker:?}"),
14690                "selection cancellation member base does not name an authored member",
14691            ));
14692        };
14693        validate_selection_cancellation_marker(marker, handle)?;
14694    }
14695    Ok(())
14696}
14697
14698fn validate_selection_cancellation_marker(
14699    marker: &SelectionCancellation,
14700    handle: &DurableOperationHandle,
14701) -> Result<()> {
14702    if marker.selection_group_id != handle.selection_group_id
14703        || marker.member_key != handle.key
14704        || marker.member_index != handle.index
14705        || marker.member_base_sequence != handle.base_sequence
14706        || marker.member_size != handle.size
14707        || marker.operation_kind != handle.kind
14708        || marker.operation_identity != handle.identity
14709    {
14710        return Err(invalid_recorded_history(
14711            "selection_cancellation_member_mismatch",
14712            handle.base_sequence,
14713            "SelectionOperationCancelled matching the authored selection handle",
14714            &format!("{marker:?}"),
14715            "selection cancellation history targets different authored member metadata",
14716        ));
14717    }
14718    Ok(())
14719}
14720
14721/// Future returned by [`DurableOperationHandle::await_result`].
14722pub struct DurableOperationAwaitCall {
14723    handle: DurableOperationHandle,
14724}
14725
14726impl Future for DurableOperationAwaitCall {
14727    type Output = Result<ParallelResult>;
14728
14729    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14730        let mut state = match self.handle.ctx.state.lock() {
14731            Ok(state) => state,
14732            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14733        };
14734        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
14735            return Poll::Ready(Err(error));
14736        }
14737        match state.prepare_selection_handle_cancellation(&self.handle) {
14738            Ok(true) => return Poll::Pending,
14739            Ok(false) => {}
14740            Err(error) => return Poll::Ready(Err(error)),
14741        }
14742        match selection_cancellation_for_handle(&state, &self.handle) {
14743            Err(error) => return Poll::Ready(Err(error)),
14744            Ok(false) => {}
14745            Ok(true) => {
14746                state.advance_cancellation_receipt(
14747                    &self.handle.selection_group_id,
14748                    self.handle.base_sequence,
14749                );
14750                return Poll::Ready(Err(Error::DurableOperationCancelled(
14751                    DurableOperationCancelled {
14752                        selection_group_id: self.handle.selection_group_id.clone(),
14753                        member_key: self.handle.key.clone(),
14754                        member_index: self.handle.index,
14755                        operation_kind: self.handle.kind.clone(),
14756                        operation_identity: self.handle.identity.clone(),
14757                    },
14758                )));
14759            }
14760        }
14761        match recorded_selection_member_outcome(&state, &self.handle) {
14762            Ok(Some(result)) => {
14763                state.advance_cancellation_handle(&self.handle, false);
14764                Poll::Ready(Ok(result))
14765            }
14766            Ok(None) => Poll::Pending,
14767            Err(error) => {
14768                if !workflow_task_integrity_error(&error) {
14769                    state.advance_cancellation_handle(&self.handle, true);
14770                }
14771                Poll::Ready(Err(error))
14772            }
14773        }
14774    }
14775}
14776
14777fn validate_selection_delivery_handle(
14778    state: &WorkflowState,
14779    handle: &DurableOperationHandle,
14780) -> Result<()> {
14781    let path = state
14782        .recorded_commands
14783        .iter()
14784        .find(|command| command.sequence() == handle.base_sequence)
14785        .and_then(|command| match command {
14786            RecordedCommand::Activity {
14787                parallel_group_path,
14788                ..
14789            }
14790            | RecordedCommand::ChildWorkflow {
14791                parallel_group_path,
14792                ..
14793            }
14794            | RecordedCommand::Timer {
14795                parallel_group_path,
14796                ..
14797            }
14798            | RecordedCommand::SignalWait {
14799                parallel_group_path,
14800                ..
14801            }
14802            | RecordedCommand::ConditionWait {
14803                parallel_group_path,
14804                ..
14805            } => parallel_group_path.as_ref(),
14806            _ => None,
14807        })
14808        .and_then(|path| path.first());
14809    let matches = path.is_some_and(|entry| {
14810        entry.parallel_group_mode.as_deref() == Some("select")
14811            && entry.parallel_group_id == handle.selection_group_id
14812            && entry.selection_member_key.as_ref() == Some(&handle.key)
14813            && entry.selection_member_index == Some(handle.index)
14814            && entry.selection_member_base_sequence == Some(handle.base_sequence)
14815            && entry.selection_member_size == Some(handle.size)
14816            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
14817    });
14818    if !matches
14819        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
14820            != handle.identity
14821    {
14822        return Err(invalid_recorded_history(
14823            "cooperative_cancellation_call_mismatch",
14824            handle.base_sequence,
14825            "selection handle matching its authored durable identity",
14826            &format!("{handle:?}"),
14827            "selection handle identity or member metadata changed before cancellation replay",
14828        ));
14829    }
14830    Ok(())
14831}
14832
14833/// Future returned by [`DurableOperationHandle::cancel`].
14834pub struct CancelDurableOperationCall {
14835    handle: DurableOperationHandle,
14836    emitted: bool,
14837}
14838
14839impl Future for CancelDurableOperationCall {
14840    type Output = Result<()>;
14841
14842    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14843        let ctx = self.handle.ctx.clone();
14844        let mut state = match ctx.state.lock() {
14845            Ok(state) => state,
14846            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14847        };
14848        match selection_cancellation_for_handle(&state, &self.handle) {
14849            Err(error) => return Poll::Ready(Err(error)),
14850            Ok(true) => {
14851                state.advance_cancellation_receipt(
14852                    &self.handle.selection_group_id,
14853                    self.handle.base_sequence,
14854                );
14855                return Poll::Ready(Ok(()));
14856            }
14857            Ok(false) => {}
14858        }
14859        if recorded_selection_member_is_terminal(&state, &self.handle) {
14860            return Poll::Ready(Ok(()));
14861        }
14862        if !self.emitted {
14863            state.commands.push(json!({
14864                "type": "cancel_selection_operation",
14865                "selection_group_id": self.handle.selection_group_id,
14866                "member_key": self.handle.key,
14867                "member_index": self.handle.index,
14868                "member_base_sequence": self.handle.base_sequence,
14869                "member_size": self.handle.size,
14870                "operation_kind": self.handle.kind,
14871                "operation_identity": self.handle.identity,
14872            }));
14873            self.emitted = true;
14874        }
14875        // Unit completes the request, not the member's outcome. Following
14876        // workflow commands commit atomically with this cancellation request.
14877        // Waiting here would need another workflow task that cancellation
14878        // alone does not create. await_result still requires recorded history.
14879        Poll::Ready(Ok(()))
14880    }
14881}
14882
14883trait PollNestedResultExt<T> {
14884    fn flatten_result(self) -> Poll<Result<T>>;
14885}
14886
14887impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
14888    fn flatten_result(self) -> Poll<Result<T>> {
14889        match self {
14890            Poll::Ready(Ok(result)) => Poll::Ready(result),
14891            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14892            Poll::Pending => Poll::Pending,
14893        }
14894    }
14895}
14896
14897struct SagaCompensation {
14898    activity_type: String,
14899    options: ActivityOptions,
14900    arguments: AvroValue,
14901    registration_order: usize,
14902}
14903
14904/// Workflow-local deterministic saga compensation helper.
14905///
14906/// Register each compensation only after its forward step succeeds. Passing
14907/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
14908/// reverse registration order after any failure, including cooperative
14909/// cancellation. Each compensation is an ordinary durable activity, so replay,
14910/// duplicate delivery, and worker restart use existing history semantics.
14911pub struct Saga {
14912    ctx: WorkflowContext,
14913    compensations: Vec<SagaCompensation>,
14914}
14915
14916impl Saga {
14917    fn new(ctx: WorkflowContext) -> Self {
14918        Self {
14919            ctx,
14920            compensations: Vec::new(),
14921        }
14922    }
14923
14924    pub fn add_compensation<T: Serialize>(
14925        &mut self,
14926        activity_type: impl Into<String>,
14927        args: T,
14928    ) -> Result<&mut Self> {
14929        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
14930    }
14931
14932    pub fn add_compensation_with_options<T: Serialize>(
14933        &mut self,
14934        activity_type: impl Into<String>,
14935        options: ActivityOptions,
14936        args: T,
14937    ) -> Result<&mut Self> {
14938        let activity_type = activity_type.into();
14939        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
14940            return Err(Error::Codec(
14941                "saga compensation activity type must be non-empty without surrounding whitespace"
14942                    .to_string(),
14943            ));
14944        }
14945        options.validate().map_err(Error::InvalidActivityOptions)?;
14946        let arguments = AvroValue::from_serialize(&args)?;
14947        let registration_order = self.compensations.len() + 1;
14948        self.compensations.push(SagaCompensation {
14949            activity_type,
14950            options,
14951            arguments,
14952            registration_order,
14953        });
14954        Ok(self)
14955    }
14956
14957    /// Compensate `initiating_failure` and return the failure that must remain.
14958    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
14959        let _shield = match self.ctx.cancellation_shield() {
14960            Ok(shield) => shield,
14961            Err(error) => return error,
14962        };
14963        while let Some(compensation) = self.compensations.pop() {
14964            if let Err(compensation_failure) = self
14965                .ctx
14966                .activity_with_options(
14967                    compensation.activity_type.clone(),
14968                    compensation.options,
14969                    compensation.arguments,
14970                )
14971                .await
14972            {
14973                if workflow_task_integrity_error(&compensation_failure) {
14974                    return compensation_failure;
14975                }
14976                return Error::SagaCompensationFailed(SagaCompensationFailure {
14977                    initiating_failure: Box::new(initiating_failure),
14978                    compensation_failure: Box::new(compensation_failure),
14979                    compensation_activity_type: compensation.activity_type,
14980                    compensation_registration_order: compensation.registration_order,
14981                });
14982            }
14983        }
14984        initiating_failure
14985    }
14986
14987    /// Return a successful forward value or compensate and preserve its failure.
14988    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
14989        match outcome {
14990            Ok(value) => Ok(value),
14991            Err(error) => Err(self.compensate(error).await),
14992        }
14993    }
14994}
14995
14996pub struct ActivityCall {
14997    ctx: WorkflowContext,
14998    activity_type: String,
14999    options: ActivityOptions,
15000    worker_session: Option<WorkerSessionOptions>,
15001    args: Option<Result<AvroValue>>,
15002    scheduled: bool,
15003    local: bool,
15004    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
15005    parallel_group_path: Vec<ParallelGroupMetadata>,
15006}
15007
15008impl ActivityCall {
15009    fn poll_avro_value(
15010        mut self: Pin<&mut Self>,
15011        _cx: &mut TaskContext<'_>,
15012    ) -> Poll<Result<AvroValue>> {
15013        let ctx = self.ctx.clone();
15014        let mut state = match ctx.state.lock() {
15015            Ok(state) => state,
15016            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15017        };
15018
15019        if let Some(result) = &self.local_result {
15020            return match result.lock() {
15021                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
15022                    Poll::Ready(result.map_err(Error::ActivityFailed))
15023                }),
15024                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15025            };
15026        }
15027        if self.scheduled {
15028            return Poll::Pending;
15029        }
15030
15031        let options = match self.options.validate() {
15032            Ok(options) => options,
15033            Err(error) => {
15034                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
15035            }
15036        };
15037        if self.local {
15038            if self.worker_session.is_some() {
15039                return Poll::Ready(Err(Error::WorkerLoop(
15040                    "local activities cannot use worker-session routing".into(),
15041                )));
15042            }
15043            if let Err(error) = local_activity::validate(&options) {
15044                return Poll::Ready(Err(error));
15045            }
15046        }
15047        let session = match self
15048            .worker_session
15049            .as_ref()
15050            .map(WorkerSessionOptions::to_wire)
15051            .transpose()
15052        {
15053            Ok(value) => value,
15054            Err(error) => return Poll::Ready(Err(error)),
15055        };
15056        let session_queue = session
15057            .as_ref()
15058            .and_then(|session| session["queue"].as_str());
15059        let task_queue = options
15060            .task_queue
15061            .clone()
15062            .or_else(|| session_queue.map(str::to_owned))
15063            .unwrap_or_else(|| state.task_queue.clone());
15064        if session_queue.is_some_and(|queue| queue != task_queue) {
15065            return Poll::Ready(Err(Error::WorkerLoop(
15066                "worker-session queue must match the activity task queue".into(),
15067            )));
15068        }
15069        let current_recorded_options = RecordedActivityOptions {
15070            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
15071            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
15072            retry_policy: current_activity_retry_snapshot(&options),
15073            worker_session: session,
15074        };
15075
15076        let cursor = state.command_cursor;
15077        let call_kind = if self.local {
15078            CancellationCallKind::LocalActivity
15079        } else {
15080            CancellationCallKind::Activity
15081        };
15082        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15083            return Poll::Ready(Err(error));
15084        }
15085        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
15086            Ok(recorded) => recorded,
15087            Err(error) => return Poll::Ready(Err(error)),
15088        };
15089        if let Some(recorded) = recorded {
15090            let sequence = recorded.sequence();
15091            match recorded {
15092                RecordedCommand::Activity {
15093                    activity_type,
15094                    cancellation_policy,
15095                    options: recorded_options,
15096                    outcome,
15097                    parallel_group_path,
15098                    ..
15099                } => {
15100                    let current_policy = options
15101                        .cancellation_policy
15102                        .unwrap_or(CancellationPolicy::TryCancel)
15103                        .as_str();
15104                    if cancellation_policy != current_policy {
15105                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15106                            ReplayFailure::new(
15107                                "activity_cancellation_policy_changed",
15108                                Some(sequence),
15109                                Some(cancellation_policy),
15110                                Some(current_policy.to_string()),
15111                                "Activity cancellation policy changed during replay",
15112                            ),
15113                        )));
15114                    }
15115                    if let Err(error) = ensure_parallel_path_matches(
15116                        sequence,
15117                        parallel_group_path.as_deref(),
15118                        &self.parallel_group_path,
15119                    ) {
15120                        return Poll::Ready(Err(error));
15121                    }
15122                    if let Some(recorded_type) = activity_type {
15123                        if recorded_type != self.activity_type {
15124                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15125                                ReplayFailure::new(
15126                                    "recorded_command_detail_mismatch",
15127                                    Some(sequence),
15128                                    Some(format!("activity:{recorded_type}")),
15129                                    Some(format!("activity:{}", self.activity_type)),
15130                                    "recorded activity type differs from the current workflow command",
15131                                ),
15132                            )));
15133                        }
15134                    }
15135                    if let Some(recorded_options) = recorded_options {
15136                        if recorded_options.worker_session
15137                            != current_recorded_options.worker_session
15138                        {
15139                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15140                                "activity_worker_session_mismatch", Some(sequence),
15141                                Some(activity_options_description(&recorded_options)),
15142                                Some(activity_options_description(&current_recorded_options)),
15143                                "recorded worker-session routing differs from the current activity",
15144                            ))));
15145                        }
15146                        if !recorded_options
15147                            .task_queue
15148                            .matches_current(&current_recorded_options.task_queue)
15149                        {
15150                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15151                                ReplayFailure::new(
15152                                    "activity_task_queue_mismatch",
15153                                    Some(sequence),
15154                                    Some(activity_options_description(&recorded_options)),
15155                                    Some(activity_options_description(&current_recorded_options)),
15156                                    "recorded activity task queue differs from the current workflow command",
15157                                ),
15158                            )));
15159                        }
15160                        if (self.local
15161                            && matches!(
15162                                recorded_options.execution_mode,
15163                                RecordedSnapshotValue::Unknown
15164                            ))
15165                            || !recorded_options
15166                                .execution_mode
15167                                .matches_current(&current_recorded_options.execution_mode)
15168                        {
15169                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15170                                ReplayFailure::new(
15171                                    "activity_execution_mode_mismatch",
15172                                    Some(sequence),
15173                                    Some(activity_options_description(&recorded_options)),
15174                                    Some(activity_options_description(&current_recorded_options)),
15175                                    "recorded activity execution mode differs from the current workflow command",
15176                                ),
15177                            )));
15178                        }
15179                        if !recorded_options
15180                            .retry_policy
15181                            .matches_current(&current_recorded_options.retry_policy)
15182                        {
15183                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15184                                ReplayFailure::new(
15185                                    "activity_retry_policy_mismatch",
15186                                    Some(sequence),
15187                                    Some(activity_options_description(&recorded_options)),
15188                                    Some(activity_options_description(&current_recorded_options)),
15189                                    "recorded activity retry policy differs from the current workflow command",
15190                                ),
15191                            )));
15192                        }
15193                    }
15194                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
15195                        return Poll::Ready(Err(error));
15196                    }
15197                    match state.prepare_scalar_cancellation(
15198                        cursor,
15199                        call_kind,
15200                        &self.parallel_group_path,
15201                    ) {
15202                        Ok(true) => {
15203                            self.scheduled = true;
15204                            return Poll::Pending;
15205                        }
15206                        Ok(false) => {}
15207                        Err(error) => return Poll::Ready(Err(error)),
15208                    }
15209                    state.command_cursor += 1;
15210                    if let Some(outcome) = outcome {
15211                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15212                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
15213                    }
15214                    state.matched_recorded_pending = true;
15215                    self.scheduled = true;
15216                    return Poll::Pending;
15217                }
15218                other => {
15219                    return Poll::Ready(Err(command_mismatch(
15220                        &other,
15221                        format!("activity:{}", self.activity_type),
15222                    )));
15223                }
15224            }
15225        }
15226
15227        if !self.scheduled {
15228            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15229                Ok(args) => args,
15230                Err(error) => return Poll::Ready(Err(error)),
15231            };
15232            let arguments = normalize_avro_arguments(args);
15233            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
15234                Ok(envelope) => envelope,
15235                Err(error) => return Poll::Ready(Err(error)),
15236            };
15237
15238            let mut command = serde_json::Map::from_iter([
15239                (
15240                    "type".to_string(),
15241                    json!(if self.local {
15242                        "record_local_activity"
15243                    } else {
15244                        "schedule_activity"
15245                    }),
15246                ),
15247                (
15248                    "activity_type".to_string(),
15249                    json!(self.activity_type.clone()),
15250                ),
15251                ("queue".to_string(), json!(task_queue)),
15252                ("arguments".to_string(), envelope),
15253            ]);
15254            for (field, value) in [
15255                ("start_to_close_timeout", options.start_to_close_timeout),
15256                (
15257                    "schedule_to_start_timeout",
15258                    options.schedule_to_start_timeout,
15259                ),
15260                (
15261                    "schedule_to_close_timeout",
15262                    options.schedule_to_close_timeout,
15263                ),
15264                ("heartbeat_timeout", options.heartbeat_timeout),
15265            ] {
15266                if let Some(value) = value {
15267                    command.insert(field.to_string(), json!(value));
15268                }
15269            }
15270            if let Some(retry_policy) = &options.retry_policy {
15271                command.insert("retry_policy".to_string(), retry_policy.clone());
15272            }
15273            if let Some(policy) = options.cancellation_policy {
15274                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
15275            }
15276            if let Some(session) = current_recorded_options.worker_session {
15277                command.insert("worker_session".into(), session);
15278            }
15279            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15280            ctx.apply_scope_membership(&mut command);
15281            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
15282                Ok(true) => {
15283                    self.scheduled = true;
15284                    return Poll::Pending;
15285                }
15286                Ok(false) => {}
15287                Err(error) => return Poll::Ready(Err(error)),
15288            }
15289            if self.local {
15290                command.remove("queue");
15291                command.insert("execution_mode".into(), json!("local"));
15292                let result = Arc::new(Mutex::new(None));
15293                let command_index = state.commands.len();
15294                state.local_activity_requests.push(local_activity::Request {
15295                    command_index,
15296                    options,
15297                    arguments,
15298                    result: result.clone(),
15299                });
15300                self.local_result = Some(result);
15301            }
15302            state.commands.push(Value::Object(command));
15303            self.scheduled = true;
15304        }
15305
15306        Poll::Pending
15307    }
15308}
15309
15310impl Future for ActivityCall {
15311    type Output = Result<Value>;
15312
15313    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15314        match self.poll_avro_value(cx) {
15315            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
15316            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15317            Poll::Pending => Poll::Pending,
15318        }
15319    }
15320}
15321
15322/// Future returned by [`WorkflowContext::sleep`].
15323pub struct TimerCall {
15324    ctx: WorkflowContext,
15325    delay_seconds: Option<u64>,
15326    scheduled: bool,
15327    matched_pending: bool,
15328    parallel_group_path: Vec<ParallelGroupMetadata>,
15329}
15330
15331impl Future for TimerCall {
15332    type Output = Result<()>;
15333
15334    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15335        if self.matched_pending {
15336            return Poll::Pending;
15337        }
15338
15339        let ctx = self.ctx.clone();
15340        let Some(requested_delay) = self.delay_seconds else {
15341            return Poll::Ready(Err(Error::TimerDurationOverflow));
15342        };
15343        let mut state = match ctx.state.lock() {
15344            Ok(state) => state,
15345            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15346        };
15347
15348        let cursor = state.command_cursor;
15349        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15350            return Poll::Ready(Err(error));
15351        }
15352        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
15353        {
15354            Ok(recorded) => recorded,
15355            Err(error) => return Poll::Ready(Err(error)),
15356        };
15357        if let Some(recorded) = recorded {
15358            match recorded {
15359                RecordedCommand::Timer {
15360                    sequence,
15361                    delay_seconds,
15362                    fired,
15363                    parallel_group_path,
15364                    ..
15365                } => {
15366                    if let Err(error) =
15367                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
15368                    {
15369                        return Poll::Ready(Err(error));
15370                    }
15371                    if let Err(error) = ensure_parallel_path_matches(
15372                        sequence,
15373                        parallel_group_path.as_deref(),
15374                        &self.parallel_group_path,
15375                    ) {
15376                        return Poll::Ready(Err(error));
15377                    }
15378                    if delay_seconds != requested_delay {
15379                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15380                            ReplayFailure::new(
15381                                "timer_delay_mismatch",
15382                                Some(sequence),
15383                                Some(format!("timer:{delay_seconds}s")),
15384                                Some(format!("timer:{requested_delay}s")),
15385                                "recorded timer delay differs from the current workflow command",
15386                            ),
15387                        )));
15388                    }
15389                    if let Err(error) =
15390                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
15391                    {
15392                        return Poll::Ready(Err(error));
15393                    }
15394                    match state.prepare_scalar_cancellation(
15395                        cursor,
15396                        CancellationCallKind::Timer,
15397                        &self.parallel_group_path,
15398                    ) {
15399                        Ok(true) => {
15400                            self.scheduled = true;
15401                            self.matched_pending = true;
15402                            return Poll::Pending;
15403                        }
15404                        Ok(false) => {}
15405                        Err(error) => return Poll::Ready(Err(error)),
15406                    }
15407                    state.command_cursor += 1;
15408                    if fired {
15409                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15410                        return Poll::Ready(Ok(()));
15411                    }
15412                    state.matched_recorded_pending = true;
15413                    self.scheduled = true;
15414                    self.matched_pending = true;
15415                    return Poll::Pending;
15416                }
15417                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
15418            }
15419        }
15420
15421        if !self.scheduled {
15422            let mut command = serde_json::Map::from_iter([
15423                ("type".to_string(), json!("start_timer")),
15424                ("delay_seconds".to_string(), json!(requested_delay)),
15425            ]);
15426            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
15427                Ok(Some(proof)) => {
15428                    command.insert("cancellation_cleanup".into(), proof);
15429                }
15430                Ok(None) => {}
15431                Err(error) => return Poll::Ready(Err(error)),
15432            }
15433            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15434            ctx.apply_scope_membership(&mut command);
15435            match state.prepare_scalar_cancellation(
15436                cursor,
15437                CancellationCallKind::Timer,
15438                &self.parallel_group_path,
15439            ) {
15440                Ok(true) => {
15441                    self.scheduled = true;
15442                    self.matched_pending = true;
15443                    return Poll::Pending;
15444                }
15445                Ok(false) => {}
15446                Err(error) => return Poll::Ready(Err(error)),
15447            }
15448            state.commands.push(Value::Object(command));
15449            self.scheduled = true;
15450        }
15451
15452        Poll::Pending
15453    }
15454}
15455
15456/// Future returned by [`WorkflowContext::wait_condition`].
15457pub struct ConditionWaitCall {
15458    ctx: WorkflowContext,
15459    options: ConditionWaitOptions,
15460    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
15461    occurrence_id: Option<String>,
15462    opened_wait: bool,
15463    parallel_group_path: Vec<ParallelGroupMetadata>,
15464}
15465
15466impl Future for ConditionWaitCall {
15467    type Output = Result<ConditionWaitResult>;
15468
15469    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15470        if self.opened_wait {
15471            return Poll::Pending;
15472        }
15473
15474        let options = match self.options.validate() {
15475            Ok(options) => options,
15476            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
15477        };
15478        let ctx = self.ctx.clone();
15479        let occurrence_id = match self.occurrence_id.as_ref() {
15480            Some(occurrence_id) => occurrence_id.clone(),
15481            None => {
15482                let mut state = match ctx.state.lock() {
15483                    Ok(state) => state,
15484                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15485                };
15486                let ordinal = state.condition_wait_occurrence_counter;
15487                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
15488                    Some(next) => next,
15489                    None => {
15490                        return Poll::Ready(Err(Error::WorkerLoop(
15491                            "condition wait occurrence counter overflowed".to_string(),
15492                        )))
15493                    }
15494                };
15495                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
15496                drop(state);
15497                self.occurrence_id = Some(occurrence_id.clone());
15498                occurrence_id
15499            }
15500        };
15501
15502        let recorded_result = {
15503            let mut state = match ctx.state.lock() {
15504                Ok(state) => state,
15505                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15506            };
15507            let initial_cursor = state.command_cursor;
15508            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
15509                return Poll::Ready(Err(error));
15510            }
15511            let recorded = match state
15512                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
15513            {
15514                Ok(recorded) => recorded,
15515                Err(error) => return Poll::Ready(Err(error)),
15516            };
15517            let Some(recorded) = recorded else {
15518                drop(state);
15519                return self.poll_new_condition(options);
15520            };
15521            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
15522                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
15523            }
15524
15525            let mut cursor = state.command_cursor;
15526            let mut result = None;
15527            let mut pending_delivery = false;
15528            loop {
15529                if cursor > initial_cursor
15530                    && matches!(
15531                        state.recorded_commands.get(cursor),
15532                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
15533                    )
15534                {
15535                    break;
15536                }
15537                let recorded = match state
15538                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
15539                {
15540                    Ok(recorded) => recorded,
15541                    Err(error) => return Poll::Ready(Err(error)),
15542                };
15543                let Some(RecordedCommand::ConditionWait {
15544                    sequence,
15545                    occurrence_id: ref recorded_occurrence_id,
15546                    ref condition_key,
15547                    ref predicate_identity,
15548                    timeout_seconds,
15549                    result: recorded_result,
15550                    ref parallel_group_path,
15551                    ..
15552                }) = recorded
15553                else {
15554                    break;
15555                };
15556
15557                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
15558                    break;
15559                }
15560                if let Err(error) = ensure_parallel_path_matches(
15561                    sequence,
15562                    parallel_group_path.as_deref(),
15563                    &self.parallel_group_path,
15564                ) {
15565                    return Poll::Ready(Err(error));
15566                }
15567                if let Err(error) = validate_recorded_condition_wait(
15568                    sequence,
15569                    recorded_occurrence_id,
15570                    condition_key.as_deref(),
15571                    predicate_identity,
15572                    timeout_seconds,
15573                    &occurrence_id,
15574                    &options,
15575                ) {
15576                    return Poll::Ready(Err(error));
15577                }
15578                if result == Some(ConditionWaitResult::TimedOut) {
15579                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15580                        "condition_wait_reopened_after_timeout",
15581                        Some(sequence),
15582                        Some("timed-out condition is terminal".to_string()),
15583                        Some("another physical wait-open".to_string()),
15584                        "condition history reopened one logical wait after its durable timeout",
15585                    ))));
15586                }
15587                if let Err(error) =
15588                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
15589                {
15590                    return Poll::Ready(Err(error));
15591                }
15592                match state.prepare_scalar_cancellation(
15593                    cursor,
15594                    CancellationCallKind::Condition,
15595                    &self.parallel_group_path,
15596                ) {
15597                    Ok(pending) => pending_delivery |= pending,
15598                    Err(error) => return Poll::Ready(Err(error)),
15599                }
15600                result = recorded_result;
15601                if result.is_some() {
15602                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15603                }
15604                cursor += 1;
15605            }
15606            state.command_cursor = cursor;
15607            if pending_delivery {
15608                self.opened_wait = true;
15609                return Poll::Pending;
15610            }
15611            result
15612        };
15613
15614        if let Some(result) = recorded_result {
15615            return Poll::Ready(Ok(result));
15616        }
15617
15618        self.poll_open_condition(options, true)
15619    }
15620}
15621
15622impl ConditionWaitCall {
15623    fn poll_new_condition(
15624        self: Pin<&mut Self>,
15625        options: ValidatedConditionWaitOptions,
15626    ) -> Poll<Result<ConditionWaitResult>> {
15627        self.poll_open_condition(options, false)
15628    }
15629
15630    fn poll_open_condition(
15631        mut self: Pin<&mut Self>,
15632        options: ValidatedConditionWaitOptions,
15633        recorded_wait: bool,
15634    ) -> Poll<Result<ConditionWaitResult>> {
15635        {
15636            let ctx = self.ctx.clone();
15637            let mut state = match ctx.state.lock() {
15638                Ok(state) => state,
15639                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15640            };
15641            let cursor = state.command_cursor;
15642            match state.prepare_scalar_cancellation(
15643                cursor,
15644                CancellationCallKind::Condition,
15645                &self.parallel_group_path,
15646            ) {
15647                Ok(true) => {
15648                    self.opened_wait = true;
15649                    return Poll::Pending;
15650                }
15651                Ok(false) => {}
15652                Err(error) => return Poll::Ready(Err(error)),
15653            }
15654        }
15655        let selection_member = self
15656            .parallel_group_path
15657            .first()
15658            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
15659        match (self.predicate)() {
15660            Ok(true) if !selection_member || recorded_wait => {
15661                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
15662            }
15663            Ok(_) => {}
15664            Err(error) => return Poll::Ready(Err(error)),
15665        }
15666        if options.timeout_seconds == Some(0) && !selection_member {
15667            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
15668        }
15669
15670        let ctx = self.ctx.clone();
15671        let mut state = match ctx.state.lock() {
15672            Ok(state) => state,
15673            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15674        };
15675        let mut command = serde_json::Map::from_iter([
15676            ("type".to_string(), json!("open_condition_wait")),
15677            (
15678                "condition_wait_occurrence_id".to_string(),
15679                json!(self.occurrence_id.as_deref().unwrap_or_default()),
15680            ),
15681            ("condition_key".to_string(), json!(options.condition_key)),
15682            (
15683                "condition_definition_fingerprint".to_string(),
15684                json!(options.predicate_identity),
15685            ),
15686        ]);
15687        if let Some(timeout_seconds) = options.timeout_seconds {
15688            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
15689        }
15690        apply_parallel_group_path(&mut command, &self.parallel_group_path);
15691        ctx.apply_scope_membership(&mut command);
15692        state.commands.push(Value::Object(command));
15693        drop(state);
15694        self.opened_wait = true;
15695        Poll::Pending
15696    }
15697}
15698
15699fn validate_recorded_condition_wait(
15700    sequence: u64,
15701    recorded_occurrence_id: &str,
15702    recorded_key: Option<&str>,
15703    recorded_predicate_identity: &str,
15704    recorded_timeout_seconds: Option<u64>,
15705    current_occurrence_id: &str,
15706    current: &ValidatedConditionWaitOptions,
15707) -> Result<()> {
15708    if recorded_occurrence_id != current_occurrence_id {
15709        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15710            "condition_wait_occurrence_mismatch",
15711            Some(sequence),
15712            Some(recorded_occurrence_id.to_string()),
15713            Some(current_occurrence_id.to_string()),
15714            "recorded condition occurrence differs from the current authored wait position",
15715        )));
15716    }
15717    if recorded_key != Some(current.condition_key.as_str()) {
15718        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15719            "condition_wait_key_mismatch",
15720            Some(sequence),
15721            recorded_key.map(str::to_string),
15722            Some(current.condition_key.clone()),
15723            "recorded condition identity differs from the current workflow wait",
15724        )));
15725    }
15726    if recorded_predicate_identity != current.predicate_identity {
15727        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15728            "condition_wait_predicate_mismatch",
15729            Some(sequence),
15730            Some(recorded_predicate_identity.to_string()),
15731            Some(current.predicate_identity.clone()),
15732            "recorded condition predicate behavior differs from current workflow code",
15733        )));
15734    }
15735    if recorded_timeout_seconds != current.timeout_seconds {
15736        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15737            "condition_wait_timeout_mismatch",
15738            Some(sequence),
15739            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
15740            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
15741            "recorded condition timeout differs from the current workflow wait",
15742        )));
15743    }
15744    Ok(())
15745}
15746
15747/// Future returned by [`WorkflowContext::start_child_workflow`].
15748pub struct ChildWorkflowCall {
15749    ctx: WorkflowContext,
15750    workflow_type: String,
15751    options: ChildWorkflowOptions,
15752    args: Option<Result<AvroValue>>,
15753    scheduled: bool,
15754    matched_pending: bool,
15755    parallel_group_path: Vec<ParallelGroupMetadata>,
15756}
15757
15758impl ChildWorkflowCall {
15759    fn poll_avro_value(
15760        mut self: Pin<&mut Self>,
15761        _cx: &mut TaskContext<'_>,
15762    ) -> Poll<Result<ChildWorkflowAvroResult>> {
15763        if self.matched_pending {
15764            return Poll::Pending;
15765        }
15766
15767        let ctx = self.ctx.clone();
15768        let mut state = match ctx.state.lock() {
15769            Ok(state) => state,
15770            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15771        };
15772
15773        let cursor = state.command_cursor;
15774        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15775            return Poll::Ready(Err(error));
15776        }
15777        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
15778        {
15779            Ok(recorded) => recorded,
15780            Err(error) => return Poll::Ready(Err(error)),
15781        };
15782        if let Some(recorded) = recorded {
15783            let sequence = recorded.sequence();
15784            match recorded {
15785                RecordedCommand::ChildWorkflow {
15786                    workflow_type,
15787                    policies,
15788                    outcome,
15789                    parallel_group_path,
15790                    ..
15791                } => {
15792                    if let Err(error) = ensure_parallel_path_matches(
15793                        sequence,
15794                        parallel_group_path.as_deref(),
15795                        &self.parallel_group_path,
15796                    ) {
15797                        return Poll::Ready(Err(error));
15798                    }
15799                    if let Some(recorded_type) = workflow_type {
15800                        if recorded_type != self.workflow_type {
15801                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15802                                ReplayFailure::new(
15803                                    "recorded_command_detail_mismatch",
15804                                    Some(sequence),
15805                                    Some(format!("child workflow:{recorded_type}")),
15806                                    Some(format!("child workflow:{}", self.workflow_type)),
15807                                    "recorded child workflow type differs from the current workflow command",
15808                                ),
15809                            )));
15810                        }
15811                    }
15812                    if let Err(error) =
15813                        ensure_child_policies_match(sequence, &policies, &self.options)
15814                    {
15815                        return Poll::Ready(Err(error));
15816                    }
15817                    if let Err(error) =
15818                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
15819                    {
15820                        return Poll::Ready(Err(error));
15821                    }
15822                    match state.prepare_scalar_cancellation(
15823                        cursor,
15824                        CancellationCallKind::Child,
15825                        &self.parallel_group_path,
15826                    ) {
15827                        Ok(true) => {
15828                            self.scheduled = true;
15829                            self.matched_pending = true;
15830                            return Poll::Pending;
15831                        }
15832                        Ok(false) => {}
15833                        Err(error) => return Poll::Ready(Err(error)),
15834                    }
15835                    state.command_cursor += 1;
15836                    if let Some(outcome) = outcome {
15837                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15838                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
15839                    }
15840                    state.matched_recorded_pending = true;
15841                    self.scheduled = true;
15842                    self.matched_pending = true;
15843                    return Poll::Pending;
15844                }
15845                other => {
15846                    return Poll::Ready(Err(command_mismatch(
15847                        &other,
15848                        format!("child workflow:{}", self.workflow_type),
15849                    )));
15850                }
15851            }
15852        }
15853
15854        if !self.scheduled {
15855            if self.options.task_queue.trim().is_empty() {
15856                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15857                    "task_queue must not be empty".to_string(),
15858                )));
15859            }
15860            for (name, value) in [
15861                (
15862                    "execution_timeout_seconds",
15863                    self.options.execution_timeout_seconds,
15864                ),
15865                ("run_timeout_seconds", self.options.run_timeout_seconds),
15866            ] {
15867                if value == Some(0) {
15868                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
15869                        "{name} must be at least 1"
15870                    ))));
15871                }
15872            }
15873
15874            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15875                Ok(args) => args,
15876                Err(error) => return Poll::Ready(Err(error)),
15877            };
15878            let arguments = match encode_typed_envelope(
15879                &normalize_avro_arguments(args),
15880                &state.payload_codec,
15881            ) {
15882                Ok(arguments) => arguments,
15883                Err(error) => return Poll::Ready(Err(error)),
15884            };
15885            let mut command = json!({
15886                "type": "start_child_workflow",
15887                "workflow_type": self.workflow_type,
15888                "queue": self.options.task_queue,
15889                "parent_close_policy": self.options.parent_close_policy.as_str(),
15890                "arguments": arguments,
15891            });
15892            let object = command
15893                .as_object_mut()
15894                .expect("child workflow command is always an object");
15895            if self.options.cancellation_policy != CancellationPolicy::Abandon {
15896                object.insert(
15897                    "cancellation_policy".to_string(),
15898                    json!(self.options.cancellation_policy.as_str()),
15899                );
15900            }
15901            if let Some(policy) = &self.options.retry_policy {
15902                let mut retry_policy = serde_json::Map::new();
15903                if let Some(max_attempts) = policy.max_attempts {
15904                    if max_attempts == 0 {
15905                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15906                            "retry_policy.max_attempts must be at least 1".to_string(),
15907                        )));
15908                    }
15909                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
15910                }
15911                if !policy.backoff_seconds.is_empty() {
15912                    retry_policy
15913                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
15914                }
15915                if !policy.non_retryable_error_types.is_empty() {
15916                    retry_policy.insert(
15917                        "non_retryable_error_types".to_string(),
15918                        json!(policy.non_retryable_error_types),
15919                    );
15920                }
15921                if retry_policy.is_empty() {
15922                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15923                        "retry_policy must configure at least one field".to_string(),
15924                    )));
15925                }
15926                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
15927            }
15928            if let Some(seconds) = self.options.execution_timeout_seconds {
15929                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
15930            }
15931            if let Some(seconds) = self.options.run_timeout_seconds {
15932                object.insert("run_timeout_seconds".to_string(), json!(seconds));
15933            }
15934            apply_parallel_group_path(object, &self.parallel_group_path);
15935            ctx.apply_scope_membership(object);
15936            match state.prepare_scalar_cancellation(
15937                cursor,
15938                CancellationCallKind::Child,
15939                &self.parallel_group_path,
15940            ) {
15941                Ok(true) => {
15942                    self.scheduled = true;
15943                    self.matched_pending = true;
15944                    return Poll::Pending;
15945                }
15946                Ok(false) => {}
15947                Err(error) => return Poll::Ready(Err(error)),
15948            }
15949            state.commands.push(command);
15950            self.scheduled = true;
15951        }
15952
15953        Poll::Pending
15954    }
15955}
15956
15957impl Future for ChildWorkflowCall {
15958    type Output = Result<ChildWorkflowResult>;
15959
15960    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15961        match self.poll_avro_value(cx) {
15962            Poll::Ready(Ok(result)) => match result.result.into_json() {
15963                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
15964                    parent: result.parent,
15965                    child: result.child,
15966                    child_workflow_type: result.child_workflow_type,
15967                    result: projected,
15968                })),
15969                Err(error) => Poll::Ready(Err(error)),
15970            },
15971            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15972            Poll::Pending => Poll::Pending,
15973        }
15974    }
15975}
15976
15977fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
15978    Error::NonDeterministicReplay(ReplayFailure::new(
15979        "recorded_command_mismatch",
15980        Some(recorded.sequence()),
15981        Some(recorded.shape().to_string()),
15982        Some(actual.into()),
15983        "current workflow command does not match the recorded durable command sequence",
15984    ))
15985}
15986
15987pub struct SignalCall {
15988    ctx: WorkflowContext,
15989    signal_name: String,
15990    runtime_reserved_allowed: bool,
15991    opened_wait: bool,
15992    matched_pending: bool,
15993    parallel_group_path: Vec<ParallelGroupMetadata>,
15994}
15995
15996impl SignalCall {
15997    fn poll_avro_value(
15998        mut self: Pin<&mut Self>,
15999        _cx: &mut TaskContext<'_>,
16000    ) -> Poll<Result<Vec<AvroValue>>> {
16001        if self.matched_pending {
16002            return Poll::Pending;
16003        }
16004        if !self.runtime_reserved_allowed {
16005            if let Err(error) = validate_user_signal_name(&self.signal_name) {
16006                return Poll::Ready(Err(error));
16007            }
16008        }
16009
16010        let ctx = self.ctx.clone();
16011        let mut state = match ctx.state.lock() {
16012            Ok(state) => state,
16013            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16014        };
16015
16016        let cursor = state.command_cursor;
16017        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
16018            return Poll::Ready(Err(error));
16019        }
16020        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
16021        {
16022            Ok(recorded) => recorded,
16023            Err(error) => return Poll::Ready(Err(error)),
16024        };
16025        if let Some(recorded) = recorded {
16026            match recorded {
16027                RecordedCommand::SignalWait {
16028                    sequence,
16029                    signal_name,
16030                    value,
16031                    parallel_group_path,
16032                } => {
16033                    if let Err(error) = ensure_parallel_path_matches(
16034                        sequence,
16035                        parallel_group_path.as_deref(),
16036                        &self.parallel_group_path,
16037                    ) {
16038                        return Poll::Ready(Err(error));
16039                    }
16040                    if signal_name != self.signal_name {
16041                        return Poll::Ready(Err(Error::NonDeterministicReplay(
16042                            ReplayFailure::new(
16043                                "recorded_command_detail_mismatch",
16044                                Some(sequence),
16045                                Some(format!("signal wait:{signal_name}")),
16046                                Some(format!("signal wait:{}", self.signal_name)),
16047                                "recorded signal name differs from the current workflow command",
16048                            ),
16049                        )));
16050                    }
16051
16052                    if let Err(error) =
16053                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
16054                    {
16055                        return Poll::Ready(Err(error));
16056                    }
16057                    match state.prepare_scalar_cancellation(
16058                        cursor,
16059                        CancellationCallKind::Signal,
16060                        &self.parallel_group_path,
16061                    ) {
16062                        Ok(true) => {
16063                            self.opened_wait = true;
16064                            self.matched_pending = true;
16065                            return Poll::Pending;
16066                        }
16067                        Ok(false) => {}
16068                        Err(error) => return Poll::Ready(Err(error)),
16069                    }
16070                    state.command_cursor += 1;
16071                    if let Some(value) = value {
16072                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
16073                        return Poll::Ready(Ok(value));
16074                    }
16075                    if state
16076                        .resume_signal
16077                        .as_ref()
16078                        .is_some_and(|signal| signal.signal_name == self.signal_name)
16079                    {
16080                        let signal = state
16081                            .resume_signal
16082                            .take()
16083                            .expect("matching resume signal is present");
16084                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
16085                        return Poll::Ready(Ok(signal.arguments));
16086                    }
16087
16088                    state.matched_recorded_pending = true;
16089                    self.opened_wait = true;
16090                    self.matched_pending = true;
16091                    return Poll::Pending;
16092                }
16093                other => {
16094                    return Poll::Ready(Err(command_mismatch(
16095                        &other,
16096                        format!("signal wait:{}", self.signal_name),
16097                    )));
16098                }
16099            }
16100        }
16101
16102        match state.prepare_scalar_cancellation(
16103            cursor,
16104            CancellationCallKind::Signal,
16105            &self.parallel_group_path,
16106        ) {
16107            Ok(true) => {
16108                self.opened_wait = true;
16109                self.matched_pending = true;
16110                return Poll::Pending;
16111            }
16112            Ok(false) => {}
16113            Err(error) => return Poll::Ready(Err(error)),
16114        }
16115
16116        if state
16117            .resume_signal
16118            .as_ref()
16119            .is_some_and(|signal| signal.signal_name == self.signal_name)
16120        {
16121            let signal = state
16122                .resume_signal
16123                .take()
16124                .expect("matching resume signal is present");
16125            state.unavailable_cancellation_boundary(&self.parallel_group_path);
16126            return Poll::Ready(Ok(signal.arguments));
16127        }
16128
16129        if !self.opened_wait {
16130            let mut command = serde_json::Map::from_iter([
16131                ("type".to_string(), json!("open_signal_wait")),
16132                ("signal_name".to_string(), json!(self.signal_name)),
16133            ]);
16134            apply_parallel_group_path(&mut command, &self.parallel_group_path);
16135            ctx.apply_scope_membership(&mut command);
16136            state.commands.push(Value::Object(command));
16137            self.opened_wait = true;
16138        }
16139
16140        Poll::Pending
16141    }
16142}
16143
16144impl Future for SignalCall {
16145    type Output = Result<Vec<Value>>;
16146
16147    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
16148        match self.poll_avro_value(cx) {
16149            Poll::Ready(Ok(values)) => Poll::Ready(
16150                values
16151                    .into_iter()
16152                    .map(AvroValue::into_json)
16153                    .collect::<Result<Vec<_>>>(),
16154            ),
16155            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
16156            Poll::Pending => Poll::Pending,
16157        }
16158    }
16159}
16160
16161#[derive(Clone, Debug)]
16162pub struct ActivityContext {
16163    client: Client,
16164    pub task_id: String,
16165    pub activity_attempt_id: String,
16166    pub lease_owner: String,
16167    pub activity_type: String,
16168    pub attempt_number: u64,
16169    retry_info: ActivityRetryInfo,
16170    activity_execution_id: Option<String>,
16171    workflow_id: Option<String>,
16172    run_id: Option<String>,
16173    pub task_queue: String,
16174    pub worker_id: String,
16175    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
16176    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
16177    worker_session: Option<WorkerSession>,
16178}
16179
16180impl ActivityContext {
16181    /// Logical Server activity execution ID, stable across that activity's retries.
16182    ///
16183    /// This is the received claim identity, including for worker-session activities.
16184    /// It is unavailable when an older Server omits it, for inline local activities
16185    /// before the Server records their command, and in Server-free tests. It is
16186    /// never derived from a per-attempt task or attempt ID. Use an application
16187    /// business key when this value is unavailable.
16188    pub fn activity_execution_id(&self) -> Option<&str> {
16189        self.activity_execution_id.as_deref()
16190    }
16191
16192    /// Owning workflow instance ID from the claim (or parent local workflow task).
16193    /// Older claims and Server-free activity tests can report `None`.
16194    pub fn workflow_id(&self) -> Option<&str> {
16195        self.workflow_id.as_deref()
16196    }
16197
16198    /// Owning workflow run ID from the claim (or parent local workflow task).
16199    /// Older claims and Server-free activity tests can report `None`.
16200    pub fn run_id(&self) -> Option<&str> {
16201        self.run_id.as_deref()
16202    }
16203
16204    /// Immutable original attempt identity and received retry policy.
16205    pub fn retry_info(&self) -> &ActivityRetryInfo {
16206        &self.retry_info
16207    }
16208
16209    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
16210        if let Some(heartbeats) = &self.local_heartbeats {
16211            return heartbeats
16212                .lock()
16213                .map_err(|_| Error::WorkflowStatePoisoned)?
16214                .record(details);
16215        }
16216        if let Some(guard) = &self.claim_guard {
16217            return guard.heartbeat(self, details).await;
16218        }
16219        if let Some(session) = &self.worker_session {
16220            if !session.active() {
16221                return Err(Error::ActivityExecutionAbandoned(
16222                    "worker-session lease or TTL is no longer active".into(),
16223                ));
16224            }
16225            let result = self
16226                .client
16227                .heartbeat_activity_task_value(
16228                    &self.task_id,
16229                    &self.activity_attempt_id,
16230                    &self.lease_owner,
16231                    details,
16232                )
16233                .await;
16234            return worker_session::settle_activity_heartbeat(
16235                session,
16236                result,
16237                &self.task_id,
16238                &self.activity_attempt_id,
16239                &self.lease_owner,
16240            );
16241        }
16242        self.client
16243            .heartbeat_activity_task(
16244                &self.task_id,
16245                &self.activity_attempt_id,
16246                &self.lease_owner,
16247                details,
16248            )
16249            .await
16250    }
16251}
16252
16253fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
16254    validate_payload_codec(codec)?;
16255    match value {
16256        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
16257            value, codec,
16258        )?)),
16259        None => Ok(AvroValue::Array(Vec::new())),
16260    }
16261}
16262
16263fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
16264    let Some(signal_name) = task
16265        .signal_name
16266        .as_deref()
16267        .filter(|value| !value.is_empty())
16268    else {
16269        return Ok(None);
16270    };
16271    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
16272    let AvroValue::Array(arguments) = decoded else {
16273        unreachable!("normalize_avro_arguments always returns an array");
16274    };
16275
16276    Ok(Some(ResumeSignal {
16277        signal_name: signal_name.to_string(),
16278        arguments,
16279    }))
16280}
16281
16282fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
16283    validate_payload_codec(&task.payload_codec)?;
16284    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
16285    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
16286    for event in &task.history_events {
16287        validate_history_event_payloads(event, &task.payload_codec)?;
16288    }
16289    Ok(())
16290}
16291
16292fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
16293    validate_payload_codec(&task.payload_codec)?;
16294    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
16295}
16296
16297fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
16298    validate_payload_codec(&task.payload_codec)?;
16299    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
16300    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
16301    for event in &task.history_events {
16302        validate_history_event_payloads(event, &task.payload_codec)?;
16303    }
16304
16305    let Some(export) = task.history_export.as_ref() else {
16306        return Ok(());
16307    };
16308    let export_codec = match export.get("payloads") {
16309        Some(payloads) => declared_payload_codec(payloads, "codec")?,
16310        None => None,
16311    }
16312    .unwrap_or(&task.payload_codec);
16313    validate_payload_codec(export_codec)?;
16314
16315    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
16316        for event in events {
16317            let event_type = event
16318                .get("event_type")
16319                .or_else(|| event.get("type"))
16320                .and_then(Value::as_str)
16321                .unwrap_or_default();
16322            if let Some(payload) = event.get("payload") {
16323                validate_history_payloads(event_type, payload, export_codec)?;
16324            }
16325        }
16326    }
16327    for signal in export
16328        .get("signals")
16329        .and_then(Value::as_array)
16330        .into_iter()
16331        .flatten()
16332    {
16333        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
16334        validate_payload_codec(codec)?;
16335        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
16336    }
16337    for activity in export
16338        .get("activities")
16339        .and_then(Value::as_array)
16340        .into_iter()
16341        .flatten()
16342    {
16343        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
16344        validate_payload_codec(codec)?;
16345        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
16346        validate_optional_inbound_payload(activity.get("result"), codec)?;
16347    }
16348    Ok(())
16349}
16350
16351fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
16352    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
16353}
16354
16355fn validate_history_payloads(
16356    event_type: &str,
16357    payload: &Value,
16358    fallback_codec: &str,
16359) -> Result<()> {
16360    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
16361    validate_payload_codec(codec)?;
16362    for field in history_payload_fields(event_type) {
16363        validate_optional_inbound_payload(payload.get(*field), codec)?;
16364    }
16365    Ok(())
16366}
16367
16368const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
16369
16370fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
16371    match event_type {
16372        "ActivityCompleted" => &["result"],
16373        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
16374        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
16375        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
16376        "ChildRunCompleted" => &["result", "output"],
16377        "WorkflowCompleted" => &["output"],
16378        "ServiceCallStarted"
16379        | "ServiceCallCompleted"
16380        | "ServiceCallFailed"
16381        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
16382        _ => &[],
16383    }
16384}
16385
16386fn signal_history_payload(payload: &Value) -> Option<&Value> {
16387    SIGNAL_HISTORY_PAYLOAD_FIELDS
16388        .iter()
16389        .find_map(|field| payload.get(*field))
16390}
16391
16392fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
16393    match value.get(field) {
16394        None => Ok(None),
16395        Some(Value::String(codec)) => Ok(Some(codec)),
16396        Some(_) => Err(invalid_payload_envelope()),
16397    }
16398}
16399
16400fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
16401    validate_payload_codec(codec)?;
16402    if let Some(value) = value.filter(|value| !value.is_null()) {
16403        decode_wire_avro_value(value, codec)?;
16404    }
16405    Ok(())
16406}
16407
16408fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
16409    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
16410        invalid_recorded_history(
16411            "parallel_group_metadata_invalid",
16412            sequence,
16413            "non-empty parallel_group_id",
16414            &payload.to_string(),
16415            "parallel-group history is missing its stable identity",
16416        )
16417    })?;
16418    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
16419        invalid_recorded_history(
16420            "parallel_group_metadata_invalid",
16421            sequence,
16422            "activity, child, timer, signal, condition, or mixed group kind",
16423            &payload.to_string(),
16424            "parallel-group history is missing its group kind",
16425        )
16426    })?;
16427    if !matches!(
16428        kind.as_str(),
16429        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
16430    ) {
16431        return Err(invalid_recorded_history(
16432            "parallel_group_metadata_invalid",
16433            sequence,
16434            "activity, child, timer, signal, condition, or mixed group kind",
16435            &kind,
16436            "parallel-group history contains an unsupported group kind",
16437        ));
16438    }
16439    let base_sequence = payload
16440        .get("parallel_group_base_sequence")
16441        .and_then(value_as_u64)
16442        .filter(|value| *value > 0)
16443        .ok_or_else(|| {
16444            invalid_recorded_history(
16445                "parallel_group_metadata_invalid",
16446                sequence,
16447                "positive parallel_group_base_sequence",
16448                &payload.to_string(),
16449                "parallel-group history contains an invalid base sequence",
16450            )
16451        })?;
16452    let size = payload
16453        .get("parallel_group_size")
16454        .and_then(value_as_u64)
16455        .and_then(|value| usize::try_from(value).ok())
16456        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
16457        .ok_or_else(|| {
16458            invalid_recorded_history(
16459                "parallel_group_metadata_invalid",
16460                sequence,
16461                "bounded positive parallel_group_size",
16462                &payload.to_string(),
16463                "parallel-group history contains an invalid group size",
16464            )
16465        })?;
16466    let index = payload
16467        .get("parallel_group_index")
16468        .and_then(value_as_u64)
16469        .and_then(|value| usize::try_from(value).ok())
16470        .filter(|value| *value < size)
16471        .ok_or_else(|| {
16472            invalid_recorded_history(
16473                "parallel_group_metadata_invalid",
16474                sequence,
16475                "parallel_group_index within group bounds",
16476                &payload.to_string(),
16477                "parallel-group history contains an invalid member index",
16478            )
16479        })?;
16480    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
16481        return Err(invalid_recorded_history(
16482            "parallel_group_metadata_invalid",
16483            sequence,
16484            "base sequence plus member index equals workflow sequence",
16485            &payload.to_string(),
16486            "parallel-group path does not preserve durable workflow position",
16487        ));
16488    }
16489    let mode = payload
16490        .get("parallel_group_mode")
16491        .and_then(Value::as_str)
16492        .unwrap_or("all");
16493    if !matches!(mode, "all" | "select") {
16494        return Err(invalid_recorded_history(
16495            "parallel_group_metadata_invalid",
16496            sequence,
16497            "parallel group mode all or select",
16498            mode,
16499            "parallel-group history contains an unsupported group mode",
16500        ));
16501    }
16502    let expected_id = if mode == "select" {
16503        format!("select-calls:{base_sequence}:{size}")
16504    } else {
16505        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
16506    };
16507    if group_id != expected_id {
16508        return Err(invalid_recorded_history(
16509            "parallel_group_metadata_invalid",
16510            sequence,
16511            &expected_id,
16512            &group_id,
16513            "parallel-group history contains an incompatible stable group ID",
16514        ));
16515    }
16516    let selection_member_key = if mode == "select" {
16517        Some(selection_key_from_value(
16518            payload.get("selection_member_key"),
16519            sequence,
16520        )?)
16521    } else {
16522        None
16523    };
16524    let selection_member_index = if mode == "select" {
16525        Some(required_parallel_usize(
16526            payload,
16527            "selection_member_index",
16528            sequence,
16529        )?)
16530    } else {
16531        None
16532    };
16533    let selection_member_base_sequence = if mode == "select" {
16534        Some(
16535            payload
16536                .get("selection_member_base_sequence")
16537                .and_then(value_as_u64)
16538                .filter(|value| *value >= base_sequence)
16539                .ok_or_else(|| {
16540                    invalid_recorded_history(
16541                        "parallel_group_metadata_invalid",
16542                        sequence,
16543                        "selection member base within its group",
16544                        &payload.to_string(),
16545                        "selection history contains an invalid member base sequence",
16546                    )
16547                })?,
16548        )
16549    } else {
16550        None
16551    };
16552    let selection_member_size = if mode == "select" {
16553        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
16554        if member_size == 0 {
16555            return Err(invalid_recorded_history(
16556                "parallel_group_metadata_invalid",
16557                sequence,
16558                "positive selection member size",
16559                &payload.to_string(),
16560                "selection history contains an invalid member size",
16561            ));
16562        }
16563        Some(member_size)
16564    } else {
16565        None
16566    };
16567    let selection_member_kind = if mode == "select" {
16568        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
16569            invalid_recorded_history(
16570                "parallel_group_metadata_invalid",
16571                sequence,
16572                "selection member operation kind",
16573                &payload.to_string(),
16574                "selection history is missing its authored member kind",
16575            )
16576        })?;
16577        if !matches!(
16578            kind.as_str(),
16579            "activity" | "child" | "timer" | "signal" | "condition" | "group"
16580        ) {
16581            return Err(invalid_recorded_history(
16582                "parallel_group_metadata_invalid",
16583                sequence,
16584                "activity, child, timer, signal, condition, or group selection member kind",
16585                &kind,
16586                "selection history contains an unsupported member kind",
16587            ));
16588        }
16589        Some(kind)
16590    } else {
16591        None
16592    };
16593    if let (Some(member_base), Some(member_size)) =
16594        (selection_member_base_sequence, selection_member_size)
16595    {
16596        let member_end = member_base
16597            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
16598            .ok_or_else(|| {
16599                invalid_recorded_history(
16600                    "parallel_group_metadata_invalid",
16601                    sequence,
16602                    "bounded selection member range",
16603                    &payload.to_string(),
16604                    "selection member range overflowed",
16605                )
16606            })?;
16607        let group_end = base_sequence
16608            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
16609            .unwrap_or(u64::MAX);
16610        if sequence < member_base || sequence >= member_end || member_end > group_end {
16611            return Err(invalid_recorded_history(
16612                "parallel_group_metadata_invalid",
16613                sequence,
16614                "workflow sequence within one bounded selection member",
16615                &payload.to_string(),
16616                "selection member range does not contain its durable leaf",
16617            ));
16618        }
16619    }
16620    Ok(ParallelGroupMetadata {
16621        parallel_group_id: group_id,
16622        parallel_group_kind: kind,
16623        parallel_group_base_sequence: base_sequence,
16624        parallel_group_size: size,
16625        parallel_group_index: index,
16626        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
16627        selection_member_key,
16628        selection_member_index,
16629        selection_member_base_sequence,
16630        selection_member_size,
16631        selection_member_kind,
16632    })
16633}
16634
16635fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
16636    payload
16637        .get(field)
16638        .and_then(value_as_u64)
16639        .and_then(|value| usize::try_from(value).ok())
16640        .ok_or_else(|| {
16641            invalid_recorded_history(
16642                "parallel_group_metadata_invalid",
16643                sequence,
16644                &format!("non-negative integer {field}"),
16645                &payload.to_string(),
16646                "selection history contains invalid member metadata",
16647            )
16648        })
16649}
16650
16651fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
16652    match value {
16653        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
16654        Some(value) => value_as_u64(value)
16655            .and_then(|value| usize::try_from(value).ok())
16656            .map(SelectionKey::Index)
16657            .ok_or_else(|| {
16658                invalid_recorded_history(
16659                    "selection_member_key_invalid",
16660                    sequence,
16661                    "non-empty string or non-negative integer member key",
16662                    &value.to_string(),
16663                    "selection history contains an invalid member key",
16664                )
16665            }),
16666        None => Err(invalid_recorded_history(
16667            "selection_member_key_missing",
16668            sequence,
16669            "selection_member_key",
16670            "<missing>",
16671            "selection history is missing its stable member key",
16672        )),
16673    }
16674}
16675
16676fn recorded_parallel_group_path(
16677    events: &[&HistoryEvent],
16678    sequence: u64,
16679) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16680    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
16681    for event in events {
16682        let payload = &event.payload;
16683        let has_metadata = payload.get("parallel_group_path").is_some()
16684            || payload.get("parallel_group_id").is_some()
16685            || payload.get("parallel_group_kind").is_some()
16686            || payload.get("parallel_group_base_sequence").is_some()
16687            || payload.get("parallel_group_size").is_some()
16688            || payload.get("parallel_group_index").is_some()
16689            || payload.get("parallel_group_mode").is_some()
16690            || payload.get("selection_member_key").is_some();
16691        if !has_metadata {
16692            continue;
16693        }
16694
16695        let top_level = recorded_parallel_group_entry(payload, sequence)?;
16696        let path = match payload.get("parallel_group_path") {
16697            None => vec![top_level.clone()],
16698            Some(Value::Array(entries)) if !entries.is_empty() => entries
16699                .iter()
16700                .map(|entry| recorded_parallel_group_entry(entry, sequence))
16701                .collect::<Result<Vec<_>>>()?,
16702            Some(value) => {
16703                return Err(invalid_recorded_history(
16704                    "parallel_group_metadata_invalid",
16705                    sequence,
16706                    "non-empty parallel_group_path list",
16707                    &value.to_string(),
16708                    "parallel-group history contains an invalid group path",
16709                ));
16710            }
16711        };
16712        if path.last() != Some(&top_level) {
16713            return Err(invalid_recorded_history(
16714                "parallel_group_metadata_invalid",
16715                sequence,
16716                &serde_json::to_string(&path.last()).unwrap_or_default(),
16717                &serde_json::to_string(&top_level).unwrap_or_default(),
16718                "parallel-group top-level fields do not match the innermost path entry",
16719            ));
16720        }
16721        if recorded.as_ref().is_some_and(|existing| existing != &path) {
16722            return Err(invalid_recorded_history(
16723                "parallel_group_history_conflict",
16724                sequence,
16725                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
16726                &serde_json::to_string(&path).unwrap_or_default(),
16727                "parallel-group metadata changed between scheduling and resolution history",
16728            ));
16729        }
16730        recorded = Some(path);
16731    }
16732    Ok(recorded)
16733}
16734
16735fn recorded_commands(
16736    events: &[HistoryEvent],
16737    fallback_codec: &str,
16738    parent: WorkflowIdentity,
16739) -> Result<Vec<RecordedCommand>> {
16740    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
16741    let mut last_new_sequence = None;
16742
16743    for event in events {
16744        let is_activity = matches!(
16745            event.event_type.as_str(),
16746            "ActivityScheduled"
16747                | "ActivityStarted"
16748                | "ActivityHeartbeatRecorded"
16749                | "ActivityRetryScheduled"
16750                | "ActivityCompleted"
16751                | "ActivityFailed"
16752                | "ActivityCancelled"
16753                | "ActivityTimedOut"
16754        );
16755        let is_workflow_timer = matches!(
16756            event.event_type.as_str(),
16757            "TimerScheduled" | "TimerCancelled" | "TimerFired"
16758        ) && !is_internal_timer_event(event);
16759        let is_child_workflow = matches!(
16760            event.event_type.as_str(),
16761            "ChildWorkflowScheduled"
16762                | "ChildRunStarted"
16763                | "ChildRunCompleted"
16764                | "ChildRunFailed"
16765                | "ChildRunCancelled"
16766                | "ChildRunTerminated"
16767        );
16768        let is_signal_wait = is_recorded_signal_wait_event(event);
16769        let is_condition_wait = is_recorded_condition_wait_event(event);
16770        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
16771        let is_side_effect = event.event_type == "SideEffectRecorded";
16772        let is_version_marker = event.event_type == "VersionMarkerRecorded";
16773        let is_memo = event.event_type == "MemoUpserted";
16774        let is_service_operation = nexus::is_service_event(event);
16775        if !is_activity
16776            && !is_workflow_timer
16777            && !is_child_workflow
16778            && !is_signal_wait
16779            && !is_condition_wait
16780            && !is_search_attributes
16781            && !is_side_effect
16782            && !is_version_marker
16783            && !is_memo
16784            && !is_service_operation
16785        {
16786            continue;
16787        }
16788
16789        let sequence = durable_event_sequence(event).ok_or_else(|| {
16790            Error::NonDeterministicReplay(ReplayFailure::new(
16791                "durable_command_sequence_missing",
16792                None,
16793                Some("positive workflow sequence".to_string()),
16794                Some(event.event_type.clone()),
16795                "durable command history event has no workflow sequence",
16796            ))
16797        })?;
16798        if sequence == 0 {
16799            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
16800                "durable_command_sequence_invalid",
16801                Some(sequence),
16802                Some("positive workflow sequence".to_string()),
16803                Some(sequence.to_string()),
16804                "durable command history uses an invalid workflow sequence",
16805            )));
16806        }
16807        if !events_by_sequence.contains_key(&sequence) {
16808            if let Some(previous) = last_new_sequence {
16809                if sequence < previous {
16810                    return Err(invalid_recorded_history(
16811                        "durable_command_sequence_mismatch",
16812                        sequence,
16813                        &format!("workflow sequence greater than {previous}"),
16814                        &sequence.to_string(),
16815                        "durable commands are not strictly ordered by their recorded workflow sequence",
16816                    ));
16817                }
16818            }
16819            last_new_sequence = Some(sequence);
16820        }
16821        events_by_sequence.entry(sequence).or_default().push(event);
16822    }
16823
16824    let commands: Vec<RecordedCommand> = events_by_sequence
16825        .into_iter()
16826        .map(|(sequence, sequence_events)| {
16827            let activity_events: Vec<_> = sequence_events
16828                .iter()
16829                .copied()
16830                .filter(|event| event.event_type.starts_with("Activity"))
16831                .collect();
16832            let timer_events: Vec<_> = sequence_events
16833                .iter()
16834                .copied()
16835                .filter(|event| event.event_type.starts_with("Timer"))
16836                .collect();
16837            let child_events: Vec<_> = sequence_events
16838                .iter()
16839                .copied()
16840                .filter(|event| {
16841                    event.event_type == "ChildWorkflowScheduled"
16842                        || event.event_type.starts_with("ChildRun")
16843                })
16844                .collect();
16845            let signal_wait_events: Vec<_> = sequence_events
16846                .iter()
16847                .copied()
16848                .filter(|event| is_recorded_signal_wait_event(event))
16849                .collect();
16850            let condition_wait_events: Vec<_> = sequence_events
16851                .iter()
16852                .copied()
16853                .filter(|event| is_recorded_condition_wait_event(event))
16854                .collect();
16855            let search_attribute_events: Vec<_> = sequence_events
16856                .iter()
16857                .copied()
16858                .filter(|event| event.event_type == "SearchAttributesUpserted")
16859                .collect();
16860            let side_effect_events: Vec<_> = sequence_events
16861                .iter()
16862                .copied()
16863                .filter(|event| event.event_type == "SideEffectRecorded")
16864                .collect();
16865            let version_marker_events: Vec<_> = sequence_events
16866                .iter()
16867                .copied()
16868                .filter(|event| event.event_type == "VersionMarkerRecorded")
16869                .collect();
16870            let memo_events: Vec<_> = sequence_events
16871                .iter()
16872                .copied()
16873                .filter(|event| event.event_type == "MemoUpserted")
16874                .collect();
16875            let service_events: Vec<_> = sequence_events.iter().copied()
16876                .filter(|event| nexus::is_service_event(event)).collect();
16877
16878            let command_kind_count = usize::from(!activity_events.is_empty())
16879                + usize::from(!timer_events.is_empty())
16880                + usize::from(!child_events.is_empty())
16881                + usize::from(!signal_wait_events.is_empty())
16882                + usize::from(!condition_wait_events.is_empty())
16883                + usize::from(!search_attribute_events.is_empty())
16884                + usize::from(!side_effect_events.is_empty())
16885                + usize::from(!version_marker_events.is_empty())
16886                + usize::from(!memo_events.is_empty())
16887                + usize::from(!service_events.is_empty());
16888            if command_kind_count > 1 {
16889                let actual = [
16890                    (!activity_events.is_empty()).then_some("activity"),
16891                    (!timer_events.is_empty()).then_some("timer"),
16892                    (!child_events.is_empty()).then_some("child workflow"),
16893                    (!signal_wait_events.is_empty()).then_some("signal wait"),
16894                    (!condition_wait_events.is_empty()).then_some("condition wait"),
16895                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
16896                    (!side_effect_events.is_empty()).then_some("side effect"),
16897                    (!version_marker_events.is_empty()).then_some("version marker"),
16898                    (!memo_events.is_empty()).then_some("memo upsert"),
16899                    (!service_events.is_empty()).then_some("service operation"),
16900                ]
16901                .into_iter()
16902                .flatten()
16903                .collect::<Vec<_>>()
16904                .join(" and ");
16905                return Err(invalid_recorded_history(
16906                    "durable_command_sequence_collision",
16907                    sequence,
16908                    "one durable command kind",
16909                    &actual,
16910                    "one workflow sequence records more than one durable command kind",
16911                ));
16912            }
16913
16914            if !service_events.is_empty() {
16915                return Ok(RecordedCommand::ServiceOperation {
16916                    sequence, call: nexus::recorded_call(&service_events, sequence, fallback_codec, &parent)?,
16917                });
16918            }
16919
16920            if !activity_events.is_empty() {
16921                let parallel_group_path =
16922                    recorded_parallel_group_path(&activity_events, sequence)?;
16923                let scheduled_count = activity_events
16924                    .iter()
16925                    .filter(|event| event.event_type == "ActivityScheduled")
16926                    .count();
16927                if scheduled_count > 1 {
16928                    return Err(invalid_recorded_history(
16929                        "duplicate_activity_schedule",
16930                        sequence,
16931                        "at most one ActivityScheduled event",
16932                        "multiple ActivityScheduled events",
16933                        "activity history schedules more than one command at one workflow sequence",
16934                    ));
16935                }
16936                let activity_type = activity_events.iter().find_map(|event| {
16937                    event
16938                        .payload
16939                        .get("activity_type")
16940                        .or_else(|| event.payload.get("activity_name"))
16941                        .and_then(Value::as_str)
16942                        .map(str::to_string)
16943                });
16944                if activity_events.iter().filter_map(|event| {
16945                    event
16946                        .payload
16947                        .get("activity_type")
16948                        .or_else(|| event.payload.get("activity_name"))
16949                        .and_then(Value::as_str)
16950                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
16951                    return Err(invalid_recorded_history(
16952                        "activity_identity_mismatch",
16953                        sequence,
16954                        activity_type.as_deref().unwrap_or("one activity identity"),
16955                        "conflicting activity identities",
16956                        "activity lifecycle events at one workflow sequence disagree on identity",
16957                    ));
16958                }
16959                let terminal: Vec<_> = activity_events
16960                    .iter()
16961                    .copied()
16962                    .filter(|event| {
16963                        matches!(
16964                            event.event_type.as_str(),
16965                            "ActivityCompleted"
16966                                | "ActivityFailed"
16967                                | "ActivityCancelled"
16968                                | "ActivityTimedOut"
16969                        )
16970                    })
16971                    .collect();
16972                let duplicate_delivery = terminal.first().is_some_and(|first| {
16973                    terminal.iter().all(|event| {
16974                        event.event_type == first.event_type && event.payload == first.payload
16975                    })
16976                });
16977                if terminal.len() > 1 && !duplicate_delivery {
16978                    return Err(invalid_recorded_history(
16979                        "duplicate_activity_terminal_event",
16980                        sequence,
16981                        "at most one terminal activity event",
16982                        "multiple terminal activity events",
16983                        "activity history settles one command more than once",
16984                    ));
16985                }
16986                let outcome = terminal
16987                    .first()
16988                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
16989                    .transpose()?;
16990                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
16991                let activity_snapshot = activity_events
16992                    .iter()
16993                    .find(|event| event.event_type == "ActivityScheduled")
16994                    .and_then(|event| event.payload.get("activity"))
16995                    .and_then(Value::as_object);
16996                let options = Some(match activity_snapshot {
16997                    Some(activity) => RecordedActivityOptions {
16998                        task_queue: recorded_optional_string(activity, "queue"),
16999                        execution_mode,
17000                        retry_policy: recorded_activity_retry_snapshot(
17001                            activity.get("retry_policy"),
17002                        ),
17003                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
17004                    },
17005                    None => RecordedActivityOptions {
17006                        task_queue: RecordedSnapshotValue::Unknown,
17007                        execution_mode,
17008                        retry_policy: recorded_activity_retry_snapshot(None),
17009                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
17010                    },
17011                });
17012                return Ok(RecordedCommand::Activity {
17013                    sequence,
17014                    activity_type,
17015                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
17016                    options,
17017                    outcome,
17018                    parallel_group_path,
17019                });
17020            }
17021
17022            if !child_events.is_empty() {
17023                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
17024                let scheduled: Vec<_> = child_events
17025                    .iter()
17026                    .copied()
17027                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
17028                    .collect();
17029                if scheduled.len() != 1 {
17030                    return Err(invalid_recorded_history(
17031                        "child_workflow_schedule_missing_or_duplicate",
17032                        sequence,
17033                        "one ChildWorkflowScheduled event",
17034                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
17035                        "child workflow replay requires exactly one recorded schedule event",
17036                    ));
17037                }
17038                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
17039                let workflow_type = child_events.iter().find_map(|event| {
17040                    event
17041                        .payload
17042                        .get("child_workflow_type")
17043                        .or_else(|| event.payload.get("workflow_type"))
17044                        .and_then(Value::as_str)
17045                        .filter(|value| !value.is_empty())
17046                        .map(str::to_string)
17047                });
17048                if child_events
17049                    .iter()
17050                    .filter_map(|event| {
17051                        event
17052                            .payload
17053                            .get("child_workflow_type")
17054                            .or_else(|| event.payload.get("workflow_type"))
17055                            .and_then(Value::as_str)
17056                    })
17057                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
17058                {
17059                    return Err(invalid_recorded_history(
17060                        "child_workflow_identity_mismatch",
17061                        sequence,
17062                        workflow_type
17063                            .as_deref()
17064                            .unwrap_or("one child workflow type"),
17065                        "conflicting child workflow types",
17066                        "child workflow lifecycle events at one sequence disagree on type",
17067                    ));
17068                }
17069                let mut outcomes = child_workflow_outcomes(
17070                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
17071                    fallback_codec,
17072                    parent.clone(),
17073                )?;
17074                let terminal_events = child_events
17075                    .iter()
17076                    .copied()
17077                    .filter(|event| event.event_type.starts_with("ChildRun"))
17078                    .collect::<Vec<_>>();
17079                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
17080                    terminal_events.iter().all(|event| {
17081                        event.event_type == first.event_type && event.payload == first.payload
17082                    })
17083                });
17084                if outcomes.len() > 1 && !duplicate_delivery {
17085                    return Err(invalid_recorded_history(
17086                        "duplicate_child_workflow_terminal_event",
17087                        sequence,
17088                        "at most one terminal child event",
17089                        "multiple terminal child events",
17090                        "child workflow history settles one command more than once",
17091                    ));
17092                }
17093                return Ok(RecordedCommand::ChildWorkflow {
17094                    sequence,
17095                    workflow_type,
17096                    policies,
17097                    outcome: outcomes.pop(),
17098                    parallel_group_path,
17099                });
17100            }
17101
17102            if !signal_wait_events.is_empty() {
17103                let opened: Vec<_> = signal_wait_events
17104                    .iter()
17105                    .copied()
17106                    .filter(|event| event.event_type == "SignalWaitOpened")
17107                    .collect();
17108                if opened.len() != 1 {
17109                    return Err(invalid_recorded_history(
17110                        "signal_wait_open_missing_or_duplicate",
17111                        sequence,
17112                        "one SignalWaitOpened event",
17113                        &format!("{} SignalWaitOpened events", opened.len()),
17114                        "signal replay requires exactly one canonical wait-open event",
17115                    ));
17116                }
17117
17118                let applied: Vec<_> = signal_wait_events
17119                    .iter()
17120                    .copied()
17121                    .filter(|event| event.event_type == "SignalApplied")
17122                    .collect();
17123                if applied.len() > 1 {
17124                    return Err(invalid_recorded_history(
17125                        "duplicate_signal_wait_apply",
17126                        sequence,
17127                        "at most one SignalApplied event",
17128                        "multiple SignalApplied events",
17129                        "signal history applies one durable wait more than once",
17130                    ));
17131                }
17132
17133                let signal_names = signal_wait_events
17134                    .iter()
17135                    .map(|event| required_signal_wait_name(event, sequence))
17136                    .collect::<Result<Vec<_>>>()?;
17137                let signal_name = signal_names
17138                    .first()
17139                    .expect("signal wait events are not empty")
17140                    .clone();
17141                if signal_names.iter().any(|candidate| candidate != &signal_name) {
17142                    return Err(invalid_recorded_history(
17143                        "signal_wait_identity_mismatch",
17144                        sequence,
17145                        &signal_name,
17146                        "conflicting signal names",
17147                        "signal wait lifecycle events at one workflow sequence disagree on identity",
17148                    ));
17149                }
17150                let value = applied
17151                    .first()
17152                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
17153                    .transpose()?;
17154                return Ok(RecordedCommand::SignalWait {
17155                    sequence,
17156                    signal_name,
17157                    value,
17158                    parallel_group_path: recorded_parallel_group_path(
17159                        &signal_wait_events,
17160                        sequence,
17161                    )?,
17162                });
17163            }
17164
17165            if !condition_wait_events.is_empty() {
17166                return recorded_condition_wait(
17167                    sequence,
17168                    &condition_wait_events,
17169                    events,
17170                );
17171            }
17172
17173            if !search_attribute_events.is_empty() {
17174                if search_attribute_events.len() != 1 {
17175                    return Err(invalid_recorded_history(
17176                        "duplicate_search_attribute_update",
17177                        sequence,
17178                        "one SearchAttributesUpserted event",
17179                        &format!(
17180                            "{} SearchAttributesUpserted events",
17181                            search_attribute_events.len()
17182                        ),
17183                        "search-attribute history records one workflow command more than once",
17184                    ));
17185                }
17186                let payload = &search_attribute_events[0].payload;
17187                let attributes = payload
17188                    .get("attributes")
17189                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
17190                    .cloned()
17191                    .ok_or_else(|| {
17192                        invalid_recorded_history(
17193                            "search_attribute_update_missing",
17194                            sequence,
17195                            "non-empty attributes object",
17196                            "missing or invalid attributes",
17197                            "search-attribute history is missing its recorded mutation",
17198                        )
17199                    })?;
17200                let attribute_types =
17201                    recorded_search_attribute_types(payload, &attributes, sequence)?;
17202                return Ok(RecordedCommand::SearchAttributes {
17203                    sequence,
17204                    attributes,
17205                    attribute_types,
17206                });
17207            }
17208
17209            if !side_effect_events.is_empty() {
17210                if side_effect_events.len() != 1 {
17211                    return Err(invalid_recorded_history(
17212                        "duplicate_side_effect_record",
17213                        sequence,
17214                        "one SideEffectRecorded event",
17215                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
17216                        "side-effect history records one workflow command more than once",
17217                    ));
17218                }
17219                let event = side_effect_events[0];
17220                let result = event.payload.get("result").ok_or_else(|| {
17221                    invalid_recorded_history(
17222                        "side_effect_result_missing",
17223                        sequence,
17224                        "recorded result payload",
17225                        "missing result",
17226                        "side-effect history is missing its recorded value",
17227                    )
17228                })?;
17229                let has_published_envelope = result.as_str().is_some()
17230                    || result.as_object().is_some_and(|envelope| {
17231                        envelope.get("codec").and_then(Value::as_str).is_some()
17232                            && envelope.get("blob").and_then(Value::as_str).is_some()
17233                    });
17234                if !has_published_envelope {
17235                    return Err(invalid_recorded_history(
17236                        "side_effect_payload_malformed",
17237                        sequence,
17238                        "payload blob or {codec, blob} envelope",
17239                        &result.to_string(),
17240                        "side-effect history result does not use a published payload envelope",
17241                    ));
17242                }
17243                let codec = event
17244                    .payload
17245                    .get("payload_codec")
17246                    .and_then(Value::as_str)
17247                    .unwrap_or(fallback_codec);
17248                let value = decode_wire_avro_value(result, codec).map_err(|error| {
17249                    if error.to_string().contains("unsupported_payload_codec") {
17250                        return error;
17251                    }
17252
17253                    invalid_recorded_history(
17254                        "side_effect_payload_incompatible",
17255                        sequence,
17256                        &format!("valid {codec} payload envelope"),
17257                        &error.to_string(),
17258                        "side-effect history payload cannot be decoded with its recorded codec",
17259                    )
17260                })?;
17261                return Ok(RecordedCommand::SideEffect { sequence, value });
17262            }
17263
17264            if !version_marker_events.is_empty() {
17265                if version_marker_events.len() != 1 {
17266                    return Err(invalid_recorded_history(
17267                        "duplicate_version_marker_record",
17268                        sequence,
17269                        "one VersionMarkerRecorded event",
17270                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
17271                        "version-marker history records one workflow command more than once",
17272                    ));
17273                }
17274                let payload = &version_marker_events[0].payload;
17275                let change_id = payload
17276                    .get("change_id")
17277                    .and_then(Value::as_str)
17278                    .filter(|value| !value.is_empty())
17279                    .map(str::to_string)
17280                    .ok_or_else(|| {
17281                        invalid_recorded_history(
17282                            "version_marker_field_missing",
17283                            sequence,
17284                            "non-empty change_id",
17285                            "missing or invalid change_id",
17286                            "version-marker history is missing its stable change ID",
17287                        )
17288                    })?;
17289                let version = required_version_i32(payload, "version", sequence)?;
17290                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
17291                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
17292                if min_supported > max_supported || version < min_supported || version > max_supported {
17293                    return Err(invalid_recorded_history(
17294                        "version_marker_history_range_invalid",
17295                        sequence,
17296                        "min_supported <= version <= max_supported",
17297                        &format!("{min_supported} <= {version} <= {max_supported}"),
17298                        "recorded version marker contains an internally incompatible range",
17299                    ));
17300                }
17301                return Ok(RecordedCommand::VersionMarker {
17302                    sequence,
17303                    change_id,
17304                    version,
17305                });
17306            }
17307
17308            if !memo_events.is_empty() {
17309                if memo_events.len() != 1 {
17310                    return Err(invalid_recorded_history(
17311                        "duplicate_memo_upsert_record",
17312                        sequence,
17313                        "one MemoUpserted event",
17314                        &format!("{} MemoUpserted events", memo_events.len()),
17315                        "memo history records one workflow update more than once",
17316                    ));
17317                }
17318                let payload = &memo_events[0].payload;
17319                let entries = payload.get("entries").cloned().ok_or_else(|| {
17320                    invalid_recorded_history(
17321                        "memo_entries_missing",
17322                        sequence,
17323                        "memo entries object",
17324                        "missing entries",
17325                        "MemoUpserted history is missing replay identity entries",
17326                    )
17327                })?;
17328                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
17329                    invalid_recorded_history(
17330                        "memo_entries_invalid",
17331                        sequence,
17332                        "valid canonical memo entries",
17333                        &error.to_string(),
17334                        "MemoUpserted history contains invalid replay identity entries",
17335                    )
17336                })?;
17337                let merged = payload.get("merged").cloned().ok_or_else(|| {
17338                    invalid_recorded_history(
17339                        "memo_merged_projection_missing",
17340                        sequence,
17341                        "merged memo projection",
17342                        "missing merged",
17343                        "MemoUpserted history is missing its merged projection",
17344                    )
17345                })?;
17346                decode_memo_history_map(&merged, false).map_err(|error| {
17347                    invalid_recorded_history(
17348                        "memo_merged_projection_invalid",
17349                        sequence,
17350                        "valid merged memo projection",
17351                        &error.to_string(),
17352                        "MemoUpserted history contains an invalid merged projection",
17353                    )
17354                })?;
17355
17356                return Ok(RecordedCommand::Memo { sequence, entries });
17357            }
17358            let scheduled: Vec<_> = timer_events
17359                .iter()
17360                .copied()
17361                .filter(|event| event.event_type == "TimerScheduled")
17362                .collect();
17363            let fired: Vec<_> = timer_events
17364                .iter()
17365                .copied()
17366                .filter(|event| event.event_type == "TimerFired")
17367                .collect();
17368            if scheduled.len() != 1 {
17369                return Err(invalid_recorded_history(
17370                    "timer_schedule_missing_or_duplicate",
17371                    sequence,
17372                    "one TimerScheduled event",
17373                    &format!("{} TimerScheduled events", scheduled.len()),
17374                    "timer replay requires exactly one recorded schedule event",
17375                ));
17376            }
17377            if fired.len() > 1 {
17378                return Err(invalid_recorded_history(
17379                    "duplicate_timer_fire",
17380                    sequence,
17381                    "at most one TimerFired event",
17382                    "multiple TimerFired events",
17383                    "timer history contains more than one fire event for a workflow sequence",
17384                ));
17385            }
17386
17387            let scheduled = scheduled[0];
17388            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
17389            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
17390            if let Some(fired) = fired.first() {
17391                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
17392                if fired_timer_id != timer_id {
17393                    return Err(invalid_recorded_history(
17394                        "timer_identity_mismatch",
17395                        sequence,
17396                        &timer_id,
17397                        &fired_timer_id,
17398                        "TimerFired does not correspond to the recorded TimerScheduled event",
17399                    ));
17400                }
17401                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
17402                if fired_delay != delay_seconds {
17403                    return Err(invalid_recorded_history(
17404                        "timer_history_delay_mismatch",
17405                        sequence,
17406                        &delay_seconds.to_string(),
17407                        &fired_delay.to_string(),
17408                        "TimerScheduled and TimerFired record different delays",
17409                    ));
17410                }
17411            }
17412
17413            Ok(RecordedCommand::Timer {
17414                sequence,
17415                delay_seconds,
17416                fired: !fired.is_empty(),
17417                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
17418            })
17419        })
17420        .collect::<Result<_>>()?;
17421
17422    let mut marker_decisions = HashMap::new();
17423    for command in &commands {
17424        if let RecordedCommand::VersionMarker {
17425            sequence,
17426            change_id,
17427            version,
17428        } = command
17429        {
17430            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
17431                if version != first_version {
17432                    return Err(invalid_recorded_history(
17433                        "version_marker_conflict",
17434                        *sequence,
17435                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
17436                        &format!("version {version} at sequence {sequence}"),
17437                        "workflow history contains conflicting decisions for one stable change ID",
17438                    ));
17439                }
17440            } else {
17441                marker_decisions.insert(change_id.clone(), (*version, *sequence));
17442            }
17443        }
17444    }
17445
17446    Ok(commands)
17447}
17448
17449fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
17450    payload
17451        .get(field)
17452        .and_then(Value::as_i64)
17453        .and_then(|value| i32::try_from(value).ok())
17454        .ok_or_else(|| {
17455            invalid_recorded_history(
17456                "version_marker_field_missing",
17457                sequence,
17458                &format!("integer {field}"),
17459                "missing or out-of-range integer",
17460                "version-marker history is missing a required integer field",
17461            )
17462        })
17463}
17464
17465fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
17466    event
17467        .payload
17468        .get("sequence")
17469        .or_else(|| event.payload.get("workflow_sequence"))
17470        .or_else(|| event.raw.get("sequence"))
17471        .or_else(|| event.raw.get("workflow_sequence"))
17472        .and_then(value_as_u64)
17473}
17474
17475fn is_internal_timer_event(event: &HistoryEvent) -> bool {
17476    matches!(
17477        event
17478            .payload
17479            .get("timer_kind")
17480            .or_else(|| event.raw.get("timer_kind"))
17481            .and_then(Value::as_str),
17482        Some("condition_timeout" | "signal_timeout")
17483    )
17484}
17485
17486fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
17487    matches!(
17488        event.event_type.as_str(),
17489        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
17490    )
17491}
17492
17493fn recorded_condition_wait(
17494    sequence: u64,
17495    condition_events: &[&HistoryEvent],
17496    all_events: &[HistoryEvent],
17497) -> Result<RecordedCommand> {
17498    let opened = condition_events
17499        .iter()
17500        .copied()
17501        .filter(|event| event.event_type == "ConditionWaitOpened")
17502        .collect::<Vec<_>>();
17503    if opened.len() != 1 {
17504        return Err(invalid_recorded_history(
17505            "condition_wait_open_missing_or_duplicate",
17506            sequence,
17507            "one ConditionWaitOpened event",
17508            &format!("{} ConditionWaitOpened events", opened.len()),
17509            "condition replay requires exactly one canonical wait-open event",
17510        ));
17511    }
17512    let terminal = condition_events
17513        .iter()
17514        .copied()
17515        .filter(|event| {
17516            matches!(
17517                event.event_type.as_str(),
17518                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
17519            )
17520        })
17521        .collect::<Vec<_>>();
17522    if terminal.len() > 1 {
17523        return Err(invalid_recorded_history(
17524            "duplicate_condition_wait_terminal_event",
17525            sequence,
17526            "at most one condition terminal event",
17527            "multiple condition terminal events",
17528            "condition history settles one durable wait more than once",
17529        ));
17530    }
17531
17532    let opened = opened[0];
17533    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
17534    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
17535    for event in condition_events
17536        .iter()
17537        .copied()
17538        .filter(|event| !std::ptr::eq(*event, opened))
17539    {
17540        let event_wait_id = required_condition_wait_id(event, sequence)?;
17541        if event_wait_id != condition_wait_id {
17542            return Err(invalid_recorded_history(
17543                "condition_wait_id_mismatch",
17544                sequence,
17545                &condition_wait_id,
17546                &event_wait_id,
17547                "condition lifecycle events at one sequence disagree on wait identity",
17548            ));
17549        }
17550        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
17551        if event_occurrence_id != occurrence_id {
17552            return Err(invalid_recorded_history(
17553                "condition_wait_occurrence_history_mismatch",
17554                sequence,
17555                &occurrence_id,
17556                &event_occurrence_id,
17557                "condition lifecycle events at one sequence disagree on authored occurrence identity",
17558            ));
17559        }
17560    }
17561
17562    let condition_key = optional_non_empty_history_string(opened, "condition_key");
17563    let predicate_identity = opened
17564        .payload
17565        .get("condition_definition_fingerprint")
17566        .and_then(Value::as_str)
17567        .filter(|value| !value.is_empty())
17568        .map(str::to_string)
17569        .ok_or_else(|| {
17570            invalid_recorded_history(
17571                "condition_wait_predicate_fingerprint_missing",
17572                sequence,
17573                "non-empty condition_definition_fingerprint",
17574                &opened.event_type,
17575                "canonical condition history is missing its predicate identity",
17576            )
17577        })?;
17578    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
17579    for event in condition_events
17580        .iter()
17581        .copied()
17582        .filter(|event| !std::ptr::eq(*event, opened))
17583    {
17584        for (field, opened_value) in [
17585            ("condition_key", condition_key.as_deref()),
17586            (
17587                "condition_definition_fingerprint",
17588                Some(predicate_identity.as_str()),
17589            ),
17590        ] {
17591            if let Some(value) = optional_non_empty_history_string(event, field) {
17592                if opened_value.is_some_and(|opened_value| opened_value != value) {
17593                    return Err(invalid_recorded_history(
17594                        "condition_wait_definition_history_mismatch",
17595                        sequence,
17596                        opened_value.unwrap_or_default(),
17597                        &value,
17598                        "condition lifecycle events disagree on the recorded definition",
17599                    ));
17600                }
17601            }
17602        }
17603        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
17604            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
17605                return Err(invalid_recorded_history(
17606                    "condition_wait_definition_history_mismatch",
17607                    sequence,
17608                    &format!("{}s", timeout_seconds.unwrap_or_default()),
17609                    &format!("{event_timeout}s"),
17610                    "condition lifecycle events disagree on the recorded timeout",
17611                ));
17612            }
17613        }
17614    }
17615
17616    let timeout_timer_events = all_events
17617        .iter()
17618        .filter(|event| {
17619            matches!(
17620                event.event_type.as_str(),
17621                "TimerScheduled" | "TimerCancelled" | "TimerFired"
17622            ) && event.payload.get("timer_kind").and_then(Value::as_str)
17623                == Some("condition_timeout")
17624                && event
17625                    .payload
17626                    .get("condition_wait_id")
17627                    .and_then(Value::as_str)
17628                    == Some(condition_wait_id.as_str())
17629        })
17630        .collect::<Vec<_>>();
17631    let scheduled = timeout_timer_events
17632        .iter()
17633        .copied()
17634        .filter(|event| event.event_type == "TimerScheduled")
17635        .collect::<Vec<_>>();
17636    let fired = timeout_timer_events
17637        .iter()
17638        .copied()
17639        .filter(|event| event.event_type == "TimerFired")
17640        .collect::<Vec<_>>();
17641    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
17642        return Err(invalid_recorded_history(
17643            "condition_wait_timeout_history_invalid",
17644            sequence,
17645            "one timeout schedule and at most one fire",
17646            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
17647            "condition timeout history has a missing or duplicate lifecycle event",
17648        ));
17649    }
17650    if let Some(scheduled) = scheduled.first() {
17651        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
17652        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
17653        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
17654            return Err(invalid_recorded_history(
17655                "condition_wait_timeout_delay_mismatch",
17656                sequence,
17657                &format!("{}s", timeout_seconds.unwrap_or_default()),
17658                &format!("{delay_seconds}s"),
17659                "condition timeout timer differs from the wait definition",
17660            ));
17661        }
17662        if let Some(fired) = fired.first() {
17663            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
17664            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
17665            if fired_timer_id != timer_id || fired_delay != delay_seconds {
17666                return Err(invalid_recorded_history(
17667                    "condition_wait_timeout_identity_mismatch",
17668                    sequence,
17669                    &format!("{timer_id}:{delay_seconds}s"),
17670                    &format!("{fired_timer_id}:{fired_delay}s"),
17671                    "condition timeout fire does not match its durable schedule",
17672                ));
17673            }
17674        }
17675    }
17676
17677    let result = terminal.first().map(|event| {
17678        if event.event_type == "ConditionWaitTimedOut" {
17679            ConditionWaitResult::TimedOut
17680        } else {
17681            ConditionWaitResult::Satisfied
17682        }
17683    });
17684    let result = if !fired.is_empty() {
17685        if result == Some(ConditionWaitResult::Satisfied) {
17686            return Err(invalid_recorded_history(
17687                "condition_wait_terminal_conflict",
17688                sequence,
17689                "one satisfied or timed-out outcome",
17690                "satisfied event and fired timeout",
17691                "condition history records conflicting terminal outcomes",
17692            ));
17693        }
17694        Some(ConditionWaitResult::TimedOut)
17695    } else {
17696        result
17697    };
17698
17699    Ok(RecordedCommand::ConditionWait {
17700        sequence,
17701        occurrence_id,
17702        condition_key,
17703        predicate_identity,
17704        timeout_seconds,
17705        result,
17706        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
17707    })
17708}
17709
17710fn recorded_condition_group_path(
17711    condition_events: &[&HistoryEvent],
17712    all_events: &[HistoryEvent],
17713    sequence: u64,
17714) -> Result<Option<Vec<ParallelGroupMetadata>>> {
17715    let opened = condition_events
17716        .iter()
17717        .copied()
17718        .find(|event| event.event_type == "ConditionWaitOpened")
17719        .expect("canonical condition opener is validated first");
17720    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
17721    let previous_events = all_events
17722        .iter()
17723        .take_while(|event| !std::ptr::eq(*event, opened))
17724        .collect::<Vec<_>>();
17725    let originals = previous_events
17726        .iter()
17727        .copied()
17728        .filter(|event| event.event_type == "ConditionWaitOpened")
17729        .filter(|event| {
17730            event
17731                .payload
17732                .get("condition_wait_occurrence_id")
17733                .and_then(Value::as_str)
17734                == Some(occurrence.as_str())
17735        })
17736        .collect::<Vec<_>>();
17737    let Some(original) = originals.first().copied() else {
17738        return recorded_parallel_group_path(condition_events, sequence);
17739    };
17740    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
17741    if authored_sequence == sequence {
17742        return recorded_parallel_group_path(condition_events, sequence);
17743    }
17744    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
17745    if original_path.is_none() {
17746        return recorded_parallel_group_path(condition_events, sequence);
17747    }
17748    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
17749    let identity_matches = [
17750        "condition_key",
17751        "condition_definition_fingerprint",
17752        "timeout_seconds",
17753    ]
17754    .iter()
17755    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
17756    let previous = originals
17757        .iter()
17758        .copied()
17759        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
17760        .max_by_key(|event| durable_event_sequence(event));
17761    let previously_satisfied = previous.is_some_and(|previous| {
17762        previous_events.iter().any(|event| {
17763            event.event_type == "ConditionWaitSatisfied"
17764                && event.payload.get("condition_wait_id")
17765                    == previous.payload.get("condition_wait_id")
17766                && event.payload.get("condition_wait_occurrence_id")
17767                    == previous.payload.get("condition_wait_occurrence_id")
17768                && durable_event_sequence(event) == durable_event_sequence(previous)
17769        })
17770    });
17771    if !identity_matches || reopened_path != original_path || !previously_satisfied {
17772        return Err(invalid_recorded_history(
17773            "condition_wait_group_reopen_mismatch",
17774            sequence,
17775            "same authored condition and group path after a satisfied physical wait",
17776            &opened.payload.to_string(),
17777            "grouped condition reopen has no matching recorded predecessor",
17778        ));
17779    }
17780    Ok(reopened_path)
17781}
17782
17783fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17784    event
17785        .payload
17786        .get("condition_wait_occurrence_id")
17787        .and_then(Value::as_str)
17788        .filter(|value| !value.is_empty())
17789        .map(str::to_string)
17790        .ok_or_else(|| {
17791            invalid_recorded_history(
17792                "condition_wait_occurrence_id_missing",
17793                sequence,
17794                "non-empty condition_wait_occurrence_id",
17795                &event.event_type,
17796                "condition history is missing authored occurrence identity",
17797            )
17798        })
17799}
17800
17801fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17802    event
17803        .payload
17804        .get("condition_wait_id")
17805        .and_then(Value::as_str)
17806        .filter(|value| !value.is_empty())
17807        .map(str::to_string)
17808        .ok_or_else(|| {
17809            invalid_recorded_history(
17810                "condition_wait_id_missing",
17811                sequence,
17812                "non-empty condition_wait_id",
17813                &event.event_type,
17814                "canonical condition history is missing its durable wait identity",
17815            )
17816        })
17817}
17818
17819fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
17820    event
17821        .payload
17822        .get(field)
17823        .and_then(Value::as_str)
17824        .filter(|value| !value.is_empty())
17825        .map(str::to_string)
17826}
17827
17828fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
17829    match event.payload.get(field) {
17830        None | Some(Value::Null) => Ok(None),
17831        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
17832            invalid_recorded_history(
17833                "condition_wait_definition_invalid",
17834                sequence,
17835                &format!("non-negative integer {field}"),
17836                &value.to_string(),
17837                "condition history contains an invalid numeric definition field",
17838            )
17839        }),
17840    }
17841}
17842
17843fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
17844    event
17845        .payload
17846        .get("signal_name")
17847        .or_else(|| event.raw.get("signal_name"))
17848        .and_then(Value::as_str)
17849        .filter(|value| !value.is_empty())
17850        .map(str::to_string)
17851        .ok_or_else(|| {
17852            invalid_recorded_history(
17853                "signal_wait_name_missing",
17854                sequence,
17855                "non-empty signal_name",
17856                &event.event_type,
17857                "canonical signal-wait history is missing its signal identity",
17858            )
17859        })
17860}
17861
17862fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
17863    // Applying a buffered control-plane signal has no authored call sequence.
17864    // Its outer sequence orders history events and must not become a wait.
17865    if event.event_type == "SignalApplied"
17866        && event
17867            .payload
17868            .get("signal_wait_id")
17869            .and_then(Value::as_str)
17870            .is_some_and(|id| id.starts_with("signal-command:"))
17871        && event.payload.get("sequence").is_none()
17872        && event.payload.get("workflow_sequence").is_none()
17873    {
17874        return false;
17875    }
17876    matches!(
17877        event.event_type.as_str(),
17878        "SignalWaitOpened" | "SignalApplied"
17879    )
17880}
17881
17882fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
17883    event
17884        .payload
17885        .get(field)
17886        .and_then(Value::as_str)
17887        .filter(|value| !value.is_empty())
17888        .map(str::to_string)
17889        .ok_or_else(|| {
17890            invalid_recorded_history(
17891                "timer_history_field_missing",
17892                sequence,
17893                field,
17894                &event.event_type,
17895                "timer history is missing a required identity field",
17896            )
17897        })
17898}
17899
17900fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
17901    event
17902        .payload
17903        .get(field)
17904        .and_then(value_as_u64)
17905        .ok_or_else(|| {
17906            invalid_recorded_history(
17907                "timer_history_field_missing",
17908                sequence,
17909                field,
17910                &event.event_type,
17911                "timer history is missing a required numeric field",
17912            )
17913        })
17914}
17915
17916fn recorded_search_attribute_types(
17917    payload: &Value,
17918    attributes: &Value,
17919    sequence: u64,
17920) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
17921    let Some(raw_types) = payload.get("attribute_types") else {
17922        // This is the explicit compatibility rule for histories recorded
17923        // before typed identity was persisted. Values still constrain replay;
17924        // the unknown type snapshot does not assert a typed match.
17925        return Ok(RecordedSnapshotValue::Unknown);
17926    };
17927    let Some(raw_types) = raw_types.as_object() else {
17928        return Err(invalid_recorded_history(
17929            "search_attribute_types_malformed",
17930            sequence,
17931            "canonical attribute type map",
17932            &raw_types.to_string(),
17933            "search-attribute history contains malformed type identity",
17934        ));
17935    };
17936    let attribute_keys = attributes
17937        .as_object()
17938        .expect("recorded search attributes were validated as an object");
17939    let mut types = BTreeMap::new();
17940    for (key, value) in raw_types {
17941        let Some(attribute_type) = value.as_str() else {
17942            return Err(invalid_recorded_history(
17943                "search_attribute_types_malformed",
17944                sequence,
17945                "canonical string type name",
17946                &value.to_string(),
17947                "search-attribute history contains a non-string type identity",
17948            ));
17949        };
17950        if !attribute_keys.contains_key(key)
17951            || !matches!(
17952                attribute_type,
17953                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
17954            )
17955        {
17956            return Err(invalid_recorded_history(
17957                "search_attribute_types_malformed",
17958                sequence,
17959                "canonical types for keys present in attributes",
17960                &format!("{key}:{attribute_type}"),
17961                "search-attribute history contains unsupported or orphaned type identity",
17962            ));
17963        }
17964        types.insert(key.clone(), attribute_type.to_string());
17965    }
17966    Ok(RecordedSnapshotValue::Known(types))
17967}
17968
17969fn invalid_recorded_history(
17970    reason: &str,
17971    sequence: u64,
17972    expected: &str,
17973    actual: &str,
17974    message: &str,
17975) -> Error {
17976    Error::NonDeterministicReplay(ReplayFailure::new(
17977        reason,
17978        Some(sequence),
17979        Some(expected.to_string()),
17980        Some(actual.to_string()),
17981        message,
17982    ))
17983}
17984
17985type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
17986
17987fn activity_outcome(
17988    event: &HistoryEvent,
17989    fallback_codec: &str,
17990    recorded_activity_type: Option<String>,
17991) -> Result<ActivityOutcome> {
17992    if event.event_type == "ActivityCompleted" {
17993        let codec = event
17994            .payload
17995            .get("payload_codec")
17996            .and_then(Value::as_str)
17997            .unwrap_or(fallback_codec);
17998        return Ok(Ok(decode_wire_avro_value(
17999            event.payload.get("result").unwrap_or(&Value::Null),
18000            codec,
18001        )?));
18002    }
18003
18004    let payload = &event.payload;
18005    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
18006        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
18007        "ActivityCancelled" => (
18008            ActivityFailureKind::Cancelled,
18009            "cancelled",
18010            "activity was cancelled",
18011        ),
18012        "ActivityTimedOut" => (
18013            ActivityFailureKind::TimedOut,
18014            "timeout",
18015            "activity timed out",
18016        ),
18017        _ => unreachable!("activity_outcome is called only for terminal activity events"),
18018    };
18019    let exception = payload
18020        .get("exception")
18021        .filter(|value| !value.is_null())
18022        .cloned();
18023    let failure_category = payload_string(payload, "failure_category");
18024    let timeout_kind = payload_string(payload, "timeout_kind");
18025    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
18026        ActivityFailureKind::Failed => failure_category
18027            .clone()
18028            .unwrap_or_else(|| fallback_reason.to_string()),
18029        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
18030        ActivityFailureKind::TimedOut => timeout_kind
18031            .clone()
18032            .unwrap_or_else(|| fallback_reason.to_string()),
18033    });
18034    let message = payload_string(payload, "message")
18035        .or_else(|| {
18036            exception
18037                .as_ref()
18038                .and_then(|value| payload_string(value, "message"))
18039        })
18040        .unwrap_or_else(|| fallback_message.to_string());
18041
18042    Ok(Err(ActivityFailure {
18043        kind,
18044        reason,
18045        message,
18046        activity_execution_id: payload_string(payload, "activity_execution_id"),
18047        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
18048        activity_type: payload_string(payload, "activity_type")
18049            .or_else(|| payload_string(payload, "activity_name"))
18050            .or(recorded_activity_type),
18051        activity_class: payload_string(payload, "activity_class"),
18052        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
18053        failure_id: payload_string(payload, "failure_id"),
18054        failure_category,
18055        timeout_kind,
18056        non_retryable: payload
18057            .get("non_retryable")
18058            .and_then(Value::as_bool)
18059            .unwrap_or(false),
18060        exception_type: payload_string(payload, "exception_type").or_else(|| {
18061            exception
18062                .as_ref()
18063                .and_then(|value| payload_string(value, "type"))
18064        }),
18065        exception_class: payload_string(payload, "exception_class").or_else(|| {
18066            exception
18067                .as_ref()
18068                .and_then(|value| payload_string(value, "class"))
18069        }),
18070        code: payload
18071            .get("code")
18072            .filter(|value| !value.is_null())
18073            .cloned(),
18074        exception,
18075    }))
18076}
18077
18078type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
18079
18080fn child_workflow_outcomes(
18081    events: &[HistoryEvent],
18082    fallback_codec: &str,
18083    parent: WorkflowIdentity,
18084) -> Result<Vec<ChildWorkflowOutcome>> {
18085    let mut outcomes = Vec::new();
18086
18087    for event in events {
18088        let kind = match event.event_type.as_str() {
18089            "ChildRunCompleted" => None,
18090            "ChildRunFailed" => Some((
18091                ChildWorkflowFailureKind::Failed,
18092                "child_workflow",
18093                "child workflow failed",
18094            )),
18095            "ChildRunCancelled" => Some((
18096                ChildWorkflowFailureKind::Cancelled,
18097                "cancelled",
18098                "child workflow was cancelled",
18099            )),
18100            "ChildRunTerminated" => Some((
18101                ChildWorkflowFailureKind::Terminated,
18102                "terminated",
18103                "child workflow was terminated",
18104            )),
18105            _ => continue,
18106        };
18107        let payload = &event.payload;
18108        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
18109        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
18110        let child_workflow_type = payload_string(payload, "child_workflow_type");
18111
18112        if let Some((kind, reason, fallback_message)) = kind {
18113            let exception = payload
18114                .get("exception")
18115                .filter(|value| !value.is_null())
18116                .cloned();
18117            let message = payload_string(payload, "message")
18118                .or_else(|| {
18119                    exception
18120                        .as_ref()
18121                        .and_then(|value| payload_string(value, "message"))
18122                })
18123                .unwrap_or_else(|| fallback_message.to_string());
18124            let exception_type = payload_string(payload, "exception_type").or_else(|| {
18125                exception
18126                    .as_ref()
18127                    .and_then(|value| payload_string(value, "type"))
18128            });
18129            let exception_class = payload_string(payload, "exception_class").or_else(|| {
18130                exception
18131                    .as_ref()
18132                    .and_then(|value| payload_string(value, "class"))
18133            });
18134            outcomes.push(Err(ChildWorkflowFailure {
18135                kind,
18136                reason: reason.to_string(),
18137                message,
18138                parent_workflow_id: parent.workflow_id.clone(),
18139                parent_workflow_run_id: parent.run_id.clone(),
18140                child_workflow_id,
18141                child_workflow_run_id,
18142                child_workflow_type,
18143                failure_id: payload_string(payload, "failure_id"),
18144                failure_category: payload_string(payload, "failure_category"),
18145                exception_type,
18146                exception_class,
18147                non_retryable: payload
18148                    .get("non_retryable")
18149                    .and_then(Value::as_bool)
18150                    .unwrap_or(false),
18151                code: payload
18152                    .get("code")
18153                    .filter(|value| !value.is_null())
18154                    .cloned(),
18155                exception,
18156            }));
18157            continue;
18158        }
18159
18160        let codec = payload
18161            .get("payload_codec")
18162            .and_then(Value::as_str)
18163            .unwrap_or(fallback_codec);
18164        let result = payload
18165            .get("result")
18166            .or_else(|| payload.get("output"))
18167            .unwrap_or(&Value::Null);
18168        outcomes.push(Ok(ChildWorkflowAvroResult {
18169            parent: parent.clone(),
18170            child: WorkflowIdentity {
18171                workflow_id: child_workflow_id,
18172                run_id: child_workflow_run_id,
18173            },
18174            child_workflow_type,
18175            result: decode_wire_avro_value(result, codec)?,
18176        }));
18177    }
18178
18179    Ok(outcomes)
18180}
18181
18182fn payload_string(payload: &Value, key: &str) -> Option<String> {
18183    payload
18184        .get(key)
18185        .and_then(Value::as_str)
18186        .filter(|value| !value.is_empty())
18187        .map(str::to_string)
18188}
18189
18190fn recorded_activity_failure_boundary(
18191    ctx: &WorkflowContext,
18192    error: &Error,
18193) -> Option<(u64, String)> {
18194    let Error::ActivityFailed(failure) = error else {
18195        return None;
18196    };
18197    if failure.kind != ActivityFailureKind::Failed {
18198        return None;
18199    }
18200    let activity_execution_id = failure
18201        .activity_execution_id
18202        .as_deref()
18203        .filter(|value| !value.is_empty())?;
18204    let state = ctx.state.lock().ok()?;
18205    let mut matches = state.recorded_commands.iter().filter_map(|command| {
18206        let RecordedCommand::Activity {
18207            sequence,
18208            outcome: Some(Err(recorded_failure)),
18209            ..
18210        } = command
18211        else {
18212            return None;
18213        };
18214        (*sequence > 0 && recorded_failure == failure)
18215            .then_some((*sequence, activity_execution_id.to_string()))
18216    });
18217    let boundary = matches.next()?;
18218    matches.next().is_none().then_some(boundary)
18219}
18220
18221fn workflow_failure_command(
18222    error: &Error,
18223    failed_activity_boundary: Option<(u64, String)>,
18224) -> Value {
18225    let (exception_type, exception_class, properties) = match error {
18226        Error::NexusOperationFailed(failure) => (
18227            "NexusOperationFailed",
18228            "durable_workflow::NexusOperationFailure",
18229            json!({"service_call_id":failure.service_call_id, "status":failure.status,
18230                "caller_observed_error_type":failure.exception_type, "service_exception":failure.exception}),
18231        ),
18232        Error::ActivityFailed(failure) => (
18233            match failure.kind {
18234                ActivityFailureKind::Failed => "ActivityFailed",
18235                ActivityFailureKind::Cancelled => "ActivityCancelled",
18236                ActivityFailureKind::TimedOut => "ActivityTimedOut",
18237            },
18238            "durable_workflow::ActivityFailure",
18239            json!({
18240                "reason": failure.reason,
18241                "activity_execution_id": failure.activity_execution_id,
18242                "activity_attempt_id": failure.activity_attempt_id,
18243                "activity_type": failure.activity_type,
18244                "activity_class": failure.activity_class,
18245                "attempt_number": failure.attempt_number,
18246                "failure_id": failure.failure_id,
18247                "failure_category": failure.failure_category,
18248                "timeout_kind": failure.timeout_kind,
18249                "activity_non_retryable": failure.non_retryable,
18250                "activity_exception_type": failure.exception_type,
18251                "activity_exception_class": failure.exception_class,
18252                "activity_code": failure.code,
18253                "activity_exception": failure.exception,
18254            }),
18255        ),
18256        Error::ChildWorkflowFailed(failure) => (
18257            match failure.kind {
18258                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
18259                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
18260                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
18261            },
18262            "durable_workflow::ChildWorkflowFailure",
18263            json!({
18264                "reason": failure.reason,
18265                "parent_workflow_id": failure.parent_workflow_id,
18266                "parent_workflow_run_id": failure.parent_workflow_run_id,
18267                "child_workflow_id": failure.child_workflow_id,
18268                "child_workflow_run_id": failure.child_workflow_run_id,
18269                "child_workflow_type": failure.child_workflow_type,
18270                "failure_id": failure.failure_id,
18271                "failure_category": failure.failure_category,
18272                "child_exception_type": failure.exception_type,
18273                "child_exception_class": failure.exception_class,
18274                "child_non_retryable": failure.non_retryable,
18275                "child_code": failure.code,
18276                "child_exception": failure.exception,
18277            }),
18278        ),
18279        Error::ParallelFailed(failure) => (
18280            "ParallelFailed",
18281            "durable_workflow::ParallelFailure",
18282            json!({
18283                "parallel_group_id": failure.group_id,
18284                "parallel_member_path": failure.member_path,
18285                "parallel_group_path": failure.group_path,
18286                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
18287                "cause_type": workflow_error_type(&failure.cause),
18288                "cause_message": failure.cause.to_string(),
18289            }),
18290        ),
18291        Error::SagaCompensationFailed(failure) => (
18292            "SagaCompensationFailed",
18293            "durable_workflow::SagaCompensationFailure",
18294            json!({
18295                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
18296                "initiating_failure_message": failure.initiating_failure.to_string(),
18297                "compensation_activity_type": failure.compensation_activity_type,
18298                "compensation_registration_order": failure.compensation_registration_order,
18299                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
18300                "compensation_failure_message": failure.compensation_failure.to_string(),
18301            }),
18302        ),
18303        Error::WorkflowCancellationRequested(_) => (
18304            "WorkflowCancellationRequested",
18305            "durable_workflow::WorkflowCancellationRequested",
18306            json!({"reason": "cancelled"}),
18307        ),
18308        Error::CooperativeCancellationRequested(cancellation) => (
18309            "WorkflowCancellationRequested",
18310            "durable_workflow::CooperativeCancellationRequested",
18311            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
18312                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
18313        ),
18314        Error::CancellationScopeRequested(cancellation) => (
18315            "WorkflowCancellationRequested",
18316            "durable_workflow::CancellationScopeRequested",
18317            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
18318                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
18319                "cancellation":cancellation.context.to_value()}),
18320        ),
18321        Error::NonDeterministicReplay(_) => (
18322            "NonDeterministicReplay",
18323            "durable_workflow::Error",
18324            Value::Null,
18325        ),
18326        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
18327    };
18328    let non_retryable = match error {
18329        Error::ActivityFailed(failure) => failure.non_retryable,
18330        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
18331        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
18332        Error::SagaCompensationFailed(failure) => {
18333            workflow_error_non_retryable(&failure.compensation_failure)
18334        }
18335        Error::WorkflowCancellationRequested(_)
18336        | Error::CooperativeCancellationRequested(_)
18337        | Error::CancellationScopeRequested(_) => true,
18338        Error::NonDeterministicReplay(_) => true,
18339        _ => false,
18340    };
18341
18342    let mut command = json!({
18343        "type": "fail_workflow",
18344        "message": error.to_string(),
18345        "exception_type": exception_type,
18346        "exception_class": exception_class,
18347        "non_retryable": non_retryable,
18348        "exception": {
18349            "type": exception_type,
18350            "class": exception_class,
18351            "message": error.to_string(),
18352            "properties": properties,
18353        }
18354    });
18355
18356    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
18357        command["failed_step_sequence"] = json!(sequence);
18358        command["failed_activity_execution_id"] = json!(activity_execution_id);
18359    }
18360
18361    command
18362}
18363
18364fn workflow_error_type(error: &Error) -> &'static str {
18365    match error {
18366        Error::NexusOperationFailed(_) => "NexusOperationFailed",
18367        Error::ActivityFailed(failure) => match failure.kind {
18368            ActivityFailureKind::Failed => "ActivityFailed",
18369            ActivityFailureKind::Cancelled => "ActivityCancelled",
18370            ActivityFailureKind::TimedOut => "ActivityTimedOut",
18371        },
18372        Error::ChildWorkflowFailed(failure) => match failure.kind {
18373            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
18374            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
18375            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
18376        },
18377        Error::ParallelFailed(_) => "ParallelFailed",
18378        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
18379        Error::WorkflowCancellationRequested(_)
18380        | Error::CooperativeCancellationRequested(_)
18381        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
18382        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
18383        _ => "RustWorkflowError",
18384    }
18385}
18386
18387fn workflow_error_non_retryable(error: &Error) -> bool {
18388    match error {
18389        Error::ActivityFailed(failure) => failure.non_retryable,
18390        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
18391        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
18392        Error::SagaCompensationFailed(failure) => {
18393            workflow_error_non_retryable(&failure.compensation_failure)
18394        }
18395        Error::WorkflowCancellationRequested(_)
18396        | Error::CooperativeCancellationRequested(_)
18397        | Error::CancellationScopeRequested(_)
18398        | Error::NonDeterministicReplay(_) => true,
18399        _ => false,
18400    }
18401}
18402
18403fn workflow_task_integrity_error(error: &Error) -> bool {
18404    matches!(
18405        error,
18406        Error::NonDeterministicReplay(_)
18407            | Error::Protocol(_)
18408            | Error::CancellationScopeExecutionUnavailable
18409            | Error::MissingWorkflowCommandIdentity
18410            | Error::WorkflowStatePoisoned
18411    )
18412}
18413
18414fn decode_signal_event_arguments(
18415    event: &HistoryEvent,
18416    fallback_codec: &str,
18417) -> Result<Vec<AvroValue>> {
18418    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
18419    validate_payload_codec(codec)?;
18420    let raw = signal_history_payload(&event.payload);
18421    let decoded = match raw.filter(|value| !value.is_null()) {
18422        Some(value) => decode_wire_avro_value(value, codec)?,
18423        None => AvroValue::Array(Vec::new()),
18424    };
18425    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
18426        unreachable!("normalize_avro_arguments always returns an array");
18427    };
18428    Ok(arguments)
18429}
18430
18431fn decode_update_event_arguments(
18432    event: &HistoryEvent,
18433    fallback_codec: &str,
18434) -> Result<Vec<AvroValue>> {
18435    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
18436    validate_payload_codec(codec)?;
18437    let decoded = match event
18438        .payload
18439        .get("arguments")
18440        .filter(|value| !value.is_null())
18441    {
18442        Some(value) => decode_wire_avro_value(value, codec)?,
18443        None => AvroValue::Array(Vec::new()),
18444    };
18445    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
18446        unreachable!("normalize_avro_arguments always returns an array");
18447    };
18448    Ok(arguments)
18449}
18450
18451fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
18452    let Some(export_events) = task
18453        .history_export
18454        .as_ref()
18455        .and_then(|export| export.get("history_events"))
18456        .and_then(Value::as_array)
18457    else {
18458        return Ok(());
18459    };
18460
18461    if export_events.len() > task.history_events.len() {
18462        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
18463    }
18464
18465    Ok(())
18466}
18467
18468fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
18469    let Some(export) = task.history_export.as_ref() else {
18470        return Ok(());
18471    };
18472    let signals = export
18473        .get("signals")
18474        .and_then(Value::as_array)
18475        .cloned()
18476        .unwrap_or_default();
18477    let activities = export
18478        .get("activities")
18479        .and_then(Value::as_array)
18480        .cloned()
18481        .unwrap_or_default();
18482    let export_codec = export
18483        .get("payloads")
18484        .and_then(|payloads| payloads.get("codec"))
18485        .and_then(Value::as_str)
18486        .unwrap_or(&task.payload_codec)
18487        .to_string();
18488    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
18489
18490    for event in &mut task.history_events {
18491        if event.event_type == "ActivityCompleted" {
18492            let sequence = event
18493                .payload
18494                .get("sequence")
18495                .or_else(|| event.payload.get("workflow_sequence"))
18496                .and_then(value_as_u64);
18497            let Some(activity) = sequence.and_then(|sequence| {
18498                activities.iter().find(|activity| {
18499                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
18500                })
18501            }) else {
18502                continue;
18503            };
18504            let Some(payload) = event.payload.as_object_mut() else {
18505                continue;
18506            };
18507            if missing_payload(payload.get("result")) {
18508                if let Some(result) = activity
18509                    .get("result")
18510                    .filter(|value| !missing_payload(Some(value)))
18511                {
18512                    payload.insert("result".to_string(), result.clone());
18513                }
18514            }
18515            for field in ["payload_codec", "activity_type"] {
18516                if payload
18517                    .get(field)
18518                    .and_then(Value::as_str)
18519                    .unwrap_or_default()
18520                    .is_empty()
18521                {
18522                    if let Some(value) = activity.get(field) {
18523                        payload.insert(field.to_string(), value.clone());
18524                    }
18525                }
18526            }
18527            continue;
18528        }
18529
18530        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
18531            continue;
18532        }
18533        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
18534        let command_id = event
18535            .payload
18536            .get("workflow_command_id")
18537            .or_else(|| event.raw.get("workflow_command_id"))
18538            .and_then(Value::as_str);
18539        let signal_name = event
18540            .payload
18541            .get("signal_name")
18542            .and_then(Value::as_str)
18543            .unwrap_or_default()
18544            .to_string();
18545        let matched = signals
18546            .iter()
18547            .find(|signal| {
18548                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
18549            })
18550            .or_else(|| {
18551                signals.iter().find(|signal| {
18552                    command_id.is_some()
18553                        && signal.get("command_id").and_then(Value::as_str) == command_id
18554                })
18555            })
18556            .or_else(|| {
18557                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
18558                let signal = signals
18559                    .iter()
18560                    .filter(|signal| {
18561                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
18562                    })
18563                    .nth(*offset);
18564                if signal.is_some() {
18565                    *offset += 1;
18566                }
18567                signal
18568            });
18569        let Some(signal) = matched else {
18570            continue;
18571        };
18572        let signal_codec = signal
18573            .get("payload_codec")
18574            .and_then(Value::as_str)
18575            .unwrap_or(&export_codec);
18576        let Some(payload) = event.payload.as_object_mut() else {
18577            continue;
18578        };
18579        if missing_payload(payload.get("arguments")) {
18580            if let Some(arguments) = signal
18581                .get("arguments")
18582                .filter(|value| !missing_payload(Some(value)))
18583            {
18584                let envelope = match arguments {
18585                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
18586                    other => other.clone(),
18587                };
18588                payload.insert("arguments".to_string(), envelope);
18589            }
18590        }
18591        if payload
18592            .get("payload_codec")
18593            .and_then(Value::as_str)
18594            .unwrap_or_default()
18595            .is_empty()
18596        {
18597            payload.insert("payload_codec".to_string(), json!(signal_codec));
18598        }
18599    }
18600
18601    Ok(())
18602}
18603
18604fn missing_payload(value: Option<&Value>) -> bool {
18605    match value {
18606        None | Some(Value::Null) => true,
18607        Some(Value::String(value)) => value.is_empty(),
18608        Some(_) => false,
18609    }
18610}
18611
18612fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
18613    history_signal_events(
18614        &task.history_events,
18615        task.history_export.as_ref(),
18616        &task.payload_codec,
18617    )
18618}
18619
18620fn history_signal_events(
18621    history_events: &[HistoryEvent],
18622    history_export: Option<&Value>,
18623    payload_codec: &str,
18624) -> Result<Vec<QuerySignal>> {
18625    let export_signals = history_export
18626        .and_then(|export| export.get("signals"))
18627        .and_then(Value::as_array)
18628        .cloned()
18629        .unwrap_or_default();
18630    let export_codec = history_export
18631        .and_then(|export| export.get("payloads"))
18632        .and_then(|payloads| payloads.get("codec"))
18633        .and_then(Value::as_str)
18634        .unwrap_or(payload_codec);
18635    let mut name_offsets: HashMap<String, usize> = HashMap::new();
18636    let mut signals: Vec<QuerySignal> = Vec::new();
18637    let mut signal_indices = HashMap::new();
18638    let mut command_indices = HashMap::new();
18639
18640    for event in history_events {
18641        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
18642            continue;
18643        }
18644
18645        let name = event
18646            .payload
18647            .get("signal_name")
18648            .and_then(Value::as_str)
18649            .unwrap_or_default();
18650        if name.is_empty() {
18651            continue;
18652        }
18653        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
18654        let command_id = event
18655            .payload
18656            .get("workflow_command_id")
18657            .or_else(|| event.raw.get("workflow_command_id"))
18658            .and_then(Value::as_str);
18659        let matched_export = export_signals
18660            .iter()
18661            .find(|candidate| {
18662                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
18663            })
18664            .or_else(|| {
18665                export_signals.iter().find(|candidate| {
18666                    command_id.is_some()
18667                        && candidate.get("command_id").and_then(Value::as_str) == command_id
18668                })
18669            })
18670            .or_else(|| {
18671                let offset = name_offsets.entry(name.to_string()).or_default();
18672                let candidate = export_signals
18673                    .iter()
18674                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
18675                    .nth(*offset);
18676                if candidate.is_some() {
18677                    *offset += 1;
18678                }
18679                candidate
18680            });
18681        let codec = event
18682            .payload
18683            .get("payload_codec")
18684            .and_then(Value::as_str)
18685            .or_else(|| {
18686                matched_export
18687                    .and_then(|signal| signal.get("payload_codec"))
18688                    .and_then(Value::as_str)
18689            })
18690            .unwrap_or(export_codec);
18691        let raw_arguments = signal_history_payload(&event.payload)
18692            .filter(|value| !value.is_null())
18693            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
18694        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
18695        let workflow_sequence = event
18696            .payload
18697            .get("workflow_sequence")
18698            .and_then(value_as_u64)
18699            .or_else(|| {
18700                matched_export
18701                    .and_then(|signal| signal.get("workflow_sequence"))
18702                    .and_then(value_as_u64)
18703            });
18704
18705        let id = signal_id.or_else(|| {
18706            matched_export
18707                .and_then(|signal| signal.get("id"))
18708                .and_then(Value::as_str)
18709        });
18710        let command_id = command_id.or_else(|| {
18711            matched_export
18712                .and_then(|signal| signal.get("command_id"))
18713                .and_then(Value::as_str)
18714        });
18715        let duplicate = id
18716            .and_then(|id| signal_indices.get(id))
18717            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
18718            .copied();
18719        let index = duplicate.unwrap_or(signals.len());
18720        if let Some(index) = duplicate {
18721            let original = &mut signals[index];
18722            let same_arguments = if event.event_type == "SignalApplied" {
18723                if let Some(value) = event.payload.get("value") {
18724                    let expected = match original.avro_arguments.as_slice() {
18725                        [] => AvroValue::Boolean(true),
18726                        [value] => value.clone(),
18727                        values => AvroValue::Array(values.to_vec()),
18728                    };
18729                    let applied = decode_wire_avro_value(value, codec)?;
18730                    applied == expected
18731                        || applied == AvroValue::Array(original.avro_arguments.clone())
18732                } else {
18733                    original.avro_arguments == avro_arguments
18734                }
18735            } else {
18736                original.avro_arguments == avro_arguments
18737            };
18738            if original.name != name
18739                || !same_arguments
18740                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
18741            {
18742                return Err(Error::Codec("conflicting committed signal identity".into()));
18743            }
18744            if original.id.is_none() {
18745                original.id = id.map(str::to_string);
18746            }
18747            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
18748        } else {
18749            signals.push(QuerySignal {
18750                id: id.map(str::to_string),
18751                name: name.to_string(),
18752                arguments,
18753                avro_arguments,
18754                workflow_sequence,
18755            });
18756        }
18757        if let Some(id) = id {
18758            signal_indices.insert(id.to_string(), index);
18759        }
18760        if let Some(id) = command_id {
18761            command_indices.insert(id.to_string(), index);
18762        }
18763    }
18764
18765    if signals.is_empty() {
18766        for signal in export_signals {
18767            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
18768                continue;
18769            }
18770            let Some(name) = signal.get("name").and_then(Value::as_str) else {
18771                continue;
18772            };
18773            let codec = signal
18774                .get("payload_codec")
18775                .and_then(Value::as_str)
18776                .unwrap_or(export_codec);
18777            let (arguments, avro_arguments) =
18778                decode_query_signal_arguments(signal.get("arguments"), codec)?;
18779            signals.push(QuerySignal {
18780                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
18781                name: name.to_string(),
18782                arguments,
18783                avro_arguments,
18784                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
18785            });
18786        }
18787        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
18788    }
18789
18790    Ok(signals)
18791}
18792
18793fn decode_query_signal_arguments(
18794    raw: Option<&Value>,
18795    codec: &str,
18796) -> Result<(Vec<Value>, Vec<AvroValue>)> {
18797    validate_payload_codec(codec)?;
18798    let decoded = match raw.filter(|value| !value.is_null()) {
18799        Some(value) => decode_wire_avro_value(value, codec)?,
18800        None => AvroValue::Array(Vec::new()),
18801    };
18802    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
18803        unreachable!("normalize_avro_arguments always returns an array");
18804    };
18805    let arguments = avro_arguments
18806        .iter()
18807        .cloned()
18808        .map(AvroValue::into_json)
18809        .collect::<Result<Vec<_>>>()?;
18810    Ok((arguments, avro_arguments))
18811}
18812
18813fn value_as_u64(value: &Value) -> Option<u64> {
18814    value
18815        .as_u64()
18816        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
18817}
18818
18819#[cfg(test)]
18820mod tests {
18821    use super::*;
18822    #[cfg(feature = "telemetry")]
18823    static OBSERVABILITY_PROPAGATOR_TEST_LOCK: tokio::sync::Mutex<()> =
18824        tokio::sync::Mutex::const_new(());
18825    mod activity_cancellation_policies;
18826    mod activity_lease_worker;
18827    mod cancellation_scope_admission;
18828    mod cancellation_scope_authoring;
18829    mod cancellation_scope_history;
18830    mod cancellation_scope_opening;
18831    mod cancellation_scope_replay;
18832    mod child_workflow_policies;
18833    mod cooperative_cancellation;
18834    mod local_activity;
18835    mod nexus;
18836    mod runtime_payloads;
18837    mod runtime_uploads;
18838    mod version_marker_contract;
18839    mod worker_capacity;
18840    mod worker_session;
18841    use std::{
18842        fs,
18843        io::{Read, Write},
18844        net::{SocketAddr, TcpListener, TcpStream},
18845        process::Command as ProcessCommand,
18846        sync::atomic::AtomicUsize,
18847        thread,
18848    };
18849
18850    #[derive(Clone, Copy, Debug)]
18851    enum InvalidTaskPayloadCodec {
18852        Missing,
18853        Null,
18854        NonString,
18855    }
18856
18857    impl InvalidTaskPayloadCodec {
18858        fn label(self) -> &'static str {
18859            match self {
18860                Self::Missing => "missing",
18861                Self::Null => "null",
18862                Self::NonString => "non-string",
18863            }
18864        }
18865
18866        fn apply(self, task: &mut Value) {
18867            let task = task.as_object_mut().expect("task fixture object");
18868            match self {
18869                Self::Missing => {
18870                    task.remove("payload_codec");
18871                }
18872                Self::Null => {
18873                    task.insert("payload_codec".to_string(), Value::Null);
18874                }
18875                Self::NonString => {
18876                    task.insert("payload_codec".to_string(), json!(42));
18877                }
18878            }
18879        }
18880    }
18881
18882    fn fixture_envelope(value: Value) -> Value {
18883        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
18884    }
18885
18886    fn fixture_blob(value: Value) -> String {
18887        encode_payload(&value, DEFAULT_CODEC)
18888            .expect("encode Avro test fixture")
18889            .blob
18890    }
18891
18892    #[test]
18893    fn client_builder_rejects_the_sdk_owned_api_suffix() {
18894        for base_url in [
18895            "http://127.0.0.1:8080/api",
18896            "http://localhost:8080/api/",
18897            "https://runtime.example.test/namespaces/orders/api",
18898        ] {
18899            let error = Client::builder(base_url)
18900                .build()
18901                .expect_err("SDK-owned /api suffix must be rejected during build");
18902
18903            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
18904            assert!(
18905                error.to_string().contains("SDK appends /api automatically"),
18906                "the validation error must explain how to fix the endpoint"
18907            );
18908        }
18909    }
18910
18911    #[test]
18912    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
18913        for (base_url, expected) in [
18914            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
18915            (
18916                "http://localhost:8080/durable-workflow/",
18917                "http://localhost:8080/durable-workflow",
18918            ),
18919            (
18920                "https://runtime.example.test/namespaces/orders",
18921                "https://runtime.example.test/namespaces/orders",
18922            ),
18923            (
18924                "https://runtime.example.test/gateway/api/namespaces/orders",
18925                "https://runtime.example.test/gateway/api/namespaces/orders",
18926            ),
18927            (
18928                "https://api.example.test/runtime/orders/",
18929                "https://api.example.test/runtime/orders",
18930            ),
18931        ] {
18932            let client = Client::builder(base_url)
18933                .build()
18934                .expect("Server and Cloud runtime base URL must remain valid");
18935
18936            assert_eq!(client.base_url, expected);
18937        }
18938    }
18939
18940    #[test]
18941    fn workflow_completion_uses_the_additive_command_protocol_floor() {
18942        assert_eq!(
18943            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
18944            MINIMUM_WORKER_PROTOCOL_VERSION
18945        );
18946        assert_eq!(
18947            workflow_completion_protocol_version(&[json!({
18948                "type": "upsert_search_attributes",
18949                "attributes": {"OrderStatus": "waiting"},
18950            })]),
18951            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
18952        );
18953        assert_eq!(
18954            workflow_completion_protocol_version(&[json!({
18955                "type": "upsert_search_attributes",
18956                "attributes": {"OrderStatus": "waiting"},
18957                "attribute_types": {"OrderStatus": "keyword"},
18958            })]),
18959            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
18960        );
18961        assert_eq!(
18962            workflow_completion_protocol_version(&[
18963                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
18964                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18965            ]),
18966            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
18967        );
18968        assert_eq!(
18969            workflow_completion_protocol_version(&[
18970                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
18971                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18972            ]),
18973            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
18974        );
18975        assert_eq!(
18976            workflow_completion_protocol_version(&[json!({
18977                "type": "open_condition_wait",
18978                "condition_wait_occurrence_id": "rust:condition-wait:0",
18979                "condition_key": "ready",
18980            })]),
18981            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18982        );
18983        assert_eq!(
18984            workflow_completion_protocol_version_with_message_streams(
18985                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
18986                true,
18987            ),
18988            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
18989        );
18990        assert_eq!(
18991            workflow_completion_protocol_version_with_message_streams(
18992                &[json!({
18993                    "type": "open_condition_wait",
18994                    "condition_wait_occurrence_id": "rust:condition-wait:0",
18995                    "condition_key": "ready",
18996                })],
18997                true,
18998            ),
18999            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
19000        );
19001    }
19002
19003    #[test]
19004    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
19005        let manifest = portable_worker_affinity_capability_manifest();
19006
19007        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
19008            assert_eq!(manifest[capability]["supported"], json!(false));
19009            assert_eq!(
19010                manifest[capability]["minimum_protocol_version"],
19011                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
19012            );
19013            assert!(manifest[capability]["reason"]
19014                .as_str()
19015                .is_some_and(|reason| !reason.is_empty()));
19016        }
19017    }
19018
19019    fn typed_fidelity_probe() -> AvroValue {
19020        AvroValue::Map(BTreeMap::from([
19021            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
19022            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
19023            (
19024                "numeric".to_string(),
19025                AvroValue::Map(BTreeMap::from([
19026                    ("0".to_string(), AvroValue::String("zero".to_string())),
19027                    ("1".to_string(), AvroValue::String("one".to_string())),
19028                ])),
19029            ),
19030            (
19031                "nested".to_string(),
19032                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
19033                    "enabled".to_string(),
19034                    AvroValue::Boolean(true),
19035                )]))]),
19036            ),
19037            (
19038                "projection_collisions".to_string(),
19039                AvroValue::Array(projection_collision_probe()),
19040            ),
19041        ]))
19042    }
19043
19044    fn projection_collision_probe() -> Vec<AvroValue> {
19045        vec![
19046            AvroValue::Map(BTreeMap::from([
19047                ("$type".to_string(), AvroValue::String("bytes".to_string())),
19048                (
19049                    "base64".to_string(),
19050                    AvroValue::String("ordinary user text".to_string()),
19051                ),
19052            ])),
19053            AvroValue::Map(BTreeMap::from([
19054                ("$type".to_string(), AvroValue::String("map".to_string())),
19055                (
19056                    "entries".to_string(),
19057                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
19058                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
19059                        (
19060                            "value".to_string(),
19061                            AvroValue::String("user map".to_string()),
19062                        ),
19063                    ]))]),
19064                ),
19065            ])),
19066        ]
19067    }
19068
19069    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19070    struct TypedContract {
19071        nested: TypedNested,
19072        mode: TypedMode,
19073        optional: Option<String>,
19074        absent: Option<String>,
19075        items: Vec<i64>,
19076        labels: BTreeMap<String, String>,
19077        bytes: serde_bytes::ByteBuf,
19078        signed: i64,
19079        finite: f64,
19080    }
19081
19082    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19083    struct TypedNested {
19084        enabled: bool,
19085    }
19086
19087    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19088    enum TypedMode {
19089        Detailed { label: String },
19090    }
19091
19092    fn typed_contract() -> TypedContract {
19093        TypedContract {
19094            nested: TypedNested { enabled: true },
19095            mode: TypedMode::Detailed {
19096                label: "compiler-checked".to_string(),
19097            },
19098            optional: Some("present".to_string()),
19099            absent: None,
19100            items: vec![i64::MIN, 0, i64::MAX],
19101            labels: BTreeMap::from([
19102                ("language".to_string(), "rust".to_string()),
19103                ("wire".to_string(), "avro".to_string()),
19104            ]),
19105            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
19106            signed: -9_223_372_036_854_775_000,
19107            finite: 12.5,
19108        }
19109    }
19110
19111    #[derive(Clone, Debug, Default, PartialEq)]
19112    struct ReplayCounterState {
19113        loaded: Option<String>,
19114        count: i64,
19115        finished: bool,
19116    }
19117
19118    fn replay_counter_worker() -> Worker {
19119        let client = Client::new("http://127.0.0.1:8080").expect("client");
19120        let mut worker = Worker::new(client, "rust-workers");
19121        worker.register_replayed_workflow(
19122            "replay-counter",
19123            ReplayCounterState::default,
19124            |ctx, _input, state| async move {
19125                let loaded = ctx.activity("load-counter", json!([])).await?;
19126                state.update(|current| {
19127                    current.loaded = loaded.as_str().map(str::to_string);
19128                })?;
19129                for _ in 0..2 {
19130                    let signal = ctx.wait_signal("increment").await?;
19131                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
19132                    state.update(|current| current.count += amount)?;
19133                }
19134                state.update(|current| current.finished = true)?;
19135                state.read(|current| Ok(json!(current.count)))?
19136            },
19137        );
19138        worker.register_replayed_query::<ReplayCounterState, _, _>(
19139            "replay-counter",
19140            "current",
19141            |_ctx, state, _args| async move {
19142                Ok(json!({
19143                    "loaded": state.loaded,
19144                    "count": state.count,
19145                    "finished": state.finished,
19146                }))
19147            },
19148        );
19149        worker.register_replayed_query::<ReplayCounterState, _, _>(
19150            "replay-counter",
19151            "detached-mutation",
19152            |_ctx, state, _args| async move {
19153                let mut detached = (*state).clone();
19154                detached.count = 999;
19155                Ok(json!(detached.count))
19156            },
19157        );
19158        worker.register_replayed_query::<ReplayCounterState, _, _>(
19159            "replay-counter",
19160            "failed-mutation",
19161            |_ctx, state, _args| async move {
19162                let mut detached = (*state).clone();
19163                detached.count = 999;
19164                Err(Error::WorkerLoop("query refused".to_string()))
19165            },
19166        );
19167        worker
19168    }
19169
19170    fn replay_counter_query(
19171        query_name: &str,
19172        history_events: Value,
19173        run_status: &str,
19174    ) -> QueryTask {
19175        let arguments = fixture_envelope(json!([]));
19176        serde_json::from_value(json!({
19177            "query_task_id": format!("query-{query_name}"),
19178            "workflow_type": "replay-counter",
19179            "query_name": query_name,
19180            "payload_codec": DEFAULT_CODEC,
19181            "workflow_arguments": arguments.clone(),
19182            "query_arguments": arguments,
19183            "history_events": history_events,
19184            "run_status": run_status,
19185        }))
19186        .expect("query task")
19187    }
19188
19189    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
19190        workflow_context_with_codec(history, DEFAULT_CODEC)
19191    }
19192
19193    fn workflow_context_with_codec(
19194        history: Vec<HistoryEvent>,
19195        payload_codec: &str,
19196    ) -> WorkflowContext {
19197        WorkflowContext {
19198            cancellation_scope_id: "root".into(),
19199            state: Arc::new(Mutex::new(
19200                WorkflowState::new_with_identity(
19201                    history,
19202                    None,
19203                    None,
19204                    "rust-workers".to_string(),
19205                    payload_codec.to_string(),
19206                    None,
19207                )
19208                .expect("valid workflow history"),
19209            )),
19210        }
19211    }
19212
19213    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
19214        HistoryEvent {
19215            event_type: event_type.to_string(),
19216            payload,
19217            raw: HashMap::new(),
19218        }
19219    }
19220
19221    fn parallel_path_entry(
19222        kind: &str,
19223        base: u64,
19224        size: usize,
19225        index: usize,
19226    ) -> ParallelGroupMetadata {
19227        parallel_group_entry(base, size, index, kind)
19228    }
19229
19230    fn parallel_history_event(
19231        event_type: &str,
19232        sequence: u64,
19233        identity_field: &str,
19234        identity: &str,
19235        path: Vec<ParallelGroupMetadata>,
19236        result: Option<Value>,
19237    ) -> HistoryEvent {
19238        let mut payload = serde_json::Map::from_iter([
19239            ("sequence".to_string(), json!(sequence)),
19240            (identity_field.to_string(), json!(identity)),
19241        ]);
19242        let inner = path.last().expect("parallel history path");
19243        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
19244        payload.insert("parallel_group_path".to_string(), json!(path));
19245        if let Some(result) = result {
19246            let field = if event_type == "ChildRunCompleted" {
19247                "result"
19248            } else {
19249                "result"
19250            };
19251            payload.insert(field.to_string(), fixture_envelope(result));
19252            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
19253        }
19254        history_event(event_type, Value::Object(payload))
19255    }
19256
19257    fn nested_parallel_operations() -> Vec<ParallelOperation> {
19258        vec![
19259            ParallelOperation::activity("first", json!([])),
19260            ParallelOperation::group(vec![
19261                ParallelOperation::child_workflow(
19262                    "second",
19263                    ChildWorkflowOptions::new("child-workers"),
19264                    json!([]),
19265                ),
19266                ParallelOperation::activity("third", json!([])),
19267            ]),
19268        ]
19269    }
19270
19271    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
19272        let outer = [
19273            parallel_path_entry("mixed", 1, 3, 0),
19274            parallel_path_entry("mixed", 1, 3, 1),
19275            parallel_path_entry("mixed", 1, 3, 2),
19276        ];
19277        [
19278            vec![outer[0].clone()],
19279            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
19280            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
19281        ]
19282    }
19283
19284    #[test]
19285    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
19286        let ctx = workflow_context(Vec::new());
19287        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19288        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19289
19290        assert!(matches!(
19291            call.as_mut().poll(&mut task_context),
19292            Poll::Pending
19293        ));
19294        let commands = ctx.take_commands().expect("parallel commands");
19295        assert_eq!(
19296            commands
19297                .iter()
19298                .map(|command| command["type"].as_str().unwrap_or_default())
19299                .collect::<Vec<_>>(),
19300            [
19301                "schedule_activity",
19302                "start_child_workflow",
19303                "schedule_activity"
19304            ]
19305        );
19306        let paths = nested_parallel_paths();
19307        for (command, path) in commands.iter().zip(paths) {
19308            assert_eq!(command["parallel_group_path"], json!(path));
19309            assert_eq!(
19310                command["parallel_group_id"],
19311                json!(path.last().expect("inner group").parallel_group_id)
19312            );
19313        }
19314    }
19315
19316    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
19317        let paths = nested_parallel_paths();
19318        let third = parallel_history_event(
19319            "ActivityCompleted",
19320            3,
19321            "activity_type",
19322            "third",
19323            paths[2].clone(),
19324            Some(json!("three")),
19325        );
19326        vec![
19327            parallel_history_event(
19328                "ActivityCompleted",
19329                1,
19330                "activity_type",
19331                "first",
19332                paths[0].clone(),
19333                Some(json!("one")),
19334            ),
19335            parallel_history_event(
19336                "ChildWorkflowScheduled",
19337                2,
19338                "child_workflow_type",
19339                "second",
19340                paths[1].clone(),
19341                None,
19342            ),
19343            parallel_history_event(
19344                "ChildRunCompleted",
19345                2,
19346                "child_workflow_type",
19347                "second",
19348                paths[1].clone(),
19349                Some(json!("two")),
19350            ),
19351            third.clone(),
19352            third,
19353        ]
19354    }
19355
19356    #[test]
19357    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
19358        for _restart_or_completed_replay in 0..2 {
19359            let ctx = workflow_context(completed_nested_parallel_history());
19360            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19361            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19362            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
19363                panic!("completed nested parallel history must replay");
19364            };
19365            assert_eq!(
19366                results,
19367                vec![
19368                    ParallelResult::Activity(json!("one")),
19369                    ParallelResult::Group(vec![
19370                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
19371                            parent: WorkflowIdentity {
19372                                workflow_id: None,
19373                                run_id: None,
19374                            },
19375                            child: WorkflowIdentity {
19376                                workflow_id: None,
19377                                run_id: None,
19378                            },
19379                            child_workflow_type: Some("second".to_string()),
19380                            result: json!("two"),
19381                        }),
19382                        ParallelResult::Activity(json!("three")),
19383                    ]),
19384                ]
19385            );
19386            assert!(ctx.take_commands().expect("commands").is_empty());
19387            ctx.ensure_history_consumed().expect("history consumed");
19388        }
19389    }
19390
19391    #[test]
19392    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
19393        let paths = nested_parallel_paths();
19394        let history = vec![
19395            parallel_history_event(
19396                "ActivityCompleted",
19397                1,
19398                "activity_type",
19399                "first",
19400                paths[0].clone(),
19401                Some(json!("one")),
19402            ),
19403            parallel_history_event(
19404                "ChildWorkflowScheduled",
19405                2,
19406                "child_workflow_type",
19407                "second",
19408                paths[1].clone(),
19409                None,
19410            ),
19411            parallel_history_event(
19412                "ChildRunFailed",
19413                2,
19414                "child_workflow_type",
19415                "second",
19416                paths[1].clone(),
19417                None,
19418            ),
19419            parallel_history_event(
19420                "ActivityCompleted",
19421                3,
19422                "activity_type",
19423                "third",
19424                paths[2].clone(),
19425                Some(json!("late")),
19426            ),
19427        ];
19428        let ctx = workflow_context(history);
19429        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19430        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19431        let outcome = call.as_mut().poll(&mut task_context);
19432        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
19433            panic!("one failed child must return a typed partial failure: {outcome:?}");
19434        };
19435        assert_eq!(failure.member_path, [1, 0]);
19436        assert_eq!(failure.group_id, "parallel-calls:1:3");
19437        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
19438        assert_eq!(
19439            failure
19440                .completed
19441                .iter()
19442                .map(|completion| completion.member_path.clone())
19443                .collect::<Vec<_>>(),
19444            [vec![0], vec![1, 1]]
19445        );
19446    }
19447
19448    #[test]
19449    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
19450        let paths = nested_parallel_paths();
19451        let history = vec![
19452            parallel_history_event(
19453                "ActivityScheduled",
19454                1,
19455                "activity_type",
19456                "first",
19457                paths[0].clone(),
19458                None,
19459            ),
19460            parallel_history_event(
19461                "ChildWorkflowScheduled",
19462                2,
19463                "child_workflow_type",
19464                "second",
19465                paths[1].clone(),
19466                None,
19467            ),
19468            parallel_history_event(
19469                "ActivityScheduled",
19470                3,
19471                "activity_type",
19472                "third",
19473                paths[2].clone(),
19474                None,
19475            ),
19476        ];
19477        for _restart in 0..2 {
19478            let ctx = workflow_context(history.clone());
19479            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19480            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19481            let outcome = call.as_mut().poll(&mut task_context);
19482            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
19483            assert!(ctx.take_commands().expect("commands").is_empty());
19484        }
19485    }
19486
19487    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
19488        vec![selection_group_entry(
19489            1,
19490            2,
19491            index,
19492            "activity",
19493            &SelectionMemberMetadata {
19494                key: SelectionKey::Name(key.to_string()),
19495                index,
19496                base_sequence: index as u64 + 1,
19497                size: 1,
19498                kind: "activity".to_string(),
19499            },
19500        )]
19501    }
19502
19503    fn selection_activity_event(
19504        event_type: &str,
19505        index: usize,
19506        key: &str,
19507        result: Option<Value>,
19508    ) -> HistoryEvent {
19509        let sequence = index as u64 + 1;
19510        let mut event = parallel_history_event(
19511            event_type,
19512            sequence,
19513            "activity_type",
19514            &format!("{key}-activity"),
19515            selection_path(index, key),
19516            result,
19517        );
19518        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
19519        event.raw.insert(
19520            "id".to_string(),
19521            json!(if event_type == "ActivityCompleted" {
19522                format!("event-{key}")
19523            } else {
19524                format!("{event_type}-{key}")
19525            }),
19526        );
19527        event
19528    }
19529
19530    fn selection_winner_marker() -> HistoryEvent {
19531        history_event(
19532            "SelectionResolved",
19533            json!({
19534                "selection_group_id": "select-calls:1:2",
19535                "selection_group_base_sequence": 1,
19536                "selection_group_size": 2,
19537                "member_key": "fast",
19538                "member_index": 1,
19539                "member_base_sequence": 2,
19540                "member_size": 1,
19541                "operation_kind": "activity",
19542                "operation_identity": "activity-fast",
19543                "outcome": "completed",
19544                "resolution_event_id": "event-fast",
19545                "resolution_event_type": "ActivityCompleted",
19546            }),
19547        )
19548    }
19549
19550    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
19551        ctx.select_keyed(vec![
19552            (
19553                "slow",
19554                ParallelOperation::activity_with_options(
19555                    "slow-activity",
19556                    ActivityOptions::new().task_queue("default"),
19557                    json!([]),
19558                ),
19559            ),
19560            (
19561                "fast",
19562                ParallelOperation::activity_with_options(
19563                    "fast-activity",
19564                    ActivityOptions::new().task_queue("default"),
19565                    json!([]),
19566                ),
19567            ),
19568        ])
19569    }
19570
19571    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
19572        let ctx = workflow_context(history);
19573        let mut call = Box::pin(keyed_activity_selection(&ctx));
19574        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19575        let selected = match call.as_mut().poll(&mut task_context) {
19576            Poll::Ready(Ok(selected)) => selected,
19577            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
19578            Poll::Pending => panic!("persisted selection winner must replay without pending"),
19579        };
19580        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
19581        assert_eq!(
19582            selected.value,
19583            Some(ParallelResult::Activity(json!("winner-value")))
19584        );
19585        let slow = selected
19586            .handle(&SelectionKey::Name("slow".to_string()))
19587            .expect("slow handle")
19588            .clone();
19589        let mut await_slow = Box::pin(slow.await_result());
19590        assert!(matches!(
19591            await_slow.as_mut().poll(&mut task_context),
19592            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
19593        ));
19594        assert!(ctx.take_commands().expect("commands").is_empty());
19595    }
19596
19597    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
19598
19599    fn canonical_selection_history() -> Vec<HistoryEvent> {
19600        const FIXTURE: &[u8] =
19601            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
19602        assert_eq!(
19603            format!("{:x}", Sha256::digest(FIXTURE)),
19604            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
19605        );
19606        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
19607
19608        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
19609    }
19610
19611    #[test]
19612    fn selection_fresh_process_entrypoint() {
19613        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
19614            return;
19615        };
19616        let persisted = fs::read(path).expect("persisted selection history");
19617        assert_eq!(
19618            format!("{:x}", Sha256::digest(&persisted)),
19619            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
19620        );
19621        let fixture: Value =
19622            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
19623        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
19624            .expect("valid persisted selection history");
19625
19626        assert_persisted_selection_replay(history);
19627    }
19628
19629    #[test]
19630    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
19631        let ctx = workflow_context(Vec::new());
19632        let mut call = Box::pin(keyed_activity_selection(&ctx));
19633        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19634
19635        assert!(matches!(
19636            call.as_mut().poll(&mut task_context),
19637            Poll::Pending
19638        ));
19639        let commands = ctx.take_commands().expect("selection commands");
19640        assert_eq!(commands.len(), 2);
19641        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
19642        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
19643        assert!(commands.iter().all(|command| {
19644            command["parallel_group_id"] == json!("select-calls:1:2")
19645                && command["parallel_group_mode"] == json!("select")
19646        }));
19647    }
19648
19649    #[test]
19650    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
19651        let ctx = workflow_context(Vec::new());
19652        let mut invalid = Box::pin(ctx.select_keyed(vec![(
19653            "",
19654            ParallelOperation::activity("invalid", json!([])),
19655        )]));
19656        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19657        assert!(matches!(
19658            invalid.as_mut().poll(&mut task_context),
19659            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
19660                reason: "selection_key_invalid",
19661                ..
19662            })))
19663        ));
19664
19665        for invalid_key in [json!(""), json!(-1)] {
19666            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
19667            event.payload["selection_member_key"] = invalid_key.clone();
19668            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
19669            assert!(matches!(
19670                WorkflowState::new_with_identity(
19671                    vec![event],
19672                    None,
19673                    None,
19674                    "rust-workers".to_string(),
19675                    DEFAULT_CODEC.to_string(),
19676                    None,
19677                ),
19678                Err(Error::NonDeterministicReplay(_))
19679            ));
19680        }
19681    }
19682
19683    #[test]
19684    fn selection_preserves_valid_named_and_numeric_keys() {
19685        let ctx = workflow_context(Vec::new());
19686        let mut selection = Box::pin(ctx.select_keyed(vec![
19687            (
19688                SelectionKey::Index(0),
19689                ParallelOperation::activity("numeric", json!([])),
19690            ),
19691            (
19692                SelectionKey::Name("named".to_string()),
19693                ParallelOperation::timer(Duration::from_secs(1)),
19694            ),
19695        ]));
19696        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19697
19698        assert!(matches!(
19699            selection.as_mut().poll(&mut task_context),
19700            Poll::Pending
19701        ));
19702        let commands = ctx.take_commands().expect("selection commands");
19703        assert_eq!(commands[0]["selection_member_key"], json!(0));
19704        assert_eq!(commands[1]["selection_member_key"], json!("named"));
19705    }
19706
19707    #[test]
19708    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
19709        let history = canonical_selection_history();
19710        assert_persisted_selection_replay(history.clone());
19711
19712        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19713            .join("tests/fixtures/durable_selection_runtime_history.json");
19714        let output =
19715            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
19716                .args([
19717                    "--exact",
19718                    "tests::selection_fresh_process_entrypoint",
19719                    "--nocapture",
19720                ])
19721                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
19722                .output()
19723                .expect("run fresh selection replay process");
19724
19725        assert!(
19726            output.status.success(),
19727            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
19728            String::from_utf8_lossy(&output.stdout),
19729            String::from_utf8_lossy(&output.stderr),
19730        );
19731    }
19732
19733    #[test]
19734    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
19735        let mut history = canonical_selection_history();
19736        history.retain(|event| event.event_type != "SelectionResolved");
19737        let ctx = workflow_context(history);
19738        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19739        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19740
19741        assert!(matches!(
19742            selection.as_mut().poll(&mut task_context),
19743            Poll::Pending
19744        ));
19745        assert!(ctx.take_commands().expect("commands").is_empty());
19746        assert!(
19747            ctx.matched_recorded_pending()
19748                .expect("selection pending state"),
19749            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
19750        );
19751    }
19752
19753    #[test]
19754    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
19755        for (terminal_event, predicate_satisfied, timeout_seconds) in [
19756            ("ConditionWaitSatisfied", true, None),
19757            ("ConditionWaitTimedOut", false, Some(0)),
19758        ] {
19759            let member = SelectionMemberMetadata {
19760                key: SelectionKey::Name("condition".to_string()),
19761                index: 0,
19762                base_sequence: 1,
19763                size: 1,
19764                kind: "condition".to_string(),
19765            };
19766            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
19767            let mut payload = json!({
19768                "sequence": 1,
19769                "condition_wait_id": "condition-1",
19770                "condition_wait_occurrence_id": "rust:condition-wait:0",
19771                "condition_key": "ready",
19772                "condition_definition_fingerprint": "sha256:ready-v1",
19773                "parallel_group_path": path,
19774            });
19775            payload
19776                .as_object_mut()
19777                .expect("condition history payload")
19778                .extend(
19779                    serde_json::to_value(&path[0])
19780                        .expect("condition selection metadata")
19781                        .as_object()
19782                        .expect("condition selection metadata object")
19783                        .clone(),
19784                );
19785            if let Some(timeout_seconds) = timeout_seconds {
19786                payload["timeout_seconds"] = json!(timeout_seconds);
19787            }
19788            let history = vec![
19789                history_event("ConditionWaitOpened", payload.clone()),
19790                history_event(terminal_event, payload),
19791            ];
19792            let ctx = workflow_context(history);
19793            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
19794            if timeout_seconds.is_some() {
19795                options = options.timeout(Duration::ZERO);
19796            }
19797            let mut selection = Box::pin(ctx.select_keyed(vec![(
19798                "condition",
19799                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
19800            )]));
19801            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19802
19803            assert!(matches!(
19804                selection.as_mut().poll(&mut task_context),
19805                Poll::Pending
19806            ));
19807            assert!(ctx.take_commands().expect("commands").is_empty());
19808            assert!(
19809                ctx.matched_recorded_pending()
19810                    .expect("condition selection pending state"),
19811                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
19812            );
19813        }
19814    }
19815
19816    #[test]
19817    fn selection_immediate_condition_members_open_a_durable_wait() {
19818        for predicate_satisfied in [true, false] {
19819            let ctx = workflow_context(Vec::new());
19820            let mut selection = Box::pin(ctx.select_keyed(vec![(
19821                "condition",
19822                ParallelOperation::condition(
19823                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
19824                    move || Ok(predicate_satisfied),
19825                ),
19826            )]));
19827            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19828
19829            assert!(matches!(
19830                selection.as_mut().poll(&mut task_context),
19831                Poll::Pending
19832            ));
19833            let commands = ctx.take_commands().expect("condition selection command");
19834            assert_eq!(commands.len(), 1);
19835            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
19836            assert_eq!(commands[0]["timeout_seconds"], json!(0));
19837            assert_eq!(
19838                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
19839                json!("select")
19840            );
19841        }
19842    }
19843
19844    #[test]
19845    fn selection_loser_cancellation_is_explicit_and_idempotent() {
19846        let history = vec![
19847            selection_activity_event("ActivityScheduled", 0, "slow", None),
19848            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19849            selection_winner_marker(),
19850        ];
19851        let ctx = workflow_context(history.clone());
19852        let mut call = Box::pin(keyed_activity_selection(&ctx));
19853        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19854        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19855            panic!("winner must replay");
19856        };
19857        let slow = selected
19858            .handle(&SelectionKey::Name("slow".to_string()))
19859            .expect("slow handle")
19860            .clone();
19861        let mut cancel = Box::pin(slow.cancel());
19862        assert!(matches!(
19863            cancel.as_mut().poll(&mut task_context),
19864            Poll::Ready(Ok(()))
19865        ));
19866        assert!(matches!(
19867            cancel.as_mut().poll(&mut task_context),
19868            Poll::Ready(Ok(()))
19869        ));
19870        let mut outcome = Box::pin(slow.await_result());
19871        assert!(matches!(
19872            outcome.as_mut().poll(&mut task_context),
19873            Poll::Pending
19874        ));
19875        let commands = ctx.take_commands().expect("cancel command");
19876        assert_eq!(commands.len(), 1);
19877        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
19878        assert_eq!(commands[0]["member_key"], json!("slow"));
19879
19880        let mut cancelled_history = history;
19881        cancelled_history.push(history_event(
19882            "SelectionOperationCancelled",
19883            json!({
19884                "selection_group_id": "select-calls:1:2",
19885                "member_key": "slow",
19886                "member_index": 0,
19887                "member_base_sequence": 1,
19888                "member_size": 1,
19889                "operation_kind": "activity",
19890                "operation_identity": "activity-slow",
19891                "cancelled_at": "2026-08-27T00:00:00Z",
19892            }),
19893        ));
19894        let replayed = workflow_context(cancelled_history);
19895        let mut call = Box::pin(keyed_activity_selection(&replayed));
19896        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19897            panic!("winner must replay after cancellation");
19898        };
19899        let slow = selected
19900            .handle(&SelectionKey::Name("slow".to_string()))
19901            .expect("slow handle")
19902            .clone();
19903        let mut cancel = Box::pin(slow.cancel());
19904        assert!(matches!(
19905            cancel.as_mut().poll(&mut task_context),
19906            Poll::Ready(Ok(()))
19907        ));
19908        assert!(replayed.take_commands().expect("commands").is_empty());
19909    }
19910
19911    #[test]
19912    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
19913        let base_history = vec![
19914            selection_activity_event("ActivityScheduled", 0, "slow", None),
19915            selection_activity_event("ActivityScheduled", 1, "fast", None),
19916            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19917            selection_winner_marker(),
19918        ];
19919        for (field, corrupt) in [
19920            ("member_key", json!("fast")),
19921            ("member_index", json!(1)),
19922            ("member_base_sequence", json!(3)),
19923            ("member_size", json!(2)),
19924            ("operation_kind", json!("timer")),
19925            ("operation_identity", json!("forged")),
19926        ] {
19927            let mut cancellation = json!({
19928                "selection_group_id": "select-calls:1:2",
19929                "member_key": "slow",
19930                "member_index": 0,
19931                "member_base_sequence": 1,
19932                "member_size": 1,
19933                "operation_kind": "activity",
19934                "operation_identity": "activity-slow",
19935            });
19936            cancellation[field] = corrupt;
19937            let mut history = base_history.clone();
19938            history.push(history_event("SelectionOperationCancelled", cancellation));
19939            let ctx = workflow_context(history);
19940            let mut selection = Box::pin(keyed_activity_selection(&ctx));
19941            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19942
19943            assert!(matches!(
19944                selection.as_mut().poll(&mut task_context),
19945                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19946            ));
19947        }
19948    }
19949
19950    #[test]
19951    fn selection_child_identity_prefers_the_durable_run_id() {
19952        let ctx = workflow_context(vec![history_event(
19953            "ChildWorkflowScheduled",
19954            json!({
19955                "sequence": 1,
19956                "child_workflow_type": "child",
19957                "child_workflow_instance_id": "child-instance",
19958                "child_workflow_run_id": "child-run",
19959            }),
19960        )]);
19961        let state = ctx.state.lock().expect("workflow state");
19962
19963        assert_eq!(
19964            selection_operation_identity(&state, "child", 1, 1),
19965            "child-run"
19966        );
19967    }
19968
19969    #[test]
19970    fn selection_activity_identity_requires_canonical_execution_id() {
19971        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
19972        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
19973        let mut fast_completed =
19974            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
19975        for event in [&mut fast_open, &mut fast_completed] {
19976            event
19977                .payload
19978                .as_object_mut()
19979                .expect("activity payload")
19980                .remove("activity_execution_id");
19981            event.payload["activity_id"] = json!("forged-activity-id");
19982        }
19983        let mut marker = selection_winner_marker();
19984        marker.payload["operation_identity"] = json!("forged-activity-id");
19985        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
19986        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19987        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19988
19989        assert!(matches!(
19990            selection.as_mut().poll(&mut task_context),
19991            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19992        ));
19993    }
19994
19995    #[test]
19996    fn selection_completion_before_cancellation_remains_awaitable() {
19997        let history = vec![
19998            selection_activity_event("ActivityScheduled", 0, "slow", None),
19999            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
20000            selection_winner_marker(),
20001            selection_activity_event(
20002                "ActivityCompleted",
20003                0,
20004                "slow",
20005                Some(json!("completed-first")),
20006            ),
20007        ];
20008        let ctx = workflow_context(history);
20009        let mut selection = Box::pin(keyed_activity_selection(&ctx));
20010        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20011        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
20012            panic!("winner must replay");
20013        };
20014        let slow = selected
20015            .handle(&SelectionKey::Name("slow".to_string()))
20016            .expect("slow handle")
20017            .clone();
20018        let mut cancel = Box::pin(slow.cancel());
20019        assert!(matches!(
20020            cancel.as_mut().poll(&mut task_context),
20021            Poll::Ready(Ok(()))
20022        ));
20023        let mut await_slow = Box::pin(slow.await_result());
20024        assert!(matches!(
20025            await_slow.as_mut().poll(&mut task_context),
20026            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
20027        ));
20028        let commands = ctx.take_commands().expect("commands");
20029        assert!(commands.is_empty());
20030    }
20031
20032    #[test]
20033    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
20034        let nested_member = SelectionMemberMetadata {
20035            key: SelectionKey::Name("nested".to_string()),
20036            index: 0,
20037            base_sequence: 1,
20038            size: 2,
20039            kind: "group".to_string(),
20040        };
20041        let deadline_member = SelectionMemberMetadata {
20042            key: SelectionKey::Name("deadline".to_string()),
20043            index: 1,
20044            base_sequence: 3,
20045            size: 1,
20046            kind: "timer".to_string(),
20047        };
20048        let nested_paths = [
20049            vec![
20050                selection_group_entry(1, 3, 0, "mixed", &nested_member),
20051                parallel_group_entry(1, 2, 0, "activity"),
20052            ],
20053            vec![
20054                selection_group_entry(1, 3, 1, "mixed", &nested_member),
20055                parallel_group_entry(1, 2, 1, "activity"),
20056            ],
20057        ];
20058        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
20059        let mut timer_fired = parallel_history_event(
20060            "TimerFired",
20061            3,
20062            "timer_id",
20063            "timer-3",
20064            deadline_path.clone(),
20065            None,
20066        );
20067        timer_fired.payload["delay_seconds"] = json!(0);
20068        timer_fired
20069            .raw
20070            .insert("id".to_string(), json!("timer-fired"));
20071        let mut timer_scheduled = parallel_history_event(
20072            "TimerScheduled",
20073            3,
20074            "timer_id",
20075            "timer-3",
20076            deadline_path,
20077            None,
20078        );
20079        timer_scheduled.payload["delay_seconds"] = json!(0);
20080        let history = vec![
20081            parallel_history_event(
20082                "ActivityScheduled",
20083                1,
20084                "activity_type",
20085                "nested-first",
20086                nested_paths[0].clone(),
20087                None,
20088            ),
20089            parallel_history_event(
20090                "ActivityScheduled",
20091                2,
20092                "activity_type",
20093                "nested-second",
20094                nested_paths[1].clone(),
20095                None,
20096            ),
20097            timer_scheduled,
20098            timer_fired,
20099            history_event(
20100                "SelectionResolved",
20101                json!({
20102                    "selection_group_id": "select-calls:1:3",
20103                    "selection_group_base_sequence": 1,
20104                    "selection_group_size": 3,
20105                    "member_key": "deadline",
20106                    "member_index": 1,
20107                    "member_base_sequence": 3,
20108                    "member_size": 1,
20109                    "operation_kind": "timer",
20110                    "operation_identity": "timer-3",
20111                    "outcome": "completed",
20112                    "resolution_event_id": "timer-fired",
20113                    "resolution_event_type": "TimerFired",
20114                }),
20115            ),
20116            parallel_history_event(
20117                "ActivityFailed",
20118                2,
20119                "activity_type",
20120                "nested-second",
20121                nested_paths[1].clone(),
20122                None,
20123            ),
20124        ];
20125        let ctx = workflow_context(history);
20126        let mut selection = Box::pin(ctx.select_keyed(vec![
20127            (
20128                "nested",
20129                ParallelOperation::group(vec![
20130                    ParallelOperation::activity("nested-first", json!([])),
20131                    ParallelOperation::activity("nested-second", json!([])),
20132                ]),
20133            ),
20134            ("deadline", ParallelOperation::timer(Duration::ZERO)),
20135        ]));
20136        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20137        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
20138            panic!("deadline winner must replay");
20139        };
20140        let nested = selected
20141            .handle(&SelectionKey::Name("nested".to_string()))
20142            .expect("nested handle")
20143            .clone();
20144        let mut cancel = Box::pin(nested.cancel());
20145        assert!(matches!(
20146            cancel.as_mut().poll(&mut task_context),
20147            Poll::Ready(Ok(()))
20148        ));
20149        let mut await_nested = Box::pin(nested.await_result());
20150
20151        assert!(matches!(
20152            await_nested.as_mut().poll(&mut task_context),
20153            Poll::Ready(Err(Error::ActivityFailed(_)))
20154        ));
20155        assert!(ctx.take_commands().expect("commands").is_empty());
20156    }
20157
20158    #[test]
20159    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
20160        let ctx = workflow_context(Vec::new());
20161        let mut call = Box::pin(ctx.select(vec![
20162            ParallelOperation::child_workflow(
20163                "child",
20164                ChildWorkflowOptions::new("children"),
20165                json!([]),
20166            ),
20167            ParallelOperation::timer(Duration::from_secs(30)),
20168            ParallelOperation::signal("approval"),
20169            ParallelOperation::condition(
20170                ConditionWaitOptions::new("ready", "sha256:ready"),
20171                || Ok(false),
20172            ),
20173            ParallelOperation::group(vec![
20174                ParallelOperation::activity("nested-one", json!([])),
20175                ParallelOperation::activity("nested-two", json!([])),
20176            ]),
20177        ]));
20178        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20179        assert!(matches!(
20180            call.as_mut().poll(&mut task_context),
20181            Poll::Pending
20182        ));
20183        let commands = ctx.take_commands().expect("selection commands");
20184        assert_eq!(
20185            commands
20186                .iter()
20187                .map(|command| command["type"].as_str().unwrap_or_default())
20188                .collect::<Vec<_>>(),
20189            [
20190                "start_child_workflow",
20191                "start_timer",
20192                "open_signal_wait",
20193                "open_condition_wait",
20194                "schedule_activity",
20195                "schedule_activity",
20196            ]
20197        );
20198        assert!(commands.iter().all(|command| {
20199            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
20200        }));
20201        assert_eq!(
20202            commands[4]["parallel_group_path"].as_array().map(Vec::len),
20203            Some(2)
20204        );
20205        assert_eq!(
20206            commands[4]["parallel_group_path"][0]["selection_member_kind"],
20207            json!("group")
20208        );
20209        assert_eq!(
20210            commands[5]["parallel_group_path"][0]["selection_member_kind"],
20211            json!("group")
20212        );
20213
20214        let one_leaf_ctx = workflow_context(Vec::new());
20215        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
20216            ParallelOperation::activity("nested-only", json!([])),
20217        ])]));
20218        assert!(matches!(
20219            one_leaf.as_mut().poll(&mut task_context),
20220            Poll::Pending
20221        ));
20222        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
20223        assert_eq!(one_leaf_commands.len(), 1);
20224        assert_eq!(
20225            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
20226            json!("group")
20227        );
20228        assert_eq!(
20229            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
20230            json!(1)
20231        );
20232    }
20233
20234    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
20235        let mut saga = ctx.saga();
20236        let outcome = async {
20237            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
20238            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
20239            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
20240            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
20241            ctx.activity("trip.charge", json!([])).await?;
20242            Ok(json!({"status": "booked"}))
20243        }
20244        .await;
20245        saga.finish(outcome).await
20246    }
20247
20248    fn saga_activity(
20249        event_type: &str,
20250        sequence: u64,
20251        activity_type: &str,
20252        result: Option<Value>,
20253    ) -> HistoryEvent {
20254        let mut payload = json!({
20255            "sequence": sequence,
20256            "activity_type": activity_type,
20257            "message": format!("{activity_type} failed"),
20258            "exception_type": "PlannedFailure",
20259            "non_retryable": true,
20260        });
20261        if let Some(result) = result {
20262            payload["result"] = fixture_envelope(result);
20263        }
20264        history_event(event_type, payload)
20265    }
20266
20267    #[test]
20268    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
20269        let completed_hotel_compensation = saga_activity(
20270            "ActivityCompleted",
20271            4,
20272            "trip.cancel-hotel",
20273            Some(Value::Null),
20274        );
20275        let history = vec![
20276            saga_activity(
20277                "ActivityCompleted",
20278                1,
20279                "trip.reserve-flight",
20280                Some(json!("flight-1")),
20281            ),
20282            saga_activity(
20283                "ActivityCompleted",
20284                2,
20285                "trip.reserve-hotel",
20286                Some(json!("hotel-1")),
20287            ),
20288            saga_activity("ActivityFailed", 3, "trip.charge", None),
20289            completed_hotel_compensation.clone(),
20290            completed_hotel_compensation,
20291        ];
20292
20293        for _restart in 0..2 {
20294            let ctx = workflow_context(history.clone());
20295            let mut future = Box::pin(trip_saga(ctx.clone()));
20296            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20297            assert!(matches!(
20298                future.as_mut().poll(&mut task_context),
20299                Poll::Pending
20300            ));
20301            let commands = ctx.take_commands().expect("compensation command");
20302            assert_eq!(commands.len(), 1);
20303            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
20304        }
20305    }
20306
20307    #[test]
20308    fn saga_compensation_failure_preserves_both_typed_failures() {
20309        let history = vec![
20310            saga_activity(
20311                "ActivityCompleted",
20312                1,
20313                "trip.reserve-flight",
20314                Some(json!("flight-1")),
20315            ),
20316            saga_activity(
20317                "ActivityCompleted",
20318                2,
20319                "trip.reserve-hotel",
20320                Some(json!("hotel-1")),
20321            ),
20322            saga_activity("ActivityFailed", 3, "trip.charge", None),
20323            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
20324        ];
20325        let ctx = workflow_context(history);
20326        let mut future = Box::pin(trip_saga(ctx));
20327        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20328        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
20329            future.as_mut().poll(&mut task_context)
20330        else {
20331            panic!("compensation failure must remain structured");
20332        };
20333        assert!(matches!(
20334            *failure.initiating_failure,
20335            Error::ActivityFailed(_)
20336        ));
20337        assert!(matches!(
20338            *failure.compensation_failure,
20339            Error::ActivityFailed(_)
20340        ));
20341        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
20342        assert_eq!(failure.compensation_registration_order, 2);
20343    }
20344
20345    #[test]
20346    fn saga_compensates_cooperative_cancellation() {
20347        let ctx = workflow_context(vec![saga_activity(
20348            "ActivityCompleted",
20349            1,
20350            "trip.reserve-flight",
20351            Some(json!("flight-1")),
20352        )]);
20353        ctx.state.lock().expect("state").cancel_requested = true;
20354        let run = {
20355            let ctx = ctx.clone();
20356            async move {
20357                let mut saga = ctx.saga();
20358                let outcome = async {
20359                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
20360                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
20361                    ctx.throw_if_cancellation_requested()?;
20362                    Ok(json!("unexpected"))
20363                }
20364                .await;
20365                saga.finish(outcome).await
20366            }
20367        };
20368        let mut future = Box::pin(run);
20369        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20370        assert!(matches!(
20371            future.as_mut().poll(&mut task_context),
20372            Poll::Pending
20373        ));
20374        let commands = ctx.take_commands().expect("cancellation compensation");
20375        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
20376    }
20377
20378    #[test]
20379    fn optional_task_observability_fields_round_trip_without_interpretation() {
20380        let context = json!({"schema": "unknown", "carrier": {"traceparent": "untrusted"}});
20381        let dispatch = json!({"task_id": "other-task"});
20382        let links = json!({"links": []});
20383        let mut value = json!({
20384            "task_id": "task", "query_task_id": "query", "workflow_type": "workflow",
20385            "activity_type": "activity", "query_name": "query", "payload_codec": "avro"
20386        });
20387        let workflow: WorkflowTask =
20388            serde_json::from_value(value.clone()).expect("legacy workflow task");
20389        let activity: ActivityTask =
20390            serde_json::from_value(value.clone()).expect("legacy activity task");
20391        let query: QueryTask = serde_json::from_value(value.clone()).expect("legacy query task");
20392        assert!(workflow.observability_context.is_none());
20393        assert!(activity.observability_context.is_none());
20394        assert!(query.observability_context.is_none());
20395        assert!(activity.workflow_id.is_none());
20396        assert!(activity.run_id.is_none());
20397        assert!(activity.activity_execution_id.is_none());
20398
20399        value["observability_context"] = context.clone();
20400        value["dispatch_observability_context"] = dispatch.clone();
20401        value["observability_links"] = links.clone();
20402        value["workflow_id"] = json!("workflow-id");
20403        value["run_id"] = json!("run-id");
20404        value["activity_execution_id"] = json!("activity-id");
20405        let workflow: WorkflowTask =
20406            serde_json::from_value(value.clone()).expect("workflow metadata");
20407        let activity: ActivityTask =
20408            serde_json::from_value(value.clone()).expect("activity metadata");
20409        let query: QueryTask = serde_json::from_value(value).expect("query metadata");
20410        for fields in [
20411            (
20412                workflow.observability_context,
20413                workflow.dispatch_observability_context,
20414                workflow.observability_links,
20415            ),
20416            (
20417                activity.observability_context,
20418                activity.dispatch_observability_context,
20419                activity.observability_links,
20420            ),
20421            (
20422                query.observability_context,
20423                query.dispatch_observability_context,
20424                query.observability_links,
20425            ),
20426        ] {
20427            assert_eq!(
20428                fields,
20429                (
20430                    Some(context.clone()),
20431                    Some(dispatch.clone()),
20432                    Some(links.clone())
20433                )
20434            );
20435        }
20436        assert_eq!(activity.workflow_id.as_deref(), Some("workflow-id"));
20437        assert_eq!(activity.run_id.as_deref(), Some("run-id"));
20438        assert_eq!(
20439            activity.activity_execution_id.as_deref(),
20440            Some("activity-id")
20441        );
20442    }
20443
20444    fn workflow_task(
20445        workflow_type: &str,
20446        history_events: Vec<HistoryEvent>,
20447        payload_codec: &str,
20448    ) -> WorkflowTask {
20449        WorkflowTask {
20450            task_id: format!("wft-{workflow_type}"),
20451            observability_context: None,
20452            dispatch_observability_context: None,
20453            observability_links: None,
20454            workflow_command_id: None,
20455            workflow_id: Some(format!("wf-{workflow_type}")),
20456            run_id: Some(format!("run-{workflow_type}")),
20457            workflow_type: workflow_type.to_string(),
20458            cancel_requested: false,
20459            payload_codec: payload_codec.to_string(),
20460            arguments: Some(
20461                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
20462            ),
20463            total_history_events: Some(history_events.len() as u64),
20464            history_size_bytes: None,
20465            continue_as_new_recommended: None,
20466            history_budget_pressure: None,
20467            history_events,
20468            next_history_page_token: None,
20469            workflow_task_attempt: 1,
20470            workflow_signal_id: None,
20471            signal_name: None,
20472            signal_arguments: None,
20473            workflow_update_id: None,
20474            update_name: None,
20475            lease_owner: Some("rust-worker".to_string()),
20476        }
20477    }
20478
20479    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
20480    struct SideEffectProbe {
20481        request_id: String,
20482        attempt: u32,
20483    }
20484
20485    #[test]
20486    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
20487        let calls = AtomicUsize::new(0);
20488        let ctx = workflow_context(Vec::new());
20489        let value = ctx
20490            .side_effect(|| {
20491                calls.fetch_add(1, Ordering::SeqCst);
20492                SideEffectProbe {
20493                    request_id: "request-42".to_string(),
20494                    attempt: 3,
20495                }
20496            })
20497            .expect("first side effect");
20498        assert_eq!(value.attempt, 3);
20499        assert_eq!(calls.load(Ordering::SeqCst), 1);
20500        let commands = ctx.take_commands().expect("commands");
20501        assert_eq!(commands.len(), 1);
20502        assert_eq!(commands[0]["type"], "record_side_effect");
20503        assert_eq!(
20504            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
20505            serde_json::to_value(&value).expect("value")
20506        );
20507
20508        let replay = workflow_context(vec![history_event(
20509            "SideEffectRecorded",
20510            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20511        )]);
20512        let replayed: SideEffectProbe = replay
20513            .side_effect(|| {
20514                calls.fetch_add(1, Ordering::SeqCst);
20515                panic!("committed side-effect callbacks must not run during replay")
20516            })
20517            .expect("replayed side effect");
20518        assert_eq!(replayed, value);
20519        assert_eq!(calls.load(Ordering::SeqCst), 1);
20520        assert!(replay.take_commands().expect("commands").is_empty());
20521        replay.ensure_history_consumed().expect("history consumed");
20522    }
20523
20524    #[test]
20525    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
20526        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
20527        let value = ctx
20528            .side_effect(|| SideEffectProbe {
20529                request_id: "avro-request".to_string(),
20530                attempt: 1,
20531            })
20532            .expect("Avro side effect");
20533        let uuid = ctx.uuid_v4().expect("deterministic UUID");
20534        let commands = ctx.take_commands().expect("commands");
20535        assert_eq!(commands.len(), 2);
20536        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
20537        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
20538        assert_eq!(
20539            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
20540            serde_json::to_value(&value).expect("value")
20541        );
20542
20543        let replay = workflow_context_with_codec(
20544            vec![
20545                history_event(
20546                    "SideEffectRecorded",
20547                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20548                ),
20549                history_event(
20550                    "SideEffectRecorded",
20551                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
20552                ),
20553            ],
20554            DEFAULT_CODEC,
20555        );
20556        let replayed: SideEffectProbe = replay
20557            .side_effect(|| panic!("Avro callback must not run"))
20558            .expect("replayed Avro value");
20559        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
20560        assert_eq!(replayed, value);
20561        assert_eq!(replayed_uuid, uuid);
20562        assert!(replay.take_commands().expect("commands").is_empty());
20563    }
20564
20565    #[test]
20566    fn typed_side_effect_replay_preserves_bytes_and_maps() {
20567        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
20568        let value = ctx
20569            .side_effect_avro_value(typed_fidelity_probe)
20570            .expect("typed side effect");
20571        let commands = ctx.take_commands().expect("side-effect command");
20572        assert_eq!(
20573            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20574                .expect("recorded side effect"),
20575            value
20576        );
20577
20578        let replay = workflow_context_with_codec(
20579            vec![history_event(
20580                "SideEffectRecorded",
20581                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20582            )],
20583            DEFAULT_CODEC,
20584        );
20585        assert_eq!(
20586            replay
20587                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
20588                .expect("replayed typed side effect"),
20589            value
20590        );
20591    }
20592
20593    #[test]
20594    fn ordered_side_effects_share_the_durable_command_stream() {
20595        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
20596        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
20597        let ctx = workflow_context(vec![
20598            history_event(
20599                "SideEffectRecorded",
20600                json!({"sequence": 1, "result": first}),
20601            ),
20602            history_event(
20603                "SideEffectRecorded",
20604                json!({"sequence": 2, "result": second}),
20605            ),
20606        ]);
20607        let first: String = ctx
20608            .side_effect(|| panic!("first callback must not run"))
20609            .expect("first replay");
20610        let second: i32 = ctx
20611            .side_effect(|| panic!("second callback must not run"))
20612            .expect("second replay");
20613        assert_eq!(first, "first");
20614        assert_eq!(second, 29);
20615        ctx.ensure_history_consumed().expect("ordered history");
20616
20617        let reordered = workflow_context(vec![history_event(
20618            "VersionMarkerRecorded",
20619            json!({
20620                "sequence": 1,
20621                "change_id": "before-side-effect",
20622                "version": 1,
20623                "min_supported": 1,
20624                "max_supported": 1,
20625            }),
20626        )]);
20627        let error = reordered
20628            .side_effect(|| "new".to_string())
20629            .expect_err("command reordering must fail");
20630        assert!(matches!(
20631            error,
20632            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20633                if reason == "recorded_command_mismatch"
20634        ));
20635    }
20636
20637    #[test]
20638    fn legacy_patch_preserves_pending_and_completed_activity_history() {
20639        for completed in [false, true] {
20640            let mut history = vec![history_event(
20641                "ActivityScheduled",
20642                json!({"sequence": 1, "activity_type": "old"}),
20643            )];
20644            if completed {
20645                history.push(history_event(
20646                    "ActivityCompleted",
20647                    json!({
20648                        "sequence": 1,
20649                        "activity_type": "old",
20650                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
20651                    }),
20652                ));
20653            }
20654            for _cold_replay in 0..2 {
20655                let ctx = workflow_context(history.clone());
20656                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
20657                assert!(!ctx.patched("added-step").expect("same frozen decision"));
20658                ctx.deprecate_patch("added-step")
20659                    .expect("retained boundary");
20660                let mut activity = Box::pin(ctx.activity("old", json!([])));
20661                let mut context = TaskContext::from_waker(noop_waker_ref());
20662                match activity.as_mut().poll(&mut context) {
20663                    Poll::Ready(result) => {
20664                        assert!(completed);
20665                        assert_eq!(result.expect("recorded result"), json!(41));
20666                        ctx.ensure_history_consumed().expect("old command retained");
20667                    }
20668                    Poll::Pending => assert!(!completed),
20669                }
20670                assert!(ctx.take_commands().expect("commands").is_empty());
20671            }
20672        }
20673    }
20674
20675    #[test]
20676    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
20677        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
20678        assert!(!ctx.patched("added-step").expect("legacy completed run"));
20679        ctx.deprecate_patch("added-step")
20680            .expect("same legacy decision");
20681        assert!(ctx.take_commands().expect("commands").is_empty());
20682        ctx.ensure_history_consumed().expect("completed history");
20683    }
20684
20685    #[test]
20686    fn legacy_patch_rejects_a_range_without_the_original_branch() {
20687        let ctx = workflow_context(vec![history_event(
20688            "ActivityScheduled",
20689            json!({"sequence": 1, "activity_type": "old"}),
20690        )]);
20691        let error = ctx
20692            .get_version("added-step", 0, 1)
20693            .expect_err("legacy is unsupported");
20694        assert!(matches!(
20695            error,
20696            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20697                if reason == "version_marker_incompatible_range"
20698        ));
20699        assert!(!ctx
20700            .patched("supported-step")
20701            .expect("failed check did not consume history"));
20702        assert!(ctx.take_commands().expect("commands").is_empty());
20703    }
20704
20705    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
20706        let mut event = history_event(
20707            "VersionMarkerRecorded",
20708            json!({
20709                "sequence": sequence,
20710                "change_id": "retained-patch",
20711                "version": version,
20712                "min_supported": -1,
20713                "max_supported": 1,
20714            }),
20715        );
20716        event.raw.insert("timestamp".into(), json!(time));
20717        event
20718    }
20719
20720    #[test]
20721    fn retained_patch_markers_preserve_each_original_boundary() {
20722        for completed in [false, true] {
20723            let mut history = vec![
20724                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20725                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20726                history_event(
20727                    "ActivityScheduled",
20728                    json!({"sequence": 3, "activity_type": "old"}),
20729                ),
20730            ];
20731            if completed {
20732                history.push(history_event(
20733                    "ActivityCompleted",
20734                    json!({
20735                        "sequence": 3,
20736                        "activity_type": "old",
20737                        "result": fixture_envelope(json!(41)),
20738                    }),
20739                ));
20740            }
20741            for _cold_replay in 0..2 {
20742                let ctx = workflow_context(history.clone());
20743                assert!(ctx.patched("retained-patch").unwrap());
20744                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20745                assert!(ctx.patched("retained-patch").unwrap());
20746                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20747                ctx.deprecate_patch("retained-patch").unwrap();
20748                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20749                let mut activity = Box::pin(ctx.activity("old", json!([])));
20750                let mut context = TaskContext::from_waker(noop_waker_ref());
20751                match activity.as_mut().poll(&mut context) {
20752                    Poll::Ready(result) => {
20753                        assert!(completed);
20754                        assert_eq!(result.unwrap(), json!(41));
20755                        ctx.ensure_history_consumed().unwrap();
20756                    }
20757                    Poll::Pending => assert!(!completed),
20758                }
20759                assert!(ctx.take_commands().unwrap().is_empty());
20760                let state = ctx.state.lock().unwrap();
20761                for (actual, original) in state.history_events.iter().zip(&history) {
20762                    assert_eq!(actual.payload, original.payload);
20763                    assert_eq!(actual.raw, original.raw);
20764                }
20765            }
20766        }
20767    }
20768
20769    #[test]
20770    fn retained_patch_aliases_do_not_skip_intervening_operations() {
20771        let ctx = workflow_context(vec![
20772            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20773            history_event(
20774                "SideEffectRecorded",
20775                json!({
20776                    "sequence": 2, "result": fixture_envelope(json!("between")),
20777                }),
20778            ),
20779            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
20780            history_event(
20781                "VersionMarkerRecorded",
20782                json!({
20783                    "sequence": 4, "change_id": "other-patch", "version": 1,
20784                    "min_supported": -1, "max_supported": 1,
20785                }),
20786            ),
20787        ]);
20788        assert!(ctx.patched("retained-patch").unwrap());
20789        assert!(ctx.patched("retained-patch").unwrap());
20790        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20791        assert_eq!(
20792            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
20793            "between"
20794        );
20795        ctx.deprecate_patch("retained-patch").unwrap();
20796        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20797        ctx.deprecate_patch("retained-patch").unwrap();
20798        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20799        assert!(ctx.patched("other-patch").unwrap());
20800        ctx.ensure_history_consumed().unwrap();
20801        assert!(ctx.take_commands().unwrap().is_empty());
20802    }
20803
20804    #[test]
20805    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
20806        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
20807        alias.payload["max_supported"] = json!(3);
20808        let ctx = workflow_context(vec![
20809            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20810            alias,
20811        ]);
20812        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
20813        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
20814        assert!(matches!(error,
20815            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20816                if reason == "version_marker_incompatible_range"));
20817        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20818        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
20819        ctx.ensure_history_consumed().unwrap();
20820        assert!(ctx.take_commands().unwrap().is_empty());
20821    }
20822
20823    #[test]
20824    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
20825        let ctx = workflow_context(Vec::new());
20826        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
20827        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
20828        assert!(ctx.patched("new-search").expect("patch"));
20829        ctx.deprecate_patch("new-search").expect("deprecate patch");
20830        let commands = ctx.take_commands().expect("commands");
20831        assert_eq!(commands.len(), 2);
20832        assert_eq!(commands[0]["type"], "record_version_marker");
20833        assert_eq!(commands[0]["version"], 2);
20834        assert_eq!(commands[1]["change_id"], "new-search");
20835
20836        let replay = workflow_context(vec![history_event(
20837            "VersionMarkerRecorded",
20838            json!({
20839                "sequence": 1,
20840                "change_id": "checkout-v2",
20841                "version": 2,
20842                "min_supported": 1,
20843                "max_supported": 2,
20844            }),
20845        )]);
20846        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
20847        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
20848        assert!(replay.take_commands().expect("commands").is_empty());
20849        replay.ensure_history_consumed().expect("history consumed");
20850    }
20851
20852    #[test]
20853    fn version_markers_reject_incompatible_or_malformed_history() {
20854        let incompatible = workflow_context(vec![history_event(
20855            "VersionMarkerRecorded",
20856            json!({
20857                "sequence": 1,
20858                "change_id": "checkout-v2",
20859                "version": 1,
20860                "min_supported": 1,
20861                "max_supported": 2,
20862            }),
20863        )]);
20864        let error = incompatible
20865            .get_version("checkout-v2", 2, 3)
20866            .expect_err("old version is unsupported");
20867        assert!(matches!(
20868            error,
20869            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20870                if reason == "version_marker_incompatible_range"
20871        ));
20872
20873        for (history, reason) in [
20874            (
20875                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
20876                "side_effect_result_missing",
20877            ),
20878            (
20879                vec![history_event(
20880                    "SideEffectRecorded",
20881                    json!({
20882                        "sequence": 1,
20883                        "result": {"codec": "avro", "blob": "not-base64"},
20884                    }),
20885                )],
20886                "side_effect_payload_incompatible",
20887            ),
20888            (
20889                vec![history_event(
20890                    "SideEffectRecorded",
20891                    json!({"sequence": 1, "result": {"unwrapped": true}}),
20892                )],
20893                "side_effect_payload_malformed",
20894            ),
20895            (
20896                vec![history_event(
20897                    "VersionMarkerRecorded",
20898                    json!({
20899                        "sequence": 1,
20900                        "change_id": "change",
20901                        "version": 1,
20902                        "min_supported": 2,
20903                        "max_supported": 1,
20904                    }),
20905                )],
20906                "version_marker_history_range_invalid",
20907            ),
20908        ] {
20909            let error = WorkflowState::new(
20910                history,
20911                "rust-workers".to_string(),
20912                DEFAULT_CODEC.to_string(),
20913                None,
20914            )
20915            .expect_err("malformed history must fail");
20916            assert!(matches!(
20917                error,
20918                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
20919                    if actual == reason
20920            ));
20921        }
20922    }
20923
20924    #[test]
20925    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
20926        let history = vec![history_event(
20927            "SearchAttributesUpserted",
20928            json!({
20929                "sequence": 1,
20930                "attributes": {"customer_tier": "gold"},
20931                "attribute_types": {"customer_tier": "keyword"},
20932                "merged": {"customer_tier": "gold"}
20933            }),
20934        )];
20935
20936        let matching = workflow_context(history.clone());
20937        matching
20938            .upsert_search_attributes(
20939                SearchAttributeUpdate::new()
20940                    .keyword("customer_tier", "gold")
20941                    .expect("keyword update"),
20942            )
20943            .expect("matching typed update must replay");
20944        matching
20945            .ensure_history_consumed()
20946            .expect("history consumed");
20947
20948        let changed_type = workflow_context(history.clone());
20949        let error = changed_type
20950            .upsert_search_attributes(
20951                SearchAttributeUpdate::new()
20952                    .string("customer_tier", "gold")
20953                    .expect("string update"),
20954            )
20955            .expect_err("same JSON value with a different declaration must be nondeterministic");
20956        let Error::NonDeterministicReplay(failure) = error else {
20957            panic!("typed identity drift must be a replay failure");
20958        };
20959        assert_eq!(failure.reason, "search_attribute_type_mismatch");
20960        assert_eq!(failure.sequence, Some(1));
20961
20962        let changed_value = workflow_context(history);
20963        let error = changed_value
20964            .upsert_search_attributes(
20965                SearchAttributeUpdate::new()
20966                    .keyword("customer_tier", "platinum")
20967                    .expect("keyword update"),
20968            )
20969            .expect_err("changed values must be nondeterministic");
20970        let Error::NonDeterministicReplay(failure) = error else {
20971            panic!("value drift must be a replay failure");
20972        };
20973        assert_eq!(failure.reason, "search_attribute_value_mismatch");
20974    }
20975
20976    #[test]
20977    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
20978        let history = vec![history_event(
20979            "SearchAttributesUpserted",
20980            json!({
20981                "sequence": 1,
20982                "attributes": {"customer_tier": "gold"},
20983                "merged": {"customer_tier": "gold"}
20984            }),
20985        )];
20986
20987        for update in [
20988            SearchAttributeUpdate::new()
20989                .keyword("customer_tier", "gold")
20990                .expect("keyword update"),
20991            SearchAttributeUpdate::new()
20992                .string("customer_tier", "gold")
20993                .expect("string update"),
20994        ] {
20995            let restarted = workflow_context(history.clone());
20996            restarted
20997                .upsert_search_attributes(update)
20998                .expect("legacy history constrains values but has unknown type identity");
20999            restarted
21000                .ensure_history_consumed()
21001                .expect("history consumed");
21002        }
21003    }
21004
21005    #[test]
21006    fn search_attribute_command_emits_canonical_types() {
21007        let ctx = workflow_context(Vec::new());
21008        ctx.upsert_search_attributes(
21009            SearchAttributeUpdate::new()
21010                .keyword("customer_tier", "gold")
21011                .expect("keyword update")
21012                .int("attempts", 3)
21013                .expect("int update")
21014                .delete("obsolete")
21015                .expect("delete update"),
21016        )
21017        .expect("valid search attributes");
21018
21019        assert_eq!(
21020            ctx.take_commands().expect("commands"),
21021            vec![json!({
21022                "type": "upsert_search_attributes",
21023                "attributes": {
21024                    "attempts": 3,
21025                    "customer_tier": "gold",
21026                    "obsolete": null
21027                },
21028                "attribute_types": {
21029                    "attempts": "int",
21030                    "customer_tier": "keyword"
21031                }
21032            })]
21033        );
21034    }
21035
21036    #[test]
21037    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
21038        let duplicate_side_effect = WorkflowState::new(
21039            vec![
21040                history_event(
21041                    "SideEffectRecorded",
21042                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
21043                ),
21044                history_event(
21045                    "SideEffectRecorded",
21046                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
21047                ),
21048            ],
21049            "rust-workers".to_string(),
21050            DEFAULT_CODEC.to_string(),
21051            None,
21052        )
21053        .expect_err("duplicate side effect");
21054        assert!(matches!(
21055            duplicate_side_effect,
21056            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21057                if reason == "duplicate_side_effect_record"
21058        ));
21059
21060        let marker = |sequence, version| {
21061            history_event(
21062                "VersionMarkerRecorded",
21063                json!({
21064                    "sequence": sequence,
21065                    "change_id": "same-change",
21066                    "version": version,
21067                    "min_supported": -1,
21068                    "max_supported": 1,
21069                }),
21070            )
21071        };
21072        let duplicate_marker = WorkflowState::new(
21073            vec![marker(1, 1), marker(3, -1)],
21074            "rust-workers".to_string(),
21075            DEFAULT_CODEC.to_string(),
21076            None,
21077        )
21078        .expect_err("conflicting marker");
21079        assert!(matches!(
21080            duplicate_marker,
21081            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21082                if reason == "version_marker_conflict"
21083        ));
21084    }
21085
21086    #[test]
21087    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
21088        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
21089        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
21090        invalid_alias.payload["max_supported"] = json!(0);
21091        for (history, expected_reason) in [
21092            (
21093                vec![marker.clone(), marker.clone()],
21094                "duplicate_version_marker_record",
21095            ),
21096            (
21097                vec![marker, invalid_alias],
21098                "version_marker_history_range_invalid",
21099            ),
21100        ] {
21101            let error =
21102                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
21103                    .expect_err("invalid historical alias");
21104            assert!(matches!(error,
21105                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
21106                    if reason == expected_reason));
21107        }
21108    }
21109
21110    #[test]
21111    fn retained_patch_aliases_require_the_original_call_boundary() {
21112        let ctx = workflow_context(vec![
21113            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
21114            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21115        ]);
21116        assert!(ctx.patched("retained-patch").unwrap());
21117        assert!(ctx.ensure_history_consumed().is_err());
21118        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21119        ctx.deprecate_patch("retained-patch").unwrap();
21120        ctx.ensure_history_consumed().unwrap();
21121        assert!(ctx.take_commands().unwrap().is_empty());
21122    }
21123
21124    #[test]
21125    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
21126        let ctx = workflow_context(vec![
21127            history_event(
21128                "SideEffectRecorded",
21129                json!({
21130                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
21131                }),
21132            ),
21133            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21134        ]);
21135        assert!(!ctx.patched("retained-patch").unwrap());
21136        assert_eq!(
21137            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
21138            "old-operation"
21139        );
21140        let error = ctx.patched("retained-patch").unwrap_err();
21141        assert!(matches!(error,
21142            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21143                if reason == "version_marker_conflict"));
21144        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21145        assert!(ctx.take_commands().unwrap().is_empty());
21146    }
21147
21148    #[test]
21149    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
21150        let mut state = WorkflowState::new(
21151            Vec::new(),
21152            "rust-workers".to_string(),
21153            DEFAULT_CODEC.to_string(),
21154            None,
21155        )
21156        .expect("workflow state");
21157        state.workflow_command_identity = "command-7".to_string();
21158        let context = WorkflowContext {
21159            state: Arc::new(Mutex::new(state)),
21160            cancellation_scope_id: "root".into(),
21161        };
21162        let item =
21163            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
21164
21165        context
21166            .append_workflow_stream("output", &[item], Some(10))
21167            .expect("append command");
21168        context
21169            .error_workflow_stream("output", "producer failed", None)
21170            .expect("error command");
21171        let commands = context.take_commands().expect("commands");
21172
21173        assert_eq!(commands[0]["type"], "record_side_effect");
21174        assert_eq!(
21175            commands[0]["workflow_stream"]["command_identity"],
21176            "command-7"
21177        );
21178        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
21179        assert_eq!(
21180            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
21181            "dw-stream:command-7:0:0"
21182        );
21183        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
21184
21185        let recorded = history_event(
21186            "SideEffectRecorded",
21187            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
21188        );
21189        let mut replay_state = WorkflowState::new(
21190            vec![recorded],
21191            "rust-workers".to_string(),
21192            DEFAULT_CODEC.to_string(),
21193            None,
21194        )
21195        .expect("replay state");
21196        replay_state.workflow_command_identity = "command-7".to_string();
21197        let replay_context = WorkflowContext {
21198            state: Arc::new(Mutex::new(replay_state)),
21199            cancellation_scope_id: "root".into(),
21200        };
21201        replay_context
21202            .append_workflow_stream(
21203                "output",
21204                &[WorkflowStreamAppendItem::from_reference(
21205                    "s3://bucket/item.avro",
21206                )],
21207                Some(10),
21208            )
21209            .expect("replayed append");
21210        assert!(replay_context
21211            .take_commands()
21212            .expect("replayed commands")
21213            .is_empty());
21214    }
21215
21216    #[test]
21217    fn workflow_stream_authoring_requires_server_durable_command_identity() {
21218        let context = workflow_context(Vec::new());
21219        let error = context
21220            .append_workflow_stream(
21221                "output",
21222                &[WorkflowStreamAppendItem::from_reference(
21223                    "s3://bucket/item.avro",
21224                )],
21225                None,
21226            )
21227            .expect_err("stream append without durable command identity must fail closed");
21228
21229        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
21230        assert!(context.take_commands().expect("commands").is_empty());
21231    }
21232
21233    #[test]
21234    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
21235        let client = Client::builder("http://localhost:8080").build().unwrap();
21236        let mut worker = Worker::new(client, "rust-workers");
21237        worker.register_workflow("streams.worker", |ctx, _| async move {
21238            ctx.append_workflow_stream(
21239                "output",
21240                &[WorkflowStreamAppendItem::new(json!("hello"))?],
21241                None,
21242            )?;
21243            ctx.close_workflow_stream("output", None)?;
21244            Ok(json!("done"))
21245        });
21246        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
21247            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
21248            task.workflow_command_id = command_id.clone();
21249            let expected_identity = command_id
21250                .as_deref()
21251                .filter(|id| !id.is_empty())
21252                .unwrap_or(&task.task_id)
21253                .to_string();
21254            let commands = worker
21255                .execute_workflow_task(task)
21256                .expect("ordinary worker stream output");
21257            assert_eq!(commands.len(), 3);
21258            assert_eq!(
21259                commands[0]["workflow_stream"]["command_identity"],
21260                expected_identity
21261            );
21262            assert_eq!(
21263                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
21264                format!("dw-stream:{expected_identity}:0:0")
21265            );
21266            assert_eq!(
21267                commands[1]["workflow_stream"]["command_identity"],
21268                expected_identity
21269            );
21270            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
21271            let history = commands[..2]
21272                .iter()
21273                .enumerate()
21274                .map(|(index, command)| {
21275                    history_event(
21276                        "SideEffectRecorded",
21277                        json!({"sequence":index + 1,"result":command["result"]}),
21278                    )
21279                })
21280                .collect();
21281            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
21282            replay.task_id = "replacement-task".to_string();
21283            let replayed = worker
21284                .execute_workflow_task(replay)
21285                .expect("replacement worker consumes recorded stream effects");
21286            assert_eq!(replayed.len(), 1);
21287            assert_eq!(replayed[0]["type"], "complete_workflow");
21288        }
21289        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
21290        missing.task_id.clear();
21291        assert!(matches!(
21292            worker.execute_workflow_task(missing),
21293            Err(Error::MissingWorkflowCommandIdentity)
21294        ));
21295    }
21296
21297    #[test]
21298    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
21299        fn worker(calls: Arc<AtomicUsize>) -> Worker {
21300            let client = Client::new("http://127.0.0.1:8080").expect("client");
21301            let mut worker = Worker::new(client, "rust-workers");
21302            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
21303                let calls = Arc::clone(&calls);
21304                async move {
21305                    let captured = ctx.side_effect(|| {
21306                        calls.fetch_add(1, Ordering::SeqCst);
21307                        "captured-once".to_string()
21308                    })?;
21309                    let version = ctx.get_version("cold-restart", 1, 2)?;
21310                    Ok(json!({"captured": captured, "version": version}))
21311                }
21312            });
21313            worker
21314        }
21315
21316        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
21317            WorkflowTask {
21318                task_id: "wft-side-effect-version".to_string(),
21319                observability_context: None,
21320                dispatch_observability_context: None,
21321                observability_links: None,
21322                workflow_command_id: None,
21323                workflow_id: Some("wf-side-effect-version".to_string()),
21324                run_id: Some("run-side-effect-version".to_string()),
21325                workflow_type: "rust.side-effect-version".to_string(),
21326                cancel_requested: false,
21327                payload_codec: DEFAULT_CODEC.to_string(),
21328                arguments: Some(
21329                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
21330                ),
21331                history_events,
21332                total_history_events: None,
21333                history_size_bytes: None,
21334                continue_as_new_recommended: None,
21335                history_budget_pressure: None,
21336                next_history_page_token: None,
21337                workflow_task_attempt: 1,
21338                workflow_signal_id: None,
21339                signal_name: None,
21340                signal_arguments: None,
21341                workflow_update_id: None,
21342                update_name: None,
21343                lease_owner: Some("rust-worker".to_string()),
21344            }
21345        }
21346
21347        let calls = Arc::new(AtomicUsize::new(0));
21348        let initial = worker(Arc::clone(&calls))
21349            .execute_workflow_task(task(Vec::new()))
21350            .expect("initial execution");
21351        assert_eq!(
21352            initial
21353                .iter()
21354                .map(|command| &command["type"])
21355                .collect::<Vec<_>>(),
21356            vec![
21357                "record_side_effect",
21358                "record_version_marker",
21359                "complete_workflow"
21360            ]
21361        );
21362        assert_eq!(calls.load(Ordering::SeqCst), 1);
21363
21364        let restarted = worker(Arc::clone(&calls));
21365        let replayed = restarted
21366            .execute_workflow_task(task(vec![
21367                history_event(
21368                    "SideEffectRecorded",
21369                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
21370                ),
21371                history_event(
21372                    "VersionMarkerRecorded",
21373                    json!({
21374                        "sequence": 2,
21375                        "change_id": "cold-restart",
21376                        "version": 2,
21377                        "min_supported": 1,
21378                        "max_supported": 2,
21379                    }),
21380                ),
21381            ]))
21382            .expect("cold replay");
21383        assert_eq!(replayed.len(), 1);
21384        assert_eq!(replayed[0]["type"], "complete_workflow");
21385        assert_eq!(calls.load(Ordering::SeqCst), 1);
21386    }
21387
21388    #[test]
21389    fn side_effect_replay_rejects_changed_rust_value_type() {
21390        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
21391        let ctx = workflow_context(vec![history_event(
21392            "SideEffectRecorded",
21393            json!({"sequence": 1, "result": result}),
21394        )]);
21395        let error = ctx
21396            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
21397            .expect_err("changed type must fail replay");
21398        assert!(matches!(
21399            error,
21400            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21401                if reason == "side_effect_type_mismatch"
21402        ));
21403    }
21404
21405    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
21406        vec![
21407            history_event(
21408                "ActivityScheduled",
21409                json!({
21410                    "sequence": 1,
21411                    "activity_type": "flaky",
21412                    "activity_execution_id": "act-1",
21413                    "activity": {
21414                        "id": "act-1",
21415                        "sequence": 1,
21416                        "type": "flaky",
21417                        "queue": "critical-activities",
21418                        "execution_mode": null,
21419                        "retry_policy": {
21420                            "snapshot_version": 1,
21421                            "max_attempts": 3,
21422                            "backoff_seconds": [2, 4],
21423                            "start_to_close_timeout": 30,
21424                            "schedule_to_start_timeout": 5,
21425                            "schedule_to_close_timeout": 90,
21426                            "heartbeat_timeout": 10,
21427                            "non_retryable_error_types": ["PermanentError"]
21428                        }
21429                    }
21430                }),
21431            ),
21432            history_event(
21433                "ActivityStarted",
21434                json!({
21435                    "sequence": 1,
21436                    "activity_type": "flaky",
21437                    "activity_execution_id": "act-1",
21438                    "activity_attempt_id": "attempt-1",
21439                    "attempt_number": 1
21440                }),
21441            ),
21442            history_event(
21443                "ActivityRetryScheduled",
21444                json!({
21445                    "sequence": 1,
21446                    "activity_type": "flaky",
21447                    "activity_execution_id": "act-1",
21448                    "activity_attempt_id": "attempt-1",
21449                    "attempt_number": 1,
21450                    "retry_after_attempt": 1,
21451                    "retry_backoff_seconds": 2,
21452                    "failure_category": "activity",
21453                    "exception_type": "TransientError"
21454                }),
21455            ),
21456            history_event(
21457                "ActivityStarted",
21458                json!({
21459                    "sequence": 1,
21460                    "activity_type": "flaky",
21461                    "activity_execution_id": "act-1",
21462                    "activity_attempt_id": "attempt-2",
21463                    "attempt_number": 2
21464                }),
21465            ),
21466            history_event(
21467                "ActivityCompleted",
21468                json!({
21469                    "sequence": 1,
21470                    "activity_type": "flaky",
21471                    "activity_execution_id": "act-1",
21472                    "activity_attempt_id": "attempt-2",
21473                    "attempt_number": 2,
21474                    "payload_codec": DEFAULT_CODEC,
21475                    "result": fixture_envelope(json!({"status":"recovered"}))
21476                }),
21477            ),
21478        ]
21479    }
21480
21481    fn retry_activity_options() -> ActivityOptions {
21482        ActivityOptions::new()
21483            .task_queue("critical-activities")
21484            .retry_policy(
21485                ActivityRetryPolicy::new(3)
21486                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
21487                    .non_retryable_error_type("PermanentError"),
21488            )
21489            .start_to_close_timeout(Duration::from_secs(30))
21490            .schedule_to_start_timeout(Duration::from_secs(5))
21491            .schedule_to_close_timeout(Duration::from_secs(90))
21492            .heartbeat_timeout(Duration::from_secs(10))
21493    }
21494
21495    #[test]
21496    fn fixed_avro_value_round_trips_json_values() {
21497        let value = json!({"greeting": "hello", "count": 3, "ok": true});
21498        let envelope = PayloadEnvelope::avro(&value).expect("encode");
21499        assert_eq!(envelope.codec, DEFAULT_CODEC);
21500        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
21501    }
21502
21503    #[tokio::test]
21504    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
21505        let client = Client::new("http://127.0.0.1:8080").expect("client");
21506        let mut worker = Worker::new(client, "rust-workers");
21507        worker.register_typed_workflow(
21508            "typed.contract.workflow",
21509            |_ctx, input: TypedContract| async move { Ok(input) },
21510        );
21511        worker.register_typed_activity(
21512            "typed.contract.activity",
21513            |_ctx, input: TypedContract| async move { Ok(input) },
21514        );
21515
21516        let expected = typed_contract();
21517        let arguments = AvroValue::Array(vec![
21518            AvroValue::from_serialize(&expected).expect("typed request")
21519        ]);
21520        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
21521        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
21522        workflow.arguments = Some(envelope.clone());
21523        let commands = worker
21524            .execute_workflow_task(workflow)
21525            .expect("typed workflow task");
21526        let workflow_result: TypedContract =
21527            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21528                .expect("workflow result envelope")
21529                .deserialize()
21530                .expect("workflow result type");
21531        assert_eq!(workflow_result, expected);
21532
21533        let activity = ActivityTask {
21534            task_id: "typed-contract-activity".to_string(),
21535            workflow_id: None,
21536            run_id: None,
21537            activity_execution_id: None,
21538            observability_context: None,
21539            dispatch_observability_context: None,
21540            observability_links: None,
21541            activity_attempt_id: Some("typed-contract-attempt".to_string()),
21542            attempt_id: None,
21543            activity_type: "typed.contract.activity".to_string(),
21544            payload_codec: DEFAULT_CODEC.to_string(),
21545            arguments: Some(envelope),
21546            attempt_number: 1,
21547            lease_owner: Some("rust-worker".to_string()),
21548        };
21549        let activity_result: TypedContract = worker
21550            .execute_activity_task(activity)
21551            .await
21552            .expect("typed activity task")
21553            .deserialize()
21554            .expect("activity result type");
21555        assert_eq!(activity_result, expected);
21556    }
21557
21558    #[test]
21559    fn typed_entry_mismatch_refuses_before_body_and_preserves_original_input() {
21560        let calls = Arc::new(AtomicUsize::new(0));
21561        let observed = Arc::clone(&calls);
21562        let client = Client::new("http://127.0.0.1:8080").expect("client");
21563        let mut worker = Worker::new(client.clone(), "rust-workers");
21564        worker.register_typed_workflow("entry.safe", move |_ctx, input: i64| {
21565            observed.fetch_add(1, Ordering::SeqCst);
21566            async move { Ok(input) }
21567        });
21568        let mut task = workflow_task("entry.safe", Vec::new(), DEFAULT_CODEC);
21569        task.arguments = Some(fixture_envelope(json!(["private-original-value"])));
21570        let original = task.clone();
21571        let error = worker
21572            .execute_workflow_task(task)
21573            .expect_err("incompatible entry must refuse the task, not fail the run");
21574        assert_eq!(calls.load(Ordering::SeqCst), 0);
21575        assert!(error
21576            .to_string()
21577            .contains("workflow_entry_arguments_mismatch:"));
21578        assert!(!error.to_string().contains("private-original-value"));
21579
21580        let mut compatible = Worker::new(client, "rust-workers");
21581        compatible
21582            .register_typed_workflow("entry.safe", |_ctx, input: String| async move { Ok(input) });
21583        let commands = compatible
21584            .execute_workflow_task(original)
21585            .expect("same recorded input");
21586        assert_eq!(commands[0]["type"], "complete_workflow");
21587        assert_eq!(
21588            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).unwrap(),
21589            json!("private-original-value")
21590        );
21591    }
21592
21593    #[test]
21594    fn typed_entry_replayed_mismatch_refuses_before_state_factory_and_body() {
21595        let factories = Arc::new(AtomicUsize::new(0));
21596        let observed = Arc::clone(&factories);
21597        let client = Client::new("http://127.0.0.1:8080").expect("client");
21598        let mut worker = Worker::new(client, "rust-workers");
21599        worker.register_typed_replayed_workflow(
21600            "entry.replayed",
21601            move || {
21602                observed.fetch_add(1, Ordering::SeqCst);
21603                ()
21604            },
21605            |_ctx, _input: i64, _state| async move {
21606                panic!("body must not start");
21607                #[allow(unreachable_code)]
21608                Ok(0_i64)
21609            },
21610        );
21611        let mut task = workflow_task("entry.replayed", Vec::new(), DEFAULT_CODEC);
21612        task.arguments = Some(fixture_envelope(json!(["private-replayed-value"])));
21613        let error = worker
21614            .execute_workflow_task(task)
21615            .expect_err("entry refusal");
21616        assert_eq!(factories.load(Ordering::SeqCst), 0);
21617        assert!(error
21618            .to_string()
21619            .contains("workflow_entry_arguments_mismatch:"));
21620        assert!(!error.to_string().contains("private-replayed-value"));
21621
21622        let replay = worker.workflows["entry.replayed"].replay.as_ref().unwrap();
21623        let Err(error) = replay(
21624            workflow_context(Vec::new()),
21625            AvroValue::Array(vec![AvroValue::String("private-replayed-value".into())]),
21626        ) else {
21627            panic!("query replay must refuse before creating application state");
21628        };
21629        assert_eq!(factories.load(Ordering::SeqCst), 0);
21630        assert!(!error.to_string().contains("private-replayed-value"));
21631    }
21632
21633    #[test]
21634    fn typed_entry_deserializes_once_before_entering_application_code() {
21635        static DECODES: AtomicUsize = AtomicUsize::new(0);
21636        struct Counted(i64);
21637        impl<'de> Deserialize<'de> for Counted {
21638            fn deserialize<D: Deserializer<'de>>(
21639                deserializer: D,
21640            ) -> std::result::Result<Self, D::Error> {
21641                DECODES.fetch_add(1, Ordering::SeqCst);
21642                i64::deserialize(deserializer).map(Self)
21643            }
21644        }
21645        DECODES.store(0, Ordering::SeqCst);
21646        let client = Client::new("http://127.0.0.1:8080").expect("client");
21647        let mut worker = Worker::new(client, "rust-workers");
21648        worker.register_typed_workflow(
21649            "entry.once",
21650            |_ctx, input: Counted| async move { Ok(input.0) },
21651        );
21652        let mut task = workflow_task("entry.once", Vec::new(), DEFAULT_CODEC);
21653        task.arguments = Some(fixture_envelope(json!([7])));
21654        let commands = worker.execute_workflow_task(task).expect("typed result");
21655        assert_eq!(commands[0]["type"], "complete_workflow");
21656        assert_eq!(DECODES.load(Ordering::SeqCst), 1);
21657    }
21658
21659    #[test]
21660    fn typed_entry_body_input_error_remains_a_business_failure() {
21661        let client = Client::new("http://127.0.0.1:8080").expect("client");
21662        let mut worker = Worker::new(client, "rust-workers");
21663        worker.register_typed_workflow("entry.body", |_ctx, _input: i64| async move {
21664            Err::<i64, _>(handler_type_error::<i64>(
21665                HandlerKind::Workflow,
21666                "entry.body",
21667                HandlerValueKind::Input,
21668                "deliberate body error",
21669            ))
21670        });
21671        let mut task = workflow_task("entry.body", Vec::new(), DEFAULT_CODEC);
21672        task.arguments = Some(fixture_envelope(json!([7])));
21673        let commands = worker
21674            .execute_workflow_task(task)
21675            .expect("business failure command");
21676        assert_eq!(commands[0]["type"], "fail_workflow");
21677        assert!(commands[0]["message"]
21678            .as_str()
21679            .unwrap()
21680            .contains("deliberate body error"));
21681    }
21682
21683    #[test]
21684    fn typed_entry_body_cannot_claim_the_adapter_refusal() {
21685        let client = Client::new("http://127.0.0.1:8080").expect("client");
21686        let mut worker = Worker::new(client, "rust-workers");
21687        worker.register_typed_workflow("entry.body.refusal", |_ctx, _input: i64| async move {
21688            Err::<i64, _>(handler_type_error::<i64>(
21689                HandlerKind::Workflow,
21690                "entry.body.refusal",
21691                HandlerValueKind::Input,
21692                "workflow_entry_arguments_mismatch: deliberate body error",
21693            ))
21694        });
21695        let mut task = workflow_task("entry.body.refusal", Vec::new(), DEFAULT_CODEC);
21696        task.arguments = Some(fixture_envelope(json!([7])));
21697        let commands = worker
21698            .execute_workflow_task(task)
21699            .expect("business failure");
21700        assert_eq!(commands[0]["type"], "fail_workflow");
21701    }
21702
21703    #[tokio::test]
21704    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
21705        let client = Client::new("http://127.0.0.1:8080").expect("client");
21706        let mut worker = Worker::new(client, "rust-workers");
21707        worker.register_typed_workflow(
21708            "typed.shape.workflow",
21709            |_ctx, input: TypedContract| async move { Ok(input) },
21710        );
21711        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
21712            Ok(f64::NAN)
21713        });
21714
21715        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
21716        workflow.arguments = Some(
21717            encode_typed_envelope(
21718                &AvroValue::Array(vec![
21719                    AvroValue::String("first".to_string()),
21720                    AvroValue::String("second".to_string()),
21721                ]),
21722                DEFAULT_CODEC,
21723            )
21724            .expect("malformed typed arguments"),
21725        );
21726        let error = worker
21727            .execute_workflow_task(workflow)
21728            .expect_err("entry shape mismatch refuses the task");
21729        let message = error.to_string();
21730        assert!(message.contains("workflow_entry_arguments_mismatch:"));
21731        assert!(message.contains("typed.shape.workflow"));
21732        assert!(message.contains(type_name::<TypedContract>()));
21733
21734        let activity = ActivityTask {
21735            task_id: "typed-unsupported-activity".to_string(),
21736            workflow_id: None,
21737            run_id: None,
21738            activity_execution_id: None,
21739            observability_context: None,
21740            dispatch_observability_context: None,
21741            observability_links: None,
21742            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
21743            attempt_id: None,
21744            activity_type: "typed.unsupported.activity".to_string(),
21745            payload_codec: DEFAULT_CODEC.to_string(),
21746            arguments: Some(
21747                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21748                    .expect("unit arguments"),
21749            ),
21750            attempt_number: 1,
21751            lease_owner: Some("rust-worker".to_string()),
21752        };
21753        let Error::HandlerType {
21754            handler_kind,
21755            handler_name,
21756            value_kind,
21757            rust_type,
21758            message,
21759        } = worker
21760            .execute_activity_task(activity)
21761            .await
21762            .expect_err("non-finite handler output must fail")
21763        else {
21764            panic!("expected contextual handler type failure");
21765        };
21766        assert_eq!(handler_kind, HandlerKind::Activity);
21767        assert_eq!(handler_name, "typed.unsupported.activity");
21768        assert_eq!(value_kind, HandlerValueKind::Result);
21769        assert_eq!(rust_type, type_name::<f64>());
21770        assert!(message.contains("non_finite_float"));
21771    }
21772
21773    #[tokio::test]
21774    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
21775        #[derive(Clone, Default)]
21776        struct State {
21777            observed: Option<TypedContract>,
21778        }
21779
21780        let client = Client::new("http://127.0.0.1:8080").expect("client");
21781        let mut worker = Worker::new(client, "rust-workers");
21782        worker.register_typed_replayed_workflow(
21783            "typed.contract.replayed",
21784            State::default,
21785            |ctx, input: TypedContract, state| async move {
21786                let result: TypedContract =
21787                    ctx.activity_typed("typed.contract.activity", input).await?;
21788                state.update(|current| current.observed = Some(result.clone()))?;
21789                Ok(result)
21790            },
21791        );
21792        worker.register_replayed_query::<State, _, _>(
21793            "typed.contract.replayed",
21794            "observed",
21795            |_ctx, state, _args| async move {
21796                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
21797            },
21798        );
21799
21800        let expected = typed_contract();
21801        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
21802        let workflow_arguments =
21803            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
21804                .expect("workflow arguments");
21805        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
21806        let task = QueryTask {
21807            query_task_id: "typed-replay-query".to_string(),
21808            observability_context: None,
21809            dispatch_observability_context: None,
21810            observability_links: None,
21811            query_task_attempt: 1,
21812            lease_owner: Some("rust-worker".to_string()),
21813            workflow_id: Some("typed-replay".to_string()),
21814            run_id: Some("typed-replay-run".to_string()),
21815            workflow_type: "typed.contract.replayed".to_string(),
21816            query_name: "observed".to_string(),
21817            payload_codec: DEFAULT_CODEC.to_string(),
21818            workflow_arguments: Some(workflow_arguments),
21819            query_arguments: Some(
21820                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21821                    .expect("query arguments"),
21822            ),
21823            history_events: vec![
21824                history_event(
21825                    "ActivityScheduled",
21826                    json!({
21827                        "sequence": 1,
21828                        "activity_type": "typed.contract.activity"
21829                    }),
21830                ),
21831                history_event(
21832                    "ActivityCompleted",
21833                    json!({
21834                        "sequence": 1,
21835                        "activity_type": "typed.contract.activity",
21836                        "payload_codec": DEFAULT_CODEC,
21837                        "result": result
21838                    }),
21839                ),
21840            ],
21841            history_export: None,
21842            run_status: Some("completed".to_string()),
21843        };
21844
21845        assert_eq!(
21846            worker
21847                .execute_query_task(task)
21848                .await
21849                .expect("typed replay query")
21850                .deserialize::<i64>()
21851                .expect("query result"),
21852            expected.signed
21853        );
21854    }
21855
21856    #[tokio::test]
21857    async fn update_context_preserves_workflow_input_and_committed_signals() {
21858        let client = Client::new("http://127.0.0.1:8080").expect("client");
21859        let mut worker = Worker::new(client, "rust-workers");
21860        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
21861        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
21862        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
21863        let expected_input = workflow_input.clone();
21864        let expected_signals = signal_arguments.clone();
21865        let handler = move |context: QueryContext, arguments: AvroValue| {
21866            let expected_input = expected_input.clone();
21867            let expected_signals = expected_signals.clone();
21868            async move {
21869                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
21870                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
21871                assert_eq!(context.workflow_input_avro_value(), &expected_input);
21872                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
21873                assert_eq!(
21874                    context.signals_avro_value("changed"),
21875                    vec![expected_signals.clone()]
21876                );
21877                assert_eq!(
21878                    context.signals("changed"),
21879                    vec![expected_signals
21880                        .into_iter()
21881                        .map(AvroValue::into_json)
21882                        .collect::<Result<Vec<_>>>()?]
21883                );
21884                assert_eq!(
21885                    context.signal_events()[0].id.as_deref(),
21886                    Some("signal-original")
21887                );
21888                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
21889                Ok(arguments)
21890            }
21891        };
21892        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
21893        worker.register_update_avro_value("snapshot", "inspect", handler);
21894        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
21895        let update_envelope =
21896            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
21897        let mut task = workflow_task(
21898            "snapshot",
21899            vec![
21900                history_event(
21901                    "SignalReceived",
21902                    json!({
21903                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
21904                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
21905                    }),
21906                ),
21907                history_event(
21908                    "UpdateAccepted",
21909                    json!({
21910                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
21911                    }),
21912                ),
21913            ],
21914            DEFAULT_CODEC,
21915        );
21916        task.arguments =
21917            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
21918        task.workflow_update_id = Some("update-original".into());
21919        task.update_name = Some("inspect".into());
21920        let query = QueryTask {
21921            query_task_id: "query-snapshot".into(),
21922            observability_context: None,
21923            dispatch_observability_context: None,
21924            observability_links: None,
21925            query_task_attempt: 1,
21926            lease_owner: None,
21927            workflow_id: task.workflow_id.clone(),
21928            run_id: task.run_id.clone(),
21929            workflow_type: task.workflow_type.clone(),
21930            query_name: "inspect".into(),
21931            payload_codec: DEFAULT_CODEC.into(),
21932            workflow_arguments: task.arguments.clone(),
21933            query_arguments: Some(update_envelope),
21934            history_events: task.history_events.clone(),
21935            history_export: None,
21936            run_status: Some("running".into()),
21937        };
21938        assert_eq!(
21939            worker
21940                .execute_query_task(query)
21941                .await
21942                .expect("query snapshot"),
21943            update_arguments
21944        );
21945        for _ in 0..2 {
21946            let commands = worker
21947                .execute_workflow_task(task.clone())
21948                .expect("cold update snapshot");
21949            assert_eq!(commands[0]["type"], "complete_update");
21950            assert_eq!(commands[0]["update_id"], "update-original");
21951            assert_eq!(
21952                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21953                    .expect("update result"),
21954                update_arguments
21955            );
21956        }
21957    }
21958
21959    #[test]
21960    fn committed_signal_snapshot_counts_identities_once() {
21961        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
21962        let received = history_event(
21963            "SignalReceived",
21964            json!({
21965                "signal_id": "signal-first", "workflow_command_id": "command-first",
21966                "signal_name": "changed", "arguments": arguments.clone(),
21967            }),
21968        );
21969        let applied = history_event(
21970            "SignalApplied",
21971            json!({
21972                "signal_id": "signal-first", "workflow_command_id": "command-first",
21973                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
21974            }),
21975        );
21976        let distinct = history_event(
21977            "SignalReceived",
21978            json!({
21979                "signal_id": "signal-second", "workflow_command_id": "command-second",
21980                "signal_name": "changed", "arguments": arguments,
21981            }),
21982        );
21983        let history = vec![received.clone(), applied.clone(), distinct];
21984        let signals =
21985            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
21986        assert_eq!(signals.len(), 2);
21987        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21988        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
21989        assert_eq!(signals[0].workflow_sequence, Some(1));
21990        assert_eq!(signals[0].arguments, signals[1].arguments);
21991        let mut command_only = received.clone();
21992        command_only
21993            .payload
21994            .as_object_mut()
21995            .expect("payload")
21996            .remove("signal_id");
21997        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
21998            .expect("command identity");
21999        assert_eq!(signals.len(), 1);
22000        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
22001        let mut conflicting = applied;
22002        conflicting.payload["value"] =
22003            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
22004        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
22005    }
22006
22007    #[test]
22008    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
22009        for arguments in [
22010            vec![],
22011            vec![AvroValue::Array(vec![
22012                AvroValue::Long(1),
22013                AvroValue::Long(2),
22014            ])],
22015            vec![AvroValue::Bytes(vec![0, 255])],
22016            vec![AvroValue::Null],
22017            vec![AvroValue::Boolean(false)],
22018            vec![
22019                AvroValue::Long(1),
22020                AvroValue::Array(vec![AvroValue::Long(2)]),
22021            ],
22022        ] {
22023            let applied = match arguments.as_slice() {
22024                [] => AvroValue::Boolean(true),
22025                [value] => value.clone(),
22026                values => AvroValue::Array(values.to_vec()),
22027            };
22028            for applied in [applied, AvroValue::Array(arguments.clone())] {
22029                let events = vec![
22030                    history_event(
22031                        "SignalReceived",
22032                        json!({
22033                            "signal_id": "original", "signal_name": "changed",
22034                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
22035                        }),
22036                    ),
22037                    history_event(
22038                        "SignalApplied",
22039                        json!({
22040                            "signal_id": "original", "signal_name": "changed",
22041                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
22042                        }),
22043                    ),
22044                ];
22045                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
22046                    .expect("canonical signal snapshot");
22047                assert_eq!(signals.len(), 1);
22048                assert_eq!(signals[0].avro_arguments, arguments);
22049            }
22050        }
22051    }
22052
22053    #[tokio::test]
22054    async fn update_context_rejects_malformed_snapshot_before_handler() {
22055        let client = Client::new("http://127.0.0.1:8080").expect("client");
22056        let mut worker = Worker::new(client, "rust-workers");
22057        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
22058        let calls = Arc::new(AtomicUsize::new(0));
22059        let observed = Arc::clone(&calls);
22060        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
22061            observed.fetch_add(1, Ordering::SeqCst);
22062            async { Ok(Value::Null) }
22063        });
22064        let mut task = workflow_task(
22065            "snapshot",
22066            vec![history_event(
22067                "UpdateAccepted",
22068                json!({
22069                    "update_id": "update-original", "update_name": "inspect",
22070                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
22071                }),
22072            )],
22073            DEFAULT_CODEC,
22074        );
22075        task.workflow_update_id = Some("update-original".into());
22076        task.update_name = Some("inspect".into());
22077        let mut bad_input = task.clone();
22078        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
22079        assert!(worker.execute_workflow_task(bad_input).is_err());
22080        task.history_events.insert(0, history_event("SignalReceived", json!({
22081            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
22082        })));
22083        assert!(worker.execute_workflow_task(task).is_err());
22084        assert_eq!(calls.load(Ordering::SeqCst), 0);
22085    }
22086
22087    #[tokio::test]
22088    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
22089        let client = Client::new("http://127.0.0.1:8080").expect("client");
22090        let mut worker = Worker::new(client, "rust-workers");
22091        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
22092        worker
22093            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
22094        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
22095            Ok(input)
22096        });
22097        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
22098            Ok(input)
22099        });
22100        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
22101            Ok(AvroValue::Array(
22102                ctx.wait_signal_avro_value("changed").await?,
22103            ))
22104        });
22105
22106        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
22107        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
22108
22109        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
22110        workflow.arguments = Some(envelope.clone());
22111        let commands = worker
22112            .execute_workflow_task(workflow)
22113            .expect("typed workflow task");
22114        assert_eq!(commands[0]["type"], "complete_workflow");
22115        assert_eq!(
22116            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22117                .expect("typed workflow result"),
22118            arguments
22119        );
22120
22121        let activity = ActivityTask {
22122            task_id: "activity-typed".to_string(),
22123            workflow_id: None,
22124            run_id: None,
22125            activity_execution_id: None,
22126            observability_context: None,
22127            dispatch_observability_context: None,
22128            observability_links: None,
22129            activity_attempt_id: Some("attempt-typed".to_string()),
22130            attempt_id: None,
22131            activity_type: "typed.activity".to_string(),
22132            payload_codec: DEFAULT_CODEC.to_string(),
22133            arguments: Some(envelope.clone()),
22134            attempt_number: 1,
22135            lease_owner: Some("rust-worker".to_string()),
22136        };
22137        assert_eq!(
22138            worker
22139                .execute_activity_task(activity)
22140                .await
22141                .expect("typed activity result"),
22142            arguments
22143        );
22144
22145        let query = QueryTask {
22146            query_task_id: "query-typed".to_string(),
22147            observability_context: None,
22148            dispatch_observability_context: None,
22149            observability_links: None,
22150            query_task_attempt: 1,
22151            lease_owner: Some("rust-worker".to_string()),
22152            workflow_id: Some("typed-1".to_string()),
22153            run_id: Some("run-typed".to_string()),
22154            workflow_type: "typed.echo".to_string(),
22155            query_name: "inspect".to_string(),
22156            payload_codec: DEFAULT_CODEC.to_string(),
22157            workflow_arguments: Some(
22158                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
22159                    .expect("workflow input"),
22160            ),
22161            query_arguments: Some(envelope.clone()),
22162            history_events: Vec::new(),
22163            history_export: None,
22164            run_status: Some("running".to_string()),
22165        };
22166        assert_eq!(
22167            worker
22168                .execute_query_task(query)
22169                .await
22170                .expect("typed query result"),
22171            arguments
22172        );
22173
22174        let mut update = workflow_task(
22175            "typed.echo",
22176            vec![history_event(
22177                "UpdateAccepted",
22178                json!({
22179                    "update_id": "update-typed",
22180                    "update_name": "replace",
22181                    "arguments": envelope.clone(),
22182                }),
22183            )],
22184            DEFAULT_CODEC,
22185        );
22186        update.workflow_update_id = Some("update-typed".to_string());
22187        update.update_name = Some("replace".to_string());
22188        let commands = worker
22189            .execute_workflow_task(update)
22190            .expect("typed update task");
22191        assert_eq!(commands[0]["type"], "complete_update");
22192        assert_eq!(
22193            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22194                .expect("typed update result"),
22195            arguments
22196        );
22197
22198        let mut signal = workflow_task(
22199            "typed.signal",
22200            vec![history_event(
22201                "SignalReceived",
22202                json!({
22203                    "signal_id": "signal-typed",
22204                    "signal_name": "changed",
22205                    "arguments": envelope.clone(),
22206                }),
22207            )],
22208            DEFAULT_CODEC,
22209        );
22210        signal.workflow_signal_id = Some("signal-typed".to_string());
22211        signal.signal_name = Some("changed".to_string());
22212        signal.signal_arguments = Some(envelope);
22213        let commands = worker
22214            .execute_workflow_task(signal)
22215            .expect("typed signal resume");
22216        assert_eq!(
22217            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22218                .expect("typed signal result"),
22219            arguments
22220        );
22221    }
22222
22223    #[tokio::test]
22224    async fn typed_helpers_never_parse_json_inspection_projection() {
22225        let collision_values = projection_collision_probe();
22226        let expected = AvroValue::Array(collision_values.clone());
22227        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
22228
22229        let activity_context = workflow_context_with_codec(
22230            vec![history_event(
22231                "ActivityCompleted",
22232                json!({
22233                    "sequence": 1,
22234                    "activity_type": "collision.activity",
22235                    "payload_codec": DEFAULT_CODEC,
22236                    "result": envelope.clone(),
22237                }),
22238            )],
22239            DEFAULT_CODEC,
22240        );
22241        assert_eq!(
22242            activity_context
22243                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
22244                .await
22245                .expect("typed activity collision result"),
22246            expected
22247        );
22248
22249        let signal_context = workflow_context_with_codec(
22250            vec![
22251                history_event(
22252                    "SignalWaitOpened",
22253                    json!({"sequence": 1, "signal_name": "collision"}),
22254                ),
22255                history_event(
22256                    "SignalApplied",
22257                    json!({
22258                        "sequence": 1,
22259                        "signal_name": "collision",
22260                        "payload_codec": DEFAULT_CODEC,
22261                        "value": envelope.clone(),
22262                    }),
22263                ),
22264            ],
22265            DEFAULT_CODEC,
22266        );
22267        assert_eq!(
22268            signal_context
22269                .wait_signal_avro_value("collision")
22270                .await
22271                .expect("typed signal collision arguments"),
22272            collision_values
22273        );
22274
22275        let child_context = workflow_context_with_codec(
22276            vec![
22277                history_event(
22278                    "ChildWorkflowScheduled",
22279                    json!({
22280                        "sequence": 1,
22281                        "child_workflow_instance_id": "collision-child",
22282                        "child_workflow_run_id": "collision-run",
22283                        "child_workflow_type": "collision.child",
22284                    }),
22285                ),
22286                history_event(
22287                    "ChildRunCompleted",
22288                    json!({
22289                        "sequence": 1,
22290                        "child_workflow_instance_id": "collision-child",
22291                        "child_workflow_run_id": "collision-run",
22292                        "child_workflow_type": "collision.child",
22293                        "payload_codec": DEFAULT_CODEC,
22294                        "result": envelope,
22295                    }),
22296                ),
22297            ],
22298            DEFAULT_CODEC,
22299        );
22300        let child = child_context
22301            .start_child_workflow_avro_value(
22302                "collision.child",
22303                ChildWorkflowOptions::new("collision-workers"),
22304                AvroValue::Array(Vec::new()),
22305            )
22306            .await
22307            .expect("typed child collision result");
22308        assert_eq!(child.result, expected);
22309    }
22310
22311    #[tokio::test]
22312    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
22313        let client = Client::new("http://127.0.0.1:8080").expect("client");
22314        let mut worker = Worker::new(client, "rust-workers");
22315        worker.register_replayed_workflow_avro_value(
22316            "typed.replayed",
22317            || (),
22318            |_ctx, input, _state| async move { Ok(input) },
22319        );
22320        worker.register_replayed_query_avro_value::<(), _, _>(
22321            "typed.replayed",
22322            "inspect",
22323            |ctx, _state, args| async move {
22324                let mut signals = ctx.signals_avro_value("collision");
22325                let signal = signals
22326                    .pop()
22327                    .map(AvroValue::Array)
22328                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
22329                Ok(AvroValue::Array(vec![
22330                    ctx.workflow_input_avro_value().clone(),
22331                    signal,
22332                    args,
22333                ]))
22334            },
22335        );
22336        let arguments = AvroValue::Array(projection_collision_probe());
22337        let signal_arguments =
22338            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
22339        let task = QueryTask {
22340            query_task_id: "query-typed-replay".to_string(),
22341            observability_context: None,
22342            dispatch_observability_context: None,
22343            observability_links: None,
22344            query_task_attempt: 1,
22345            lease_owner: Some("rust-worker".to_string()),
22346            workflow_id: Some("typed-replay".to_string()),
22347            run_id: Some("run-typed-replay".to_string()),
22348            workflow_type: "typed.replayed".to_string(),
22349            query_name: "inspect".to_string(),
22350            payload_codec: DEFAULT_CODEC.to_string(),
22351            workflow_arguments: Some(
22352                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
22353            ),
22354            query_arguments: Some(
22355                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
22356            ),
22357            history_events: vec![history_event(
22358                "SignalReceived",
22359                json!({
22360                    "signal_id": "collision-signal",
22361                    "signal_name": "collision",
22362                    "workflow_sequence": 1,
22363                    "payload_codec": DEFAULT_CODEC,
22364                    "arguments": signal_arguments,
22365                }),
22366            )],
22367            history_export: None,
22368            run_status: Some("completed".to_string()),
22369        };
22370
22371        assert_eq!(
22372            worker
22373                .execute_query_task(task)
22374                .await
22375                .expect("typed replay query"),
22376            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
22377        );
22378    }
22379
22380    #[test]
22381    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
22382        let value = BTreeMap::from([(1_i32, "integer key")]);
22383        let error = PayloadEnvelope::avro(&value)
22384            .expect_err("integer map keys must fail")
22385            .to_string();
22386
22387        assert!(error.contains("invalid_map_key"));
22388    }
22389
22390    #[test]
22391    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
22392        let envelope = PayloadEnvelope {
22393            codec: "json".to_string(),
22394            blob: r#"{"greeting":"hello"}"#.to_string(),
22395        };
22396
22397        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
22398        let diagnostic = error.to_string();
22399        assert!(diagnostic.contains("unsupported_payload_codec"));
22400        assert!(diagnostic.contains("codec=\"avro\""));
22401        assert!(diagnostic.contains("HTTP document transport"));
22402    }
22403
22404    #[test]
22405    fn untagged_json_payload_value_fails_closed() {
22406        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
22407            .expect_err("untagged JSON payload values must fail");
22408        let diagnostic = error.to_string();
22409        assert!(diagnostic.contains("unsupported_payload_codec"));
22410        assert!(diagnostic.contains("untagged durable payload"));
22411        assert!(diagnostic.contains("HTTP document transport"));
22412    }
22413
22414    #[test]
22415    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
22416        let envelope = PayloadEnvelope {
22417            codec: DEFAULT_CODEC.to_string(),
22418            blob: BASE64.encode([0x01]),
22419        };
22420
22421        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
22422        assert!(error.to_string().contains("invalid_payload_framing"));
22423    }
22424
22425    #[tokio::test]
22426    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
22427        let server = MockWorkerServer::start();
22428        let client = Client::builder(server.base_url())
22429            .timeout(Duration::from_secs(2))
22430            .build()
22431            .expect("client");
22432        let invalid_commands = [
22433            json!({
22434                "type": "complete_workflow",
22435                "result": {"codec": "json", "blob": null}
22436            }),
22437            json!({
22438                "type": "schedule_activity",
22439                "arguments": {"codec": "yaml", "blob": "ignored"}
22440            }),
22441            json!({
22442                "type": "start_child_workflow",
22443                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
22444            }),
22445            json!({"type": "continue_as_new", "arguments": []}),
22446            json!({"type": "complete_update"}),
22447            json!({"type": "record_side_effect", "result": null}),
22448            json!({
22449                "type": "start_service_operation",
22450                "payload_codec": DEFAULT_CODEC,
22451                "request_payload": "raw-avro-bytes"
22452            }),
22453        ];
22454
22455        for command in invalid_commands {
22456            let error = client
22457                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
22458                .await
22459                .expect_err("invalid durable payload must fail locally");
22460            let diagnostic = error.to_string();
22461            assert!(
22462                diagnostic.contains("unsupported_payload_codec")
22463                    || diagnostic.contains("invalid_payload_envelope")
22464                    || diagnostic.contains("untagged durable payload"),
22465                "unexpected validation diagnostic: {diagnostic}"
22466            );
22467        }
22468
22469        assert_eq!(
22470            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
22471            0,
22472            "invalid command payloads must not reach HTTP transport"
22473        );
22474    }
22475
22476    #[test]
22477    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
22478        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
22479        let commands = [
22480            json!({"type": "complete_workflow", "result": envelope.clone()}),
22481            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
22482            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
22483            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
22484            json!({"type": "complete_update", "result": envelope.clone()}),
22485            json!({"type": "record_side_effect", "result": envelope.clone()}),
22486            json!({
22487                "type": "start_service_operation",
22488                "payload_codec": DEFAULT_CODEC,
22489                "request_payload": envelope.clone()
22490            }),
22491            json!({
22492                "type": "complete_workflow",
22493                "result": envelope,
22494                "metadata": {
22495                    "codec": "json",
22496                    "payload_codec": "customer-codec",
22497                    "result": {"codec": "yaml", "blob": null}
22498                }
22499            }),
22500        ];
22501
22502        validate_workflow_task_commands(&commands)
22503            .expect("customer metadata must not become a protocol codec declaration");
22504    }
22505
22506    #[test]
22507    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
22508        assert_eq!(
22509            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
22510            AvroValue::Array(Vec::new())
22511        );
22512        assert_eq!(
22513            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
22514            AvroValue::Array(Vec::new())
22515        );
22516
22517        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22518        signal.signal_name = Some("empty-signal".to_string());
22519        signal.signal_arguments = None;
22520        let decoded = decode_resume_signal(&signal)
22521            .expect("valid Avro signal")
22522            .expect("named signal resumes the workflow");
22523        assert!(decoded.arguments.is_empty());
22524    }
22525
22526    #[tokio::test]
22527    async fn malformed_task_level_codecs_become_pre_handler_failures() {
22528        let client = Client::new("http://127.0.0.1:8080").expect("client");
22529        let mut worker = Worker::new(client, "rust-workers");
22530        let handler_calls = Arc::new(AtomicUsize::new(0));
22531
22532        let calls = Arc::clone(&handler_calls);
22533        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22534            calls.fetch_add(1, Ordering::SeqCst);
22535            async move { Ok(Value::Null) }
22536        });
22537        let calls = Arc::clone(&handler_calls);
22538        worker.register_activity("codec.activity", move |_ctx, _args| {
22539            calls.fetch_add(1, Ordering::SeqCst);
22540            async move { Ok(Value::Null) }
22541        });
22542        let calls = Arc::clone(&handler_calls);
22543        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22544            calls.fetch_add(1, Ordering::SeqCst);
22545            async move { Ok(Value::Null) }
22546        });
22547
22548        let mut failures = Vec::new();
22549        for codec_case in [
22550            InvalidTaskPayloadCodec::Missing,
22551            InvalidTaskPayloadCodec::Null,
22552            InvalidTaskPayloadCodec::NonString,
22553        ] {
22554            let mut workflow = json!({
22555                "task_id": format!("workflow-{}", codec_case.label()),
22556                "workflow_type": "codec.workflow"
22557            });
22558            codec_case.apply(&mut workflow);
22559            match serde_json::from_value::<WorkflowTask>(workflow) {
22560                Ok(task) => match worker.execute_workflow_task(task) {
22561                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
22562                    outcome => failures.push(format!(
22563                        "workflow {} codec returned {outcome:?}",
22564                        codec_case.label()
22565                    )),
22566                },
22567                Err(error) => failures.push(format!(
22568                    "workflow {} codec failed transport deserialization: {error}",
22569                    codec_case.label()
22570                )),
22571            }
22572
22573            let mut activity = json!({
22574                "task_id": format!("activity-{}", codec_case.label()),
22575                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
22576                "activity_type": "codec.activity",
22577                "attempt_number": 1
22578            });
22579            codec_case.apply(&mut activity);
22580            match serde_json::from_value::<ActivityTask>(activity) {
22581                Ok(task) => match worker.execute_activity_task(task).await {
22582                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
22583                    outcome => failures.push(format!(
22584                        "activity {} codec returned {outcome:?}",
22585                        codec_case.label()
22586                    )),
22587                },
22588                Err(error) => failures.push(format!(
22589                    "activity {} codec failed transport deserialization: {error}",
22590                    codec_case.label()
22591                )),
22592            }
22593
22594            let mut query = json!({
22595                "query_task_id": format!("query-{}", codec_case.label()),
22596                "workflow_type": "codec.workflow",
22597                "query_name": "known"
22598            });
22599            codec_case.apply(&mut query);
22600            match serde_json::from_value::<QueryTask>(query) {
22601                Ok(task) => match worker.execute_query_task(task).await {
22602                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
22603                    outcome => failures.push(format!(
22604                        "query {} codec returned {outcome:?}",
22605                        codec_case.label()
22606                    )),
22607                },
22608                Err(error) => failures.push(format!(
22609                    "query {} codec failed transport deserialization: {error}",
22610                    codec_case.label()
22611                )),
22612            }
22613        }
22614
22615        assert!(failures.is_empty(), "{}", failures.join("\n"));
22616        assert_eq!(
22617            handler_calls.load(Ordering::SeqCst),
22618            0,
22619            "invalid task codecs must not invoke a handler"
22620        );
22621    }
22622
22623    #[tokio::test]
22624    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
22625        for codec_case in [
22626            InvalidTaskPayloadCodec::Missing,
22627            InvalidTaskPayloadCodec::Null,
22628            InvalidTaskPayloadCodec::NonString,
22629        ] {
22630            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
22631            let client = Client::builder(server.base_url())
22632                .timeout(Duration::from_secs(2))
22633                .build()
22634                .expect("client");
22635            let mut worker = Worker::new(client, "rust-workers")
22636                .worker_id("codec-worker")
22637                .poll_timeout(Duration::from_millis(10));
22638            let handler_calls = Arc::new(AtomicUsize::new(0));
22639
22640            let calls = Arc::clone(&handler_calls);
22641            worker.register_workflow("codec.workflow", move |_ctx, _args| {
22642                calls.fetch_add(1, Ordering::SeqCst);
22643                async move { Ok(Value::Null) }
22644            });
22645            let calls = Arc::clone(&handler_calls);
22646            worker.register_activity("codec.activity", move |_ctx, _args| {
22647                calls.fetch_add(1, Ordering::SeqCst);
22648                async move { Ok(Value::Null) }
22649            });
22650            let calls = Arc::clone(&handler_calls);
22651            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22652                calls.fetch_add(1, Ordering::SeqCst);
22653                async move { Ok(Value::Null) }
22654            });
22655
22656            assert_eq!(
22657                worker.run_once().await.expect("invalid tasks are settled"),
22658                3,
22659                "all {} codec tasks must be handled",
22660                codec_case.label()
22661            );
22662            assert_eq!(
22663                handler_calls.load(Ordering::SeqCst),
22664                0,
22665                "{} task codecs must fail before every handler",
22666                codec_case.label()
22667            );
22668
22669            for path in [
22670                "/api/worker/workflow-tasks/codec-workflow/fail",
22671                "/api/worker/activity-tasks/codec-activity/fail",
22672                "/api/worker/query-tasks/codec-query/fail",
22673            ] {
22674                let body = server.request_body(path);
22675                assert!(
22676                    body["failure"]["message"]
22677                        .as_str()
22678                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
22679                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
22680                    codec_case.label()
22681                );
22682            }
22683            assert_eq!(
22684                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
22685                    ["reason"],
22686                "query_payload_decode_failed"
22687            );
22688            for path in [
22689                "/api/worker/workflow-tasks/codec-workflow/complete",
22690                "/api/worker/activity-tasks/codec-activity/complete",
22691                "/api/worker/query-tasks/codec-query/complete",
22692            ] {
22693                assert_eq!(
22694                    server.request_count(path),
22695                    0,
22696                    "invalid {} codec task reached {path}",
22697                    codec_case.label()
22698                );
22699            }
22700        }
22701    }
22702
22703    #[tokio::test]
22704    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
22705        let client = Client::new("http://127.0.0.1:8080").expect("client");
22706        let mut worker = Worker::new(client, "rust-workers");
22707        let handler_calls = Arc::new(AtomicUsize::new(0));
22708
22709        let calls = Arc::clone(&handler_calls);
22710        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22711            calls.fetch_add(1, Ordering::SeqCst);
22712            async move { Ok(Value::Null) }
22713        });
22714        let calls = Arc::clone(&handler_calls);
22715        worker.register_activity("codec.activity", move |_ctx, _args| {
22716            calls.fetch_add(1, Ordering::SeqCst);
22717            async move { Ok(Value::Null) }
22718        });
22719        let calls = Arc::clone(&handler_calls);
22720        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
22721            calls.fetch_add(1, Ordering::SeqCst);
22722            async move { Ok(Value::Null) }
22723        });
22724        let calls = Arc::clone(&handler_calls);
22725        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22726            calls.fetch_add(1, Ordering::SeqCst);
22727            async move { Ok(Value::Null) }
22728        });
22729
22730        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22731        workflow.payload_codec = "json".to_string();
22732        workflow.arguments = None;
22733        let error = worker
22734            .execute_workflow_task(workflow)
22735            .expect_err("task codec must be checked before workflow invocation");
22736        assert!(error.to_string().contains("unsupported_payload_codec"));
22737
22738        let activity = ActivityTask {
22739            task_id: "activity-invalid-codec".to_string(),
22740            workflow_id: None,
22741            run_id: None,
22742            activity_execution_id: None,
22743            observability_context: None,
22744            dispatch_observability_context: None,
22745            observability_links: None,
22746            activity_attempt_id: None,
22747            attempt_id: None,
22748            activity_type: "codec.activity".to_string(),
22749            payload_codec: "unknown".to_string(),
22750            arguments: None,
22751            attempt_number: 1,
22752            lease_owner: None,
22753        };
22754        let error = worker
22755            .execute_activity_task(activity)
22756            .await
22757            .expect_err("task codec must be checked before activity invocation");
22758        assert!(error.to_string().contains("unsupported_payload_codec"));
22759
22760        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22761        update.workflow_update_id = Some("update-invalid-codec".to_string());
22762        update.update_name = Some("known".to_string());
22763        update.history_events.push(history_event(
22764            "UpdateAccepted",
22765            json!({
22766                "update_id": "update-invalid-codec",
22767                "update_name": "known",
22768                "arguments": {"codec": "json", "blob": null}
22769            }),
22770        ));
22771        let error = worker
22772            .execute_workflow_task(update)
22773            .expect_err("nested update codec must be checked before handler lookup");
22774        assert!(error.to_string().contains("unsupported_payload_codec"));
22775
22776        let query: QueryTask = serde_json::from_value(json!({
22777            "query_task_id": "query-invalid-codec",
22778            "workflow_type": "codec.workflow",
22779            "query_name": "known",
22780            "payload_codec": DEFAULT_CODEC,
22781            "workflow_arguments": null,
22782            "query_arguments": null,
22783            "history_export": {
22784                "payloads": {"codec": DEFAULT_CODEC},
22785                "signals": [{
22786                    "name": "empty",
22787                    "payload_codec": "json",
22788                    "arguments": null
22789                }]
22790            }
22791        }))
22792        .expect("query task");
22793        let failure = worker
22794            .execute_query_task(query)
22795            .await
22796            .expect_err("exported signal codec must be checked before query invocation");
22797        assert_eq!(failure.reason, "query_payload_decode_failed");
22798        assert!(failure.message.contains("unsupported_payload_codec"));
22799
22800        let exported_history: QueryTask = serde_json::from_value(json!({
22801            "query_task_id": "query-invalid-history-codec",
22802            "workflow_type": "codec.workflow",
22803            "query_name": "known",
22804            "payload_codec": DEFAULT_CODEC,
22805            "history_export": {
22806                "payloads": {"codec": DEFAULT_CODEC},
22807                "history_events": [{
22808                    "type": "ActivityCompleted",
22809                    "payload": {"payload_codec": "unknown", "result": null}
22810                }]
22811            }
22812        }))
22813        .expect("query task");
22814        let failure = worker
22815            .execute_query_task(exported_history)
22816            .await
22817            .expect_err("exported history codec must be checked before query invocation");
22818        assert_eq!(failure.reason, "query_payload_decode_failed");
22819        assert!(failure.message.contains("unsupported_payload_codec"));
22820        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
22821
22822        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22823        unknown_workflow.arguments = None;
22824        unknown_workflow.history_events.push(history_event(
22825            "SignalReceived",
22826            json!({
22827                "signal_name": "empty",
22828                "payload_codec": "json",
22829                "arguments": null
22830            }),
22831        ));
22832        let error = worker
22833            .execute_workflow_task(unknown_workflow)
22834            .expect_err("history codec must precede unknown workflow outcome");
22835        assert!(error.to_string().contains("unsupported_payload_codec"));
22836
22837        let unknown_activity = ActivityTask {
22838            task_id: "activity-unknown".to_string(),
22839            workflow_id: None,
22840            run_id: None,
22841            activity_execution_id: None,
22842            observability_context: None,
22843            dispatch_observability_context: None,
22844            observability_links: None,
22845            activity_attempt_id: None,
22846            attempt_id: None,
22847            activity_type: "missing".to_string(),
22848            payload_codec: "json".to_string(),
22849            arguments: None,
22850            attempt_number: 1,
22851            lease_owner: None,
22852        };
22853        let error = worker
22854            .execute_activity_task(unknown_activity)
22855            .await
22856            .expect_err("codec must precede unknown activity outcome");
22857        assert!(error.to_string().contains("unsupported_payload_codec"));
22858
22859        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22860        unknown_update.payload_codec = "json".to_string();
22861        unknown_update.arguments = None;
22862        unknown_update.workflow_update_id = Some("update-unknown".to_string());
22863        unknown_update.update_name = Some("missing".to_string());
22864        let error = worker
22865            .execute_workflow_task(unknown_update)
22866            .expect_err("codec must precede fail_update shortcut");
22867        assert!(error.to_string().contains("unsupported_payload_codec"));
22868
22869        let unknown_query: QueryTask = serde_json::from_value(json!({
22870            "query_task_id": "query-unknown",
22871            "workflow_type": "missing",
22872            "query_name": "missing",
22873            "payload_codec": "json",
22874            "workflow_arguments": null,
22875            "query_arguments": null
22876        }))
22877        .expect("query task");
22878        let failure = worker
22879            .execute_query_task(unknown_query)
22880            .await
22881            .expect_err("codec must precede unknown query outcome");
22882        assert_eq!(failure.reason, "query_payload_decode_failed");
22883        assert!(failure.message.contains("unsupported_payload_codec"));
22884    }
22885
22886    #[tokio::test]
22887    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
22888        let client = Client::new("http://127.0.0.1:8080").expect("client");
22889        let worker = Worker::new(client, "rust-workers");
22890
22891        for event_type in ["SignalReceived", "SignalApplied"] {
22892            for (payload_field, codec) in [
22893                ("value", "json"),
22894                ("input", "unknown"),
22895                ("arguments", "json"),
22896            ] {
22897                let payload = json!({
22898                    "signal_name": "empty",
22899                    payload_field: {"codec": codec, "blob": null}
22900                });
22901                let workflow = workflow_task(
22902                    "missing",
22903                    vec![history_event(event_type, payload.clone())],
22904                    DEFAULT_CODEC,
22905                );
22906                let error = worker
22907                    .execute_workflow_task(workflow)
22908                    .expect_err("signal payload codec must precede unknown workflow outcome");
22909                assert!(
22910                    error.to_string().contains("unsupported_payload_codec"),
22911                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
22912                );
22913
22914                let query: QueryTask = serde_json::from_value(json!({
22915                    "query_task_id": format!("query-{event_type}-{payload_field}"),
22916                    "workflow_type": "missing",
22917                    "query_name": "missing",
22918                    "payload_codec": DEFAULT_CODEC,
22919                    "workflow_arguments": null,
22920                    "query_arguments": null,
22921                    "history_events": [{
22922                        "event_type": event_type,
22923                        "payload": payload
22924                    }]
22925                }))
22926                .expect("query task");
22927                let failure = worker
22928                    .execute_query_task(query)
22929                    .await
22930                    .expect_err("signal payload codec must precede unknown query outcome");
22931                assert_eq!(
22932                    failure.reason, "query_payload_decode_failed",
22933                    "{event_type}.{payload_field} returned an unrelated query outcome"
22934                );
22935                assert!(
22936                    failure.message.contains("unsupported_payload_codec"),
22937                    "{event_type}.{payload_field} returned an unrelated query error: {}",
22938                    failure.message
22939                );
22940            }
22941        }
22942    }
22943
22944    #[test]
22945    fn workflow_context_schedules_activity_until_completion_is_in_history() {
22946        let ctx = WorkflowContext {
22947            cancellation_scope_id: "root".into(),
22948            state: Arc::new(Mutex::new(
22949                WorkflowState::new_with_identity(
22950                    Vec::new(),
22951                    Some("wf-parent".to_string()),
22952                    Some("run-parent".to_string()),
22953                    "rust-workers".to_string(),
22954                    DEFAULT_CODEC.to_string(),
22955                    None,
22956                )
22957                .expect("workflow state"),
22958            )),
22959        };
22960
22961        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
22962        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22963        assert!(matches!(
22964            call.as_mut().poll(&mut task_context),
22965            Poll::Pending
22966        ));
22967
22968        let commands = ctx.take_commands().expect("commands");
22969        assert_eq!(commands[0]["type"], "schedule_activity");
22970        assert_eq!(commands[0]["activity_type"], "hello.activity");
22971    }
22972
22973    #[test]
22974    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
22975        let ctx = workflow_context(Vec::new());
22976        let options = ActivityOptions::new()
22977            .task_queue("payments")
22978            .retry_policy(
22979                ActivityRetryPolicy::new(4)
22980                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
22981                    .non_retryable_error_type("ValidationError"),
22982            )
22983            .start_to_close_timeout(Duration::from_secs(120))
22984            .schedule_to_start_timeout(Duration::from_secs(10))
22985            .schedule_to_close_timeout(Duration::from_secs(300))
22986            .heartbeat_timeout(Duration::from_secs(15));
22987        let mut call = Box::pin(ctx.activity_with_options(
22988            "charge-card",
22989            options,
22990            json!([{"order_id": "o-1"}]),
22991        ));
22992        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22993
22994        assert!(matches!(
22995            call.as_mut().poll(&mut task_context),
22996            Poll::Pending
22997        ));
22998        assert!(matches!(
22999            call.as_mut().poll(&mut task_context),
23000            Poll::Pending
23001        ));
23002
23003        let commands = ctx.take_commands().expect("activity command");
23004        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
23005        assert_eq!(commands[0]["queue"], "payments");
23006        assert_eq!(
23007            commands[0]["retry_policy"],
23008            json!({
23009                "max_attempts": 4,
23010                "backoff_seconds": [1, 3, 9],
23011                "non_retryable_error_types": ["ValidationError"],
23012            })
23013        );
23014        assert_eq!(commands[0]["start_to_close_timeout"], 120);
23015        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
23016        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
23017        assert_eq!(commands[0]["heartbeat_timeout"], 15);
23018    }
23019
23020    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
23021        vec![
23022            history_event(
23023                "ActivityScheduled",
23024                json!({"sequence":1,"activity_type":"render",
23025                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
23026            ),
23027            history_event(
23028                "ActivityCompleted",
23029                json!({"sequence":1,"activity_type":"render",
23030                "payload_codec":DEFAULT_CODEC,
23031                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
23032            ),
23033        ]
23034    }
23035
23036    #[test]
23037    fn worker_session_activity_routes_to_session_queue_once() {
23038        let ctx = workflow_context(Vec::new());
23039        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23040        let mut call = Box::pin(
23041            ctx.activity("render", json!([]))
23042                .in_worker_session(session.clone()),
23043        );
23044        let mut cx = TaskContext::from_waker(noop_waker_ref());
23045        assert!(call.as_mut().poll(&mut cx).is_pending());
23046        assert!(call.as_mut().poll(&mut cx).is_pending());
23047        let commands = ctx.take_commands().unwrap();
23048        assert_eq!(commands.len(), 1);
23049        assert_eq!(commands[0]["queue"], "gpu-workers");
23050        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
23051    }
23052
23053    #[tokio::test]
23054    async fn worker_session_cold_replay_uses_recorded_avro_result() {
23055        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23056        for _replacement in 0..2 {
23057            let ctx = workflow_context(completed_worker_session_history(&session));
23058            let result: i64 = ctx
23059                .activity("render", json!([]))
23060                .in_worker_session(session.clone())
23061                .typed()
23062                .await
23063                .unwrap();
23064            assert_eq!(result, 42);
23065            assert!(ctx.take_commands().unwrap().is_empty());
23066        }
23067    }
23068
23069    #[test]
23070    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
23071        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23072        for changed in [
23073            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
23074            Some(original.clone().ttl_seconds(60)),
23075            Some(original.clone().requirements(["gpu:l4"])),
23076            None,
23077        ] {
23078            let ctx = workflow_context(completed_worker_session_history(&original));
23079            let mut call = ctx.activity_with_options(
23080                "render",
23081                ActivityOptions::new().task_queue("gpu-workers"),
23082                json!([]),
23083            );
23084            if let Some(changed) = changed {
23085                call = call.in_worker_session(changed);
23086            }
23087            let mut call = Box::pin(call);
23088            let mut cx = TaskContext::from_waker(noop_waker_ref());
23089            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23090                call.as_mut().poll(&mut cx)
23091            else {
23092                panic!("changed session must fail replay");
23093            };
23094            assert_eq!(failure.reason, "activity_worker_session_mismatch");
23095            assert!(ctx.take_commands().unwrap().is_empty());
23096        }
23097    }
23098
23099    #[test]
23100    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
23101        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23102        let ctx = workflow_context(Vec::new());
23103        let mut local = Box::pin(
23104            ctx.local_activity("render", json!([]))
23105                .in_worker_session(session.clone()),
23106        );
23107        let mut cx = TaskContext::from_waker(noop_waker_ref());
23108        assert!(matches!(
23109            local.as_mut().poll(&mut cx),
23110            Poll::Ready(Err(Error::WorkerLoop(_)))
23111        ));
23112        assert!(ctx.take_commands().unwrap().is_empty());
23113        let mut remote = Box::pin(
23114            ctx.activity_with_options(
23115                "render",
23116                ActivityOptions::new().task_queue("other"),
23117                json!([]),
23118            )
23119            .in_worker_session(session),
23120        );
23121        assert!(matches!(
23122            remote.as_mut().poll(&mut cx),
23123            Poll::Ready(Err(Error::WorkerLoop(_)))
23124        ));
23125        assert!(ctx.take_commands().unwrap().is_empty());
23126    }
23127
23128    #[test]
23129    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
23130        let ctx = workflow_context(Vec::new());
23131        let options = ActivityOptions::new().retry_policy(
23132            ActivityRetryPolicy::new(3)
23133                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
23134        );
23135        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23136        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23137
23138        assert!(matches!(
23139            call.as_mut().poll(&mut task_context),
23140            Poll::Pending
23141        ));
23142        assert_eq!(
23143            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
23144            json!([1, 2])
23145        );
23146    }
23147
23148    #[test]
23149    fn activity_options_preserve_unused_explicit_backoff_entries() {
23150        for max_attempts in [1, 2, 10] {
23151            let ctx = workflow_context(Vec::new());
23152            let options =
23153                ActivityOptions::new()
23154                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
23155                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
23156                    ));
23157            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23158            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23159            assert!(matches!(
23160                call.as_mut().poll(&mut task_context),
23161                Poll::Pending
23162            ));
23163            let commands = ctx.take_commands().expect("command");
23164            assert_eq!(commands.len(), 1);
23165            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
23166            assert_eq!(
23167                commands[0]["retry_policy"]["backoff_seconds"],
23168                json!([1, 2, 5, 10, 15, 30, 60, 120])
23169            );
23170        }
23171        let default_options = ActivityOptions::new().validate().expect("default options");
23172        let default_policy = current_activity_retry_snapshot(&default_options);
23173        assert_eq!(
23174            default_policy.max_attempts,
23175            RecordedSnapshotValue::Known(Some(1))
23176        );
23177        assert_eq!(
23178            default_policy.backoff_seconds,
23179            RecordedSnapshotValue::Known(Vec::new())
23180        );
23181    }
23182
23183    #[test]
23184    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
23185        let fixture: Value = serde_json::from_str(include_str!(
23186            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
23187        ))
23188        .expect("published PHP fixture");
23189        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
23190            .expect("unchanged published history");
23191        let matching = ActivityOptions::new().task_queue("default").retry_policy(
23192            ActivityRetryPolicy::new(1)
23193                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
23194        );
23195        let mut changed_tail = matching.clone();
23196        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
23197            [1, 2, 5, 10, 15, 30, 60, 121]
23198                .map(Duration::from_secs)
23199                .to_vec(),
23200        ));
23201        let mut changed_first = matching.clone();
23202        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
23203            [2, 2, 5, 10, 15, 30, 60, 120]
23204                .map(Duration::from_secs)
23205                .to_vec(),
23206        ));
23207        let mut changed_attempts = matching.clone();
23208        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
23209        let mut changed_types = matching.clone();
23210        changed_types
23211            .retry_policy
23212            .as_mut()
23213            .unwrap()
23214            .non_retryable_error_types = vec!["ChangedError".into()];
23215        let mut changed_start = matching.clone();
23216        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
23217        let mut changed_schedule_start = matching.clone();
23218        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
23219        let mut changed_schedule_close = matching.clone();
23220        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
23221        let mut changed_heartbeat = matching;
23222        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
23223        let unchanged_defaults = ActivityOptions::new().task_queue("default");
23224        for options in [
23225            changed_tail,
23226            changed_first,
23227            changed_attempts,
23228            changed_types,
23229            changed_start,
23230            changed_schedule_start,
23231            changed_schedule_close,
23232            changed_heartbeat,
23233            unchanged_defaults,
23234        ] {
23235            let ctx = workflow_context(history.clone());
23236            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
23237            assert!(!ctx.patched("frozen-zero").unwrap());
23238            ctx.deprecate_patch("frozen-zero").unwrap();
23239            let mut call =
23240                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
23241            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23242            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23243                call.as_mut().poll(&mut task_context)
23244            else {
23245                panic!("changed explicit policy must fail replay")
23246            };
23247            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
23248            assert_eq!(failure.sequence, Some(2));
23249            assert!(ctx.take_commands().unwrap().is_empty());
23250        }
23251    }
23252
23253    #[test]
23254    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
23255        let cases = [
23256            (
23257                ActivityOptions::new().task_queue("  "),
23258                ActivityOptionsErrorKind::EmptyTaskQueue,
23259            ),
23260            (
23261                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
23262                ActivityOptionsErrorKind::EmptyRetryPolicy,
23263            ),
23264            (
23265                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
23266                ActivityOptionsErrorKind::InvalidMaxAttempts,
23267            ),
23268            (
23269                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
23270                    max_attempts: None,
23271                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
23272                    non_retryable_error_types: Vec::new(),
23273                }),
23274                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
23275            ),
23276            (
23277                ActivityOptions::new().retry_policy(
23278                    ActivityRetryPolicy::new(2).exponential_backoff(
23279                        Duration::from_secs(1),
23280                        0,
23281                        None,
23282                    ),
23283                ),
23284                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
23285            ),
23286            (
23287                ActivityOptions::new()
23288                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
23289                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
23290            ),
23291            (
23292                ActivityOptions::new().retry_policy(
23293                    ActivityRetryPolicy::new(10_002).exponential_backoff(
23294                        Duration::from_secs(1),
23295                        1,
23296                        None,
23297                    ),
23298                ),
23299                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
23300            ),
23301            (
23302                ActivityOptions::new().retry_policy(
23303                    ActivityRetryPolicy::new(2)
23304                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
23305                ),
23306                ActivityOptionsErrorKind::BackoffOverflow,
23307            ),
23308        ];
23309
23310        for (options, expected_kind) in cases {
23311            let ctx = workflow_context(Vec::new());
23312            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23313            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23314            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
23315                call.as_mut().poll(&mut task_context)
23316            else {
23317                panic!("expected typed activity validation error");
23318            };
23319            assert_eq!(error.kind, expected_kind);
23320            assert!(ctx.take_commands().expect("commands").is_empty());
23321        }
23322    }
23323
23324    #[test]
23325    fn activity_options_validate_positive_and_ordered_timeouts() {
23326        let zero_timeout_cases = [
23327            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
23328            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
23329            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
23330            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
23331        ];
23332        for options in zero_timeout_cases {
23333            assert_eq!(
23334                options.validate().expect_err("zero timeout").kind,
23335                ActivityOptionsErrorKind::TimeoutNotPositive
23336            );
23337        }
23338
23339        let ordering_cases = [
23340            ActivityOptions::new()
23341                .heartbeat_timeout(Duration::from_secs(11))
23342                .start_to_close_timeout(Duration::from_secs(10)),
23343            ActivityOptions::new()
23344                .start_to_close_timeout(Duration::from_secs(31))
23345                .schedule_to_close_timeout(Duration::from_secs(30)),
23346            ActivityOptions::new()
23347                .schedule_to_start_timeout(Duration::from_secs(31))
23348                .schedule_to_close_timeout(Duration::from_secs(30)),
23349        ];
23350        for options in ordering_cases {
23351            assert_eq!(
23352                options.validate().expect_err("timeout order").kind,
23353                ActivityOptionsErrorKind::TimeoutOrder
23354            );
23355        }
23356
23357        assert_eq!(
23358            ActivityOptions::new()
23359                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
23360                .validate()
23361                .expect_err("protocol integer overflow")
23362                .kind,
23363            ActivityOptionsErrorKind::TimeoutOverflow
23364        );
23365    }
23366
23367    #[test]
23368    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
23369        let ctx = workflow_context(completed_retry_activity_history());
23370        let mut call =
23371            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23372        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23373
23374        assert!(matches!(
23375            call.as_mut().poll(&mut task_context),
23376            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23377        ));
23378        assert!(ctx.take_commands().expect("commands").is_empty());
23379        ctx.ensure_history_consumed().expect("history consumed");
23380    }
23381
23382    #[test]
23383    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
23384        let mut options = retry_activity_options();
23385        options
23386            .retry_policy
23387            .as_mut()
23388            .expect("retry policy")
23389            .non_retryable_error_types
23390            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
23391
23392        let new_ctx = workflow_context(Vec::new());
23393        let mut new_call =
23394            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
23395        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23396        assert!(matches!(
23397            new_call.as_mut().poll(&mut task_context),
23398            Poll::Pending
23399        ));
23400        let commands = new_ctx.take_commands().expect("commands");
23401        assert_eq!(commands.len(), 1);
23402        assert_eq!(
23403            commands[0]["retry_policy"]["non_retryable_error_types"],
23404            json!(["PermanentError"])
23405        );
23406
23407        let replay_ctx = workflow_context(completed_retry_activity_history());
23408        let mut replay_call =
23409            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
23410        assert!(matches!(
23411            replay_call.as_mut().poll(&mut task_context),
23412            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23413        ));
23414        assert!(replay_ctx.take_commands().expect("commands").is_empty());
23415        replay_ctx
23416            .ensure_history_consumed()
23417            .expect("history consumed");
23418    }
23419
23420    #[test]
23421    fn replayed_intermediate_retry_remains_pending_across_restarts() {
23422        let history = completed_retry_activity_history()
23423            .into_iter()
23424            .take(3)
23425            .collect::<Vec<_>>();
23426
23427        for _restart in 0..2 {
23428            let ctx = workflow_context(history.clone());
23429            let mut call =
23430                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23431            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23432            assert!(matches!(
23433                call.as_mut().poll(&mut task_context),
23434                Poll::Pending
23435            ));
23436            assert!(ctx.take_commands().expect("commands").is_empty());
23437        }
23438    }
23439
23440    #[test]
23441    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
23442        let mut changed_queue = retry_activity_options();
23443        changed_queue.task_queue = Some("different-queue".to_string());
23444
23445        let mut changed_max_attempts = retry_activity_options();
23446        let retry_policy = changed_max_attempts
23447            .retry_policy
23448            .as_mut()
23449            .expect("retry policy");
23450        retry_policy.max_attempts = Some(4);
23451
23452        let mut changed_backoff = retry_activity_options();
23453        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
23454        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
23455            Duration::from_secs(3),
23456            Duration::from_secs(4),
23457        ]));
23458
23459        let mut changed_non_retryable_types = retry_activity_options();
23460        let retry_policy = changed_non_retryable_types
23461            .retry_policy
23462            .as_mut()
23463            .expect("retry policy");
23464        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
23465
23466        let mut changed_start_to_close = retry_activity_options();
23467        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
23468        let mut changed_schedule_to_start = retry_activity_options();
23469        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
23470        let mut changed_schedule_to_close = retry_activity_options();
23471        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
23472        let mut changed_heartbeat = retry_activity_options();
23473        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
23474
23475        let cases = [
23476            (changed_queue, "activity_task_queue_mismatch"),
23477            (changed_max_attempts, "activity_retry_policy_mismatch"),
23478            (changed_backoff, "activity_retry_policy_mismatch"),
23479            (
23480                changed_non_retryable_types,
23481                "activity_retry_policy_mismatch",
23482            ),
23483            (changed_start_to_close, "activity_retry_policy_mismatch"),
23484            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
23485            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
23486            (changed_heartbeat, "activity_retry_policy_mismatch"),
23487        ];
23488
23489        for (options, expected_reason) in cases {
23490            let ctx = workflow_context(completed_retry_activity_history());
23491            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
23492            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23493            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23494                call.as_mut().poll(&mut task_context)
23495            else {
23496                panic!("changed activity options must fail replay");
23497            };
23498            assert_eq!(failure.reason, expected_reason);
23499            assert_eq!(failure.sequence, Some(1));
23500            assert!(ctx.take_commands().expect("commands").is_empty());
23501        }
23502    }
23503
23504    #[test]
23505    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
23506        let cases = [
23507            (
23508                "execution_mode",
23509                json!("local"),
23510                "activity_execution_mode_mismatch",
23511            ),
23512            (
23513                "snapshot_version",
23514                json!(2),
23515                "activity_retry_policy_mismatch",
23516            ),
23517        ];
23518
23519        for (field, value, expected_reason) in cases {
23520            let mut history = completed_retry_activity_history();
23521            let activity = history[0].payload["activity"]
23522                .as_object_mut()
23523                .expect("activity snapshot");
23524            if field == "execution_mode" {
23525                activity.insert(field.to_string(), value);
23526            } else {
23527                activity["retry_policy"]
23528                    .as_object_mut()
23529                    .expect("retry snapshot")
23530                    .insert(field.to_string(), value);
23531            }
23532
23533            let ctx = workflow_context(history);
23534            let mut call =
23535                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23536            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23537            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23538                call.as_mut().poll(&mut task_context)
23539            else {
23540                panic!("changed {field} must fail replay");
23541            };
23542            assert_eq!(failure.reason, expected_reason);
23543            assert_eq!(failure.sequence, Some(1));
23544            assert!(ctx.take_commands().expect("commands").is_empty());
23545        }
23546    }
23547
23548    #[test]
23549    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
23550        for (nested, field, value, terminal_only) in [
23551            (false, "execution_mode", json!("local"), false),
23552            (false, "local_activity", json!(true), false),
23553            (true, "local_activity", json!(true), false),
23554            (false, "local_activity", json!(true), true),
23555        ] {
23556            let mut history = completed_retry_activity_history();
23557            history[0]
23558                .payload
23559                .as_object_mut()
23560                .unwrap()
23561                .remove("activity");
23562            let event = if terminal_only {
23563                history.last_mut().unwrap()
23564            } else {
23565                &mut history[0]
23566            };
23567            if nested {
23568                event.payload["activity"] = json!({(field): value});
23569            } else {
23570                event.payload[field] = value;
23571            }
23572            let ctx = workflow_context(history);
23573            let mut call =
23574                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23575            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23576            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23577                call.as_mut().poll(&mut task_context)
23578            else {
23579                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
23580            };
23581            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
23582            assert_eq!(failure.sequence, Some(1));
23583            assert!(ctx.take_commands().expect("commands").is_empty());
23584        }
23585    }
23586
23587    #[test]
23588    fn activity_history_rejects_conflicting_local_execution_markers() {
23589        let mut history = completed_retry_activity_history();
23590        history.last_mut().unwrap().payload["local_activity"] = json!(true);
23591        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
23592            .expect_err("remote schedule cannot become a local completion");
23593        assert!(
23594            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
23595            if reason == "activity_execution_mode_conflict")
23596        );
23597    }
23598
23599    #[test]
23600    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
23601        let mut history = completed_retry_activity_history();
23602        let activity = history[0].payload["activity"]
23603            .as_object_mut()
23604            .expect("activity snapshot");
23605        activity.remove("execution_mode");
23606        activity.remove("retry_policy");
23607
23608        let mut current = retry_activity_options();
23609        current.start_to_close_timeout = Some(Duration::from_secs(45));
23610        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
23611        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
23612        current.heartbeat_timeout = Some(Duration::from_secs(12));
23613
23614        let ctx = workflow_context(history);
23615        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
23616        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23617        assert!(matches!(
23618            call.as_mut().poll(&mut task_context),
23619            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23620        ));
23621        assert!(ctx.take_commands().expect("commands").is_empty());
23622        ctx.ensure_history_consumed().expect("history consumed");
23623    }
23624
23625    #[test]
23626    fn terminal_activity_failed_after_start_returns_typed_failure() {
23627        let history = vec![
23628            history_event(
23629                "ActivityScheduled",
23630                json!({
23631                    "sequence": 1,
23632                    "activity_type": "flaky",
23633                    "activity_execution_id": "act-terminal",
23634                    "activity": {
23635                        "id": "act-terminal",
23636                        "sequence": 1,
23637                        "type": "flaky",
23638                        "queue": "critical-activities",
23639                        "retry_policy": {
23640                            "snapshot_version": 1,
23641                            "max_attempts": 3,
23642                            "backoff_seconds": [2, 4],
23643                            "non_retryable_error_types": ["PermanentError"]
23644                        }
23645                    }
23646                }),
23647            ),
23648            history_event(
23649                "ActivityStarted",
23650                json!({
23651                    "sequence": 1,
23652                    "activity_type": "flaky",
23653                    "activity_execution_id": "act-terminal",
23654                    "activity_attempt_id": "attempt-1",
23655                    "attempt_number": 1
23656                }),
23657            ),
23658            history_event(
23659                "ActivityFailed",
23660                json!({
23661                    "sequence": 1,
23662                    "activity_type": "flaky",
23663                    "activity_execution_id": "act-terminal",
23664                    "activity_attempt_id": "attempt-1",
23665                    "attempt_number": 1,
23666                    "failure_id": "failure-terminal",
23667                    "failure_category": "activity",
23668                    "exception_type": "PermanentError",
23669                    "message": "cannot retry",
23670                    "non_retryable": true
23671                }),
23672            ),
23673        ];
23674        let ctx = workflow_context(history);
23675        let mut call =
23676            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23677        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23678
23679        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23680            call.as_mut().poll(&mut task_context)
23681        else {
23682            panic!("terminal ActivityFailed must settle the activity future");
23683        };
23684        assert_eq!(failure.kind, ActivityFailureKind::Failed);
23685        assert_eq!(
23686            failure.activity_execution_id.as_deref(),
23687            Some("act-terminal")
23688        );
23689        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
23690        assert!(failure.non_retryable);
23691        assert!(ctx.take_commands().expect("commands").is_empty());
23692        ctx.ensure_history_consumed().expect("history consumed");
23693    }
23694
23695    #[test]
23696    fn activity_terminal_events_return_machine_readable_failures() {
23697        let cases = [
23698            (
23699                "ActivityFailed",
23700                json!({
23701                    "sequence": 1,
23702                    "activity_type": "charge-card",
23703                    "activity_execution_id": "act-1",
23704                    "activity_attempt_id": "attempt-2",
23705                    "attempt_number": 2,
23706                    "failure_id": "failure-1",
23707                    "failure_category": "activity",
23708                    "exception_type": "PaymentDeclined",
23709                    "exception_class": "payments.PaymentDeclined",
23710                    "message": "card declined",
23711                    "non_retryable": true
23712                }),
23713                ActivityFailureKind::Failed,
23714                "activity",
23715            ),
23716            (
23717                "ActivityCancelled",
23718                json!({
23719                    "sequence": 1,
23720                    "activity_type": "charge-card",
23721                    "activity_execution_id": "act-1",
23722                    "activity_attempt_id": "attempt-1"
23723                }),
23724                ActivityFailureKind::Cancelled,
23725                "cancelled",
23726            ),
23727        ];
23728
23729        for (event_type, payload, expected_kind, expected_reason) in cases {
23730            let ctx = workflow_context(vec![history_event(event_type, payload)]);
23731            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
23732            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23733            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23734                call.as_mut().poll(&mut task_context)
23735            else {
23736                panic!("expected terminal activity failure");
23737            };
23738            assert_eq!(failure.kind, expected_kind);
23739            assert_eq!(failure.reason, expected_reason);
23740            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
23741            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
23742        }
23743    }
23744
23745    #[test]
23746    fn every_activity_timeout_class_is_typed() {
23747        for timeout_kind in [
23748            "start_to_close",
23749            "schedule_to_start",
23750            "schedule_to_close",
23751            "heartbeat",
23752        ] {
23753            let ctx = workflow_context(vec![history_event(
23754                "ActivityTimedOut",
23755                json!({
23756                    "sequence": 1,
23757                    "activity_type": "slow",
23758                    "activity_execution_id": "act-timeout",
23759                    "activity_attempt_id": "attempt-timeout",
23760                    "failure_category": "timeout",
23761                    "timeout_kind": timeout_kind,
23762                    "message": "deadline expired"
23763                }),
23764            )]);
23765            let mut call = Box::pin(ctx.activity("slow", json!([])));
23766            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23767            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23768                call.as_mut().poll(&mut task_context)
23769            else {
23770                panic!("expected timeout failure");
23771            };
23772            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
23773            assert_eq!(failure.reason, timeout_kind);
23774            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
23775            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
23776        }
23777    }
23778
23779    #[test]
23780    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
23781        let ctx = workflow_context(Vec::new());
23782        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
23783        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23784
23785        assert!(matches!(
23786            sleep.as_mut().poll(&mut task_context),
23787            Poll::Pending
23788        ));
23789        assert!(matches!(
23790            sleep.as_mut().poll(&mut task_context),
23791            Poll::Pending
23792        ));
23793
23794        let commands = ctx.take_commands().expect("timer command");
23795        assert_eq!(
23796            commands,
23797            vec![json!({
23798                "type": "start_timer",
23799                "delay_seconds": 2,
23800            })]
23801        );
23802    }
23803
23804    #[test]
23805    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
23806        let history = vec![
23807            history_event(
23808                "TimerScheduled",
23809                json!({
23810                    "sequence": 1,
23811                    "timer_id": "timer-1",
23812                    "delay_seconds": 5,
23813                    "fire_at": "2026-07-11T12:00:05Z",
23814                }),
23815            ),
23816            history_event(
23817                "TimerFired",
23818                json!({
23819                    "sequence": 1,
23820                    "timer_id": "timer-1",
23821                    "delay_seconds": 5,
23822                    "fire_at": "2026-07-11T12:00:05Z",
23823                    "fired_at": "2026-07-11T12:00:05Z",
23824                }),
23825            ),
23826        ];
23827
23828        for _restart in 0..2 {
23829            let ctx = workflow_context(history.clone());
23830            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
23831            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23832            assert!(matches!(
23833                sleep.as_mut().poll(&mut task_context),
23834                Poll::Ready(Ok(()))
23835            ));
23836            assert!(ctx.take_commands().expect("commands").is_empty());
23837            ctx.ensure_history_consumed().expect("history consumed");
23838        }
23839    }
23840
23841    #[test]
23842    fn workflow_sleep_rejects_changed_delay_during_replay() {
23843        let ctx = workflow_context(vec![
23844            history_event(
23845                "TimerScheduled",
23846                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23847            ),
23848            history_event(
23849                "TimerFired",
23850                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23851            ),
23852        ]);
23853        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
23854        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23855
23856        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23857            sleep.as_mut().poll(&mut task_context)
23858        else {
23859            panic!("changed timer delay must be rejected");
23860        };
23861        assert_eq!(failure.reason, "timer_delay_mismatch");
23862        assert_eq!(failure.sequence, Some(1));
23863    }
23864
23865    #[test]
23866    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
23867        let ctx = workflow_context(Vec::new());
23868        let mut wait = Box::pin(
23869            ctx.wait_condition(
23870                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
23871                    .timeout(Duration::from_millis(60_001)),
23872                || Ok(false),
23873            ),
23874        );
23875        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23876
23877        assert!(matches!(
23878            wait.as_mut().poll(&mut task_context),
23879            Poll::Pending
23880        ));
23881        assert!(matches!(
23882            wait.as_mut().poll(&mut task_context),
23883            Poll::Pending
23884        ));
23885        assert_eq!(
23886            ctx.take_commands().expect("condition command"),
23887            vec![json!({
23888                "type": "open_condition_wait",
23889                "condition_wait_occurrence_id": "rust:condition-wait:0",
23890                "condition_key": "approval.ready",
23891                "condition_definition_fingerprint": "sha256:approval-v1",
23892                "timeout_seconds": 61,
23893            })]
23894        );
23895    }
23896
23897    #[test]
23898    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
23899        let ctx = workflow_context(Vec::new());
23900        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
23901        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23902        assert!(matches!(
23903            satisfied.as_mut().poll(&mut task_context),
23904            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23905        ));
23906
23907        let mut timed_out = Box::pin(wait_condition!(
23908            ctx,
23909            "no-wait",
23910            timeout: Duration::ZERO,
23911            || Ok(false),
23912        ));
23913        assert!(matches!(
23914            timed_out.as_mut().poll(&mut task_context),
23915            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
23916        ));
23917        assert!(ctx.take_commands().expect("commands").is_empty());
23918    }
23919
23920    #[test]
23921    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
23922        let signal_history = vec![
23923            history_event(
23924                "ConditionWaitOpened",
23925                json!({
23926                    "sequence": 4,
23927                    "condition_wait_id": "condition:4",
23928                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23929                    "condition_key": "approval",
23930                    "condition_definition_fingerprint": "sha256:approval-v1",
23931                    "timeout_seconds": 30,
23932                }),
23933            ),
23934            history_event(
23935                "SignalReceived",
23936                json!({
23937                    "workflow_sequence": 4,
23938                    "signal_name": "approve",
23939                    "arguments": fixture_envelope(json!(["Ada"])),
23940                }),
23941            ),
23942        ];
23943        for _worker_before_or_after_restart in 0..2 {
23944            let ctx = workflow_context(signal_history.clone());
23945            let predicate_ctx = ctx.clone();
23946            let mut wait = Box::pin(
23947                ctx.wait_condition(
23948                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
23949                        .timeout(Duration::from_secs(30)),
23950                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
23951                ),
23952            );
23953            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23954            assert!(matches!(
23955                wait.as_mut().poll(&mut task_context),
23956                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23957            ));
23958            assert!(ctx.take_commands().expect("commands").is_empty());
23959            ctx.ensure_history_consumed().expect("condition consumed");
23960        }
23961
23962        let update_history = vec![
23963            history_event(
23964                "ConditionWaitOpened",
23965                json!({
23966                    "sequence": 7,
23967                    "condition_wait_id": "condition:7",
23968                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23969                    "condition_key": "update-approval",
23970                    "condition_definition_fingerprint": "sha256:update-approval-v1",
23971                }),
23972            ),
23973            history_event(
23974                "UpdateApplied",
23975                json!({
23976                    "sequence": 7,
23977                    "update_id": "update-1",
23978                    "update_name": "approve",
23979                    "arguments": fixture_envelope(json!([true])),
23980                }),
23981            ),
23982        ];
23983        let ctx = workflow_context(update_history);
23984        let predicate_ctx = ctx.clone();
23985        let mut wait = Box::pin(ctx.wait_condition(
23986            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
23987            move || {
23988                Ok(predicate_ctx
23989                    .updates("approve")?
23990                    .first()
23991                    .and_then(|arguments| arguments.first())
23992                    .and_then(Value::as_bool)
23993                    == Some(true))
23994            },
23995        ));
23996        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23997        assert!(matches!(
23998            wait.as_mut().poll(&mut task_context),
23999            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24000        ));
24001        assert!(ctx.take_commands().expect("commands").is_empty());
24002        ctx.ensure_history_consumed().expect("condition consumed");
24003    }
24004
24005    #[test]
24006    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
24007        let open_history = vec![
24008            history_event(
24009                "ConditionWaitOpened",
24010                json!({
24011                    "sequence": 3,
24012                    "condition_wait_id": "condition:3",
24013                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24014                    "condition_key": "two-votes",
24015                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24016                    "timeout_seconds": 120,
24017                }),
24018            ),
24019            history_event(
24020                "SignalReceived",
24021                json!({
24022                    "workflow_sequence": 3,
24023                    "signal_name": "vote",
24024                    "arguments": fixture_envelope(json!(["first"])),
24025                }),
24026            ),
24027        ];
24028        for _worker_before_or_after_restart in 0..2 {
24029            let ctx = workflow_context(open_history.clone());
24030            let predicate_ctx = ctx.clone();
24031            let mut wait = Box::pin(
24032                ctx.wait_condition(
24033                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24034                        .timeout(Duration::from_secs(120)),
24035                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
24036                ),
24037            );
24038            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24039            assert!(matches!(
24040                wait.as_mut().poll(&mut task_context),
24041                Poll::Pending
24042            ));
24043            assert_eq!(
24044                ctx.take_commands().expect("reopened condition"),
24045                vec![json!({
24046                    "type": "open_condition_wait",
24047                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24048                    "condition_key": "two-votes",
24049                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24050                    "timeout_seconds": 120,
24051                })]
24052            );
24053        }
24054
24055        let satisfied_ctx = workflow_context(vec![
24056            history_event(
24057                "ConditionWaitOpened",
24058                json!({
24059                    "sequence": 5,
24060                    "condition_wait_id": "condition:5",
24061                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24062                    "condition_key": "approval",
24063                    "condition_definition_fingerprint": "sha256:approval-v1",
24064                }),
24065            ),
24066            history_event(
24067                "ConditionWaitSatisfied",
24068                json!({
24069                    "sequence": 5,
24070                    "condition_wait_id": "condition:5",
24071                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24072                    "condition_key": "approval",
24073                    "condition_definition_fingerprint": "sha256:approval-v1",
24074                }),
24075            ),
24076        ]);
24077        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
24078            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
24079            || Ok(false),
24080        ));
24081        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24082        assert!(matches!(
24083            satisfied.as_mut().poll(&mut task_context),
24084            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24085        ));
24086
24087        let timed_out_ctx = workflow_context(vec![
24088            history_event(
24089                "ConditionWaitOpened",
24090                json!({
24091                    "sequence": 8,
24092                    "condition_wait_id": "condition:8",
24093                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24094                    "condition_key": "approval-timeout",
24095                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
24096                    "timeout_seconds": 5,
24097                }),
24098            ),
24099            history_event(
24100                "TimerScheduled",
24101                json!({
24102                    "sequence": 9,
24103                    "timer_id": "condition-timer:9",
24104                    "timer_kind": "condition_timeout",
24105                    "condition_wait_id": "condition:8",
24106                    "delay_seconds": 5,
24107                }),
24108            ),
24109            history_event(
24110                "TimerFired",
24111                json!({
24112                    "sequence": 9,
24113                    "timer_id": "condition-timer:9",
24114                    "timer_kind": "condition_timeout",
24115                    "condition_wait_id": "condition:8",
24116                    "delay_seconds": 5,
24117                }),
24118            ),
24119        ]);
24120        let mut timed_out = Box::pin(
24121            timed_out_ctx.wait_condition(
24122                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
24123                    .timeout(Duration::from_secs(5)),
24124                || Ok(true),
24125            ),
24126        );
24127        assert!(matches!(
24128            timed_out.as_mut().poll(&mut task_context),
24129            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
24130        ));
24131    }
24132
24133    #[test]
24134    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
24135        let ctx = workflow_context(reopened_selection_condition_history());
24136        {
24137            let state = ctx.state.lock().unwrap();
24138            assert!(matches!(
24139                selection_member_recorded_command(&state, 2),
24140                Some(RecordedCommand::ConditionWait {
24141                    sequence: 3,
24142                    result: None,
24143                    ..
24144                })
24145            ));
24146        }
24147        let mut selected = Box::pin(ctx.select_keyed(vec![
24148            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
24149            (
24150                "votes",
24151                ParallelOperation::condition(
24152                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
24153                    || Ok(true),
24154                ),
24155            ),
24156        ]));
24157        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24158        assert!(selected.as_mut().poll(&mut task_context).is_pending());
24159        assert!(
24160            ctx.take_commands().unwrap().is_empty(),
24161            "true predicate must not reopen the recorded wait"
24162        );
24163        ctx.ensure_history_consumed()
24164            .expect("physical reopens are consumed while canonical selection is pending");
24165    }
24166
24167    #[test]
24168    fn reopened_selection_condition_replays_its_latest_physical_winner() {
24169        for (terminal_type, acknowledge_timeout) in [
24170            ("ConditionWaitSatisfied", false),
24171            ("ConditionWaitTimedOut", false),
24172            ("TimerFired", false),
24173            ("TimerFired", true),
24174        ] {
24175            let mut history = reopened_selection_condition_history();
24176            let original_identity = history[1].payload["condition_wait_id"].clone();
24177            let uses_timer = terminal_type == "TimerFired";
24178            let mut resolution_payload = history[3].payload.clone();
24179            if uses_timer {
24180                for event in &mut history[1..] {
24181                    event.payload["timeout_seconds"] = json!(3);
24182                }
24183                resolution_payload = history[3].payload.clone();
24184                resolution_payload["timer_kind"] = json!("condition_timeout");
24185                resolution_payload["timer_id"] = json!("condition-timeout-3");
24186                resolution_payload["delay_seconds"] = json!(3);
24187                history.push(history_event("TimerScheduled", resolution_payload.clone()));
24188            }
24189            let mut resolution = history_event(terminal_type, resolution_payload.clone());
24190            resolution
24191                .raw
24192                .insert("id".into(), json!("latest-condition-resolution"));
24193            history.push(resolution);
24194            history.push(history_event(
24195                "SelectionResolved",
24196                json!({
24197                    "selection_group_id": "select-calls:1:2",
24198                    "selection_group_base_sequence": 1,
24199                    "selection_group_size": 2,
24200                    "member_key": "votes",
24201                    "member_index": 1,
24202                    "member_base_sequence": 2,
24203                    "member_size": 1,
24204                    "operation_kind": "condition",
24205                    "operation_identity": original_identity,
24206                    "outcome": "completed",
24207                    "resolution_event_id": "latest-condition-resolution",
24208                    "resolution_event_type": terminal_type,
24209                }),
24210            ));
24211            if acknowledge_timeout {
24212                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
24213            }
24214            let ctx = workflow_context(history);
24215            let mut selected = Box::pin(ctx.select_keyed(vec![
24216                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
24217                (
24218                    "votes",
24219                    ParallelOperation::condition(
24220                        if uses_timer {
24221                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24222                                .timeout(Duration::from_secs(3))
24223                        } else {
24224                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24225                        },
24226                        || Ok(true),
24227                    ),
24228                ),
24229            ]));
24230            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24231            match selected.as_mut().poll(&mut task_context) {
24232                Poll::Ready(Ok(result)) => {
24233                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
24234                    let expected = if terminal_type == "ConditionWaitSatisfied" {
24235                        ConditionWaitResult::Satisfied
24236                    } else {
24237                        ConditionWaitResult::TimedOut
24238                    };
24239                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
24240                }
24241                other => panic!("latest physical winner must replay: {other:?}"),
24242            }
24243            assert!(ctx.take_commands().unwrap().is_empty());
24244            ctx.ensure_history_consumed()
24245                .expect("winner history consumed");
24246        }
24247    }
24248
24249    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
24250        let fixture: Value = serde_json::from_str(include_str!(
24251            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
24252        ))
24253        .expect("grouped condition fixture");
24254        fixture["history"]
24255            .as_array()
24256            .unwrap()
24257            .iter()
24258            .map(|event| {
24259                let mut payload = event["payload"].clone();
24260                let index = payload["parallel_group_index"].as_u64().unwrap();
24261                payload["parallel_group_id"] = json!("select-calls:1:2");
24262                payload["parallel_group_mode"] = json!("select");
24263                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
24264                payload["selection_member_index"] = json!(index);
24265                payload["selection_member_base_sequence"] = json!(index + 1);
24266                payload["selection_member_size"] = json!(1);
24267                payload["selection_member_kind"] =
24268                    json!(if index == 0 { "timer" } else { "condition" });
24269                history_event(event["event_type"].as_str().unwrap(), payload)
24270            })
24271            .collect()
24272    }
24273
24274    #[test]
24275    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
24276        let fixture: Value = serde_json::from_str(include_str!(
24277            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
24278        ))
24279        .expect("grouped condition fixture");
24280        let original = fixture["history"].as_array().expect("fixture history");
24281        let decode = |events: &[Value]| {
24282            let history = events
24283                .iter()
24284                .map(|event| {
24285                    history_event(
24286                        event["event_type"].as_str().unwrap(),
24287                        event["payload"].clone(),
24288                    )
24289                })
24290                .collect::<Vec<_>>();
24291            recorded_commands(
24292                &history,
24293                DEFAULT_CODEC,
24294                WorkflowIdentity {
24295                    workflow_id: None,
24296                    run_id: None,
24297                },
24298            )
24299        };
24300        assert!(decode(original).is_ok());
24301        for field in [
24302            "condition_wait_occurrence_id",
24303            "condition_key",
24304            "condition_definition_fingerprint",
24305            "timeout_seconds",
24306            "parallel_group_id",
24307            "parallel_group_size",
24308            "parallel_group_index",
24309        ] {
24310            let mut changed = original.clone();
24311            changed[3]["payload"][field] = match field {
24312                "timeout_seconds" | "parallel_group_size" => json!(30),
24313                "parallel_group_index" => json!(0),
24314                _ => json!("changed"),
24315            };
24316            assert!(
24317                decode(&changed).is_err(),
24318                "reopen must reject changed {field}"
24319            );
24320        }
24321        let mut unsettled = original.clone();
24322        unsettled.remove(2);
24323        assert!(
24324            decode(&unsettled).is_err(),
24325            "physical predecessor must be resolved"
24326        );
24327        let mut timed_out = original.clone();
24328        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
24329        assert!(decode(&timed_out).is_err(), "timeout is terminal");
24330        let mut late_resolution = original.clone();
24331        late_resolution.swap(2, 3);
24332        assert!(
24333            decode(&late_resolution).is_err(),
24334            "later history cannot authorize a reopen"
24335        );
24336    }
24337
24338    #[test]
24339    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
24340        let history = vec![
24341            history_event(
24342                "ConditionWaitOpened",
24343                json!({
24344                    "sequence": 3,
24345                    "condition_wait_id": "condition:3",
24346                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24347                    "condition_key": "two-votes",
24348                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24349                }),
24350            ),
24351            history_event(
24352                "SignalReceived",
24353                json!({
24354                    "workflow_sequence": 3,
24355                    "signal_name": "vote",
24356                    "arguments": fixture_envelope(json!(["first"])),
24357                }),
24358            ),
24359            history_event(
24360                "ConditionWaitSatisfied",
24361                json!({
24362                    "sequence": 3,
24363                    "condition_wait_id": "condition:3",
24364                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24365                    "condition_key": "two-votes",
24366                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24367                }),
24368            ),
24369            history_event(
24370                "ConditionWaitOpened",
24371                json!({
24372                    "sequence": 5,
24373                    "condition_wait_id": "condition:5",
24374                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24375                    "condition_key": "two-votes",
24376                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24377                }),
24378            ),
24379            history_event(
24380                "SignalReceived",
24381                json!({
24382                    "workflow_sequence": 5,
24383                    "signal_name": "vote",
24384                    "arguments": fixture_envelope(json!(["second"])),
24385                }),
24386            ),
24387            history_event(
24388                "ConditionWaitSatisfied",
24389                json!({
24390                    "sequence": 5,
24391                    "condition_wait_id": "condition:5",
24392                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24393                    "condition_key": "two-votes",
24394                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24395                }),
24396            ),
24397        ];
24398        for _cold_worker_or_restart in 0..2 {
24399            let ctx = workflow_context(history.clone());
24400            let predicate_ctx = ctx.clone();
24401            let mut wait = Box::pin(ctx.wait_condition(
24402                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
24403                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
24404            ));
24405            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24406
24407            assert!(matches!(
24408                wait.as_mut().poll(&mut task_context),
24409                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24410            ));
24411            assert!(ctx.take_commands().expect("commands").is_empty());
24412            ctx.ensure_history_consumed()
24413                .expect("every physical wait-open is consumed");
24414        }
24415    }
24416
24417    #[test]
24418    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
24419        let history = vec![
24420            history_event(
24421                "ConditionWaitOpened",
24422                json!({
24423                    "sequence": 3,
24424                    "condition_wait_id": "condition:3",
24425                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24426                    "condition_key": "approved",
24427                    "condition_definition_fingerprint": "sha256:approved-v1",
24428                }),
24429            ),
24430            history_event(
24431                "UpdateApplied",
24432                json!({
24433                    "sequence": 3,
24434                    "update_id": "update-1",
24435                    "update_name": "approve",
24436                    "arguments": fixture_envelope(json!([false])),
24437                }),
24438            ),
24439            history_event(
24440                "ConditionWaitOpened",
24441                json!({
24442                    "sequence": 5,
24443                    "condition_wait_id": "condition:5",
24444                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24445                    "condition_key": "approved",
24446                    "condition_definition_fingerprint": "sha256:approved-v1",
24447                }),
24448            ),
24449            history_event(
24450                "UpdateApplied",
24451                json!({
24452                    "sequence": 5,
24453                    "update_id": "update-2",
24454                    "update_name": "approve",
24455                    "arguments": fixture_envelope(json!([true])),
24456                }),
24457            ),
24458        ];
24459
24460        for _cold_worker_or_restart in 0..2 {
24461            let ctx = workflow_context(history.clone());
24462            let predicate_ctx = ctx.clone();
24463            let mut wait = Box::pin(ctx.wait_condition(
24464                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
24465                move || {
24466                    Ok(predicate_ctx
24467                        .updates("approve")?
24468                        .last()
24469                        .and_then(|arguments| arguments.first())
24470                        .and_then(Value::as_bool)
24471                        == Some(true))
24472                },
24473            ));
24474            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24475
24476            assert!(matches!(
24477                wait.as_mut().poll(&mut task_context),
24478                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24479            ));
24480            assert!(ctx.take_commands().expect("commands").is_empty());
24481            ctx.ensure_history_consumed()
24482                .expect("every update-driven reopen is consumed");
24483        }
24484    }
24485
24486    #[test]
24487    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
24488        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
24489            ("shared", "sha256:first", "shared", "sha256:second"),
24490            ("first", "sha256:shared", "second", "sha256:shared"),
24491            ("shared", "sha256:shared", "shared", "sha256:shared"),
24492            ("first", "sha256:first", "second", "sha256:second"),
24493        ] {
24494            let history = vec![
24495                history_event(
24496                    "ConditionWaitOpened",
24497                    json!({
24498                        "sequence": 3,
24499                        "condition_wait_id": "condition:3",
24500                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24501                        "condition_key": first_key,
24502                        "condition_definition_fingerprint": first_fingerprint,
24503                    }),
24504                ),
24505                history_event(
24506                    "ConditionWaitSatisfied",
24507                    json!({
24508                        "sequence": 3,
24509                        "condition_wait_id": "condition:3",
24510                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24511                        "condition_key": first_key,
24512                        "condition_definition_fingerprint": first_fingerprint,
24513                    }),
24514                ),
24515                history_event(
24516                    "ConditionWaitOpened",
24517                    json!({
24518                        "sequence": 4,
24519                        "condition_wait_id": "condition:4",
24520                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24521                        "condition_key": second_key,
24522                        "condition_definition_fingerprint": second_fingerprint,
24523                    }),
24524                ),
24525                history_event(
24526                    "ConditionWaitSatisfied",
24527                    json!({
24528                        "sequence": 4,
24529                        "condition_wait_id": "condition:4",
24530                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24531                        "condition_key": second_key,
24532                        "condition_definition_fingerprint": second_fingerprint,
24533                    }),
24534                ),
24535            ];
24536            for _cold_worker_or_restart in 0..2 {
24537                let ctx = workflow_context(history.clone());
24538                let mut task_context = TaskContext::from_waker(noop_waker_ref());
24539                let mut first = Box::pin(ctx.wait_condition(
24540                    ConditionWaitOptions::new(first_key, first_fingerprint),
24541                    || Ok(false),
24542                ));
24543                assert!(matches!(
24544                    first.as_mut().poll(&mut task_context),
24545                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24546                ));
24547
24548                let mut second = Box::pin(ctx.wait_condition(
24549                    ConditionWaitOptions::new(second_key, second_fingerprint),
24550                    || Ok(false),
24551                ));
24552                assert!(matches!(
24553                    second.as_mut().poll(&mut task_context),
24554                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24555                ));
24556                assert!(ctx.take_commands().expect("commands").is_empty());
24557                ctx.ensure_history_consumed()
24558                    .expect("each authored wait consumes one occurrence");
24559            }
24560        }
24561    }
24562
24563    #[test]
24564    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
24565        fn worker() -> Worker {
24566            let client = Client::new("http://127.0.0.1:8080").expect("client");
24567            let mut worker = Worker::new(client, "rust-workers");
24568            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
24569                let mut outcomes = Vec::new();
24570                for _ in 0..2 {
24571                    outcomes.push(
24572                        ctx.wait_condition(
24573                            ConditionWaitOptions::new("shared", "sha256:shared"),
24574                            || Ok(false),
24575                        )
24576                        .await?,
24577                    );
24578                }
24579                Ok(json!(outcomes))
24580            });
24581            worker
24582        }
24583
24584        let task = workflow_task(
24585            "rust.condition-loop",
24586            vec![
24587                history_event(
24588                    "ConditionWaitOpened",
24589                    json!({
24590                        "sequence": 1,
24591                        "condition_wait_id": "condition:1",
24592                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24593                        "condition_key": "shared",
24594                        "condition_definition_fingerprint": "sha256:shared",
24595                    }),
24596                ),
24597                history_event(
24598                    "ConditionWaitSatisfied",
24599                    json!({
24600                        "sequence": 1,
24601                        "condition_wait_id": "condition:1",
24602                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24603                        "condition_key": "shared",
24604                        "condition_definition_fingerprint": "sha256:shared",
24605                    }),
24606                ),
24607                history_event(
24608                    "ConditionWaitOpened",
24609                    json!({
24610                        "sequence": 2,
24611                        "condition_wait_id": "condition:2",
24612                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24613                        "condition_key": "shared",
24614                        "condition_definition_fingerprint": "sha256:shared",
24615                    }),
24616                ),
24617                history_event(
24618                    "ConditionWaitSatisfied",
24619                    json!({
24620                        "sequence": 2,
24621                        "condition_wait_id": "condition:2",
24622                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24623                        "condition_key": "shared",
24624                        "condition_definition_fingerprint": "sha256:shared",
24625                    }),
24626                ),
24627            ],
24628            DEFAULT_CODEC,
24629        );
24630
24631        for _cold_worker_or_restart in 0..2 {
24632            let commands = worker()
24633                .execute_workflow_task(task.clone())
24634                .expect("adjacent loop waits replay deterministically");
24635            assert_eq!(commands.len(), 1);
24636            assert_eq!(commands[0]["type"], "complete_workflow");
24637            assert_eq!(
24638                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24639                json!(["satisfied", "satisfied"])
24640            );
24641        }
24642    }
24643
24644    #[test]
24645    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
24646        let history = vec![history_event(
24647            "ConditionWaitOpened",
24648            json!({
24649                "sequence": 12,
24650                "condition_wait_id": "condition:12",
24651                "condition_wait_occurrence_id": "rust:condition-wait:0",
24652                "condition_key": "approval",
24653                "condition_definition_fingerprint": "sha256:approval-v1",
24654                "timeout_seconds": 30,
24655            }),
24656        )];
24657        for (options, expected_reason) in [
24658            (
24659                ConditionWaitOptions::new("changed", "sha256:approval-v1")
24660                    .timeout(Duration::from_secs(30)),
24661                "condition_wait_key_mismatch",
24662            ),
24663            (
24664                ConditionWaitOptions::new("approval", "sha256:approval-v2")
24665                    .timeout(Duration::from_secs(30)),
24666                "condition_wait_predicate_mismatch",
24667            ),
24668            (
24669                ConditionWaitOptions::new("approval", "sha256:approval-v1")
24670                    .timeout(Duration::from_secs(29)),
24671                "condition_wait_timeout_mismatch",
24672            ),
24673        ] {
24674            let ctx = workflow_context(history.clone());
24675            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
24676            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24677            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24678                wait.as_mut().poll(&mut task_context)
24679            else {
24680                panic!("changed condition definition must fail replay");
24681            };
24682            assert_eq!(failure.reason, expected_reason);
24683            assert_eq!(failure.sequence, Some(12));
24684        }
24685    }
24686
24687    #[test]
24688    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
24689        let error = WorkflowState::new(
24690            vec![history_event(
24691                "ConditionWaitOpened",
24692                json!({
24693                    "sequence": 12,
24694                    "condition_wait_id": "condition:12",
24695                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24696                    "condition_key": "approval",
24697                }),
24698            )],
24699            "rust-workers".to_string(),
24700            DEFAULT_CODEC.to_string(),
24701            None,
24702        )
24703        .expect_err("condition history without a predicate fingerprint must fail");
24704
24705        assert!(matches!(
24706            error,
24707            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24708                if reason == "condition_wait_predicate_fingerprint_missing"
24709        ));
24710    }
24711
24712    #[test]
24713    fn condition_wait_history_requires_authored_occurrence_identity() {
24714        let error = WorkflowState::new(
24715            vec![history_event(
24716                "ConditionWaitOpened",
24717                json!({
24718                    "sequence": 12,
24719                    "condition_wait_id": "condition:12",
24720                    "condition_key": "approval",
24721                    "condition_definition_fingerprint": "sha256:approval-v1",
24722                }),
24723            )],
24724            "rust-workers".to_string(),
24725            DEFAULT_CODEC.to_string(),
24726            None,
24727        )
24728        .expect_err("condition history without occurrence identity must fail");
24729
24730        assert!(matches!(
24731            error,
24732            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24733                if reason == "condition_wait_occurrence_id_missing"
24734        ));
24735    }
24736
24737    #[test]
24738    fn typed_search_attribute_updates_validate_emit_and_replay() {
24739        let update = SearchAttributeUpdate::new()
24740            .keyword("OrderStatus", " waiting ")
24741            .expect("keyword")
24742            .int("Attempt", 3)
24743            .expect("int")
24744            .bool("Escalated", false)
24745            .expect("bool")
24746            .keyword_list("Regions", ["us-east", "eu-west"])
24747            .expect("list")
24748            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
24749            .expect("datetime")
24750            .delete("LegacyStatus")
24751            .expect("delete");
24752        let ctx = workflow_context(Vec::new());
24753        ctx.upsert_search_attributes(update.clone())
24754            .expect("typed update");
24755        assert_eq!(
24756            ctx.take_commands().expect("search-attribute command"),
24757            vec![json!({
24758                "type": "upsert_search_attributes",
24759                "attributes": {
24760                    "Attempt": 3,
24761                    "Escalated": false,
24762                    "LegacyStatus": null,
24763                    "OrderStatus": "waiting",
24764                    "Regions": ["us-east", "eu-west"],
24765                    "UpdatedAt": "2026-08-22T04:00:00Z",
24766                },
24767                "attribute_types": {
24768                    "Attempt": "int",
24769                    "Escalated": "bool",
24770                    "OrderStatus": "keyword",
24771                    "Regions": "keyword_list",
24772                    "UpdatedAt": "datetime",
24773                },
24774            })]
24775        );
24776
24777        let replay = workflow_context(vec![history_event(
24778            "SearchAttributesUpserted",
24779            json!({
24780                "sequence": 6,
24781                "attributes": {
24782                    "Attempt": 3,
24783                    "Escalated": false,
24784                    "LegacyStatus": null,
24785                    "OrderStatus": "waiting",
24786                    "Regions": ["us-east", "eu-west"],
24787                    "UpdatedAt": "2026-08-22T04:00:00Z",
24788                },
24789                "attribute_types": {
24790                    "Attempt": "int",
24791                    "Escalated": "bool",
24792                    "OrderStatus": "keyword",
24793                    "Regions": "keyword_list",
24794                    "UpdatedAt": "datetime",
24795                },
24796                "merged": {},
24797            }),
24798        )]);
24799        replay
24800            .upsert_search_attributes(update)
24801            .expect("matching update replays");
24802        assert!(replay.take_commands().expect("commands").is_empty());
24803        replay.ensure_history_consumed().expect("history consumed");
24804
24805        let type_drift = workflow_context(vec![history_event(
24806            "SearchAttributesUpserted",
24807            json!({
24808                "sequence": 7,
24809                "attributes": {"OrderStatus": "waiting"},
24810                "attribute_types": {"OrderStatus": "keyword"},
24811                "merged": {"OrderStatus": "waiting"},
24812            }),
24813        )]);
24814        let error = type_drift
24815            .upsert_search_attributes(
24816                SearchAttributeUpdate::new()
24817                    .string("OrderStatus", "waiting")
24818                    .expect("string update"),
24819            )
24820            .expect_err("same JSON value with a changed type must fail replay");
24821        assert!(matches!(
24822            error,
24823            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24824                if reason == "search_attribute_type_mismatch"
24825        ));
24826
24827        let malformed_types = WorkflowState::new(
24828            vec![history_event(
24829                "SearchAttributesUpserted",
24830                json!({
24831                    "sequence": 8,
24832                    "attributes": {"OrderStatus": "waiting"},
24833                    "attribute_types": {"OrderStatus": "unsupported"},
24834                    "merged": {"OrderStatus": "waiting"},
24835                }),
24836            )],
24837            "rust-workers".to_string(),
24838            DEFAULT_CODEC.to_string(),
24839            None,
24840        )
24841        .expect_err("unsupported search-attribute type metadata must fail");
24842        assert!(matches!(
24843            malformed_types,
24844            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24845                if reason == "search_attribute_types_malformed"
24846        ));
24847
24848        assert!(matches!(
24849            SearchAttributeUpdate::new().keyword("bad key", "value"),
24850            Err(SearchAttributeUpdateError::InvalidKey(_))
24851        ));
24852        assert!(matches!(
24853            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
24854            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
24855        ));
24856        assert!(matches!(
24857            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
24858            Err(SearchAttributeUpdateError::ValueTooLong { .. })
24859        ));
24860        assert!(matches!(
24861            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
24862            Err(SearchAttributeUpdateError::InvalidDateTime(_))
24863        ));
24864        assert!(matches!(
24865            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
24866            Err(Error::InvalidSearchAttributeUpdate(
24867                SearchAttributeUpdateError::Empty
24868            ))
24869        ));
24870    }
24871
24872    #[test]
24873    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
24874        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
24875        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
24876
24877        assert!(SearchAttributeUpdate::new()
24878            .string("AsciiDescription", ascii)
24879            .is_ok());
24880        assert!(SearchAttributeUpdate::new()
24881            .string("Utf8Description", utf8)
24882            .is_ok());
24883        assert!(matches!(
24884            SearchAttributeUpdate::new().string(
24885                "TooLongDescription",
24886                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
24887            ),
24888            Err(SearchAttributeUpdateError::ValueTooLong {
24889                kind: "string",
24890                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
24891                ..
24892            })
24893        ));
24894    }
24895
24896    #[test]
24897    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
24898        let lone_fire = WorkflowState::new(
24899            vec![history_event(
24900                "TimerFired",
24901                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24902            )],
24903            "rust-workers".to_string(),
24904            DEFAULT_CODEC.to_string(),
24905            None,
24906        )
24907        .expect_err("TimerFired requires TimerScheduled");
24908        assert!(matches!(
24909            lone_fire,
24910            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24911                if reason == "timer_schedule_missing_or_duplicate"
24912        ));
24913
24914        let wrong_identity = WorkflowState::new(
24915            vec![
24916                history_event(
24917                    "TimerScheduled",
24918                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24919                ),
24920                history_event(
24921                    "TimerFired",
24922                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24923                ),
24924            ],
24925            "rust-workers".to_string(),
24926            DEFAULT_CODEC.to_string(),
24927            None,
24928        )
24929        .expect_err("fire must match scheduled timer identity");
24930        assert!(matches!(
24931            wrong_identity,
24932            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24933                if reason == "timer_identity_mismatch"
24934        ));
24935
24936        let duplicate_fire = WorkflowState::new(
24937            vec![
24938                history_event(
24939                    "TimerScheduled",
24940                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24941                ),
24942                history_event(
24943                    "TimerFired",
24944                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24945                ),
24946                history_event(
24947                    "TimerFired",
24948                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24949                ),
24950            ],
24951            "rust-workers".to_string(),
24952            DEFAULT_CODEC.to_string(),
24953            None,
24954        )
24955        .expect_err("a durable timer cannot fire twice");
24956        assert!(matches!(
24957            duplicate_fire,
24958            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24959                if reason == "duplicate_timer_fire"
24960        ));
24961
24962        let wrong_fired_delay = WorkflowState::new(
24963            vec![
24964                history_event(
24965                    "TimerScheduled",
24966                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24967                ),
24968                history_event(
24969                    "TimerFired",
24970                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
24971                ),
24972            ],
24973            "rust-workers".to_string(),
24974            DEFAULT_CODEC.to_string(),
24975            None,
24976        )
24977        .expect_err("timer schedule and fire delays must agree");
24978        assert!(matches!(
24979            wrong_fired_delay,
24980            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24981                if reason == "timer_history_delay_mismatch"
24982        ));
24983    }
24984
24985    #[test]
24986    fn replay_rejects_activity_moved_before_recorded_timer() {
24987        let ctx = workflow_context(vec![
24988            history_event(
24989                "TimerScheduled",
24990                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24991            ),
24992            history_event(
24993                "TimerFired",
24994                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24995            ),
24996            history_event(
24997                "ActivityCompleted",
24998                json!({
24999                    "sequence": 2,
25000                    "activity_type": "after-timer",
25001                    "payload_codec": DEFAULT_CODEC,
25002                    "result": fixture_envelope(json!("done")),
25003                }),
25004            ),
25005        ]);
25006        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
25007        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25008
25009        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25010            activity.as_mut().poll(&mut task_context)
25011        else {
25012            panic!("reordered durable command must be rejected");
25013        };
25014        assert_eq!(failure.reason, "recorded_command_mismatch");
25015        assert_eq!(failure.sequence, Some(1));
25016        assert_eq!(failure.expected.as_deref(), Some("timer"));
25017        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
25018    }
25019
25020    #[test]
25021    fn workflow_context_emits_a_typed_named_signal_wait() {
25022        let ctx = workflow_context(Vec::new());
25023        let mut signal = Box::pin(ctx.wait_signal("finish"));
25024        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25025
25026        assert!(matches!(
25027            signal.as_mut().poll(&mut task_context),
25028            Poll::Pending
25029        ));
25030        assert_eq!(
25031            ctx.take_commands().expect("signal-wait command"),
25032            vec![json!({
25033                "type": "open_signal_wait",
25034                "signal_name": "finish",
25035            })]
25036        );
25037    }
25038
25039    #[test]
25040    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
25041        let ctx = workflow_context(Vec::new());
25042        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
25043        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25044
25045        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
25046        else {
25047            panic!("runtime-reserved signal should be rejected");
25048        };
25049        assert!(message.contains("reserved by the workflow runtime"));
25050        assert!(ctx.take_commands().expect("commands").is_empty());
25051    }
25052
25053    #[tokio::test]
25054    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
25055        let client = Client::builder("http://127.0.0.1:9")
25056            .build()
25057            .expect("client");
25058        let error = client
25059            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
25060            .await
25061            .expect_err("runtime-reserved signal should be rejected before transport");
25062
25063        assert!(
25064            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
25065        );
25066    }
25067
25068    #[test]
25069    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
25070        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25071            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25072                value.to_string(),
25073            )]))
25074            .expect("message payload");
25075            json!({
25076                "schema": MESSAGE_STREAM_SCHEMA,
25077                "stream_name": "orders",
25078                "message_id": message_id,
25079                "position": position,
25080                "payload_envelope": payload,
25081            })
25082        }
25083
25084        fn opened(sequence: u64) -> HistoryEvent {
25085            history_event(
25086                "SignalWaitOpened",
25087                json!({
25088                    "sequence": sequence,
25089                    "signal_name": MESSAGE_STREAM_SIGNAL,
25090                }),
25091            )
25092        }
25093
25094        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25095            history_event(
25096                "SignalApplied",
25097                json!({
25098                    "sequence": sequence,
25099                    "signal_name": MESSAGE_STREAM_SIGNAL,
25100                    "value": fixture_envelope(json!([delivery])),
25101                }),
25102            )
25103        }
25104
25105        fn received(delivery: Value) -> HistoryEvent {
25106            history_event(
25107                "SignalReceived",
25108                json!({
25109                    "signal_name": MESSAGE_STREAM_SIGNAL,
25110                    "arguments": fixture_envelope(json!([delivery])),
25111                    "payload_codec": DEFAULT_CODEC,
25112                }),
25113            )
25114        }
25115
25116        let client = Client::new("http://127.0.0.1:8080").expect("client");
25117        let mut worker = Worker::new(client, "rust-workers");
25118        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
25119            let messages = ctx.message_stream("orders")?.receive(2).await?;
25120            Ok(json!(messages
25121                .into_iter()
25122                .map(|message| message.message_id)
25123                .collect::<Vec<_>>()))
25124        });
25125
25126        let first = delivery("message-1", 1, "one");
25127        let second = delivery("message-2", 2, "two");
25128        let batch = worker
25129            .execute_workflow_task_decision(workflow_task(
25130                "rust.message-stream-batch",
25131                vec![
25132                    opened(1),
25133                    received(first.clone()),
25134                    applied(1, first.clone()),
25135                    received(first.clone()),
25136                    received(second),
25137                ],
25138                DEFAULT_CODEC,
25139            ))
25140            .expect("worker task consumes the available batch");
25141
25142        assert_eq!(batch.commands.len(), 1);
25143        assert_eq!(batch.commands[0]["type"], "complete_workflow");
25144        assert_eq!(
25145            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
25146                .expect("workflow result"),
25147            json!(["message-1", "message-2"])
25148        );
25149        assert_eq!(
25150            batch.message_stream_cursors,
25151            vec![json!({"stream_name": "orders", "through_position": 2})]
25152        );
25153        assert!(batch.message_stream_waits.is_empty());
25154
25155        let partial = worker
25156            .execute_workflow_task_decision(workflow_task(
25157                "rust.message-stream-batch",
25158                vec![opened(1), received(first.clone()), applied(1, first)],
25159                DEFAULT_CODEC,
25160            ))
25161            .expect("worker task returns without waiting for a missing second item");
25162        assert_eq!(partial.commands.len(), 1);
25163        assert_eq!(partial.commands[0]["type"], "complete_workflow");
25164        assert_eq!(
25165            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
25166                .expect("workflow result"),
25167            json!(["message-1"])
25168        );
25169        assert_eq!(
25170            partial.message_stream_cursors,
25171            vec![json!({"stream_name": "orders", "through_position": 1})]
25172        );
25173        assert!(partial.message_stream_waits.is_empty());
25174    }
25175
25176    #[test]
25177    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
25178        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25179            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25180                value.to_string(),
25181            )]))
25182            .expect("message payload");
25183            json!({
25184                "schema": MESSAGE_STREAM_SCHEMA,
25185                "stream_name": "orders",
25186                "message_id": message_id,
25187                "position": position,
25188                "payload_envelope": payload,
25189            })
25190        }
25191
25192        fn opened(sequence: u64) -> HistoryEvent {
25193            history_event(
25194                "SignalWaitOpened",
25195                json!({
25196                    "sequence": sequence,
25197                    "signal_name": MESSAGE_STREAM_SIGNAL,
25198                }),
25199            )
25200        }
25201
25202        fn received(delivery: Value) -> HistoryEvent {
25203            history_event(
25204                "SignalReceived",
25205                json!({
25206                    "signal_name": MESSAGE_STREAM_SIGNAL,
25207                    "arguments": fixture_envelope(json!([delivery])),
25208                    "payload_codec": DEFAULT_CODEC,
25209                }),
25210            )
25211        }
25212
25213        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25214            history_event(
25215                "SignalApplied",
25216                json!({
25217                    "sequence": sequence,
25218                    "signal_name": MESSAGE_STREAM_SIGNAL,
25219                    "value": fixture_envelope(json!([delivery])),
25220                }),
25221            )
25222        }
25223
25224        let client = Client::new("http://127.0.0.1:8080").expect("client");
25225        let mut worker = Worker::new(client, "rust-workers");
25226        worker.register_workflow(
25227            "rust.message-stream-partial-batches",
25228            |ctx, _input| async move {
25229                let stream = ctx.message_stream("orders")?;
25230                let first = stream.receive(10).await?;
25231                let second = stream.receive(10).await?;
25232                Ok(json!([
25233                    first
25234                        .into_iter()
25235                        .map(|message| message.message_id)
25236                        .collect::<Vec<_>>(),
25237                    second
25238                        .into_iter()
25239                        .map(|message| message.message_id)
25240                        .collect::<Vec<_>>(),
25241                ]))
25242            },
25243        );
25244
25245        let first = delivery("message-1", 1, "one");
25246        let second = delivery("message-2", 2, "two");
25247        let decision = worker
25248            .execute_workflow_task_decision(workflow_task(
25249                "rust.message-stream-partial-batches",
25250                vec![
25251                    opened(1),
25252                    received(first.clone()),
25253                    applied(1, first),
25254                    opened(2),
25255                    received(second.clone()),
25256                    applied(2, second),
25257                ],
25258                DEFAULT_CODEC,
25259            ))
25260            .expect("cold replay preserves both authored receive boundaries");
25261
25262        assert_eq!(decision.commands.len(), 1);
25263        assert_eq!(decision.commands[0]["type"], "complete_workflow");
25264        assert_eq!(
25265            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
25266                .expect("workflow result"),
25267            json!([["message-1"], ["message-2"]])
25268        );
25269        assert_eq!(
25270            decision.message_stream_cursors,
25271            vec![json!({"stream_name": "orders", "through_position": 2})]
25272        );
25273        assert!(decision.message_stream_waits.is_empty());
25274    }
25275
25276    #[test]
25277    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
25278        let ctx = workflow_context(Vec::new());
25279        let stream = ctx.message_stream("orders").expect("message stream");
25280        let mut receive = Box::pin(stream.receive(10));
25281        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25282
25283        assert!(matches!(
25284            receive.as_mut().poll(&mut task_context),
25285            Poll::Pending
25286        ));
25287        assert_eq!(
25288            ctx.take_commands().expect("message-stream wait command"),
25289            vec![json!({
25290                "type": "open_signal_wait",
25291                "signal_name": MESSAGE_STREAM_SIGNAL,
25292            })]
25293        );
25294        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
25295        assert!(cursors.is_empty());
25296        assert_eq!(
25297            waits,
25298            vec![json!({"stream_name": "orders", "after_position": 0})]
25299        );
25300    }
25301
25302    #[test]
25303    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
25304        let ctx = workflow_context(vec![history_event(
25305            "SignalReceived",
25306            json!({
25307                "signal_name": MESSAGE_STREAM_SIGNAL,
25308                "arguments": fixture_envelope(json!([{
25309                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
25310                    "stream_name": "orders",
25311                    "through_position": 2,
25312                }])),
25313                "payload_codec": DEFAULT_CODEC,
25314            }),
25315        )]);
25316        let stream = ctx.message_stream("orders").expect("message stream");
25317        let mut receive = Box::pin(stream.receive(10));
25318        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25319
25320        assert!(matches!(
25321            receive.as_mut().poll(&mut task_context),
25322            Poll::Pending
25323        ));
25324        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
25325        assert_eq!(
25326            cursors,
25327            vec![json!({"stream_name": "orders", "through_position": 2})]
25328        );
25329        assert_eq!(
25330            waits,
25331            vec![json!({"stream_name": "orders", "after_position": 2})]
25332        );
25333    }
25334
25335    #[test]
25336    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
25337        let mut empty_map = BTreeMap::new();
25338        let mut nested = BTreeMap::new();
25339        nested.insert(
25340            "value".to_string(),
25341            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
25342        );
25343        let values = vec![
25344            AvroValue::Bytes(vec![0, 255]),
25345            AvroValue::Long(1),
25346            AvroValue::Double(1.0),
25347            AvroValue::Array(Vec::new()),
25348            AvroValue::Map(std::mem::take(&mut empty_map)),
25349            AvroValue::Map(nested),
25350        ];
25351        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
25352        let transport = vec![json!({
25353            "schema": MESSAGE_STREAM_SCHEMA,
25354            "stream_name": "orders",
25355            "message_id": "message-1",
25356            "position": 1,
25357            "payload_envelope": payload,
25358        })];
25359
25360        for _ in 0..2 {
25361            let Some(MessageStreamDelivery::Message(message)) =
25362                decode_message_stream_delivery(transport.clone()).expect("delivery")
25363            else {
25364                panic!("message delivery expected");
25365            };
25366            assert_eq!(message.arguments, values);
25367            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
25368            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
25369        }
25370    }
25371
25372    #[test]
25373    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
25374        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25375            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25376                value.to_string(),
25377            )]))
25378            .expect("message payload");
25379            json!({
25380                "schema": MESSAGE_STREAM_SCHEMA,
25381                "stream_name": "orders",
25382                "message_id": message_id,
25383                "position": position,
25384                "payload_envelope": payload,
25385            })
25386        }
25387
25388        fn opened(sequence: u64) -> HistoryEvent {
25389            history_event(
25390                "SignalWaitOpened",
25391                json!({
25392                    "sequence": sequence,
25393                    "signal_name": MESSAGE_STREAM_SIGNAL,
25394                }),
25395            )
25396        }
25397
25398        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25399            history_event(
25400                "SignalApplied",
25401                json!({
25402                    "sequence": sequence,
25403                    "signal_name": MESSAGE_STREAM_SIGNAL,
25404                    "value": fixture_envelope(json!([delivery])),
25405                }),
25406            )
25407        }
25408
25409        fn worker() -> Worker {
25410            let client = Client::new("http://127.0.0.1:8080").expect("client");
25411            let mut worker = Worker::new(client, "rust-workers");
25412            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
25413                let stream = ctx.message_stream("orders")?;
25414                let first = stream.receive_one().await?;
25415                let second = stream.receive_one().await?;
25416                Ok(json!([first.message_id, second.message_id]))
25417            });
25418            worker
25419        }
25420
25421        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
25422            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
25423            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
25424            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
25425            task
25426        }
25427
25428        let waiting = worker()
25429            .execute_workflow_task_decision(workflow_task(
25430                "rust.message-stream",
25431                Vec::new(),
25432                DEFAULT_CODEC,
25433            ))
25434            .expect("first worker opens the stream wait");
25435        assert_eq!(
25436            waiting.commands,
25437            vec![json!({
25438                "type": "open_signal_wait",
25439                "signal_name": MESSAGE_STREAM_SIGNAL,
25440            })]
25441        );
25442        assert!(waiting.message_stream_cursors.is_empty());
25443        assert_eq!(
25444            waiting.message_stream_waits,
25445            vec![json!({"stream_name": "orders", "after_position": 0})]
25446        );
25447
25448        let first_delivery = delivery("message-1", 1, "one");
25449        let first_arrival = worker()
25450            .execute_workflow_task_decision(task_with_resume(
25451                vec![opened(1)],
25452                first_delivery.clone(),
25453            ))
25454            .expect("replacement worker consumes the first arrival");
25455        assert_eq!(
25456            first_arrival.commands,
25457            vec![json!({
25458                "type": "open_signal_wait",
25459                "signal_name": MESSAGE_STREAM_SIGNAL,
25460            })]
25461        );
25462        assert_eq!(
25463            first_arrival.message_stream_cursors,
25464            vec![json!({"stream_name": "orders", "through_position": 1})]
25465        );
25466        assert_eq!(
25467            first_arrival.message_stream_waits,
25468            vec![json!({"stream_name": "orders", "after_position": 1})]
25469        );
25470
25471        let second_delivery = delivery("message-2", 2, "two");
25472        let first_applied = applied(1, first_delivery);
25473        let completed = worker()
25474            .execute_workflow_task_decision(task_with_resume(
25475                vec![opened(1), first_applied.clone(), opened(2)],
25476                second_delivery.clone(),
25477            ))
25478            .expect("next replacement worker consumes the second arrival");
25479        assert_eq!(completed.commands.len(), 1);
25480        assert_eq!(completed.commands[0]["type"], "complete_workflow");
25481        assert_eq!(
25482            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
25483                .expect("workflow result"),
25484            json!(["message-1", "message-2"])
25485        );
25486        assert_eq!(
25487            completed.message_stream_cursors,
25488            vec![json!({"stream_name": "orders", "through_position": 2})]
25489        );
25490        assert!(completed.message_stream_waits.is_empty());
25491
25492        let replay_history = vec![
25493            opened(1),
25494            first_applied,
25495            opened(2),
25496            applied(2, second_delivery),
25497        ];
25498        for _cold_worker_or_restart in 0..2 {
25499            let replayed = worker()
25500                .execute_workflow_task_decision(workflow_task(
25501                    "rust.message-stream",
25502                    replay_history.clone(),
25503                    DEFAULT_CODEC,
25504                ))
25505                .expect("cold worker replays each logical message exactly once");
25506            assert_eq!(replayed.commands.len(), 1);
25507            assert_eq!(
25508                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
25509                    .expect("replayed workflow result"),
25510                json!(["message-1", "message-2"])
25511            );
25512            assert_eq!(
25513                replayed.message_stream_cursors,
25514                vec![json!({"stream_name": "orders", "through_position": 2})]
25515            );
25516            assert!(replayed.message_stream_waits.is_empty());
25517        }
25518    }
25519
25520    #[test]
25521    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
25522        assert!(!worker_protocol_supports_message_streams("1.14"));
25523        assert!(worker_protocol_supports_message_streams("1.15"));
25524        assert!(worker_protocol_supports_message_streams("1.16"));
25525        assert!(worker_protocol_supports_message_streams(
25526            WORKER_PROTOCOL_VERSION
25527        ));
25528        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
25529    }
25530
25531    #[test]
25532    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
25533        let ctx = workflow_context(vec![
25534            history_event(
25535                "ConditionWaitOpened",
25536                json!({
25537                    "sequence": 1,
25538                    "condition_wait_id": "condition:1",
25539                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25540                    "condition_key": "signal:finish",
25541                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
25542                }),
25543            ),
25544            history_event(
25545                "ConditionWaitSatisfied",
25546                json!({
25547                    "sequence": 1,
25548                    "condition_wait_id": "condition:1",
25549                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25550                    "condition_key": "signal:finish",
25551                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
25552                }),
25553            ),
25554            history_event(
25555                "SignalReceived",
25556                json!({"signal_name": "finish", "arguments": []}),
25557            ),
25558        ]);
25559        let mut signal = Box::pin(ctx.wait_signal("finish"));
25560        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25561
25562        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25563            signal.as_mut().poll(&mut task_context)
25564        else {
25565            panic!("condition history must not resolve as a typed signal wait");
25566        };
25567        assert_eq!(failure.reason, "recorded_command_mismatch");
25568        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
25569    }
25570
25571    #[test]
25572    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
25573        let signal_then_timer = vec![
25574            history_event(
25575                "SignalWaitOpened",
25576                json!({"sequence": 1, "signal_name": "go"}),
25577            ),
25578            history_event(
25579                "SignalApplied",
25580                json!({
25581                    "sequence": 1,
25582                    "signal_name": "go",
25583                    "value": fixture_envelope(json!(["now"])),
25584                }),
25585            ),
25586            history_event(
25587                "TimerScheduled",
25588                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
25589            ),
25590            history_event(
25591                "TimerFired",
25592                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
25593            ),
25594        ];
25595
25596        let ctx = workflow_context(signal_then_timer.clone());
25597        let mut signal = Box::pin(ctx.wait_signal("go"));
25598        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25599        assert!(matches!(
25600            signal.as_mut().poll(&mut task_context),
25601            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
25602        ));
25603        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
25604        assert!(matches!(
25605            timer.as_mut().poll(&mut task_context),
25606            Poll::Ready(Ok(()))
25607        ));
25608        ctx.ensure_history_consumed()
25609            .expect("signal and timer history consumed in order");
25610
25611        let reordered = workflow_context(signal_then_timer);
25612        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
25613        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25614            timer_first.as_mut().poll(&mut task_context)
25615        else {
25616            panic!("timer cannot consume signal-wait-first history");
25617        };
25618        assert_eq!(failure.reason, "recorded_command_mismatch");
25619        assert_eq!(failure.sequence, Some(1));
25620        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
25621
25622        let timer_then_signal = vec![
25623            history_event(
25624                "TimerScheduled",
25625                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25626            ),
25627            history_event(
25628                "TimerFired",
25629                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25630            ),
25631            history_event(
25632                "SignalWaitOpened",
25633                json!({"sequence": 2, "signal_name": "go"}),
25634            ),
25635            history_event(
25636                "SignalApplied",
25637                json!({
25638                    "sequence": 2,
25639                    "signal_name": "go",
25640                    "value": fixture_envelope(json!([])),
25641                }),
25642            ),
25643        ];
25644        let reordered = workflow_context(timer_then_signal);
25645        let mut signal_first = Box::pin(reordered.wait_signal("go"));
25646        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25647            signal_first.as_mut().poll(&mut task_context)
25648        else {
25649            panic!("signal wait cannot consume timer-first history");
25650        };
25651        assert_eq!(failure.reason, "recorded_command_mismatch");
25652        assert_eq!(failure.sequence, Some(1));
25653        assert_eq!(failure.expected.as_deref(), Some("timer"));
25654    }
25655
25656    #[test]
25657    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
25658        let duplicate_timer = WorkflowState::new(
25659            vec![
25660                history_event(
25661                    "TimerScheduled",
25662                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25663                ),
25664                history_event(
25665                    "TimerScheduled",
25666                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
25667                ),
25668            ],
25669            "rust-workers".to_string(),
25670            DEFAULT_CODEC.to_string(),
25671            None,
25672        )
25673        .expect_err("one workflow sequence cannot schedule two timers");
25674        assert!(matches!(
25675            duplicate_timer,
25676            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25677                if reason == "timer_schedule_missing_or_duplicate"
25678        ));
25679
25680        let colliding_kinds = WorkflowState::new(
25681            vec![
25682                history_event(
25683                    "TimerScheduled",
25684                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25685                ),
25686                history_event(
25687                    "ActivityCompleted",
25688                    json!({"sequence": 1, "activity_type": "same-sequence"}),
25689                ),
25690            ],
25691            "rust-workers".to_string(),
25692            DEFAULT_CODEC.to_string(),
25693            None,
25694        )
25695        .expect_err("one workflow sequence cannot identify two command kinds");
25696        assert!(matches!(
25697            colliding_kinds,
25698            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25699                if reason == "durable_command_sequence_collision"
25700        ));
25701
25702        let duplicate_signal_wait = WorkflowState::new(
25703            vec![
25704                history_event(
25705                    "SignalWaitOpened",
25706                    json!({"sequence": 1, "signal_name": "go"}),
25707                ),
25708                history_event(
25709                    "SignalWaitOpened",
25710                    json!({"sequence": 1, "signal_name": "go"}),
25711                ),
25712            ],
25713            "rust-workers".to_string(),
25714            DEFAULT_CODEC.to_string(),
25715            None,
25716        )
25717        .expect_err("one workflow sequence cannot open two signal waits");
25718        assert!(matches!(
25719            duplicate_signal_wait,
25720            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25721                if reason == "signal_wait_open_missing_or_duplicate"
25722        ));
25723    }
25724
25725    #[test]
25726    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
25727        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
25728            .expect("side-effect result");
25729        let ctx = workflow_context(vec![history_event(
25730            "SideEffectRecorded",
25731            json!({"sequence": 99, "result": result}),
25732        )]);
25733
25734        let replayed: Value = ctx
25735            .side_effect(|| panic!("recorded side effect must not run"))
25736            .expect("positive global workflow sequence is valid");
25737        assert_eq!(replayed, json!({"captured": true}));
25738        ctx.ensure_history_consumed().expect("history consumed");
25739    }
25740
25741    #[test]
25742    fn workflow_history_rejects_zero_and_descending_command_sequences() {
25743        let result =
25744            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
25745        let zero = WorkflowState::new(
25746            vec![history_event(
25747                "SideEffectRecorded",
25748                json!({"sequence": 0, "result": result.clone()}),
25749            )],
25750            "rust-workers".to_string(),
25751            DEFAULT_CODEC.to_string(),
25752            None,
25753        )
25754        .expect_err("durable command sequences must be positive");
25755        assert!(matches!(
25756            zero,
25757            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25758                if reason == "durable_command_sequence_invalid"
25759        ));
25760
25761        let descending = WorkflowState::new(
25762            vec![
25763                history_event(
25764                    "SideEffectRecorded",
25765                    json!({"sequence": 3, "result": result}),
25766                ),
25767                history_event(
25768                    "VersionMarkerRecorded",
25769                    json!({
25770                        "sequence": 2,
25771                        "change_id": "descending-marker",
25772                        "version": 1,
25773                        "min_supported": 1,
25774                        "max_supported": 1,
25775                    }),
25776                ),
25777            ],
25778            "rust-workers".to_string(),
25779            DEFAULT_CODEC.to_string(),
25780            None,
25781        )
25782        .expect_err("new durable commands must remain strictly ordered");
25783        let Error::NonDeterministicReplay(failure) = descending else {
25784            panic!("expected typed replay failure");
25785        };
25786        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
25787        assert_eq!(failure.sequence, Some(2));
25788        assert_eq!(
25789            failure.expected.as_deref(),
25790            Some("workflow sequence greater than 3")
25791        );
25792        assert_eq!(failure.actual.as_deref(), Some("2"));
25793    }
25794
25795    #[test]
25796    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
25797        fn worker() -> Worker {
25798            let client = Client::new("http://127.0.0.1:8080").expect("client");
25799            let mut worker = Worker::new(client, "rust-workers");
25800            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
25801                ctx.wait_signal("finish").await?;
25802                let marker: String =
25803                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
25804                assert_eq!(marker, "after-finish");
25805                Ok(json!("finished"))
25806            });
25807            worker
25808        }
25809
25810        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
25811            .expect("side-effect result");
25812        let task = workflow_task(
25813            "rust.finish-after-gaps",
25814            vec![
25815                history_event(
25816                    "SignalWaitOpened",
25817                    json!({"sequence": 1, "signal_name": "finish"}),
25818                ),
25819                history_event(
25820                    "SignalReceived",
25821                    json!({
25822                        "signal_id": "increment-3",
25823                        "signal_name": "increment",
25824                        "workflow_sequence": 2,
25825                        "payload_codec": DEFAULT_CODEC,
25826                        "arguments": fixture_envelope(json!([3])),
25827                    }),
25828                ),
25829                history_event(
25830                    "SignalReceived",
25831                    json!({
25832                        "signal_id": "increment-5",
25833                        "signal_name": "increment",
25834                        "workflow_sequence": 3,
25835                        "payload_codec": DEFAULT_CODEC,
25836                        "arguments": fixture_envelope(json!([5])),
25837                    }),
25838                ),
25839                history_event(
25840                    "SignalReceived",
25841                    json!({
25842                        "signal_id": "finish",
25843                        "signal_name": "finish",
25844                        "workflow_sequence": 4,
25845                        "payload_codec": DEFAULT_CODEC,
25846                        "arguments": fixture_envelope(json!([])),
25847                    }),
25848                ),
25849                history_event(
25850                    "SignalApplied",
25851                    json!({
25852                        "sequence": 1,
25853                        "signal_id": "finish",
25854                        "signal_name": "finish",
25855                        "payload_codec": DEFAULT_CODEC,
25856                        "value": fixture_envelope(json!([])),
25857                    }),
25858                ),
25859                history_event(
25860                    "SideEffectRecorded",
25861                    json!({"sequence": 5, "result": marker}),
25862                ),
25863            ],
25864            DEFAULT_CODEC,
25865        );
25866
25867        for _original_or_cold_worker in 0..2 {
25868            let commands = worker()
25869                .execute_workflow_task(task.clone())
25870                .expect("signal gaps preserve deterministic replay");
25871            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
25872            assert_eq!(commands[0]["type"], "complete_workflow");
25873            assert_eq!(
25874                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
25875                json!("finished")
25876            );
25877        }
25878    }
25879
25880    #[test]
25881    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
25882        let ctx = workflow_context(Vec::new());
25883        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
25884        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25885        assert!(matches!(
25886            sleep.as_mut().poll(&mut task_context),
25887            Poll::Ready(Err(Error::TimerDurationOverflow))
25888        ));
25889        assert!(ctx.take_commands().expect("commands").is_empty());
25890    }
25891
25892    #[test]
25893    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
25894        let entries = AvroValue::Map(BTreeMap::from([
25895            ("text".to_string(), AvroValue::String("same".to_string())),
25896            (
25897                "nested".to_string(),
25898                AvroValue::Map(BTreeMap::from([
25899                    ("beta".to_string(), AvroValue::Long(2)),
25900                    ("alpha".to_string(), AvroValue::Long(1)),
25901                ])),
25902            ),
25903            ("long".to_string(), AvroValue::Long(7)),
25904            ("double".to_string(), AvroValue::Double(7.0)),
25905            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
25906        ]));
25907        let ctx = workflow_context(Vec::new());
25908        ctx.upsert_memo(entries.clone()).expect("valid memo update");
25909        let commands = ctx.take_commands().expect("commands");
25910
25911        assert_eq!(commands.len(), 1);
25912        assert_eq!(commands[0]["type"], "upsert_memo");
25913        let server_entries = json!({
25914            "codec": "avro",
25915            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
25916        });
25917        assert_eq!(
25918            commands[0]["entries"]
25919                .as_object()
25920                .expect("entries envelope")
25921                .keys()
25922                .collect::<Vec<_>>(),
25923            vec!["blob", "codec"]
25924        );
25925        assert_eq!(commands[0]["entries"], server_entries);
25926        let wire_entries =
25927            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
25928        assert_eq!(wire_entries, entries);
25929
25930        let history = vec![history_event(
25931            "MemoUpserted",
25932            json!({
25933                "sequence": 1,
25934                "entries": server_entries.clone(),
25935                "merged": server_entries,
25936            }),
25937        )];
25938        let replay = workflow_context(history.clone());
25939        replay
25940            .upsert_memo(entries.clone())
25941            .expect("matching replay identity");
25942        assert!(replay.take_commands().expect("replay commands").is_empty());
25943
25944        let changed_types = AvroValue::Map(BTreeMap::from([
25945            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
25946            (
25947                "nested".to_string(),
25948                AvroValue::Map(BTreeMap::from([
25949                    ("alpha".to_string(), AvroValue::Long(1)),
25950                    ("beta".to_string(), AvroValue::Long(2)),
25951                ])),
25952            ),
25953            ("long".to_string(), AvroValue::Double(7.0)),
25954            ("double".to_string(), AvroValue::Long(7)),
25955            ("binary".to_string(), AvroValue::String("same".to_string())),
25956        ]));
25957        let error = workflow_context(history)
25958            .upsert_memo(changed_types)
25959            .expect_err("memo replay identity must preserve Avro value types");
25960        assert!(matches!(
25961            error,
25962            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25963        ));
25964    }
25965
25966    #[test]
25967    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
25968        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
25969            .expect("memo envelope");
25970        let replay = workflow_context(vec![history_event(
25971            "MemoUpserted",
25972            json!({
25973                "sequence": 1,
25974                "entries": original.clone(),
25975                "merged": original
25976            }),
25977        )]);
25978        let error = replay
25979            .upsert_memo(json!({"stage": "changed"}))
25980            .expect_err("changed memo update must fail replay");
25981        assert!(matches!(
25982            error,
25983            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25984        ));
25985
25986        let invalid = workflow_context(Vec::new())
25987            .upsert_memo(
25988                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
25989            )
25990            .expect_err("oversized key");
25991        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
25992    }
25993
25994    #[test]
25995    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
25996        let negative_zero = AvroValue::Map(BTreeMap::from([(
25997            "reading".to_string(),
25998            AvroValue::Double(-0.0),
25999        )]));
26000        let negative_zero_envelope =
26001            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
26002        let history = vec![history_event(
26003            "MemoUpserted",
26004            json!({
26005                "sequence": 1,
26006                "entries": negative_zero_envelope.clone(),
26007                "merged": negative_zero_envelope,
26008            }),
26009        )];
26010
26011        workflow_context(history.clone())
26012            .upsert_memo(negative_zero)
26013            .expect("matching negative-zero history identity");
26014
26015        let error = workflow_context(history)
26016            .upsert_memo(AvroValue::Map(BTreeMap::from([(
26017                "reading".to_string(),
26018                AvroValue::Double(0.0),
26019            )])))
26020            .expect_err("positive zero must not consume negative-zero memo history");
26021        assert!(matches!(
26022            error,
26023            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
26024        ));
26025    }
26026
26027    #[test]
26028    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
26029        let supported = json!({
26030            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
26031            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
26032        });
26033        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
26034        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
26035            "workflow_memo_updates": {"supported": false},
26036            "supported_workflow_task_commands": ["upsert_memo"]
26037        }))));
26038        assert!(commands_use_workflow_memo_updates(&[json!({
26039            "type": "upsert_memo",
26040            "entries": {"stage": "processing"}
26041        })]));
26042    }
26043
26044    #[test]
26045    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
26046        let client = Client::new("http://127.0.0.1:8080").expect("client");
26047        let mut worker = Worker::new(client, "rust-workers");
26048        worker.register_workflow("rust.timer", |ctx, _input| async move {
26049            ctx.sleep(Duration::from_secs(5)).await?;
26050            ctx.activity("after-timer", json!([])).await
26051        });
26052
26053        let task = |history_events| WorkflowTask {
26054            task_id: "wft-rust-timer-1".to_string(),
26055            observability_context: None,
26056            dispatch_observability_context: None,
26057            observability_links: None,
26058            workflow_command_id: None,
26059            workflow_id: Some("wf-rust-timer".to_string()),
26060            run_id: Some("run-rust-timer".to_string()),
26061            workflow_type: "rust.timer".to_string(),
26062            cancel_requested: false,
26063            payload_codec: DEFAULT_CODEC.to_string(),
26064            arguments: Some(
26065                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26066            ),
26067            history_events,
26068            total_history_events: None,
26069            history_size_bytes: None,
26070            continue_as_new_recommended: None,
26071            history_budget_pressure: None,
26072            next_history_page_token: None,
26073            workflow_task_attempt: 1,
26074            workflow_signal_id: None,
26075            signal_name: None,
26076            signal_arguments: None,
26077            workflow_update_id: None,
26078            update_name: None,
26079            lease_owner: Some("rust-worker".to_string()),
26080        };
26081
26082        let initial = worker
26083            .execute_workflow_task(task(Vec::new()))
26084            .expect("initial timer task");
26085        assert_eq!(
26086            initial,
26087            vec![json!({"type": "start_timer", "delay_seconds": 5})]
26088        );
26089
26090        let activity_result =
26091            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
26092        let replayed = worker
26093            .execute_workflow_task(task(vec![
26094                history_event(
26095                    "TimerScheduled",
26096                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26097                ),
26098                history_event(
26099                    "TimerFired",
26100                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26101                ),
26102                history_event(
26103                    "ActivityCompleted",
26104                    json!({
26105                        "sequence": 2,
26106                        "activity_type": "after-timer",
26107                        "payload_codec": DEFAULT_CODEC,
26108                        "result": activity_result,
26109                    }),
26110                ),
26111            ]))
26112            .expect("replayed workflow task");
26113        assert_eq!(replayed.len(), 1);
26114        assert_eq!(replayed[0]["type"], "complete_workflow");
26115        assert_eq!(
26116            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
26117            json!("done")
26118        );
26119    }
26120
26121    #[test]
26122    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
26123        let client = Client::new("http://127.0.0.1:8080").expect("client");
26124        let mut worker = Worker::new(client, "rust-workers");
26125        worker.register_workflow("rust.continue", |ctx, _input| async move {
26126            ctx.continue_as_new_with_options(
26127                ContinueAsNewOptions::new()
26128                    .workflow_type("rust.next")
26129                    .task_queue("next-workers"),
26130                json!([2, {"cursor": "next"}]),
26131            )
26132        });
26133
26134        let commands = worker
26135            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
26136            .expect("continue-as-new command");
26137
26138        assert_eq!(commands.len(), 1);
26139        assert_eq!(commands[0]["type"], "continue_as_new");
26140        assert_eq!(commands[0]["workflow_type"], "rust.next");
26141        assert_eq!(commands[0]["queue"], "next-workers");
26142        assert_eq!(
26143            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
26144                .expect("continue-as-new arguments"),
26145            json!([2, {"cursor": "next"}])
26146        );
26147    }
26148
26149    #[test]
26150    fn continue_as_new_preserves_typed_arguments() {
26151        let client = Client::new("http://127.0.0.1:8080").expect("client");
26152        let mut worker = Worker::new(client, "rust-workers");
26153        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
26154            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
26155            unreachable!("continue-as-new returns a control-flow error")
26156        });
26157
26158        let commands = worker
26159            .execute_workflow_task(workflow_task(
26160                "rust.typed-continue",
26161                Vec::new(),
26162                DEFAULT_CODEC,
26163            ))
26164            .expect("typed continue-as-new command");
26165
26166        assert_eq!(commands[0]["type"], "continue_as_new");
26167        assert_eq!(
26168            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
26169                .expect("typed continue arguments"),
26170            AvroValue::Array(vec![typed_fidelity_probe()])
26171        );
26172    }
26173
26174    #[test]
26175    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
26176        let client = Client::new("http://127.0.0.1:8080").expect("client");
26177        let mut worker = Worker::new(client, "rust-workers");
26178        worker.register_workflow("rust.continue", |ctx, _input| async move {
26179            ctx.continue_as_new(json!([2]))
26180        });
26181        let task = workflow_task(
26182            "rust.continue",
26183            vec![history_event(
26184                "WorkflowContinuedAsNew",
26185                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
26186            )],
26187            DEFAULT_CODEC,
26188        );
26189
26190        for _worker_restart_or_redelivery in 0..2 {
26191            let commands = worker
26192                .execute_workflow_task(task.clone())
26193                .expect("recorded transition replays");
26194            assert!(
26195                commands.is_empty(),
26196                "replay must not emit another successor"
26197            );
26198        }
26199    }
26200
26201    #[test]
26202    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
26203        let ctx = workflow_context(Vec::new());
26204        let error = ctx
26205            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
26206            .expect_err("blank queue must be rejected");
26207
26208        let Error::InvalidContinueAsNewOptions(error) = error else {
26209            panic!("expected typed continue-as-new validation error");
26210        };
26211        assert_eq!(error.field, "task_queue");
26212        assert!(ctx.take_commands().expect("commands").is_empty());
26213    }
26214
26215    #[test]
26216    fn workflow_context_exposes_server_history_budget() {
26217        let client = Client::new("http://127.0.0.1:8080").expect("client");
26218        let mut worker = Worker::new(client, "rust-workers");
26219        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
26220            let budget = ctx.history_budget()?;
26221            Ok(json!({
26222                "events": budget.event_count,
26223                "bytes": budget.size_bytes,
26224                "recommended": budget.continue_as_new_recommended,
26225                "pressure": budget.pressure,
26226            }))
26227        });
26228        let task: WorkflowTask = serde_json::from_value(json!({
26229            "task_id": "task-history-budget",
26230            "workflow_type": "rust.history-budget",
26231            "payload_codec": DEFAULT_CODEC,
26232            "history_events": [],
26233            "total_history_events": 480,
26234            "history_size_bytes": 1_048_576,
26235            "continue_as_new_recommended": true,
26236            "history_budget_pressure": "continue_as_new_recommended",
26237        }))
26238        .expect("published workflow task");
26239
26240        let commands = worker
26241            .execute_workflow_task(task)
26242            .expect("history-budget workflow");
26243        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
26244        assert_eq!(result["events"], 480);
26245        assert_eq!(result["bytes"], 1_048_576);
26246        assert_eq!(result["recommended"], true);
26247        assert_eq!(result["pressure"], "continue_as_new_recommended");
26248    }
26249
26250    #[test]
26251    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
26252        let client = Client::new("http://127.0.0.1:8080").expect("client");
26253        let mut worker = Worker::new(client, "rust-workers");
26254        worker.register_workflow("rust.failing", |_ctx, _input| async move {
26255            Err(Error::Codec("rust_conformance_failure".to_string()))
26256        });
26257        let task = WorkflowTask {
26258            task_id: "wft-rust-failing-1".to_string(),
26259            observability_context: None,
26260            dispatch_observability_context: None,
26261            observability_links: None,
26262            workflow_command_id: None,
26263            workflow_id: Some("wf-rust-failing".to_string()),
26264            run_id: Some("run-rust-failing".to_string()),
26265            workflow_type: "rust.failing".to_string(),
26266            cancel_requested: false,
26267            payload_codec: DEFAULT_CODEC.to_string(),
26268            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26269            history_events: Vec::new(),
26270            total_history_events: Some(0),
26271            history_size_bytes: None,
26272            continue_as_new_recommended: None,
26273            history_budget_pressure: None,
26274            next_history_page_token: None,
26275            workflow_task_attempt: 1,
26276            workflow_signal_id: None,
26277            signal_name: None,
26278            signal_arguments: None,
26279            workflow_update_id: None,
26280            update_name: None,
26281            lease_owner: Some("rust-worker".to_string()),
26282        };
26283
26284        let commands = worker
26285            .execute_workflow_task(task)
26286            .expect("handler failure becomes a workflow command");
26287
26288        assert_eq!(commands.len(), 1);
26289        assert_eq!(commands[0]["type"], "fail_workflow");
26290        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
26291        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
26292        assert_eq!(commands[0]["non_retryable"], false);
26293        assert_eq!(
26294            commands[0]["message"],
26295            "codec error: rust_conformance_failure"
26296        );
26297        assert_eq!(
26298            commands[0]["exception"]["message"],
26299            "codec error: rust_conformance_failure"
26300        );
26301    }
26302
26303    #[test]
26304    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
26305        let client = Client::new("http://127.0.0.1:8080").expect("client");
26306        let mut worker = Worker::new(client, "rust-workers");
26307        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
26308            let _: String = ctx.side_effect(|| "captured".to_string())?;
26309            Err(Error::WorkerLoop("application failure".to_string()))
26310        });
26311
26312        let commands = worker
26313            .execute_workflow_task(workflow_task(
26314                "rust.failing-after-side-effect",
26315                Vec::new(),
26316                DEFAULT_CODEC,
26317            ))
26318            .expect("ordinary failure remains a workflow decision");
26319
26320        assert_eq!(commands.len(), 2);
26321        assert_eq!(commands[0]["type"], "record_side_effect");
26322        assert_eq!(commands[1]["type"], "fail_workflow");
26323    }
26324
26325    #[test]
26326    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
26327        let client = Client::new("http://127.0.0.1:8080").expect("client");
26328        let mut worker = Worker::new(client, "rust-workers");
26329        worker.register_workflow("rust.redrive", |ctx, _input| async move {
26330            ctx.activity("greet", json!([])).await?;
26331            Ok(Value::Null)
26332        });
26333        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
26334            match ctx.activity("greet", json!([])).await {
26335                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
26336                result => result,
26337            }
26338        });
26339
26340        let failed = history_event(
26341            "ActivityFailed",
26342            json!({
26343                "sequence": 1,
26344                "activity_type": "greet",
26345                "activity_execution_id": "activity-1",
26346                "message": "failed"
26347            }),
26348        );
26349        let commands = worker
26350            .execute_workflow_task(workflow_task(
26351                "rust.redrive",
26352                vec![failed.clone()],
26353                DEFAULT_CODEC,
26354            ))
26355            .expect("recorded failure becomes a workflow command");
26356        assert_eq!(commands[0]["type"], "fail_workflow");
26357        assert_eq!(commands[0]["failed_step_sequence"], 1);
26358        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
26359
26360        let translated = worker
26361            .execute_workflow_task(workflow_task(
26362                "rust.redrive-translated",
26363                vec![failed],
26364                DEFAULT_CODEC,
26365            ))
26366            .expect("translated failure becomes a workflow command");
26367        assert_eq!(translated[0]["type"], "fail_workflow");
26368        assert!(translated[0].get("failed_step_sequence").is_none());
26369        assert!(translated[0].get("failed_activity_execution_id").is_none());
26370
26371        let without_identity = worker
26372            .execute_workflow_task(workflow_task(
26373                "rust.redrive",
26374                vec![history_event(
26375                    "ActivityFailed",
26376                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
26377                )],
26378                DEFAULT_CODEC,
26379            ))
26380            .expect("incomplete identity still fails the workflow");
26381        assert!(without_identity[0].get("failed_step_sequence").is_none());
26382
26383        let timed_out = worker
26384            .execute_workflow_task(workflow_task(
26385                "rust.redrive",
26386                vec![history_event(
26387                    "ActivityTimedOut",
26388                    json!({
26389                        "sequence": 1,
26390                        "activity_type": "greet",
26391                        "activity_execution_id": "activity-timeout",
26392                    }),
26393                )],
26394                DEFAULT_CODEC,
26395            ))
26396            .expect("timeout still fails the workflow");
26397        assert!(timed_out[0].get("failed_step_sequence").is_none());
26398    }
26399
26400    #[test]
26401    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
26402        let client = Client::new("http://127.0.0.1:8080").expect("client");
26403        let mut worker = Worker::new(client, "rust-workers");
26404        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
26405            let first = ctx.activity("first", json!([])).await?;
26406            let second = ctx.activity("second", json!([first.clone()])).await?;
26407            Ok(json!({"first": first, "second": second}))
26408        });
26409        let first = history_event(
26410            "ActivityCompleted",
26411            json!({
26412                "sequence": 1,
26413                "activity_type": "first",
26414                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
26415                "payload_codec": DEFAULT_CODEC,
26416                "reused_from_run_id": "failed-run",
26417                "reused_activity_execution_id": "original-first",
26418            }),
26419        );
26420
26421        let retry = worker
26422            .execute_workflow_task(workflow_task(
26423                "rust.redrive-successor",
26424                vec![first.clone()],
26425                DEFAULT_CODEC,
26426            ))
26427            .expect("reused result replays before failed step");
26428        assert_eq!(retry.len(), 1);
26429        assert_eq!(retry[0]["type"], "schedule_activity");
26430        assert_eq!(retry[0]["activity_type"], "second");
26431        assert_eq!(
26432            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
26433            json!(["recorded"]),
26434        );
26435
26436        let second = history_event(
26437            "ActivityCompleted",
26438            json!({
26439                "sequence": 2,
26440                "activity_type": "second",
26441                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
26442                "payload_codec": DEFAULT_CODEC,
26443            }),
26444        );
26445        let completed = worker
26446            .execute_workflow_task(workflow_task(
26447                "rust.redrive-successor",
26448                vec![first, second],
26449                DEFAULT_CODEC,
26450            ))
26451            .expect("retried step completes the successor");
26452        assert_eq!(completed.len(), 1);
26453        assert_eq!(completed[0]["type"], "complete_workflow");
26454        assert_eq!(
26455            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
26456            json!({"first": "recorded", "second": "retried"}),
26457        );
26458    }
26459
26460    #[test]
26461    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
26462        let client = Client::new("http://127.0.0.1:8080").expect("client");
26463        let mut worker = Worker::new(client, "rust-workers");
26464        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
26465            Err(Error::WorkerLoop("application failure".to_string()))
26466        });
26467        let result =
26468            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
26469
26470        let error = worker
26471            .execute_workflow_task(workflow_task(
26472                "rust.removed-side-effect",
26473                vec![history_event(
26474                    "SideEffectRecorded",
26475                    json!({"sequence": 1, "result": result}),
26476                )],
26477                DEFAULT_CODEC,
26478            ))
26479            .expect_err("removed committed history must not become fail_workflow");
26480
26481        let Error::NonDeterministicReplay(failure) = error else {
26482            panic!("expected typed replay failure");
26483        };
26484        assert_eq!(failure.reason, "recorded_commands_unconsumed");
26485        assert_eq!(failure.sequence, Some(1));
26486        assert_eq!(failure.expected.as_deref(), Some("side effect"));
26487    }
26488
26489    #[test]
26490    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
26491        let client = Client::new("http://127.0.0.1:8080").expect("client");
26492        let mut worker = Worker::new(client, "rust-workers");
26493        worker.register_workflow(
26494            "rust.side-effect-before-marker-error",
26495            |ctx, _input| async move {
26496                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
26497                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
26498                ctx.get_version("restart-safe", 2, 2)?;
26499                Ok(Value::Null)
26500            },
26501        );
26502
26503        let error = worker
26504            .execute_workflow_task(workflow_task(
26505                "rust.side-effect-before-marker-error",
26506                vec![history_event(
26507                    "VersionMarkerRecorded",
26508                    json!({
26509                        "sequence": 1,
26510                        "change_id": "restart-safe",
26511                        "version": 1,
26512                        "min_supported": 1,
26513                        "max_supported": 1,
26514                    }),
26515                )],
26516                DEFAULT_CODEC,
26517            ))
26518            .expect_err("replay error must return no queued workflow commands");
26519
26520        let Error::NonDeterministicReplay(failure) = error else {
26521            panic!("expected typed replay failure");
26522        };
26523        assert_eq!(failure.reason, "version_marker_incompatible_range");
26524        assert_eq!(failure.sequence, Some(1));
26525    }
26526
26527    #[test]
26528    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
26529        let client = Client::new("http://127.0.0.1:8080").expect("client");
26530        let mut worker = Worker::new(client, "rust-workers");
26531        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
26532            ctx.sleep(Duration::from_secs(5)).await?;
26533            Ok(json!({"status": "timer fired"}))
26534        });
26535
26536        let task = WorkflowTask {
26537            task_id: "wft-rust-timer-pending".to_string(),
26538            observability_context: None,
26539            dispatch_observability_context: None,
26540            observability_links: None,
26541            workflow_command_id: None,
26542            workflow_id: Some("wf-rust-timer".to_string()),
26543            run_id: Some("run-rust-timer".to_string()),
26544            workflow_type: "rust.timer.pending".to_string(),
26545            cancel_requested: false,
26546            payload_codec: DEFAULT_CODEC.to_string(),
26547            arguments: Some(
26548                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26549            ),
26550            history_events: vec![history_event(
26551                "TimerScheduled",
26552                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26553            )],
26554            total_history_events: Some(1),
26555            history_size_bytes: None,
26556            continue_as_new_recommended: None,
26557            history_budget_pressure: None,
26558            next_history_page_token: None,
26559            workflow_task_attempt: 1,
26560            workflow_signal_id: None,
26561            signal_name: None,
26562            signal_arguments: None,
26563            workflow_update_id: None,
26564            update_name: None,
26565            lease_owner: Some("rust-worker".to_string()),
26566        };
26567
26568        for _redelivery_or_restart in 0..2 {
26569            let commands = worker
26570                .execute_workflow_task(task.clone())
26571                .expect("recorded timer remains pending");
26572            assert!(
26573                commands.is_empty(),
26574                "recorded timer must not be rescheduled"
26575            );
26576        }
26577    }
26578
26579    #[test]
26580    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
26581        let client = Client::new("http://127.0.0.1:8080").expect("client");
26582        let mut worker = Worker::new(client, "rust-workers");
26583        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
26584            Ok(json!({"status": "completed"}))
26585        });
26586        let task = WorkflowTask {
26587            task_id: "wft-rust-timer-removed".to_string(),
26588            observability_context: None,
26589            dispatch_observability_context: None,
26590            observability_links: None,
26591            workflow_command_id: None,
26592            workflow_id: Some("wf-rust-timer".to_string()),
26593            run_id: Some("run-rust-timer".to_string()),
26594            workflow_type: "rust.timer.removed".to_string(),
26595            cancel_requested: false,
26596            payload_codec: DEFAULT_CODEC.to_string(),
26597            arguments: Some(
26598                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26599            ),
26600            history_events: vec![
26601                history_event(
26602                    "TimerScheduled",
26603                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26604                ),
26605                history_event(
26606                    "TimerFired",
26607                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26608                ),
26609            ],
26610            total_history_events: Some(2),
26611            history_size_bytes: None,
26612            continue_as_new_recommended: None,
26613            history_budget_pressure: None,
26614            next_history_page_token: None,
26615            workflow_task_attempt: 1,
26616            workflow_signal_id: None,
26617            signal_name: None,
26618            signal_arguments: None,
26619            workflow_update_id: None,
26620            update_name: None,
26621            lease_owner: Some("rust-worker".to_string()),
26622        };
26623
26624        let Error::NonDeterministicReplay(failure) = worker
26625            .execute_workflow_task(task)
26626            .expect_err("removed timer must fail replay")
26627        else {
26628            panic!("expected typed replay failure");
26629        };
26630        assert_eq!(failure.reason, "recorded_commands_unconsumed");
26631        assert_eq!(failure.sequence, Some(1));
26632    }
26633
26634    #[test]
26635    fn workflow_context_emits_explicit_child_workflow_contract() {
26636        let ctx = WorkflowContext {
26637            cancellation_scope_id: "root".into(),
26638            state: Arc::new(Mutex::new(
26639                WorkflowState::new_with_identity(
26640                    Vec::new(),
26641                    Some("wf-parent".to_string()),
26642                    Some("run-parent".to_string()),
26643                    "parent-workers".to_string(),
26644                    DEFAULT_CODEC.to_string(),
26645                    None,
26646                )
26647                .expect("workflow state"),
26648            )),
26649        };
26650        let options = ChildWorkflowOptions::new("python-workers")
26651            .parent_close_policy(ParentClosePolicy::RequestCancel)
26652            .retry_policy(ChildWorkflowRetryPolicy {
26653                max_attempts: Some(3),
26654                backoff_seconds: vec![1, 5],
26655                non_retryable_error_types: vec!["ValidationError".to_string()],
26656            })
26657            .execution_timeout_seconds(600)
26658            .run_timeout_seconds(120);
26659        let mut call = Box::pin(ctx.start_child_workflow(
26660            "python.fulfil-order",
26661            options,
26662            json!([{"order_id": "order-42"}]),
26663        ));
26664        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26665
26666        assert!(matches!(
26667            call.as_mut().poll(&mut task_context),
26668            Poll::Pending
26669        ));
26670        let commands = ctx.take_commands().expect("commands");
26671        assert_eq!(commands.len(), 1);
26672        let command = &commands[0];
26673        assert_eq!(command["type"], "start_child_workflow");
26674        assert_eq!(command["workflow_type"], "python.fulfil-order");
26675        assert_eq!(command["queue"], "python-workers");
26676        assert_eq!(command["parent_close_policy"], "request_cancel");
26677        assert_eq!(command["retry_policy"]["max_attempts"], 3);
26678        assert_eq!(command["execution_timeout_seconds"], 600);
26679        assert_eq!(command["run_timeout_seconds"], 120);
26680        assert_eq!(
26681            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
26682            json!([{"order_id": "order-42"}])
26683        );
26684    }
26685
26686    fn child_parent_worker() -> Worker {
26687        let client = Client::new("http://127.0.0.1:8080").expect("client");
26688        let mut worker = Worker::new(client, "rust-parent-workers");
26689        worker.register_workflow("rust.parent", |ctx, _input| async move {
26690            let child = ctx
26691                .start_child_workflow(
26692                    "python.child",
26693                    ChildWorkflowOptions::new("python-child-workers")
26694                        .parent_close_policy(ParentClosePolicy::Terminate),
26695                    json!([{"codec_probe": [1, true, "rust"]}]),
26696                )
26697                .await?;
26698            Ok(json!({
26699                "parent_workflow_id": child.parent.workflow_id,
26700                "parent_run_id": child.parent.run_id,
26701                "child_workflow_id": child.child.workflow_id,
26702                "child_run_id": child.child.run_id,
26703                "child_workflow_type": child.child_workflow_type,
26704                "result": child.result,
26705            }))
26706        });
26707        worker
26708    }
26709
26710    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
26711        WorkflowTask {
26712            task_id: "wft-child-parent".to_string(),
26713            observability_context: None,
26714            dispatch_observability_context: None,
26715            observability_links: None,
26716            workflow_command_id: None,
26717            workflow_id: Some("wf-parent".to_string()),
26718            run_id: Some("run-parent".to_string()),
26719            workflow_type: "rust.parent".to_string(),
26720            cancel_requested: false,
26721            payload_codec: DEFAULT_CODEC.to_string(),
26722            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26723            history_events: vec![
26724                HistoryEvent {
26725                    event_type: "ChildWorkflowScheduled".to_string(),
26726                    payload: json!({
26727                        "sequence": 1,
26728                        "child_call_id": "call-child",
26729                        "child_workflow_instance_id": "wf-child",
26730                        "child_workflow_run_id": "run-child",
26731                        "child_workflow_type": "python.child",
26732                        "parent_close_policy": "terminate",
26733                    }),
26734                    raw: HashMap::new(),
26735                },
26736                HistoryEvent {
26737                    event_type: event_type.to_string(),
26738                    payload,
26739                    raw: HashMap::new(),
26740                },
26741            ],
26742            total_history_events: Some(2),
26743            history_size_bytes: None,
26744            continue_as_new_recommended: None,
26745            history_budget_pressure: None,
26746            next_history_page_token: None,
26747            workflow_task_attempt: 1,
26748            workflow_signal_id: None,
26749            signal_name: None,
26750            signal_arguments: None,
26751            workflow_update_id: None,
26752            update_name: None,
26753            lease_owner: Some("rust-worker".to_string()),
26754        }
26755    }
26756
26757    #[test]
26758    fn committed_child_result_replays_without_starting_a_duplicate() {
26759        let worker = child_parent_worker();
26760        let task = child_parent_task(
26761            "ChildRunCompleted",
26762            json!({
26763                "sequence": 1,
26764                "child_call_id": "call-child",
26765                "child_workflow_instance_id": "wf-child",
26766                "child_workflow_run_id": "run-child",
26767                "child_workflow_type": "python.child",
26768                "payload_codec": DEFAULT_CODEC,
26769                "result": fixture_envelope(json!({"from":"python","ok":true})),
26770            }),
26771        );
26772
26773        for _restart in 0..2 {
26774            let commands = worker
26775                .execute_workflow_task(task.clone())
26776                .expect("replayed parent task");
26777            assert_eq!(commands.len(), 1);
26778            assert_eq!(commands[0]["type"], "complete_workflow");
26779            assert!(!commands
26780                .iter()
26781                .any(|command| command["type"] == "start_child_workflow"));
26782            let output =
26783                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26784            assert_eq!(output["parent_workflow_id"], "wf-parent");
26785            assert_eq!(output["parent_run_id"], "run-parent");
26786            assert_eq!(output["child_workflow_id"], "wf-child");
26787            assert_eq!(output["child_run_id"], "run-child");
26788            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
26789        }
26790    }
26791
26792    #[test]
26793    fn typed_child_arguments_and_results_survive_replay() {
26794        let client = Client::new("http://127.0.0.1:8080").expect("client");
26795        let mut worker = Worker::new(client, "rust-parent-workers");
26796        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
26797            let child = ctx
26798                .start_child_workflow_avro_value(
26799                    "python.typed-child",
26800                    ChildWorkflowOptions::new("python-workers"),
26801                    AvroValue::Array(vec![typed_fidelity_probe()]),
26802                )
26803                .await?;
26804            Ok(child.result)
26805        });
26806
26807        let initial = worker
26808            .execute_workflow_task(workflow_task(
26809                "rust.typed-parent",
26810                Vec::new(),
26811                DEFAULT_CODEC,
26812            ))
26813            .expect("typed child start");
26814        assert_eq!(initial[0]["type"], "start_child_workflow");
26815        assert_eq!(
26816            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
26817                .expect("typed child arguments"),
26818            AvroValue::Array(vec![typed_fidelity_probe()])
26819        );
26820
26821        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
26822            .expect("typed child result");
26823        let task = workflow_task(
26824            "rust.typed-parent",
26825            vec![
26826                history_event(
26827                    "ChildWorkflowScheduled",
26828                    json!({
26829                        "sequence": 1,
26830                        "child_call_id": "call-typed",
26831                        "child_workflow_instance_id": "wf-child",
26832                        "child_workflow_run_id": "run-child",
26833                        "child_workflow_type": "python.typed-child",
26834                    }),
26835                ),
26836                history_event(
26837                    "ChildRunCompleted",
26838                    json!({
26839                        "sequence": 1,
26840                        "child_call_id": "call-typed",
26841                        "child_workflow_instance_id": "wf-child",
26842                        "child_workflow_run_id": "run-child",
26843                        "child_workflow_type": "python.typed-child",
26844                        "payload_codec": DEFAULT_CODEC,
26845                        "result": result,
26846                    }),
26847                ),
26848            ],
26849            DEFAULT_CODEC,
26850        );
26851
26852        let commands = worker
26853            .execute_workflow_task(task)
26854            .expect("typed child replay");
26855        assert_eq!(commands[0]["type"], "complete_workflow");
26856        assert_eq!(
26857            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
26858                .expect("typed parent result"),
26859            typed_fidelity_probe()
26860        );
26861    }
26862
26863    #[test]
26864    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
26865        let worker = child_parent_worker();
26866        let mut task = child_parent_task("unused", Value::Null);
26867        task.history_events.truncate(1);
26868        task.total_history_events = Some(1);
26869
26870        for _redelivery_or_restart in 0..2 {
26871            let commands = worker
26872                .execute_workflow_task(task.clone())
26873                .expect("recorded child remains pending");
26874            assert!(
26875                commands.is_empty(),
26876                "recorded pending child must not be started again"
26877            );
26878        }
26879    }
26880
26881    #[test]
26882    fn child_cancellation_becomes_stable_parent_failure_command() {
26883        let worker = child_parent_worker();
26884        let task = child_parent_task(
26885            "ChildRunCancelled",
26886            json!({
26887                "sequence": 1,
26888                "child_workflow_instance_id": "wf-child",
26889                "child_workflow_run_id": "run-child",
26890                "child_workflow_type": "python.child",
26891                "failure_id": "failure-child",
26892                "failure_category": "cancelled",
26893                "message": "cancelled by parent-close policy",
26894            }),
26895        );
26896
26897        let commands = worker
26898            .execute_workflow_task(task)
26899            .expect("parent settlement");
26900        assert_eq!(commands.len(), 1);
26901        assert_eq!(commands[0]["type"], "fail_workflow");
26902        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
26903        assert_eq!(
26904            commands[0]["exception"]["properties"]["reason"],
26905            "cancelled"
26906        );
26907        assert_eq!(
26908            commands[0]["exception"]["properties"]["child_workflow_run_id"],
26909            "run-child"
26910        );
26911    }
26912
26913    #[test]
26914    fn workflow_can_handle_typed_child_failure() {
26915        let client = Client::new("http://127.0.0.1:8080").expect("client");
26916        let mut worker = Worker::new(client, "rust-parent-workers");
26917        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
26918            match ctx
26919                .start_child_workflow(
26920                    "python.child",
26921                    ChildWorkflowOptions::new("python-child-workers"),
26922                    json!([]),
26923                )
26924                .await
26925            {
26926                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
26927                    "reason": failure.reason,
26928                    "failure_id": failure.failure_id,
26929                    "exception_class": failure.exception_class,
26930                    "child_run_id": failure.child_workflow_run_id,
26931                })),
26932                Err(error) => Err(error),
26933                Ok(_) => Err(Error::WorkerLoop(
26934                    "child unexpectedly succeeded".to_string(),
26935                )),
26936            }
26937        });
26938        let mut task = child_parent_task(
26939            "ChildRunFailed",
26940            json!({
26941                "sequence": 1,
26942                "child_workflow_instance_id": "wf-child",
26943                "child_workflow_run_id": "run-child",
26944                "child_workflow_type": "python.child",
26945                "failure_id": "failure-child",
26946                "failure_category": "child_workflow",
26947                "message": "payment rejected",
26948                "exception": {
26949                    "type": "PaymentRejected",
26950                    "class": "payments.PaymentRejected",
26951                    "message": "payment rejected"
26952                }
26953            }),
26954        );
26955        task.workflow_type = "rust.handled-parent".to_string();
26956        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
26957
26958        let commands = worker.execute_workflow_task(task).expect("handled failure");
26959        assert_eq!(commands[0]["type"], "complete_workflow");
26960        let output =
26961            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26962        assert_eq!(output["reason"], "child_workflow");
26963        assert_eq!(output["failure_id"], "failure-child");
26964        assert_eq!(output["exception_class"], "payments.PaymentRejected");
26965        assert_eq!(output["child_run_id"], "run-child");
26966    }
26967
26968    #[test]
26969    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
26970        let client = Client::new("http://127.0.0.1:8080").expect("client");
26971        let mut worker = Worker::new(client, "rust-workers");
26972
26973        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
26974            let signal = ctx.wait_signal("start").await?;
26975            let name = signal
26976                .first()
26977                .and_then(|value| value.as_str())
26978                .unwrap_or("world");
26979            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
26980            Ok(json!({
26981                "greeting": greeting,
26982                "language": "rust"
26983            }))
26984        });
26985
26986        let signal_arguments =
26987            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
26988        let task = WorkflowTask {
26989            task_id: "wft-rust-signal-1".to_string(),
26990            observability_context: None,
26991            dispatch_observability_context: None,
26992            observability_links: None,
26993            workflow_command_id: None,
26994            workflow_id: Some("wf-rust-hello".to_string()),
26995            run_id: Some("run-rust-hello".to_string()),
26996            workflow_type: "rust.hello_workflow".to_string(),
26997            cancel_requested: false,
26998            payload_codec: DEFAULT_CODEC.to_string(),
26999            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
27000            history_events: vec![HistoryEvent {
27001                event_type: "SignalReceived".to_string(),
27002                payload: json!({
27003                    "signal_id": "sig-rust-1",
27004                    "signal_name": "start"
27005                }),
27006                raw: HashMap::new(),
27007            }],
27008            total_history_events: Some(1),
27009            history_size_bytes: None,
27010            continue_as_new_recommended: None,
27011            history_budget_pressure: None,
27012            next_history_page_token: None,
27013            workflow_task_attempt: 1,
27014            workflow_signal_id: Some("sig-rust-1".to_string()),
27015            signal_name: Some("start".to_string()),
27016            signal_arguments: Some(signal_arguments),
27017            workflow_update_id: None,
27018            update_name: None,
27019            lease_owner: Some("rust-worker".to_string()),
27020        };
27021
27022        let commands = worker.execute_workflow_task(task).expect("workflow task");
27023
27024        assert_eq!(commands.len(), 1);
27025        assert_eq!(commands[0]["type"], "schedule_activity");
27026        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
27027        assert_eq!(
27028            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
27029            json!(["Rust"])
27030        );
27031    }
27032
27033    #[test]
27034    fn workflow_task_appends_paginated_history_events() {
27035        let mut task = WorkflowTask {
27036            task_id: "wft-rust-pages-1".to_string(),
27037            observability_context: None,
27038            dispatch_observability_context: None,
27039            observability_links: None,
27040            workflow_command_id: None,
27041            workflow_id: Some("wf-rust-pages".to_string()),
27042            run_id: Some("run-rust-pages".to_string()),
27043            workflow_type: "rust.hello_workflow".to_string(),
27044            cancel_requested: false,
27045            payload_codec: DEFAULT_CODEC.to_string(),
27046            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
27047            history_events: vec![HistoryEvent {
27048                event_type: "WorkflowStarted".to_string(),
27049                payload: json!({}),
27050                raw: HashMap::new(),
27051            }],
27052            total_history_events: Some(3),
27053            history_size_bytes: None,
27054            continue_as_new_recommended: None,
27055            history_budget_pressure: None,
27056            next_history_page_token: Some("MQ==".to_string()),
27057            workflow_task_attempt: 1,
27058            workflow_signal_id: None,
27059            signal_name: None,
27060            signal_arguments: None,
27061            workflow_update_id: None,
27062            update_name: None,
27063            lease_owner: Some("rust-worker".to_string()),
27064        };
27065
27066        task.append_history_page(WorkflowTaskHistoryPage {
27067            history_events: vec![
27068                HistoryEvent {
27069                    event_type: "SignalReceived".to_string(),
27070                    payload: json!({
27071                        "signal_id": "sig-rust-1",
27072                        "signal_name": "start",
27073                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
27074                            .expect("signal arguments")
27075                    }),
27076                    raw: HashMap::new(),
27077                },
27078                HistoryEvent {
27079                    event_type: "MarkerRecorded".to_string(),
27080                    payload: json!({"sequence": 3}),
27081                    raw: HashMap::new(),
27082                },
27083            ],
27084            total_history_events: Some(3),
27085            next_history_page_token: None,
27086        });
27087
27088        assert_eq!(task.history_events.len(), 3);
27089        assert_eq!(task.total_history_events, Some(3));
27090        assert_eq!(task.next_history_page_token, None);
27091
27092        let signal = task
27093            .history_events
27094            .iter()
27095            .find(|event| event.event_type == "SignalReceived")
27096            .expect("signal event");
27097        assert_eq!(
27098            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
27099            vec![AvroValue::String("Rust".to_string())]
27100        );
27101    }
27102
27103    #[tokio::test]
27104    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
27105        let client = Client::new("http://127.0.0.1:8080").expect("client");
27106        let mut worker = Worker::new(client, "rust-workers");
27107        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27108        worker.register_query("counter", "current", |ctx, _args| async move {
27109            let mut count = 0_i64;
27110            for signal in ctx.signal_events() {
27111                let value = signal
27112                    .arguments
27113                    .first()
27114                    .and_then(Value::as_i64)
27115                    .unwrap_or_default();
27116                match signal.name.as_str() {
27117                    "increment" => count += value,
27118                    "set" => count = value,
27119                    _ => {}
27120                }
27121            }
27122            Ok(json!(count))
27123        });
27124
27125        let task = QueryTask {
27126            query_task_id: "query-rust-counter".to_string(),
27127            observability_context: None,
27128            dispatch_observability_context: None,
27129            observability_links: None,
27130            query_task_attempt: 1,
27131            lease_owner: Some("rust-worker".to_string()),
27132            workflow_id: Some("counter-1".to_string()),
27133            run_id: Some("run-counter-1".to_string()),
27134            workflow_type: "counter".to_string(),
27135            query_name: "current".to_string(),
27136            payload_codec: DEFAULT_CODEC.to_string(),
27137            workflow_arguments: Some(
27138                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
27139            ),
27140            query_arguments: Some(
27141                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
27142            ),
27143            history_events: vec![
27144                HistoryEvent {
27145                    event_type: "SignalReceived".to_string(),
27146                    payload: json!({
27147                        "signal_id": "php-signal-1",
27148                        "signal_name": "increment",
27149                        "workflow_sequence": 1,
27150                        "payload_codec": DEFAULT_CODEC,
27151                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
27152                    }),
27153                    raw: HashMap::new(),
27154                },
27155                HistoryEvent {
27156                    event_type: "SignalReceived".to_string(),
27157                    payload: json!({
27158                        "signal_id": "python-signal-2",
27159                        "signal_name": "increment",
27160                        "workflow_sequence": 2,
27161                        "payload_codec": DEFAULT_CODEC,
27162                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
27163                    }),
27164                    raw: HashMap::new(),
27165                },
27166                HistoryEvent {
27167                    event_type: "SignalReceived".to_string(),
27168                    payload: json!({
27169                        "signal_id": "rust-signal-3",
27170                        "signal_name": "set",
27171                        "workflow_sequence": 3,
27172                        "payload_codec": DEFAULT_CODEC,
27173                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
27174                    }),
27175                    raw: HashMap::new(),
27176                },
27177            ],
27178            history_export: None,
27179            run_status: Some("completed".to_string()),
27180        };
27181
27182        let result = worker.execute_query_task(task).await.expect("query result");
27183        assert_eq!(result.into_json().expect("query projection"), json!(0));
27184    }
27185
27186    #[tokio::test]
27187    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
27188        let worker = replay_counter_worker();
27189        let running_history = json!([
27190            {
27191                "type": "ActivityCompleted",
27192                "payload": {
27193                    "sequence": 1,
27194                    "activity_type": "load-counter",
27195                    "payload_codec": DEFAULT_CODEC,
27196                    "result": fixture_envelope(json!("loaded"))
27197                }
27198            },
27199            {
27200                "type": "SignalWaitOpened",
27201                "payload": {
27202                    "sequence": 3,
27203                    "signal_name": "increment"
27204                }
27205            },
27206            {
27207                "type": "SignalReceived",
27208                "payload": {
27209                    "signal_id": "signal-3",
27210                    "signal_name": "increment",
27211                    "workflow_sequence": 2,
27212                    "payload_codec": DEFAULT_CODEC,
27213                    "arguments": fixture_envelope(json!([3]))
27214                }
27215            },
27216            {
27217                "type": "SignalApplied",
27218                "payload": {
27219                    "sequence": 3,
27220                    "signal_id": "signal-3",
27221                    "signal_name": "increment",
27222                    "payload_codec": DEFAULT_CODEC,
27223                    "value": fixture_envelope(json!([3]))
27224                }
27225            }
27226        ]);
27227
27228        let running = worker
27229            .execute_query_task(replay_counter_query(
27230                "current",
27231                running_history.clone(),
27232                "running",
27233            ))
27234            .await
27235            .expect("running replay query");
27236        assert_eq!(
27237            running.clone().into_json().expect("query projection"),
27238            json!({"loaded": "loaded", "count": 3, "finished": false})
27239        );
27240
27241        let detached = worker
27242            .execute_query_task(replay_counter_query(
27243                "detached-mutation",
27244                running_history.clone(),
27245                "running",
27246            ))
27247            .await
27248            .expect("query mutates only its detached state clone");
27249        assert_eq!(detached.into_json().expect("query projection"), json!(999));
27250        let failed = worker
27251            .execute_query_task(replay_counter_query(
27252                "failed-mutation",
27253                running_history.clone(),
27254                "running",
27255            ))
27256            .await
27257            .expect_err("failed query");
27258        assert_eq!(failed.reason, "query_rejected");
27259        let unchanged = worker
27260            .execute_query_task(replay_counter_query("current", running_history, "running"))
27261            .await
27262            .expect("later query reconstructs unchanged state");
27263        assert_eq!(unchanged, running);
27264
27265        let restarted_worker = replay_counter_worker();
27266        let empty_arguments = fixture_envelope(json!([]));
27267        let loaded_result = fixture_envelope(json!("loaded"));
27268        let signal_three = fixture_blob(json!([3]));
27269        let signal_five = fixture_blob(json!([5]));
27270        let restarted_task: QueryTask = serde_json::from_value(json!({
27271            "query_task_id": "query-after-restart",
27272            "workflow_id": "counter-1",
27273            "run_id": "run-counter-1",
27274            "workflow_type": "replay-counter",
27275            "query_name": "current",
27276            "payload_codec": DEFAULT_CODEC,
27277            "workflow_arguments": empty_arguments.clone(),
27278            "query_arguments": empty_arguments,
27279            "history_events": [],
27280            "history_export": {
27281                "payloads": {"codec": DEFAULT_CODEC},
27282                "history_events": [
27283                    {
27284                        "type": "ActivityCompleted",
27285                        "payload": {
27286                            "sequence": 1,
27287                            "activity_type": "load-counter",
27288                            "payload_codec": DEFAULT_CODEC,
27289                            "result": null
27290                        }
27291                    },
27292                    {
27293                        "type": "SignalWaitOpened",
27294                        "payload": {
27295                            "sequence": 3,
27296                            "signal_name": "increment"
27297                        }
27298                    },
27299                    {
27300                        "type": "SignalReceived",
27301                        "payload": {
27302                            "signal_id": "signal-3",
27303                            "signal_name": "increment",
27304                            "workflow_sequence": 2
27305                        }
27306                    },
27307                    {
27308                        "type": "SignalApplied",
27309                        "payload": {
27310                            "sequence": 3,
27311                            "signal_id": "signal-3",
27312                            "signal_name": "increment"
27313                        }
27314                    },
27315                    {
27316                        "type": "SignalWaitOpened",
27317                        "payload": {
27318                            "sequence": 5,
27319                            "signal_name": "increment"
27320                        }
27321                    },
27322                    {
27323                        "type": "SignalReceived",
27324                        "payload": {
27325                            "signal_id": "signal-5",
27326                            "signal_name": "increment",
27327                            "workflow_sequence": 4
27328                        }
27329                    },
27330                    {
27331                        "type": "SignalApplied",
27332                        "payload": {
27333                            "sequence": 5,
27334                            "signal_id": "signal-5",
27335                            "signal_name": "increment"
27336                        }
27337                    }
27338                ],
27339                "activities": [{
27340                    "sequence": 1,
27341                    "activity_type": "load-counter",
27342                    "payload_codec": DEFAULT_CODEC,
27343                    "result": loaded_result
27344                }],
27345                "signals": [
27346                    {
27347                        "id": "signal-3",
27348                        "name": "increment",
27349                        "workflow_sequence": 2,
27350                        "payload_codec": DEFAULT_CODEC,
27351                        "arguments": signal_three
27352                    },
27353                    {
27354                        "id": "signal-5",
27355                        "name": "increment",
27356                        "workflow_sequence": 4,
27357                        "payload_codec": DEFAULT_CODEC,
27358                        "arguments": signal_five
27359                    }
27360                ]
27361            },
27362            "run_status": "completed"
27363        }))
27364        .expect("cold replay query task");
27365        let completed = restarted_worker
27366            .execute_query_task(restarted_task)
27367            .await
27368            .expect("completed cold replay query");
27369        assert_eq!(
27370            completed.into_json().expect("query projection"),
27371            json!({"loaded": "loaded", "count": 8, "finished": true})
27372        );
27373    }
27374
27375    #[tokio::test]
27376    async fn replayed_query_replay_failures_are_machine_readable() {
27377        let worker = replay_counter_worker();
27378        let task = replay_counter_query(
27379            "current",
27380            json!([{
27381                "type": "ActivityCompleted",
27382                "payload": {
27383                    "sequence": 1,
27384                    "payload_codec": DEFAULT_CODEC,
27385                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
27386                }
27387            }]),
27388            "running",
27389        );
27390        let failure = worker
27391            .execute_query_task(task)
27392            .await
27393            .expect_err("invalid replay history payload");
27394        assert_eq!(failure.reason, "query_payload_decode_failed");
27395        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
27396        assert!(failure.message.contains("invalid_payload_framing"));
27397    }
27398
27399    #[tokio::test]
27400    async fn query_task_restores_compact_history_from_export() {
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("counter", "current", |ctx, _args| async move {
27405            Ok(json!(ctx.signals("increment")[0][0]))
27406        });
27407        let empty_arguments = fixture_envelope(json!([]));
27408        let exported_signal = fixture_blob(json!([9]));
27409        let task: QueryTask = serde_json::from_value(json!({
27410            "query_task_id": "query-export",
27411            "workflow_type": "counter",
27412            "query_name": "current",
27413            "payload_codec": DEFAULT_CODEC,
27414            "workflow_arguments": empty_arguments.clone(),
27415            "query_arguments": empty_arguments,
27416            "history_events": [],
27417            "history_export": {
27418                "payloads": {"codec": DEFAULT_CODEC},
27419                "history_events": [{
27420                    "type": "SignalReceived",
27421                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
27422                }],
27423                "signals": [{
27424                    "id": "signal-export",
27425                    "name": "increment",
27426                    "status": "applied",
27427                    "workflow_sequence": 1,
27428                    "payload_codec": DEFAULT_CODEC,
27429                    "arguments": exported_signal
27430                }]
27431            }
27432        }))
27433        .expect("query task");
27434
27435        let result = worker.execute_query_task(task).await.expect("query result");
27436        assert_eq!(result.into_json().expect("query projection"), json!(9));
27437    }
27438
27439    #[tokio::test]
27440    async fn query_task_failures_have_stable_reasons() {
27441        let client = Client::new("http://127.0.0.1:8080").expect("client");
27442        let mut worker = Worker::new(client, "rust-workers");
27443        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27444        worker.register_query(
27445            "counter",
27446            "current",
27447            |_ctx, _args| async move { Ok(json!(0)) },
27448        );
27449
27450        let base_task = QueryTask {
27451            query_task_id: "query-errors".to_string(),
27452            observability_context: None,
27453            dispatch_observability_context: None,
27454            observability_links: None,
27455            query_task_attempt: 1,
27456            lease_owner: None,
27457            workflow_id: Some("counter-errors".to_string()),
27458            run_id: Some("run-errors".to_string()),
27459            workflow_type: "counter".to_string(),
27460            query_name: "missing".to_string(),
27461            payload_codec: DEFAULT_CODEC.to_string(),
27462            workflow_arguments: Some(fixture_envelope(json!([]))),
27463            query_arguments: Some(fixture_envelope(json!([]))),
27464            history_events: Vec::new(),
27465            history_export: None,
27466            run_status: Some("running".to_string()),
27467        };
27468
27469        let unknown = worker
27470            .execute_query_task(base_task.clone())
27471            .await
27472            .expect_err("unknown query");
27473        assert_eq!(unknown.reason, "rejected_unknown_query");
27474
27475        let mut malformed = base_task;
27476        malformed.query_name = "current".to_string();
27477        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
27478        let malformed = worker
27479            .execute_query_task(malformed)
27480            .await
27481            .expect_err("malformed payload");
27482        assert_eq!(malformed.reason, "query_payload_decode_failed");
27483
27484        let client = Client::new("http://127.0.0.1:8080").expect("client");
27485        let mut unavailable_worker = Worker::new(client, "rust-workers");
27486        unavailable_worker
27487            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27488        let empty_arguments = fixture_envelope(json!([]));
27489        let unavailable_task: QueryTask = serde_json::from_value(json!({
27490            "query_task_id": "query-unavailable",
27491            "workflow_type": "counter",
27492            "query_name": "current",
27493            "payload_codec": DEFAULT_CODEC,
27494            "workflow_arguments": empty_arguments.clone(),
27495            "query_arguments": empty_arguments
27496        }))
27497        .expect("query task");
27498        let unavailable = unavailable_worker
27499            .execute_query_task(unavailable_task)
27500            .await
27501            .expect_err("query handler unavailable");
27502        assert_eq!(unavailable.reason, "query_handler_unavailable");
27503    }
27504
27505    #[tokio::test]
27506    async fn client_query_decodes_result_and_typed_failure() {
27507        let server = MockWorkerServer::start();
27508        let client = Client::builder(server.base_url())
27509            .timeout(Duration::from_secs(2))
27510            .build()
27511            .expect("client");
27512
27513        let result = client
27514            .query_workflow("counter-1", "current", json!([]))
27515            .await
27516            .expect("query result");
27517        assert_eq!(result, json!({"count": 8}));
27518
27519        let error = client
27520            .query_workflow("counter-1", "missing", json!([]))
27521            .await
27522            .expect_err("unknown query");
27523        let Error::QueryFailed(failure) = error else {
27524            panic!("expected typed query failure");
27525        };
27526        assert_eq!(failure.status, 404);
27527        assert_eq!(failure.reason, "rejected_unknown_query");
27528    }
27529
27530    const KEYED_SIGNAL_PATH: &str = "/api/workflows/keyed-1/signal/approve";
27531    const KEYED_RUN_SIGNAL_PATH: &str = "/api/workflows/keyed-1/runs/run-keyed-1/signal/approve";
27532    const KEYED_UPDATE_PATH: &str = "/api/workflows/keyed-1/update/adjust";
27533
27534    #[cfg(feature = "telemetry")]
27535    #[tokio::test]
27536    async fn optional_observability_client_uses_actual_discovery_and_preserves_business_intent() {
27537        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
27538        static PHASE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
27539        PHASE.store(0, Ordering::SeqCst);
27540        use opentelemetry::{
27541            propagation::TextMapPropagator,
27542            trace::{FutureExt, TracerProvider},
27543        };
27544        use opentelemetry_sdk::propagation::TraceContextPropagator;
27545        struct Restore;
27546        impl Drop for Restore {
27547            fn drop(&mut self) {
27548                opentelemetry::global::set_text_map_propagator(
27549                    opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
27550                );
27551            }
27552        }
27553        let _restore = Restore;
27554        opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());
27555        let headers = HashMap::from([(
27556            "traceparent".to_string(),
27557            "00-12345678901234567890123456789012-1234567890123456-01".to_string(),
27558        )]);
27559        let parent = TraceContextPropagator::new().extract(&headers);
27560        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27561            request_override: Some(|path, body, _number| {
27562                if path == "/api/cluster/info" {
27563                    return Some(if PHASE.load(Ordering::SeqCst) == 2 {
27564                        ("503 Service Unavailable", "{}".into())
27565                    } else {
27566                        ("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
27567                            "supported": true, "schema": "durable-workflow.trace-context", "version": if PHASE.load(Ordering::SeqCst) == 0 {1} else {99},
27568                            "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
27569                            "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
27570                        }}}}).to_string())
27571                    });
27572                }
27573                let body: Value = serde_json::from_str(body).ok()?;
27574                Some(("200 OK", json!({"workflow_id": "order", "run_id": "run", "workflow_type": "orders",
27575                    "outcome": "accepted", "command_id": "command", "request_id": body["request_id"],
27576                    "result": "original"}).to_string()))
27577            }),
27578            ..MockWorkerBehavior::default()
27579        });
27580        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder().build();
27581        let client = Client::new(server.base_url()).unwrap().with_telemetry(
27582            telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test")),
27583        );
27584        let input = json!([{"observability_context": {"business": "preserved"}}]);
27585        async {
27586            client
27587                .start_workflow("orders", "orders", "order", &input)
27588                .await
27589                .unwrap();
27590            assert!(server
27591                .request_body("/api/workflows")
27592                .get("observability_context")
27593                .is_none());
27594            client.cluster_info().await.unwrap();
27595            client
27596                .start_workflow("orders", "orders", "order", &input)
27597                .await
27598                .unwrap();
27599            client
27600                .signal_workflow_with_request_id("order", "ready", &input, "signal-original")
27601                .await
27602                .unwrap();
27603            client
27604                .update_workflow("order", "status", &input, Some("update-original"))
27605                .await
27606                .unwrap();
27607            client
27608                .cancel_workflow("order", WorkflowCommandOptions::default())
27609                .await
27610                .unwrap();
27611            for path in [
27612                "/api/workflows",
27613                "/api/workflows/order/signal/ready",
27614                "/api/workflows/order/update/status",
27615                "/api/workflows/order/cancel",
27616            ] {
27617                let bodies = server.request_bodies(path);
27618                let body = bodies.last().unwrap();
27619                assert_eq!(
27620                    body["observability_context"]["carrier"]["traceparent"],
27621                    headers["traceparent"]
27622                );
27623                assert!(body["observability_context"]["carrier"]
27624                    .get("baggage")
27625                    .is_none());
27626            }
27627            let starts = server.request_bodies("/api/workflows");
27628            assert_eq!(
27629                decode_wire_value(&starts[1]["input"], DEFAULT_CODEC).unwrap(),
27630                input
27631            );
27632            assert_eq!(
27633                server.request_body("/api/workflows/order/signal/ready")["request_id"],
27634                "signal-original"
27635            );
27636            assert_eq!(
27637                server.request_body("/api/workflows/order/update/status")["request_id"],
27638                "update-original"
27639            );
27640            PHASE.store(1, Ordering::SeqCst);
27641            client.cluster_info().await.unwrap();
27642            client
27643                .start_workflow("orders", "orders", "order", &input)
27644                .await
27645                .unwrap();
27646            assert!(server
27647                .request_bodies("/api/workflows")
27648                .last()
27649                .unwrap()
27650                .get("observability_context")
27651                .is_none());
27652            PHASE.store(2, Ordering::SeqCst);
27653            assert!(client.cluster_info().await.is_err());
27654            let before = server.captured_paths().len();
27655            client
27656                .start_workflow("orders", "orders", "order", &input)
27657                .await
27658                .unwrap();
27659            assert_eq!(server.captured_paths().len(), before + 1);
27660            assert!(server
27661                .request_bodies("/api/workflows")
27662                .last()
27663                .unwrap()
27664                .get("observability_context")
27665                .is_none());
27666        }
27667        .with_context(parent)
27668        .await;
27669    }
27670
27671    #[cfg(feature = "telemetry")]
27672    fn observability_worker_server(
27673        path: &str,
27674        _body: &str,
27675        _: usize,
27676    ) -> Option<(&'static str, String)> {
27677        let context = json!({"schema": "durable-workflow.trace-context", "version": 1,
27678            "carrier": {"traceparent": "00-12345678901234567890123456789012-1234567890123456-01",
27679                        "baggage": "credential=private"}});
27680        let link_context = json!({"schema": "durable-workflow.trace-context", "version": 1,
27681            "carrier": {"traceparent": "00-abcdef78901234567890123456789012-abcdef7890123456-01"}});
27682        if path == "/api/cluster/info" {
27683            return Some(("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
27684                "supported": true, "schema": "durable-workflow.trace-context", "version": 1,
27685                "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
27686                "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
27687            }}}}).to_string()));
27688        }
27689        if path.ends_with("/complete") {
27690            return Some(("200 OK", json!({"recorded": true}).to_string()));
27691        }
27692        let task_id = match path {
27693            "/api/worker/workflow-tasks/poll" => "workflow-task",
27694            "/api/worker/activity-tasks/poll" => "activity-task",
27695            "/api/worker/query-tasks/poll" => "query-task",
27696            _ => return None,
27697        };
27698        let input = encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap();
27699        let mut task = json!({"task_id": task_id, "query_task_id": task_id,
27700        "workflow_id": "workflow", "run_id": "run", "workflow_type": "wire.workflow",
27701        "activity_type": "wire.activity", "activity_execution_id": "activity",
27702        "activity_attempt_id": "attempt", "attempt_number": 3, "workflow_task_attempt": 1,
27703        "query_task_attempt": 1, "query_name": "state", "lease_owner": "test-worker",
27704        "namespace": "shipping", "task_queue": "shipping", "lease_expires_at": "2099-01-01T00:00:00Z",
27705        "payload_codec": DEFAULT_CODEC, "arguments": input, "workflow_arguments": input,
27706        "query_arguments": input, "history_events": [], "observability_context": context,
27707        "dispatch_observability_context": {"schema": "durable-workflow.queue-trace", "version": 1,
27708            "task_id": task_id, "context": link_context},
27709        "observability_links": {"schema": "durable-workflow.trace-links", "version": 1,
27710            "task_id": task_id, "run_id": "run", "namespace": "shipping", "links": [
27711                {"kind": "command", "command_id": "accepted-command", "context": link_context},
27712                {"kind": "child_outcome", "workflow_link_id": "link", "child_run_id": "child",
27713                 "child_task_id": null, "event_id": "terminal", "sequence": 7,
27714                 "event_type": "WorkflowCancelled", "context": link_context}
27715            ]}});
27716        if task_id == "workflow-task" {
27717            task["arguments"] = encode_value_envelope(
27718                &json!([{"observability_context": {"business": "preserved"}}]),
27719                DEFAULT_CODEC,
27720            )
27721            .unwrap();
27722        }
27723        Some((
27724            "200 OK",
27725            json!({"task": task, "poll_status": "leased"}).to_string(),
27726        ))
27727    }
27728
27729    #[cfg(feature = "telemetry")]
27730    #[tokio::test]
27731    async fn observability_polled_tasks_recover_parent_links_and_capture_the_actual_child_producer()
27732    {
27733        use opentelemetry::trace::TracerProvider;
27734        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
27735        opentelemetry::global::set_text_map_propagator(
27736            opentelemetry_sdk::propagation::TraceContextPropagator::new(),
27737        );
27738        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
27739        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
27740            .with_simple_exporter(exporter.clone())
27741            .build();
27742        let telemetry = telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test"));
27743        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27744            request_override: Some(observability_worker_server),
27745            ..MockWorkerBehavior::default()
27746        });
27747        let client = Client::builder(server.base_url())
27748            .namespace("shipping")
27749            .build()
27750            .unwrap();
27751        client.cluster_info().await.unwrap();
27752        let mut worker = Worker::new(client, "shipping")
27753            .worker_id("test-worker")
27754            .telemetry(telemetry);
27755        worker.register_workflow("wire.workflow", |ctx, input| async move {
27756            assert_eq!(telemetry::current_log_context()["workflow_run_id"], "run");
27757            assert_eq!(
27758                input,
27759                json!([{"observability_context": {"business": "preserved"}}])
27760            );
27761            ctx.start_child_workflow("child", ChildWorkflowOptions::new("child-workers"), input)
27762                .await?;
27763            Ok(Value::Null)
27764        });
27765        worker.register_activity("wire.activity", |_, _| async {
27766            let fields = telemetry::current_log_context();
27767            assert_eq!(fields["workflow_run_id"], "run");
27768            assert_eq!(fields["activity_id"], "activity");
27769            assert_eq!(fields["activity_attempt_id"], "attempt");
27770            assert_eq!(fields["activity_attempt_number"], "3");
27771            Ok(json!("original-result"))
27772        });
27773        worker.register_query("wire.workflow", "state", |_, _| async {
27774            assert_eq!(telemetry::current_log_context()["task_id"], "query-task");
27775            Ok(json!("original-query"))
27776        });
27777        assert_eq!(worker.run_once().await.unwrap(), 3);
27778        let spans = exporter.get_finished_spans().unwrap();
27779        assert_eq!(spans.len(), 4);
27780        let origin_trace = "12345678901234567890123456789012";
27781        for span in spans
27782            .iter()
27783            .filter(|span| span.name.as_ref() != "durable.activity.attempt")
27784        {
27785            assert_eq!(span.span_context.trace_id().to_string(), origin_trace);
27786            assert_eq!(span.parent_span_id.to_string(), "1234567890123456");
27787            assert_eq!(span.links.len(), 3);
27788            assert!(!format!("{:?}", span.attributes).contains("credential"));
27789        }
27790        let task = spans
27791            .iter()
27792            .find(|span| span.name.as_ref() == "durable.workflow.task")
27793            .unwrap();
27794        let body = server.request_body("/api/worker/workflow-tasks/workflow-task/complete");
27795        assert_eq!(body["commands"][0]["type"], "start_child_workflow");
27796        let parent = body["commands"][0]["observability_context"]["carrier"]["traceparent"]
27797            .as_str()
27798            .unwrap();
27799        assert_eq!(&parent[36..52], task.span_context.span_id().to_string());
27800        assert!(telemetry::current_log_context().is_empty());
27801        opentelemetry::global::set_text_map_propagator(
27802            opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
27803        );
27804    }
27805
27806    #[cfg(feature = "telemetry")]
27807    #[tokio::test]
27808    async fn observability_never_enters_a_query_with_a_refused_original_claim() {
27809        use opentelemetry::trace::TracerProvider;
27810        static REFUSAL: AtomicUsize = AtomicUsize::new(0);
27811        fn refused_query(path: &str, body: &str, count: usize) -> Option<(&'static str, String)> {
27812            let (status, reply) = observability_worker_server(path, body, count)?;
27813            if path != "/api/worker/query-tasks/poll" {
27814                return Some((status, reply));
27815            }
27816            let mut reply: Value = serde_json::from_str(&reply).unwrap();
27817            match REFUSAL.load(Ordering::SeqCst) {
27818                0 => reply["task"]["lease_owner"] = json!("other-worker"),
27819                1 => reply["task"]["query_task_attempt"] = json!(0),
27820                _ => reply["task"]["lease_expires_at"] = json!("2000-01-01T00:00:00Z"),
27821            }
27822            Some((status, reply.to_string()))
27823        }
27824        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
27825        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
27826            .with_simple_exporter(exporter.clone())
27827            .build();
27828        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27829            request_override: Some(refused_query),
27830            ..MockWorkerBehavior::default()
27831        });
27832        let client = Client::builder(server.base_url())
27833            .namespace("shipping")
27834            .build()
27835            .unwrap();
27836        client.cluster_info().await.unwrap();
27837        let mut worker = Worker::new(client, "shipping")
27838            .worker_id("test-worker")
27839            .telemetry(telemetry::ExecutionTelemetry::from_tracer(
27840                provider.tracer("test"),
27841            ));
27842        let calls = Arc::new(AtomicUsize::new(0));
27843        let query_calls = calls.clone();
27844        worker.register_query("wire.workflow", "state", move |_, _| {
27845            query_calls.fetch_add(1, Ordering::SeqCst);
27846            async { Ok(Value::Null) }
27847        });
27848        for refusal in 0..3 {
27849            REFUSAL.store(refusal, Ordering::SeqCst);
27850            assert!(matches!(
27851                worker.poll_query_once().await.unwrap(),
27852                ManagedPollOutcome::Handled
27853            ));
27854            assert_eq!(calls.load(Ordering::SeqCst), 0);
27855            assert!(exporter.get_finished_spans().unwrap().is_empty());
27856            assert!(telemetry::current_log_context().is_empty());
27857        }
27858        assert!(!server
27859            .captured_paths()
27860            .iter()
27861            .any(|path| path.ends_with("/complete") || path.ends_with("/fail")));
27862    }
27863
27864    fn keyed_command_request(path: &str, body: &str) -> Option<Value> {
27865        if path != KEYED_SIGNAL_PATH && path != KEYED_RUN_SIGNAL_PATH && path != KEYED_UPDATE_PATH {
27866            return None;
27867        }
27868        serde_json::from_str(body).ok()
27869    }
27870
27871    /// A #216 Server: echoes the key with `retained` and `intent_verified`.
27872    fn keyed_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27873        let request = keyed_command_request(path, body)?;
27874        let mut receipt = json!({
27875            "outcome": "accepted",
27876            "command_status": "accepted",
27877            "command_id": "cmd-keyed-1",
27878            "request_id": request["request_id"],
27879            "retained": false,
27880            "intent_verified": true,
27881        });
27882        if path == KEYED_UPDATE_PATH {
27883            receipt["update_id"] = json!("upd-keyed-1");
27884            receipt["result_envelope"] =
27885                encode_typed_envelope(&AvroValue::Long(42), DEFAULT_CODEC).expect("result");
27886        }
27887        Some(("202 Accepted", receipt.to_string()))
27888    }
27889
27890    /// A Server released before #216: accepts the body field but echoes nothing.
27891    fn legacy_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27892        keyed_command_request(path, body)?;
27893        Some((
27894            "202 Accepted",
27895            r#"{"outcome":"accepted","command_status":"accepted","command_id":"cmd-legacy"}"#
27896                .to_string(),
27897        ))
27898    }
27899
27900    fn retained_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27901        let request = keyed_command_request(path, body)?;
27902        Some((
27903            "202 Accepted",
27904            json!({
27905                "outcome": "accepted",
27906                "command_status": "accepted",
27907                "command_id": "cmd-first",
27908                "request_id": request["request_id"],
27909                "retained": true,
27910                "intent_verified": true,
27911            })
27912            .to_string(),
27913        ))
27914    }
27915
27916    fn conflicting_command_server(
27917        path: &str,
27918        body: &str,
27919        _: usize,
27920    ) -> Option<(&'static str, String)> {
27921        let request = keyed_command_request(path, body)?;
27922        let retained_type = if path == KEYED_UPDATE_PATH {
27923            "update"
27924        } else {
27925            "signal"
27926        };
27927        Some((
27928            "409 Conflict",
27929            json!({
27930                "reason": "request_id_conflict",
27931                "message": format!("request id is retained for a different {retained_type} intent"),
27932                "request_id": request["request_id"],
27933                "retained_command_id": "cmd-retained-1",
27934                "retained_command_type": retained_type,
27935                "retained_outcome": "accepted",
27936                "conflict": ["arguments", "target"],
27937                "control_plane": {"operation": retained_type},
27938            })
27939            .to_string(),
27940        ))
27941    }
27942
27943    fn closed_run_command_server(
27944        path: &str,
27945        body: &str,
27946        _: usize,
27947    ) -> Option<(&'static str, String)> {
27948        let request = keyed_command_request(path, body)?;
27949        Some((
27950            "409 Conflict",
27951            json!({
27952                "reason": "run_not_active",
27953                "message": "run is closed",
27954                "request_id": request["request_id"],
27955            })
27956            .to_string(),
27957        ))
27958    }
27959
27960    fn drop_first_keyed_signal(path: &str, request_number: usize) -> bool {
27961        path == KEYED_SIGNAL_PATH && request_number == 1
27962    }
27963
27964    fn keyed_client(server: &MockWorkerServer) -> Client {
27965        Client::builder(server.base_url())
27966            .timeout(Duration::from_secs(2))
27967            .build()
27968            .expect("client")
27969    }
27970
27971    fn keyed_handle(client: &Client) -> WorkflowHandle {
27972        WorkflowHandle {
27973            client: client.clone(),
27974            workflow_id: "keyed-1".to_string(),
27975            run_id: Some("run-keyed-1".to_string()),
27976            workflow_type: "keyed".to_string(),
27977        }
27978    }
27979
27980    fn assert_generated_request_id(request_id: &str, prefix: &str) {
27981        let suffix = request_id
27982            .strip_prefix(prefix)
27983            .unwrap_or_else(|| panic!("{request_id:?} does not start with {prefix:?}"));
27984        assert_eq!(suffix.len(), 32, "uuid4 simple hex suffix: {request_id:?}");
27985        assert!(
27986            suffix
27987                .bytes()
27988                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()),
27989            "lowercase hex suffix: {request_id:?}"
27990        );
27991        assert!(request_id.len() <= MAX_REQUEST_ID_CHARACTERS);
27992    }
27993
27994    fn assert_key_sent_only_in_body(server: &MockWorkerServer, path: &str) {
27995        let headers = server.request_headers(path);
27996        assert!(!headers.is_empty(), "no request captured for {path}");
27997        for headers in headers {
27998            let header_names: Vec<String> = headers
27999                .lines()
28000                .skip(1)
28001                .filter_map(|line| line.split_once(':'))
28002                .map(|(name, _)| name.trim().to_ascii_lowercase())
28003                .collect();
28004            assert!(
28005                !header_names.iter().any(|name| name == "x-request-id"),
28006                "the caller command key is a body field, never an X-Request-Id header: {headers}"
28007            );
28008        }
28009    }
28010
28011    #[tokio::test]
28012    async fn signal_without_key_sends_a_generated_sdk_rust_signal_key_and_returns_it() {
28013        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28014            request_override: Some(legacy_command_server),
28015            ..MockWorkerBehavior::default()
28016        });
28017        let client = keyed_client(&server);
28018
28019        let receipt = client
28020            .signal_workflow("keyed-1", "approve", json!(["ok"]))
28021            .await
28022            .expect("signal receipt");
28023
28024        let sent = server.request_body(KEYED_SIGNAL_PATH);
28025        let request_id = sent["request_id"].as_str().expect("generated request_id");
28026        assert_generated_request_id(request_id, "sdk-rust-signal-");
28027        assert_eq!(
28028            receipt,
28029            json!({
28030                "outcome": "accepted",
28031                "command_status": "accepted",
28032                "command_id": "cmd-legacy",
28033                "request_id": request_id,
28034            }),
28035            "the sent key is added when an older Server omits it"
28036        );
28037        assert_key_sent_only_in_body(&server, KEYED_SIGNAL_PATH);
28038
28039        let receipt = keyed_handle(&client)
28040            .signal_selected_run("approve", json!(["ok"]))
28041            .await
28042            .expect("selected-run signal receipt");
28043        let run_sent = server.request_body(KEYED_RUN_SIGNAL_PATH);
28044        let run_request_id = run_sent["request_id"]
28045            .as_str()
28046            .expect("generated request_id");
28047        assert_generated_request_id(run_request_id, "sdk-rust-signal-");
28048        assert_eq!(receipt["request_id"], run_request_id);
28049        assert_ne!(
28050            run_request_id, request_id,
28051            "each logical call gets its own key"
28052        );
28053        assert_key_sent_only_in_body(&server, KEYED_RUN_SIGNAL_PATH);
28054    }
28055
28056    #[tokio::test]
28057    async fn update_without_key_sends_a_generated_sdk_rust_update_key() {
28058        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28059            request_override: Some(keyed_command_server),
28060            ..MockWorkerBehavior::default()
28061        });
28062        let client = keyed_client(&server);
28063
28064        let result = client
28065            .update_workflow("keyed-1", "adjust", json!([1]), None)
28066            .await
28067            .expect("update result");
28068        assert_eq!(
28069            result,
28070            json!(42),
28071            "the decoded update result is returned unchanged"
28072        );
28073        let typed = client
28074            .update_workflow_avro_value("keyed-1", "adjust", json!([1]), None)
28075            .await
28076            .expect("typed update result");
28077        assert_eq!(typed, AvroValue::Long(42));
28078        keyed_handle(&client)
28079            .update("adjust", json!([1]), None)
28080            .await
28081            .expect("handle update result");
28082
28083        let bodies = server.request_bodies(KEYED_UPDATE_PATH);
28084        assert_eq!(bodies.len(), 3);
28085        for body in &bodies {
28086            assert_generated_request_id(
28087                body["request_id"].as_str().expect("generated request_id"),
28088                "sdk-rust-update-",
28089            );
28090            assert_eq!(body["wait_for"], "completed");
28091        }
28092        assert_ne!(bodies[0]["request_id"], bodies[1]["request_id"]);
28093        assert_ne!(bodies[1]["request_id"], bodies[2]["request_id"]);
28094        assert_key_sent_only_in_body(&server, KEYED_UPDATE_PATH);
28095    }
28096
28097    #[tokio::test]
28098    async fn explicit_command_keys_are_sent_verbatim_as_the_request_id_body_field() {
28099        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28100            request_override: Some(keyed_command_server),
28101            ..MockWorkerBehavior::default()
28102        });
28103        let client = keyed_client(&server);
28104        let handle = keyed_handle(&client);
28105
28106        let receipt = client
28107            .signal_workflow_with_request_id(
28108                "keyed-1",
28109                "approve",
28110                json!(["ok"]),
28111                "Order-42/approve",
28112            )
28113            .await
28114            .expect("signal receipt");
28115        assert_eq!(receipt["request_id"], "Order-42/approve");
28116        assert_eq!(receipt["retained"], false);
28117        assert_eq!(receipt["intent_verified"], true);
28118        handle
28119            .signal_with_request_id("approve", json!(["ok"]), "handle-signal-key")
28120            .await
28121            .expect("handle signal receipt");
28122        client
28123            .signal_workflow_run_with_request_id(
28124                "keyed-1",
28125                "run-keyed-1",
28126                "approve",
28127                json!(["ok"]),
28128                "run-signal-key",
28129            )
28130            .await
28131            .expect("selected-run signal receipt");
28132        handle
28133            .signal_selected_run_with_request_id("approve", json!(["ok"]), "handle-run-signal-key")
28134            .await
28135            .expect("handle selected-run signal receipt");
28136        let result = client
28137            .update_workflow("keyed-1", "adjust", json!([1]), Some("update-key"))
28138            .await
28139            .expect("update result");
28140        assert_eq!(result, json!(42));
28141        handle
28142            .update("adjust", json!([1]), Some("handle-update-key"))
28143            .await
28144            .expect("handle update result");
28145        handle
28146            .update_avro_value("adjust", json!([1]), Some("handle-typed-update-key"))
28147            .await
28148            .expect("handle typed update result");
28149
28150        let signal_keys: Vec<Value> = server
28151            .request_bodies(KEYED_SIGNAL_PATH)
28152            .into_iter()
28153            .map(|body| body["request_id"].clone())
28154            .collect();
28155        assert_eq!(
28156            signal_keys,
28157            [json!("Order-42/approve"), json!("handle-signal-key")]
28158        );
28159        let run_signal_keys: Vec<Value> = server
28160            .request_bodies(KEYED_RUN_SIGNAL_PATH)
28161            .into_iter()
28162            .map(|body| body["request_id"].clone())
28163            .collect();
28164        assert_eq!(
28165            run_signal_keys,
28166            [json!("run-signal-key"), json!("handle-run-signal-key")]
28167        );
28168        let update_keys: Vec<Value> = server
28169            .request_bodies(KEYED_UPDATE_PATH)
28170            .into_iter()
28171            .map(|body| body["request_id"].clone())
28172            .collect();
28173        assert_eq!(
28174            update_keys,
28175            [
28176                json!("update-key"),
28177                json!("handle-update-key"),
28178                json!("handle-typed-update-key")
28179            ]
28180        );
28181        for path in [KEYED_SIGNAL_PATH, KEYED_RUN_SIGNAL_PATH, KEYED_UPDATE_PATH] {
28182            assert_key_sent_only_in_body(&server, path);
28183        }
28184    }
28185
28186    #[tokio::test]
28187    async fn retained_receipts_are_returned_unchanged() {
28188        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28189            request_override: Some(retained_command_server),
28190            ..MockWorkerBehavior::default()
28191        });
28192        let client = keyed_client(&server);
28193
28194        let receipt = client
28195            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "retry-key")
28196            .await
28197            .expect("retained receipt");
28198
28199        assert_eq!(
28200            receipt,
28201            json!({
28202                "outcome": "accepted",
28203                "command_status": "accepted",
28204                "command_id": "cmd-first",
28205                "request_id": "retry-key",
28206                "retained": true,
28207                "intent_verified": true,
28208            })
28209        );
28210    }
28211
28212    #[tokio::test]
28213    async fn request_id_conflict_refusal_keeps_error_http_and_classifies_the_sent_key() {
28214        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28215            request_override: Some(conflicting_command_server),
28216            ..MockWorkerBehavior::default()
28217        });
28218        let client = keyed_client(&server);
28219
28220        let error = client
28221            .signal_workflow_with_request_id(
28222                "keyed-1",
28223                "approve",
28224                json!(["changed"]),
28225                "Order-42/approve",
28226            )
28227            .await
28228            .expect_err("different intent under a retained key");
28229        assert!(
28230            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT),
28231            "existing Error::Http matching keeps working: {error:?}"
28232        );
28233        assert!(error.is_request_id_conflict());
28234        assert_eq!(error.request_id().as_deref(), Some("Order-42/approve"));
28235        let conflict = error.request_id_conflict().expect("conflict details");
28236        assert_eq!(conflict.status, 409);
28237        assert_eq!(conflict.request_id, "Order-42/approve");
28238        assert_eq!(
28239            conflict.message,
28240            "request id is retained for a different signal intent"
28241        );
28242        assert_eq!(
28243            conflict.retained_command_id.as_deref(),
28244            Some("cmd-retained-1")
28245        );
28246        assert_eq!(conflict.retained_command_type.as_deref(), Some("signal"));
28247        assert_eq!(conflict.retained_outcome.as_deref(), Some("accepted"));
28248        assert_eq!(conflict.conflict, ["arguments", "target"]);
28249        assert_eq!(conflict.body["control_plane"]["operation"], "signal");
28250
28251        let error = client
28252            .update_workflow("keyed-1", "adjust", json!([2]), None)
28253            .await
28254            .expect_err("different intent under a retained generated key");
28255        let sent = server.request_body(KEYED_UPDATE_PATH);
28256        assert_eq!(
28257            error.request_id(),
28258            sent["request_id"].as_str().map(str::to_string)
28259        );
28260        assert_eq!(
28261            error
28262                .request_id_conflict()
28263                .expect("conflict details")
28264                .retained_command_type
28265                .as_deref(),
28266            Some("update")
28267        );
28268    }
28269
28270    #[tokio::test]
28271    async fn other_refusals_echoing_the_key_are_not_request_id_conflicts() {
28272        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28273            request_override: Some(closed_run_command_server),
28274            ..MockWorkerBehavior::default()
28275        });
28276        let client = keyed_client(&server);
28277
28278        let error = client
28279            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "closed-key")
28280            .await
28281            .expect_err("closed run");
28282
28283        assert!(matches!(error, Error::Http { status, .. } if status.as_u16() == 409));
28284        assert!(!error.is_request_id_conflict());
28285        assert_eq!(error.request_id_conflict(), None);
28286        assert_eq!(error.request_id().as_deref(), Some("closed-key"));
28287    }
28288
28289    #[tokio::test]
28290    async fn transport_failure_keeps_error_transport_and_the_held_key_retries_identically() {
28291        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28292            request_override: Some(keyed_command_server),
28293            drop_request: Some(drop_first_keyed_signal),
28294            ..MockWorkerBehavior::default()
28295        });
28296        let client = keyed_client(&server);
28297        let request_id = Client::generate_signal_request_id();
28298
28299        let error = client
28300            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
28301            .await
28302            .expect_err("connection closed before any response");
28303        assert!(
28304            matches!(error, Error::Transport(_)),
28305            "the transport variant is unchanged: {error:?}"
28306        );
28307        assert_eq!(
28308            error.request_id(),
28309            None,
28310            "nothing was echoed; the application holds the key it chose"
28311        );
28312
28313        let receipt = client
28314            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
28315            .await
28316            .expect("manual retry with the same key");
28317        assert_eq!(receipt["request_id"], request_id);
28318        let bodies = server.request_bodies(KEYED_SIGNAL_PATH);
28319        assert_eq!(bodies.len(), 2, "one attempt per call, no automatic retry");
28320        assert_eq!(
28321            bodies[0], bodies[1],
28322            "the retry resends the identical key and input"
28323        );
28324        assert_eq!(bodies[0]["request_id"], request_id);
28325    }
28326
28327    #[tokio::test]
28328    async fn invalid_command_keys_are_refused_before_sending() {
28329        let server = MockWorkerServer::start();
28330        let client = keyed_client(&server);
28331        let too_long = "k".repeat(MAX_REQUEST_ID_CHARACTERS + 1);
28332
28333        for request_id in ["", too_long.as_str()] {
28334            let error = client
28335                .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), request_id)
28336                .await
28337                .expect_err("invalid signal key");
28338            assert!(
28339                matches!(error, Error::Codec(ref message) if message.contains("1 to 255 Unicode characters")),
28340                "{error:?}"
28341            );
28342            let error = client
28343                .update_workflow("keyed-1", "adjust", json!([1]), Some(request_id))
28344                .await
28345                .expect_err("invalid update key");
28346            assert!(matches!(error, Error::Codec(_)), "{error:?}");
28347        }
28348        assert!(server.captured_paths().is_empty(), "nothing was sent");
28349
28350        let longest = "k".repeat(MAX_REQUEST_ID_CHARACTERS);
28351        let _ = client
28352            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &longest)
28353            .await;
28354        assert_eq!(
28355            server.request_body(KEYED_SIGNAL_PATH)["request_id"],
28356            longest
28357        );
28358    }
28359
28360    #[test]
28361    fn generated_command_keys_are_distinct_and_well_formed() {
28362        let signal = Client::generate_signal_request_id();
28363        let update = Client::generate_update_request_id();
28364        assert_generated_request_id(&signal, "sdk-rust-signal-");
28365        assert_generated_request_id(&update, "sdk-rust-update-");
28366        assert_ne!(Client::generate_signal_request_id(), signal);
28367        assert!(validate_request_id(&signal).is_ok());
28368    }
28369
28370    #[test]
28371    fn command_keys_preserve_the_published_server_unicode_character_limit() {
28372        assert!(validate_request_id(&"é".repeat(255)).is_ok());
28373        assert!(validate_request_id(&"😀".repeat(255)).is_ok());
28374        assert!(validate_request_id(&"é".repeat(256)).is_err());
28375    }
28376
28377    #[test]
28378    fn request_id_accessors_read_only_echoed_refusal_bodies() {
28379        let conflict = Error::Http {
28380            status: reqwest::StatusCode::CONFLICT,
28381            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(),
28382        };
28383        assert!(conflict.is_request_id_conflict());
28384        assert_eq!(conflict.request_id().as_deref(), Some("k1"));
28385        let details = conflict.request_id_conflict().expect("conflict details");
28386        assert_eq!(details.conflict, ["name"]);
28387        assert_eq!(
28388            details.message,
28389            "request id is retained for a different command intent"
28390        );
28391
28392        let echoed = Error::Http {
28393            status: reqwest::StatusCode::CONFLICT,
28394            body: r#"{"reason":"run_not_active","request_id":"k2"}"#.to_string(),
28395        };
28396        assert!(!echoed.is_request_id_conflict());
28397        assert_eq!(echoed.request_id().as_deref(), Some("k2"));
28398
28399        let blank = Error::Http {
28400            status: reqwest::StatusCode::UNPROCESSABLE_ENTITY,
28401            body: r#"{"request_id":""}"#.to_string(),
28402        };
28403        assert_eq!(blank.request_id(), None);
28404        let text = Error::Http {
28405            status: reqwest::StatusCode::BAD_GATEWAY,
28406            body: "upstream unavailable".to_string(),
28407        };
28408        assert_eq!(text.request_id(), None);
28409        assert!(!text.is_request_id_conflict());
28410
28411        let rejection = Error::WorkflowCommandRejected(WorkflowCommandRejection {
28412            command: WorkflowCommandKind::Cancel,
28413            status: 409,
28414            reason: "request_id_conflict".to_string(),
28415            message: "retained".to_string(),
28416            workflow_id: "wf".to_string(),
28417            run_id: None,
28418            target_scope: None,
28419            body: json!({"reason": "request_id_conflict", "request_id": "k3", "conflict": []}),
28420        });
28421        assert!(rejection.is_request_id_conflict());
28422        assert_eq!(rejection.request_id().as_deref(), Some("k3"));
28423
28424        assert_eq!(Error::Timeout.request_id(), None);
28425        assert!(!Error::Codec("local".to_string()).is_request_id_conflict());
28426    }
28427
28428    #[tokio::test]
28429    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
28430        let server = MockWorkerServer::start();
28431        let client = Client::builder(server.base_url())
28432            .timeout(Duration::from_secs(2))
28433            .build()
28434            .expect("client");
28435        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
28436
28437        client
28438            .start_workflow(
28439                "typed.echo",
28440                "rust-workers",
28441                "typed-start",
28442                arguments.clone(),
28443            )
28444            .await
28445            .expect("typed workflow start");
28446        assert_eq!(
28447            decode_wire_avro_value(
28448                &server.request_body("/api/workflows")["input"],
28449                DEFAULT_CODEC,
28450            )
28451            .expect("typed start input"),
28452            arguments
28453        );
28454
28455        client
28456            .signal_workflow("typed-1", "changed", arguments.clone())
28457            .await
28458            .expect("typed signal");
28459        assert_eq!(
28460            decode_wire_avro_value(
28461                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
28462                DEFAULT_CODEC,
28463            )
28464            .expect("typed signal input"),
28465            arguments
28466        );
28467
28468        assert_eq!(
28469            client
28470                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
28471                .await
28472                .expect("typed query"),
28473            typed_fidelity_probe()
28474        );
28475        assert_eq!(
28476            decode_wire_avro_value(
28477                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
28478                DEFAULT_CODEC,
28479            )
28480            .expect("typed query input"),
28481            arguments
28482        );
28483
28484        assert_eq!(
28485            client
28486                .update_workflow_avro_value(
28487                    "typed-1",
28488                    "replace",
28489                    arguments.clone(),
28490                    Some("typed-request"),
28491                )
28492                .await
28493                .expect("typed update"),
28494            typed_fidelity_probe()
28495        );
28496        let update = server.request_body("/api/workflows/typed-1/update/replace");
28497        assert_eq!(update["request_id"], "typed-request");
28498        assert_eq!(
28499            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
28500            arguments
28501        );
28502
28503        let handle = WorkflowHandle {
28504            client: client.clone(),
28505            workflow_id: "typed-1".to_string(),
28506            run_id: Some("run-typed-1".to_string()),
28507            workflow_type: "typed.echo".to_string(),
28508        };
28509        assert_eq!(
28510            handle
28511                .result_avro_value(WorkflowResultOptions::default())
28512                .await
28513                .expect("typed workflow result"),
28514            typed_fidelity_probe()
28515        );
28516
28517        client
28518            .complete_activity_task(
28519                "activity-typed",
28520                "attempt-typed",
28521                "rust-worker",
28522                typed_fidelity_probe(),
28523                DEFAULT_CODEC,
28524            )
28525            .await
28526            .expect("typed activity completion");
28527        assert_eq!(
28528            decode_wire_avro_value(
28529                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
28530                    ["result"],
28531                DEFAULT_CODEC,
28532            )
28533            .expect("typed activity result"),
28534            typed_fidelity_probe()
28535        );
28536        client
28537            .fail_activity_task(
28538                "activity-typed",
28539                "attempt-typed",
28540                "rust-worker",
28541                "typed failure",
28542                true,
28543            )
28544            .await
28545            .expect("activity failure");
28546    }
28547
28548    #[tokio::test]
28549    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
28550        let server = MockWorkerServer::start();
28551        let client = Client::builder(server.base_url())
28552            .timeout(Duration::from_secs(2))
28553            .build()
28554            .expect("client");
28555
28556        let options = WorkflowCommandOptions::new()
28557            .reason("cleanup requested")
28558            .request_id("cancel-17");
28559        let cancelled = client
28560            .cancel_workflow("wf-lifecycle", options)
28561            .await
28562            .expect("instance cancellation");
28563        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
28564        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
28565        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
28566        assert_eq!(
28567            server.request_body("/api/workflows/wf-lifecycle/cancel"),
28568            json!({"reason":"cleanup requested","request_id":"cancel-17"})
28569        );
28570
28571        let terminated = client
28572            .terminate_workflow(
28573                "wf-lifecycle",
28574                WorkflowCommandOptions::new().reason("forced stop"),
28575            )
28576            .await
28577            .expect("instance termination");
28578        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
28579        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
28580
28581        client
28582            .cancel_workflow_run(
28583                "wf-lifecycle",
28584                "run-current",
28585                WorkflowCommandOptions::default(),
28586            )
28587            .await
28588            .expect("selected run cancellation");
28589        client
28590            .terminate_workflow_run(
28591                "wf-lifecycle",
28592                "run-current",
28593                WorkflowCommandOptions::default(),
28594            )
28595            .await
28596            .expect("selected run termination");
28597
28598        for (command, error) in [
28599            (
28600                WorkflowCommandKind::Cancel,
28601                client
28602                    .cancel_workflow_run(
28603                        "wf-lifecycle",
28604                        "run-stale",
28605                        WorkflowCommandOptions::default(),
28606                    )
28607                    .await
28608                    .expect_err("stale cancellation must be rejected"),
28609            ),
28610            (
28611                WorkflowCommandKind::Terminate,
28612                client
28613                    .terminate_workflow_run(
28614                        "wf-lifecycle",
28615                        "run-stale",
28616                        WorkflowCommandOptions::default(),
28617                    )
28618                    .await
28619                    .expect_err("stale termination must be rejected"),
28620            ),
28621        ] {
28622            let Error::WorkflowCommandRejected(rejection) = error else {
28623                panic!("expected typed command rejection");
28624            };
28625            assert_eq!(rejection.command, command);
28626            assert_eq!(rejection.status, 409);
28627            assert_eq!(rejection.reason, "historical_run_command_rejected");
28628            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
28629            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
28630        }
28631    }
28632
28633    #[tokio::test]
28634    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
28635        let server = MockWorkerServer::start();
28636        let client = Client::builder(server.base_url())
28637            .timeout(Duration::from_secs(2))
28638            .build()
28639            .expect("client");
28640
28641        let result = client
28642            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
28643            .await
28644            .expect("redrive accepted");
28645        assert_eq!(result.workflow_id, "wf-lifecycle");
28646        assert_eq!(result.source_run_id, "run-failed");
28647        assert_eq!(result.run_id, "run-successor");
28648        assert_eq!(result.resume_step_sequence, 2);
28649        assert_eq!(
28650            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
28651            json!({"request_id":"retry-1"})
28652        );
28653
28654        let repeated = client
28655            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
28656            .await
28657            .expect("idempotent redrive response accepted");
28658        assert_eq!(repeated.run_id, "run-successor");
28659
28660        let error = client
28661            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
28662            .await
28663            .expect_err("completed run must be rejected");
28664        let Error::Http { status, body } = error else {
28665            panic!("expected HTTP redrive rejection");
28666        };
28667        assert_eq!(status.as_u16(), 409);
28668        assert!(body.contains("run_not_failed"));
28669        assert_eq!(
28670            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
28671            json!({})
28672        );
28673
28674        let handle = WorkflowHandle {
28675            client: client.clone(),
28676            workflow_id: "wf-lifecycle".to_string(),
28677            run_id: Some("run-failed".to_string()),
28678            workflow_type: "test".to_string(),
28679        };
28680        assert_eq!(
28681            handle.redrive(None).await.expect("handle redrive").run_id,
28682            "run-successor"
28683        );
28684        let missing_run = WorkflowHandle {
28685            run_id: None,
28686            ..handle
28687        };
28688        assert!(matches!(
28689            missing_run.redrive(None).await,
28690            Err(Error::Codec(_))
28691        ));
28692    }
28693
28694    #[tokio::test]
28695    async fn workflow_start_options_send_server_enforced_deadlines() {
28696        let server = MockWorkerServer::start();
28697        let client = Client::builder(server.base_url())
28698            .timeout(Duration::from_secs(2))
28699            .build()
28700            .expect("client");
28701
28702        let handle = client
28703            .start_workflow_with_options(
28704                "rust.timeout",
28705                "rust-timeouts",
28706                "wf-start-options",
28707                WorkflowStartOptions::new()
28708                    .execution_timeout_seconds(30)
28709                    .run_timeout_seconds(1),
28710                json!([]),
28711            )
28712            .await
28713            .expect("workflow start");
28714
28715        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
28716        let body = server.request_body("/api/workflows");
28717        assert_eq!(body["execution_timeout_seconds"], 30);
28718        assert_eq!(body["run_timeout_seconds"], 1);
28719
28720        let invalid = client
28721            .start_workflow_with_options(
28722                "rust.timeout",
28723                "rust-timeouts",
28724                "wf-invalid-options",
28725                WorkflowStartOptions::new()
28726                    .execution_timeout_seconds(1)
28727                    .run_timeout_seconds(2),
28728                json!([]),
28729            )
28730            .await
28731            .expect_err("invalid deadline ordering");
28732        assert!(invalid
28733            .to_string()
28734            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
28735    }
28736
28737    #[tokio::test]
28738    async fn workflow_result_returns_each_typed_terminal_outcome() {
28739        let server = MockWorkerServer::start();
28740        let client = Client::builder(server.base_url())
28741            .timeout(Duration::from_secs(2))
28742            .build()
28743            .expect("client");
28744        let options = WorkflowResultOptions {
28745            poll_interval: Duration::ZERO,
28746            timeout: Duration::from_secs(1),
28747        };
28748
28749        let failed = WorkflowHandle {
28750            client: client.clone(),
28751            workflow_id: "wf-failed".to_string(),
28752            run_id: Some("run-failed".to_string()),
28753            workflow_type: "failure".to_string(),
28754        }
28755        .result(options)
28756        .await
28757        .expect_err("failed outcome");
28758        let Error::WorkflowFailed(failure) = failed else {
28759            panic!("expected WorkflowFailed");
28760        };
28761        assert_eq!(failure.workflow_id, "wf-failed");
28762        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
28763        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
28764        assert_eq!(failure.failure_category.as_deref(), Some("application"));
28765        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
28766        assert_eq!(
28767            failure.exception_class.as_deref(),
28768            Some("billing::PaymentError")
28769        );
28770        assert_eq!(failure.non_retryable, Some(true));
28771
28772        for (workflow_id, expected_kind, expected_reason) in [
28773            (
28774                "wf-cancelled",
28775                WorkflowTerminalKind::Cancelled,
28776                "cleanup requested",
28777            ),
28778            (
28779                "wf-terminated",
28780                WorkflowTerminalKind::Terminated,
28781                "forced stop",
28782            ),
28783            (
28784                "wf-timed-out",
28785                WorkflowTerminalKind::TimedOut,
28786                "run_timeout",
28787            ),
28788        ] {
28789            let error = WorkflowHandle {
28790                client: client.clone(),
28791                workflow_id: workflow_id.to_string(),
28792                run_id: None,
28793                workflow_type: "terminal".to_string(),
28794            }
28795            .result(options)
28796            .await
28797            .expect_err("typed terminal outcome");
28798            let outcome = match error {
28799                Error::WorkflowCancelled(outcome) => outcome,
28800                Error::WorkflowTerminated(outcome) => outcome,
28801                Error::WorkflowTimedOut(outcome) => outcome,
28802                other => panic!("unexpected terminal error: {other}"),
28803            };
28804            assert_eq!(outcome.kind, expected_kind);
28805            assert_eq!(outcome.workflow_id, workflow_id);
28806            assert_eq!(outcome.reason, expected_reason);
28807        }
28808
28809        let wait_timeout = WorkflowHandle {
28810            client,
28811            workflow_id: "wf-waiting".to_string(),
28812            run_id: Some("run-waiting".to_string()),
28813            workflow_type: "waiting".to_string(),
28814        }
28815        .result(WorkflowResultOptions {
28816            poll_interval: Duration::ZERO,
28817            timeout: Duration::ZERO,
28818        })
28819        .await
28820        .expect_err("client wait timeout");
28821        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
28822            panic!("expected typed client timeout");
28823        };
28824        assert_eq!(timeout.reason, "result_wait_timeout");
28825        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
28826        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
28827    }
28828
28829    #[tokio::test]
28830    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
28831        let server = MockWorkerServer::start();
28832        let client = Client::builder(server.base_url())
28833            .timeout(Duration::from_secs(2))
28834            .build()
28835            .expect("client");
28836
28837        let handle = WorkflowHandle {
28838            client,
28839            workflow_id: "wf-selected".to_string(),
28840            run_id: Some("run-selected".to_string()),
28841            workflow_type: "selected".to_string(),
28842        };
28843        let options = WorkflowResultOptions {
28844            poll_interval: Duration::ZERO,
28845            timeout: Duration::from_secs(1),
28846        };
28847
28848        let current = handle
28849            .result(options)
28850            .await
28851            .expect("instance result follows the current run");
28852        assert_eq!(current, json!("current run output"));
28853
28854        let error = handle
28855            .result_selected_run(options)
28856            .await
28857            .expect_err("the selected run is cancelled even though the current run completed");
28858
28859        let Error::WorkflowCancelled(outcome) = error else {
28860            panic!("expected selected run cancellation");
28861        };
28862        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
28863        assert_eq!(outcome.reason, "selected run cancelled");
28864        assert_eq!(
28865            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
28866            1
28867        );
28868        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
28869    }
28870
28871    #[tokio::test]
28872    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
28873        let server = MockWorkerServer::draining_polls();
28874        let client = Client::builder(server.base_url())
28875            .timeout(Duration::from_secs(2))
28876            .build()
28877            .expect("client");
28878
28879        let workflow = client
28880            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
28881            .await
28882            .expect("workflow drain response");
28883        let activity = client
28884            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
28885            .await
28886            .expect("activity drain response");
28887        let query = client
28888            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
28889            .await
28890            .expect("query drain response");
28891
28892        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
28893            assert_eq!(
28894                outcome,
28895                WorkerPollOutcome::Stop {
28896                    poll_status: Some("draining".to_string()),
28897                    reason: Some("worker_draining".to_string()),
28898                }
28899            );
28900        }
28901
28902        assert!(client
28903            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
28904            .await
28905            .expect("compatibility poll")
28906            .is_none());
28907    }
28908
28909    #[tokio::test]
28910    async fn managed_worker_honors_drain_stop_for_every_task_family() {
28911        let server = MockWorkerServer::draining_polls();
28912        let client = Client::builder(server.base_url())
28913            .timeout(Duration::from_secs(2))
28914            .build()
28915            .expect("client");
28916
28917        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
28918            .worker_id("draining-workflow-worker")
28919            .poll_timeout(Duration::ZERO);
28920        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
28921        workflow_worker
28922            .run()
28923            .await
28924            .expect("workflow drain is a clean stop");
28925
28926        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
28927            .worker_id("draining-activity-worker")
28928            .poll_timeout(Duration::ZERO);
28929        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
28930        activity_worker
28931            .run()
28932            .await
28933            .expect("activity drain is a clean stop");
28934
28935        let mut query_worker = Worker::new(client, "rust-workers")
28936            .worker_id("draining-query-worker")
28937            .poll_timeout(Duration::ZERO);
28938        query_worker.register_query("counter", "current", |_ctx, _args| async {
28939            Ok(Value::Null)
28940        });
28941        query_worker
28942            .run()
28943            .await
28944            .expect("query drain is a clean stop");
28945    }
28946
28947    #[tokio::test]
28948    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
28949        let server = MockWorkerServer::start();
28950        let client = Client::builder(server.base_url())
28951            .timeout(Duration::from_secs(2))
28952            .build()
28953            .expect("client");
28954
28955        let details: Value = serde_json::from_str(include_str!(
28956            "../tests/fixtures/activity-heartbeat-progress.json"
28957        ))
28958        .expect("heartbeat progress fixture");
28959        // Every individual field fits Server's progress contract, while the
28960        // obsolete encoded envelope exceeded its 191-character string limit.
28961        assert!(
28962            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
28963                .unwrap()["blob"]
28964                .as_str()
28965                .unwrap()
28966                .len()
28967                > 191
28968        );
28969        let heartbeat = client
28970            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
28971            .await
28972            .expect("cancellation heartbeat");
28973        assert!(heartbeat.cancel_requested);
28974        assert!(heartbeat.should_stop());
28975        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
28976        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
28977        let heartbeat_body =
28978            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
28979        assert_eq!(heartbeat_body["details"], details);
28980        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
28981        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
28982
28983        let error = client
28984            .complete_activity_task(
28985                "activity-cancel",
28986                "attempt-cancel",
28987                "rust-worker",
28988                json!({"late":true}),
28989                DEFAULT_CODEC,
28990            )
28991            .await
28992            .expect_err("late completion must be refused");
28993        assert!(activity_task_rejection_is_final(&error));
28994        let Error::ActivityTaskRejected(rejection) = error else {
28995            panic!("expected typed activity rejection");
28996        };
28997        assert_eq!(rejection.status, 409);
28998        assert_eq!(rejection.reason, "run_cancelled");
28999        assert!(rejection.cancel_requested);
29000        assert_eq!(rejection.can_continue, Some(false));
29001    }
29002
29003    #[tokio::test]
29004    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
29005        let server = MockWorkerServer::cancelled_activity();
29006        let client = Client::builder(server.base_url())
29007            .timeout(Duration::from_secs(2))
29008            .build()
29009            .expect("client");
29010        let cancellation_observed = Arc::new(AtomicBool::new(false));
29011        let observed = Arc::clone(&cancellation_observed);
29012        let mut worker = Worker::new(client.clone(), "rust-workers")
29013            .worker_id("rust-cancel-worker")
29014            .poll_timeout(Duration::from_millis(10));
29015        worker.register_activity("cancel-aware", move |ctx, _args| {
29016            let observed = Arc::clone(&observed);
29017            async move {
29018                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
29019                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
29020                Ok(json!({"late":"completion"}))
29021            }
29022        });
29023
29024        assert_eq!(
29025            worker.run_once().await.expect("cancelled attempt handled"),
29026            1
29027        );
29028        assert!(cancellation_observed.load(Ordering::SeqCst));
29029        assert_eq!(
29030            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
29031            1
29032        );
29033
29034        let mut restarted = Worker::new(client, "rust-workers")
29035            .worker_id("rust-cancel-worker-restarted")
29036            .poll_timeout(Duration::from_millis(10));
29037        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
29038        assert_eq!(
29039            restarted
29040                .run_once()
29041                .await
29042                .expect("replacement worker continues polling"),
29043            0
29044        );
29045    }
29046
29047    #[tokio::test]
29048    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
29049        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"}"#;
29050        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
29051        let client = Client::builder(server.base_url())
29052            .timeout(Duration::from_secs(2))
29053            .build()
29054            .expect("client");
29055
29056        let direct_error = client
29057            .complete_workflow_task(
29058                "workflow-timeout-task",
29059                "timeout-worker",
29060                3,
29061                vec![json!({
29062                    "type": "complete_workflow",
29063                    "result": fixture_envelope(Value::Null)
29064                })],
29065            )
29066            .await
29067            .expect_err("the low-level client preserves the completion rejection");
29068        let Error::Http { status, body } = direct_error else {
29069            panic!("expected the original HTTP completion rejection");
29070        };
29071        assert_eq!(status, reqwest::StatusCode::CONFLICT);
29072        assert_eq!(
29073            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
29074            "run_timed_out"
29075        );
29076
29077        let mut worker = Worker::new(client, "rust-workers")
29078            .worker_id("timeout-worker")
29079            .poll_timeout(Duration::from_millis(10));
29080        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
29081            Ok(json!({"late": "result"}))
29082        });
29083
29084        assert_eq!(
29085            worker
29086                .run_once()
29087                .await
29088                .expect("authoritative selected-run timeout settles the tick"),
29089            1
29090        );
29091        assert_eq!(
29092            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
29093            2,
29094            "both the direct client proof and managed worker must see the rejection"
29095        );
29096    }
29097
29098    #[tokio::test]
29099    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
29100        for (name, status, response) in [
29101            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
29102            (
29103                "command was recorded",
29104                "409 Conflict",
29105                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29106            ),
29107            (
29108                "lease conflict",
29109                "409 Conflict",
29110                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
29111            ),
29112            (
29113                "nonterminal run",
29114                "409 Conflict",
29115                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
29116            ),
29117            (
29118                "different selected run",
29119                "409 Conflict",
29120                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"}"#,
29121            ),
29122            (
29123                "different task attempt",
29124                "409 Conflict",
29125                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29126            ),
29127            (
29128                "authentication failure",
29129                "401 Unauthorized",
29130                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29131            ),
29132            (
29133                "authorization failure",
29134                "403 Forbidden",
29135                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29136            ),
29137            (
29138                "protocol failure",
29139                "400 Bad Request",
29140                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
29141            ),
29142            (
29143                "malformed command",
29144                "422 Unprocessable Entity",
29145                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29146            ),
29147            (
29148                "transient server failure",
29149                "503 Service Unavailable",
29150                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29151            ),
29152        ] {
29153            let server = MockWorkerServer::workflow_completion(status, response);
29154            let client = Client::builder(server.base_url())
29155                .timeout(Duration::from_secs(2))
29156                .build()
29157                .expect("client");
29158            let mut worker = Worker::new(client, "rust-workers")
29159                .worker_id("timeout-worker")
29160                .poll_timeout(Duration::from_millis(10));
29161            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
29162                Ok(json!({"late": "result"}))
29163            });
29164
29165            let error = worker
29166                .run_once()
29167                .await
29168                .expect_err(&format!("{name} must remain an error"));
29169            assert!(
29170                matches!(error, Error::Http { .. } | Error::Protocol(_)),
29171                "{name} returned an unexpected error variant: {error}"
29172            );
29173        }
29174    }
29175
29176    #[tokio::test]
29177    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
29178        let server = MockWorkerServer::start();
29179        let client = Client::builder(server.base_url())
29180            .worker_token(Some("worker-secret".to_string()))
29181            .namespace("orders")
29182            .timeout(Duration::from_secs(2))
29183            .build()
29184            .expect("client");
29185        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
29186
29187        let result = client
29188            .deregister_worker_registration("worker/α space")
29189            .await
29190            .expect("deregister worker registration");
29191
29192        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
29193        assert_eq!(
29194            server.worker_protocol_for(path).as_deref(),
29195            Some(WORKER_PROTOCOL_VERSION)
29196        );
29197        assert_eq!(server.control_protocol_for(path), None);
29198        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
29199        assert_eq!(
29200            server.authorization_for(path).as_deref(),
29201            Some("Bearer worker-secret")
29202        );
29203        assert_eq!(
29204            result,
29205            WorkerDeregistrationEnvelope {
29206                worker_id: "deregistered-worker".to_string(),
29207                outcome: "deregistered".to_string(),
29208                recovered_workflow_task_count: 2,
29209            }
29210        );
29211    }
29212
29213    #[tokio::test]
29214    async fn low_level_registration_rejects_update_validators_before_transport() {
29215        let server = MockWorkerServer::start();
29216        let client = Client::builder(server.base_url())
29217            .timeout(Duration::from_secs(2))
29218            .build()
29219            .expect("client");
29220
29221        for update_validators in [json!(["approve"]), json!("approve")] {
29222            let error = client
29223                .register_worker_with_command_contracts(
29224                    "validator-claiming-worker",
29225                    "rust-workers",
29226                    vec!["orders".to_string()],
29227                    vec![],
29228                    1,
29229                    1,
29230                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
29231                    json!({
29232                        "orders": {
29233                            "queries": ["current"],
29234                            "updates": ["approve"],
29235                            "update_validators": update_validators,
29236                        },
29237                    }),
29238                )
29239                .await
29240                .expect_err("unsupported validator claims must fail before registration");
29241
29242            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
29243                panic!("expected typed unsupported-validator failure");
29244            };
29245            assert_eq!(workflow_type, "orders");
29246        }
29247        assert_eq!(server.request_count("/api/worker/register"), 0);
29248    }
29249
29250    #[tokio::test]
29251    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
29252        let server = MockWorkerServer::start();
29253        let client = Client::builder(server.base_url())
29254            .timeout(Duration::from_secs(2))
29255            .build()
29256            .expect("client");
29257        let mut worker = Worker::new(client, "rust-workers");
29258        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
29259        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
29260        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
29261        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
29262        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
29263        worker
29264            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
29265            .expect("declare workflow signals");
29266
29267        worker.register().await.expect("register handler contracts");
29268
29269        let declaration =
29270            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
29271        let expected_contracts = json!([
29272            {
29273                "name": "a-avro",
29274                "parameters": [{
29275                    "name": "args", "position": 0, "required": false,
29276                    "variadic": true, "type": null, "allows_null": true,
29277                    "default_available": false, "default": null,
29278                }],
29279            },
29280            {
29281                "name": "z-json",
29282                "parameters": [{
29283                    "name": "args", "position": 0, "required": false,
29284                    "variadic": true, "type": null, "allows_null": true,
29285                    "default_available": false, "default": null,
29286                }],
29287            },
29288        ]);
29289        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
29290        assert_eq!(declaration["query_contracts"], expected_contracts);
29291        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
29292        assert_eq!(declaration["update_contracts"], expected_contracts);
29293        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
29294        assert_eq!(declaration["signal_contracts"], expected_contracts);
29295        assert_eq!(declaration["update_validators"], json!([]));
29296    }
29297
29298    #[tokio::test]
29299    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
29300        let server = MockWorkerServer::start();
29301        let client = Client::new(server.base_url()).expect("client");
29302        let mut worker = Worker::new(client, "rust-workers");
29303        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
29304        assert!(worker
29305            .declare_workflow_signals("missing", &["finish"])
29306            .is_err());
29307        worker
29308            .declare_workflow_signals("orders", &["finish"])
29309            .unwrap();
29310        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
29311            assert!(worker.declare_workflow_signals("orders", names).is_err());
29312        }
29313        worker.register().await.unwrap();
29314        assert_eq!(
29315            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
29316                ["signals"],
29317            json!(["finish"])
29318        );
29319        worker.declare_workflow_signals("orders", &[]).unwrap();
29320        worker.register().await.unwrap();
29321        let registrations = server.request_bodies("/api/worker/register");
29322        assert_eq!(
29323            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
29324            json!([])
29325        );
29326        assert_eq!(
29327            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
29328            json!([])
29329        );
29330    }
29331
29332    #[tokio::test]
29333    async fn low_level_registration_preserves_query_and_update_contracts() {
29334        let server = MockWorkerServer::start();
29335        let client = Client::builder(server.base_url())
29336            .timeout(Duration::from_secs(2))
29337            .build()
29338            .expect("client");
29339        let contracts = json!({
29340            "orders": {
29341                "queries": ["current"],
29342                "updates": ["approve"],
29343                "update_validators": [],
29344            },
29345            "payments": {
29346                "queries": ["status"],
29347                "updates": ["capture"],
29348            },
29349        });
29350
29351        client
29352            .register_worker_with_command_contracts(
29353                "command-worker",
29354                "rust-workers",
29355                vec!["orders".to_string(), "payments".to_string()],
29356                vec![],
29357                1,
29358                1,
29359                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
29360                contracts.clone(),
29361            )
29362            .await
29363            .expect("query and update contracts must remain supported");
29364
29365        assert_eq!(
29366            server.request_body("/api/worker/register")["workflow_command_contracts"],
29367            contracts
29368        );
29369        assert!(server
29370            .request_body("/api/worker/register")
29371            .get("workflow_definition_fingerprints")
29372            .is_none());
29373    }
29374
29375    #[tokio::test]
29376    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
29377        let server = MockWorkerServer::start();
29378        let client = Client::builder(server.base_url())
29379            .timeout(Duration::from_secs(2))
29380            .build()
29381            .expect("client");
29382        let mut worker = Worker::new(client.clone(), "rust-workers");
29383        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
29384
29385        assert!(worker
29386            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
29387            .is_err());
29388        assert!(worker
29389            .set_workflow_definition_sources("orders", &[])
29390            .is_err());
29391        worker
29392            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
29393            .expect("embed workflow source");
29394        worker.register().await.expect("register worker");
29395        let first = server.request_bodies("/api/worker/register")[0]
29396            ["workflow_definition_fingerprints"]["orders"]
29397            .as_str()
29398            .expect("source-backed fingerprint")
29399            .to_string();
29400        assert!(first.starts_with("sha256:"));
29401
29402        worker
29403            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
29404            .expect("change embedded helper source");
29405        worker.register().await.expect("register changed source");
29406        let changed = server.request_bodies("/api/worker/register")[1]
29407            ["workflow_definition_fingerprints"]["orders"]
29408            .as_str()
29409            .expect("changed fingerprint")
29410            .to_string();
29411        assert_ne!(first, changed);
29412
29413        let mut replacement =
29414            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
29415        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
29416        replacement
29417            .register()
29418            .await
29419            .expect("register replacement handler");
29420        assert_eq!(
29421            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
29422            json!({})
29423        );
29424    }
29425
29426    #[tokio::test]
29427    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
29428        let server = MockWorkerServer::start();
29429        let control_only = Client::builder(server.base_url())
29430            .control_token(Some("control-secret".to_string()))
29431            .build()
29432            .expect("control client");
29433
29434        let error = control_only
29435            .register_worker("worker", "queue", vec![], vec![], 1, 1)
29436            .await
29437            .expect_err("control token must not authorize a worker request");
29438        assert!(matches!(
29439            error,
29440            Error::MissingRoleCredentials { role: "worker", .. }
29441        ));
29442        assert_eq!(server.request_count("/api/worker/register"), 0);
29443
29444        let worker_only = Client::builder(server.base_url())
29445            .worker_token(Some("worker-secret".to_string()))
29446            .build()
29447            .expect("worker client");
29448        let error = worker_only
29449            .health()
29450            .await
29451            .expect_err("worker token must not authorize a control request");
29452        assert!(matches!(
29453            error,
29454            Error::MissingRoleCredentials {
29455                role: "control",
29456                ..
29457            }
29458        ));
29459        assert_eq!(server.request_count("/api/health"), 0);
29460    }
29461
29462    #[tokio::test]
29463    async fn shared_token_supports_worker_and_control_planes() {
29464        let server = MockWorkerServer::start();
29465        let client = Client::builder(server.base_url())
29466            .token(Some("shared-secret".to_string()))
29467            .build()
29468            .expect("client");
29469
29470        client.health().await.expect("control request");
29471        client
29472            .register_worker("worker", "queue", vec![], vec![], 1, 1)
29473            .await
29474            .expect("worker request");
29475
29476        assert_eq!(
29477            server.authorization_for("/api/health").as_deref(),
29478            Some("Bearer shared-secret")
29479        );
29480        assert_eq!(
29481            server.control_protocol_for("/api/health").as_deref(),
29482            Some(CONTROL_PLANE_VERSION)
29483        );
29484        assert_eq!(
29485            server.authorization_for("/api/worker/register").as_deref(),
29486            Some("Bearer shared-secret")
29487        );
29488        assert_eq!(
29489            server
29490                .worker_protocol_for("/api/worker/register")
29491                .as_deref(),
29492            Some(WORKER_PROTOCOL_VERSION)
29493        );
29494    }
29495
29496    #[tokio::test]
29497    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
29498        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
29499        let server = MockWorkerServer::start();
29500        let client = Client::builder(server.base_url())
29501            .timeout(Duration::from_secs(2))
29502            .build()
29503            .expect("client");
29504
29505        client
29506            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
29507            .await
29508            .expect("register");
29509        client
29510            .heartbeat_worker("capture-worker", 1, 1)
29511            .await
29512            .expect("heartbeat");
29513        client
29514            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
29515            .await
29516            .expect("workflow poll");
29517        client
29518            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
29519            .await
29520            .expect("activity poll");
29521
29522        for path in [
29523            "/api/worker/register",
29524            "/api/worker/heartbeat",
29525            "/api/worker/workflow-tasks/poll",
29526            "/api/worker/activity-tasks/poll",
29527        ] {
29528            assert_eq!(
29529                server.worker_protocol_for(path).as_deref(),
29530                Some(WORKER_PROTOCOL_VERSION),
29531                "unexpected protocol for {path}"
29532            );
29533        }
29534
29535        assert_eq!(
29536            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
29537            1
29538        );
29539        assert_eq!(
29540            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
29541            500
29542        );
29543        assert_eq!(
29544            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
29545            1
29546        );
29547        assert!(
29548            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
29549                .as_str()
29550                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
29551        );
29552        assert!(
29553            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
29554                .as_str()
29555                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
29556        );
29557        let registration = server.request_body("/api/worker/register");
29558        for optional in [
29559            "cooperative_cancellation",
29560            "local_activities",
29561            "worker_sessions",
29562            "sticky_execution",
29563        ] {
29564            assert!(!registration["capabilities"]
29565                .as_array()
29566                .is_some_and(|capabilities| capabilities
29567                    .iter()
29568                    .any(|capability| capability.as_str() == Some(optional))));
29569        }
29570    }
29571
29572    #[tokio::test]
29573    async fn explicit_previous_worker_protocol_preserves_headers() {
29574        let server = MockWorkerServer::start();
29575        let client = Client::builder(server.base_url())
29576            .worker_protocol_version(WorkerProtocolVersion::V119)
29577            .timeout(Duration::from_secs(2))
29578            .build()
29579            .expect("client");
29580        client
29581            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
29582            .await
29583            .expect("register");
29584        client
29585            .heartbeat_worker("legacy-worker", 1, 1)
29586            .await
29587            .expect("heartbeat");
29588        client
29589            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
29590            .await
29591            .expect("workflow poll");
29592        client
29593            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
29594            .await
29595            .expect("activity poll");
29596        client
29597            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
29598            .await
29599            .expect("query poll");
29600        client
29601            .deregister_worker_registration("legacy-worker")
29602            .await
29603            .expect("deregister");
29604        for path in [
29605            "/api/worker/register",
29606            "/api/worker/heartbeat",
29607            "/api/worker/workflow-tasks/poll",
29608            "/api/worker/activity-tasks/poll",
29609            "/api/worker/query-tasks/poll",
29610            "/api/worker/registrations/legacy-worker",
29611        ] {
29612            assert_eq!(
29613                server.worker_protocol_for(path).as_deref(),
29614                Some("1.19"),
29615                "{path}"
29616            );
29617            assert_eq!(server.control_protocol_for(path), None, "{path}");
29618        }
29619    }
29620
29621    #[tokio::test]
29622    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
29623        let server = MockWorkerServer::start();
29624        let client = Client::builder(server.base_url())
29625            .worker_protocol_version(WorkerProtocolVersion::V119)
29626            .timeout(Duration::from_secs(2))
29627            .build()
29628            .expect("client");
29629        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
29630        let error = worker
29631            .register()
29632            .await
29633            .expect_err("legacy cooperation must be refused");
29634        assert!(matches!(
29635            error,
29636            Error::CooperativeCancellationUnavailable(_)
29637        ));
29638        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
29639    }
29640
29641    #[tokio::test]
29642    async fn query_task_endpoints_send_the_selected_worker_protocol() {
29643        let server = MockWorkerServer::start();
29644        let client = Client::builder(server.base_url())
29645            .timeout(Duration::from_secs(2))
29646            .build()
29647            .expect("client");
29648
29649        client
29650            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
29651            .await
29652            .expect("query poll");
29653        client
29654            .complete_query_task(
29655                "query-capture",
29656                "capture-worker",
29657                1,
29658                json!(8),
29659                DEFAULT_CODEC,
29660            )
29661            .await
29662            .expect("query complete");
29663        client
29664            .fail_query_task(
29665                "query-capture",
29666                "capture-worker",
29667                1,
29668                "failed",
29669                "query_rejected",
29670                "QueryFailed",
29671            )
29672            .await
29673            .expect("query fail");
29674
29675        for path in [
29676            "/api/worker/query-tasks/poll",
29677            "/api/worker/query-tasks/query-capture/complete",
29678            "/api/worker/query-tasks/query-capture/fail",
29679        ] {
29680            assert_eq!(
29681                server.worker_protocol_for(path).as_deref(),
29682                Some(WORKER_PROTOCOL_VERSION),
29683                "unexpected protocol for {path}"
29684            );
29685        }
29686
29687        assert_eq!(
29688            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
29689            1
29690        );
29691        assert!(
29692            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
29693                .as_str()
29694                .is_some_and(|id| id.starts_with("rust-query-poll-"))
29695        );
29696    }
29697
29698    #[tokio::test]
29699    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
29700        let server = MockWorkerServer::transient_worker_failures();
29701        let client = Client::builder(server.base_url())
29702            .timeout(Duration::from_secs(2))
29703            .build()
29704            .expect("client");
29705
29706        client
29707            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
29708            .await
29709            .expect("workflow poll retry");
29710        client
29711            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
29712            .await
29713            .expect("activity poll retry");
29714        client
29715            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
29716            .await
29717            .expect("query poll retry");
29718
29719        for path in [
29720            "/api/worker/workflow-tasks/poll",
29721            "/api/worker/activity-tasks/poll",
29722            "/api/worker/query-tasks/poll",
29723        ] {
29724            let bodies = server.request_bodies(path);
29725            assert_eq!(bodies.len(), 2, "{path} must be retried once");
29726            assert_eq!(
29727                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
29728                "{path} must preserve the request binding across retry"
29729            );
29730        }
29731    }
29732
29733    #[tokio::test]
29734    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
29735        let server = MockWorkerServer::consecutive_poll_failures(2);
29736        let client = Client::builder(server.base_url())
29737            .timeout(Duration::from_secs(2))
29738            .build()
29739            .expect("client");
29740        let mut worker = Worker::new(client, "capture")
29741            .worker_id("capture-worker")
29742            .poll_timeout(Duration::from_millis(10))
29743            .retry_policy(WorkerRetryPolicy {
29744                max_retries: 2,
29745                initial_backoff: Duration::from_millis(1),
29746                max_backoff: Duration::from_millis(1),
29747            });
29748        worker.register_workflow(
29749            "capture.workflow",
29750            |_ctx, _input| async move { Ok(Value::Null) },
29751        );
29752        worker.register_activity(
29753            "capture.activity",
29754            |_ctx, _input| async move { Ok(Value::Null) },
29755        );
29756        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
29757            Ok(Value::Null)
29758        });
29759
29760        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
29761
29762        for path in [
29763            "/api/worker/workflow-tasks/poll",
29764            "/api/worker/activity-tasks/poll",
29765            "/api/worker/query-tasks/poll",
29766        ] {
29767            let bodies = server.request_bodies(path);
29768            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
29769            assert!(
29770                bodies
29771                    .iter()
29772                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
29773                "{path} must preserve one request binding across every retry"
29774            );
29775        }
29776    }
29777
29778    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
29779        let reason = if unavailable {
29780            "storage_admission_unavailable"
29781        } else {
29782            "storage_pressure"
29783        };
29784        let mut body = json!({
29785            "reason": reason,
29786            "storage_state": if unavailable { "fenced" } else { "draining" },
29787            "retryable": true,
29788            "retry_after_seconds": 1,
29789        });
29790        if !mid_poll {
29791            body["request_admitted"] = json!(false);
29792        }
29793        if let Some(id) = poll_id {
29794            body["task"] = Value::Null;
29795            body["poll_status"] = json!(reason);
29796            body["poll_request_id"] = json!(id);
29797            body["retry_same_poll_request_id"] = json!(true);
29798            body["claim_admitted"] = json!(false);
29799        }
29800        body
29801    }
29802
29803    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
29804        let operation = match path {
29805            "/api/worker/register" => "register_worker",
29806            "/api/worker/heartbeat" => "heartbeat_worker",
29807            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
29808            "/api/worker/activity-tasks/poll" => "poll_activity_task",
29809            "/api/worker/query-tasks/poll" => "poll_query_task",
29810            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
29811            _ => return None,
29812        };
29813        let request: Value = serde_json::from_str(request).ok()?;
29814        let mut response = json!({
29815            "reason": "backend_unavailable",
29816            "operation": operation,
29817            "outcome": "unknown",
29818            "retryable": true,
29819            "retry_after_seconds": 1,
29820            "worker_id": request["worker_id"],
29821            "task_queue": request.get("task_queue"),
29822        });
29823        if path.ends_with("/poll") {
29824            response["task"] = Value::Null;
29825            response["poll_status"] = json!("backend_unavailable");
29826            response["poll_request_id"] = request["poll_request_id"].clone();
29827            response["retry_same_poll_request_id"] = json!(true);
29828        }
29829        Some(response)
29830    }
29831
29832    fn backend_retry_override(
29833        path: &str,
29834        request: &str,
29835        number: usize,
29836    ) -> Option<(&'static str, String)> {
29837        if number > 8 {
29838            return None;
29839        }
29840        Some((
29841            "503 Service Unavailable",
29842            backend_refusal(path, request)?.to_string(),
29843        ))
29844    }
29845
29846    fn backend_unavailable_override(
29847        path: &str,
29848        request: &str,
29849        _number: usize,
29850    ) -> Option<(&'static str, String)> {
29851        Some((
29852            "503 Service Unavailable",
29853            backend_refusal(path, request)?.to_string(),
29854        ))
29855    }
29856
29857    fn storage_worker(server: &MockWorkerServer) -> Worker {
29858        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
29859            .worker_id("storage-worker")
29860            .retry_policy(WorkerRetryPolicy {
29861                max_retries: 1,
29862                initial_backoff: Duration::from_millis(1),
29863                max_backoff: Duration::from_millis(1),
29864            })
29865    }
29866
29867    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
29868        let requests = server.requests.lock().expect("requests");
29869        let bodies: Vec<_> = requests
29870            .iter()
29871            .filter(|request| request.path == path)
29872            .map(|request| &request.body)
29873            .collect();
29874        assert_eq!(bodies.len(), count, "{path}");
29875        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
29876    }
29877
29878    #[test]
29879    fn backend_recovery_requires_the_explicit_worker_contract() {
29880        for (path, operation) in [
29881            ("/worker/register", "register_worker"),
29882            ("/worker/heartbeat", "heartbeat_worker"),
29883            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
29884            ("/worker/activity-tasks/poll", "poll_activity_task"),
29885            ("/worker/query-tasks/poll", "poll_query_task"),
29886            (
29887                "/worker/update-validation-tasks/poll",
29888                "poll_update_validation_task",
29889            ),
29890        ] {
29891            let poll_id = path.ends_with("/poll").then_some("same-poll");
29892            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
29893            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
29894                .expect("worker operation");
29895            assert_eq!(body["operation"], operation);
29896            let error = Error::Http {
29897                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29898                body: body.to_string(),
29899            };
29900            assert_eq!(
29901                worker_backend_unavailable_retry_after(&error, path, poll_id),
29902                Some(Duration::from_secs(1))
29903            );
29904            assert!(!worker_operation_is_retryable(&error));
29905            for (field, value) in [
29906                ("operation", json!("wrong_operation")),
29907                ("outcome", json!("completed")),
29908                ("retryable", json!(false)),
29909                ("retry_after_seconds", json!(0)),
29910                ("worker_id", json!("")),
29911            ] {
29912                let mut invalid = body.clone();
29913                invalid[field] = value;
29914                let error = Error::Http {
29915                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29916                    body: invalid.to_string(),
29917                };
29918                assert!(
29919                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
29920                    "{path}: {field}"
29921                );
29922                assert!(!worker_operation_is_retryable(&error));
29923            }
29924            if let Some(poll_id) = poll_id {
29925                for (field, value) in [
29926                    ("poll_request_id", json!("wrong-poll")),
29927                    ("poll_status", json!("empty")),
29928                    ("task", json!({"task_id":"claimed"})),
29929                    ("retry_same_poll_request_id", json!(false)),
29930                ] {
29931                    let mut invalid = body.clone();
29932                    invalid[field] = value;
29933                    let error = Error::Http {
29934                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29935                        body: invalid.to_string(),
29936                    };
29937                    assert!(
29938                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
29939                            .is_none(),
29940                        "{path}: {field}"
29941                    );
29942                }
29943            }
29944            let error = Error::Http {
29945                status: reqwest::StatusCode::UNAUTHORIZED,
29946                body: body.to_string(),
29947            };
29948            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
29949            assert!(!worker_operation_is_retryable(&error));
29950        }
29951    }
29952
29953    #[tokio::test]
29954    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
29955        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29956            request_override: Some(backend_retry_override),
29957            ..MockWorkerBehavior::default()
29958        });
29959        let mut worker =
29960            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
29961        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
29962        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
29963        worker.register_query("backend.workflow", "state", |_, _| async {
29964            Ok(Value::Null)
29965        });
29966        worker.register().await.expect("registration recovery");
29967        worker
29968            .client
29969            .heartbeat_worker("storage-worker", 1, 1)
29970            .await
29971            .expect("heartbeat recovery");
29972        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
29973        for path in [
29974            "/api/worker/register",
29975            "/api/worker/heartbeat",
29976            "/api/worker/workflow-tasks/poll",
29977            "/api/worker/activity-tasks/poll",
29978            "/api/worker/query-tasks/poll",
29979        ] {
29980            assert_identical_requests(&server, path, 9);
29981        }
29982    }
29983
29984    #[tokio::test]
29985    async fn backend_recovery_wait_stops_with_worker() {
29986        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29987            request_override: Some(backend_unavailable_override),
29988            ..MockWorkerBehavior::default()
29989        });
29990        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
29991            max_retries: 1,
29992            initial_backoff: Duration::from_secs(2),
29993            max_backoff: Duration::from_secs(2),
29994        });
29995        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
29996        let started = tokio::time::Instant::now();
29997        let _ = tokio::time::timeout(
29998            Duration::from_secs(1),
29999            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
30000        )
30001        .await
30002        .expect("shutdown interrupts backend wait");
30003        assert!(started.elapsed() < Duration::from_secs(1));
30004        assert!(server.request_count("/api/worker/register") >= 1);
30005    }
30006
30007    #[test]
30008    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
30009        for unavailable in [false, true] {
30010            for mid_poll in [false, true] {
30011                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
30012                let error = Error::Http {
30013                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30014                    body: body.to_string(),
30015                };
30016                assert_eq!(
30017                    worker_storage_admission_retry_after(&error, Some("same-poll")),
30018                    Some(Duration::from_secs(1))
30019                );
30020                assert!(
30021                    !worker_operation_is_retryable(&error),
30022                    "storage is not a bounded generic retry"
30023                );
30024                for (field, value) in [
30025                    ("poll_request_id", json!("wrong-poll")),
30026                    ("task", json!({"task_id":"claimed"})),
30027                    ("retryable", json!(false)),
30028                    ("retry_after_seconds", json!(0)),
30029                    ("retry_after_seconds", json!(true)),
30030                    ("retry_after_seconds", json!(1.0)),
30031                    ("storage_state", json!("normal")),
30032                    ("poll_status", json!("empty")),
30033                    ("claim_admitted", json!(true)),
30034                    ("retry_same_poll_request_id", json!(false)),
30035                    ("request_admitted", json!(true)),
30036                ] {
30037                    let mut invalid = body.clone();
30038                    invalid[field] = value;
30039                    let error = Error::Http {
30040                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30041                        body: invalid.to_string(),
30042                    };
30043                    assert!(
30044                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
30045                        "{field}"
30046                    );
30047                }
30048            }
30049        }
30050        let body = storage_refusal(None, false, false);
30051        let error = Error::Http {
30052            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30053            body: body.to_string(),
30054        };
30055        assert!(worker_storage_admission_retry_after(&error, None).is_some());
30056        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
30057        let error = Error::Http {
30058            status: reqwest::StatusCode::FORBIDDEN,
30059            body: body.to_string(),
30060        };
30061        assert!(worker_storage_admission_retry_after(&error, None).is_none());
30062        let body = storage_refusal(None, false, true);
30063        let error = Error::Http {
30064            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30065            body: body.to_string(),
30066        };
30067        assert!(worker_storage_admission_retry_after(&error, None).is_none());
30068    }
30069
30070    #[tokio::test]
30071    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
30072        for unavailable in [false, true] {
30073            for mid_poll in [false, true] {
30074                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30075                    poll_failures_per_path: 1,
30076                    storage_refusals: 7,
30077                    storage_path: Some("/poll"),
30078                    storage_unavailable: unavailable,
30079                    storage_mid_poll: mid_poll,
30080                    ..MockWorkerBehavior::default()
30081                });
30082                let mut worker = storage_worker(&server);
30083                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
30084                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
30085                for path in [
30086                    "/api/worker/workflow-tasks/poll",
30087                    "/api/worker/activity-tasks/poll",
30088                    "/api/worker/query-tasks/poll",
30089                ] {
30090                    assert_identical_requests(&server, path, 9);
30091                }
30092            }
30093        }
30094    }
30095
30096    #[tokio::test]
30097    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
30098        struct CountedBody(Arc<AtomicUsize>);
30099        impl Serialize for CountedBody {
30100            fn serialize<S: Serializer>(
30101                &self,
30102                serializer: S,
30103            ) -> std::result::Result<S::Ok, S::Error> {
30104                let count = self.0.fetch_add(1, Ordering::SeqCst);
30105                json!({"serialization":count,"lease_owner":"worker","attempt":7})
30106                    .serialize(serializer)
30107            }
30108        }
30109        for path in [
30110            "/api/worker/register",
30111            "/api/worker/heartbeat",
30112            "/api/worker/workflow-tasks/storage-task/complete",
30113            "/api/worker/workflow-tasks/storage-task/fail",
30114            "/api/worker/activity-tasks/storage-task/complete",
30115            "/api/worker/activity-tasks/storage-task/fail",
30116            "/api/worker/activity-tasks/storage-task/heartbeat",
30117            "/api/worker/query-tasks/storage-task/complete",
30118            "/api/worker/query-tasks/storage-task/fail",
30119        ] {
30120            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30121                storage_refusals: 7,
30122                storage_path: Some(path),
30123                ..MockWorkerBehavior::default()
30124            });
30125            let worker =
30126                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
30127            let calls = Arc::new(AtomicUsize::new(0));
30128            let _: Value = worker
30129                .client
30130                .request_json(
30131                    reqwest::Method::POST,
30132                    &path[4..],
30133                    RequestProtocol::DefaultWorker,
30134                    Some(&CountedBody(Arc::clone(&calls))),
30135                )
30136                .await
30137                .expect("prepared request recovery");
30138            assert_eq!(calls.load(Ordering::SeqCst), 1);
30139            assert_identical_requests(&server, path, 8);
30140        }
30141        for worker_scope in [false, true] {
30142            let path = if worker_scope {
30143                "/api/health"
30144            } else {
30145                "/api/worker/register"
30146            };
30147            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30148                storage_refusals: usize::MAX,
30149                storage_path: Some(path),
30150                ..MockWorkerBehavior::default()
30151            });
30152            let worker = storage_worker(&server);
30153            let client = worker.client.clone();
30154            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
30155            let error = if worker_scope {
30156                worker
30157                    .client
30158                    .health()
30159                    .await
30160                    .expect_err("control plane is not retried")
30161            } else {
30162                client
30163                    .request_json::<Value, Value>(
30164                        reqwest::Method::POST,
30165                        "/worker/register",
30166                        RequestProtocol::DefaultWorker,
30167                        Some(&json!({})),
30168                    )
30169                    .await
30170                    .expect_err("direct client is not retried")
30171            };
30172            assert!(worker_storage_admission_body(&error).is_some());
30173            assert_eq!(server.request_count(path), 1);
30174        }
30175    }
30176
30177    #[tokio::test]
30178    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
30179        for fail in [false, true] {
30180            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30181                storage_activity: true,
30182                storage_refusals: 7,
30183                storage_path: Some("/storage-activity/"),
30184                ..MockWorkerBehavior::default()
30185            });
30186            let mut worker = storage_worker(&server);
30187            let calls = Arc::new(AtomicUsize::new(0));
30188            let observed = Arc::clone(&calls);
30189            worker.register_activity("storage.activity", move |ctx, _| {
30190                let calls = Arc::clone(&observed);
30191                async move {
30192                    calls.fetch_add(1, Ordering::SeqCst);
30193                    ctx.heartbeat(json!({"step":2})).await?;
30194                    if fail {
30195                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
30196                    } else {
30197                        Ok(json!({"receipt":true}))
30198                    }
30199                }
30200            });
30201            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
30202            assert_eq!(calls.load(Ordering::SeqCst), 1);
30203            assert_identical_requests(
30204                &server,
30205                "/api/worker/activity-tasks/storage-activity/heartbeat",
30206                8,
30207            );
30208            let suffix = if fail { "fail" } else { "complete" };
30209            assert_identical_requests(
30210                &server,
30211                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
30212                8,
30213            );
30214            let other = if fail { "complete" } else { "fail" };
30215            assert_eq!(
30216                server.request_count(&format!(
30217                    "/api/worker/activity-tasks/storage-activity/{other}"
30218                )),
30219                0
30220            );
30221        }
30222    }
30223
30224    #[tokio::test]
30225    async fn storage_waits_are_interruptible_without_false_activity_failure() {
30226        for path in [
30227            "/api/worker/register",
30228            "/api/worker/heartbeat",
30229            "/api/worker/activity-tasks/poll",
30230            "/api/worker/activity-tasks/storage-activity/heartbeat",
30231            "/api/worker/activity-tasks/storage-activity/complete",
30232        ] {
30233            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30234                storage_activity: true,
30235                storage_refusals: usize::MAX,
30236                storage_path: Some(path),
30237                ..MockWorkerBehavior::default()
30238            });
30239            let mut worker = storage_worker(&server)
30240                .max_concurrent_workflow_tasks(1)
30241                .max_concurrent_activity_tasks(1)
30242                .retry_policy(WorkerRetryPolicy::default());
30243            worker.register_activity("storage.activity", |ctx, _| async move {
30244                ctx.heartbeat(json!({"step":2})).await?;
30245                Ok(json!({"receipt":true}))
30246            });
30247            let shutdown = async {
30248                while server.request_count(path) == 0 {
30249                    tokio::time::sleep(Duration::from_millis(1)).await;
30250                }
30251            };
30252            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
30253                .await
30254                .expect("shutdown interrupts admission");
30255            assert!(
30256                result.is_err(),
30257                "a refused operation must not appear acknowledged: {path}, {result:?}"
30258            );
30259            assert_eq!(server.request_count(path), 1);
30260            assert_eq!(
30261                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
30262                0
30263            );
30264            assert_eq!(
30265                server.request_count("/api/worker/registrations/mock-worker"),
30266                usize::from(!path.ends_with("/register"))
30267            );
30268        }
30269    }
30270
30271    #[tokio::test]
30272    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
30273        for fail in [false, true] {
30274            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30275                storage_query: true,
30276                storage_refusals: 7,
30277                storage_path: Some("/storage-query/"),
30278                ..MockWorkerBehavior::default()
30279            });
30280            let mut worker = storage_worker(&server);
30281            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
30282            let calls = Arc::new(AtomicUsize::new(0));
30283            let observed = Arc::clone(&calls);
30284            worker.register_query("storage.workflow", "state", move |_, _| {
30285                let calls = Arc::clone(&observed);
30286                async move {
30287                    calls.fetch_add(1, Ordering::SeqCst);
30288                    if fail {
30289                        Err(Error::WorkerLoop("intentional query failure".to_string()))
30290                    } else {
30291                        Ok(json!({"state":"waiting"}))
30292                    }
30293                }
30294            });
30295            assert_eq!(worker.run_once().await.expect("query settled"), 1);
30296            assert_eq!(calls.load(Ordering::SeqCst), 1);
30297            let suffix = if fail { "fail" } else { "complete" };
30298            assert_identical_requests(
30299                &server,
30300                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
30301                8,
30302            );
30303            let other = if fail { "complete" } else { "fail" };
30304            assert_eq!(
30305                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
30306                0
30307            );
30308        }
30309    }
30310
30311    #[tokio::test]
30312    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
30313        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30314            storage_refusals: 7,
30315            storage_path: Some("/poll"),
30316            unauthorized_polls: true,
30317            ..MockWorkerBehavior::default()
30318        });
30319        let error = storage_worker(&server)
30320            .run_once()
30321            .await
30322            .expect_err("auth remains terminal");
30323        assert!(matches!(
30324            error,
30325            Error::Http {
30326                status: reqwest::StatusCode::UNAUTHORIZED,
30327                ..
30328            }
30329        ));
30330        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
30331
30332        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30333            storage_refusals: 7,
30334            storage_path: Some("/activity-cancel/complete"),
30335            ..MockWorkerBehavior::default()
30336        });
30337        let worker =
30338            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
30339        let error = worker
30340            .client
30341            .complete_activity_task(
30342                "activity-cancel",
30343                "attempt-cancel",
30344                "worker",
30345                json!({}),
30346                DEFAULT_CODEC,
30347            )
30348            .await
30349            .expect_err("cancellation remains terminal");
30350        assert!(activity_task_rejection_is_final(&error));
30351        assert_identical_requests(
30352            &server,
30353            "/api/worker/activity-tasks/activity-cancel/complete",
30354            8,
30355        );
30356
30357        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30358            storage_refusals: usize::MAX,
30359            storage_path: Some("/poll"),
30360            storage_wrong_poll_id: true,
30361            ..MockWorkerBehavior::default()
30362        });
30363        assert!(storage_worker(&server).run_once().await.is_err());
30364        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
30365    }
30366
30367    #[tokio::test]
30368    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
30369        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30370            storage_refusals: usize::MAX,
30371            storage_path: Some("/poll"),
30372            ..MockWorkerBehavior::default()
30373        });
30374        let mut worker = storage_worker(&server)
30375            .max_concurrent_workflow_tasks(1)
30376            .max_concurrent_activity_tasks(1)
30377            .retry_policy(WorkerRetryPolicy::default());
30378        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
30379        let run = tokio::spawn(async move { worker.run().await });
30380        tokio::time::timeout(Duration::from_secs(2), async {
30381            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
30382                tokio::time::sleep(Duration::from_millis(1)).await;
30383            }
30384        })
30385        .await
30386        .expect("poll started");
30387        run.abort();
30388        assert!(run.await.expect_err("cancelled run").is_cancelled());
30389        tokio::time::sleep(Duration::from_millis(250)).await;
30390        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
30391    }
30392
30393    #[tokio::test]
30394    async fn query_protocol_rejection_from_older_server_is_typed() {
30395        let server = MockWorkerServer::reject_query_protocol();
30396        let client = Client::builder(server.base_url())
30397            .timeout(Duration::from_secs(2))
30398            .build()
30399            .expect("client");
30400
30401        let error = client
30402            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
30403            .await
30404            .expect_err("server below query protocol floor must reject");
30405        let Error::Protocol(failure) = error else {
30406            panic!("expected typed protocol failure");
30407        };
30408
30409        assert_eq!(failure.status, 400);
30410        assert_eq!(failure.reason, "unsupported_protocol_version");
30411        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
30412        assert_eq!(
30413            failure.requested_version.as_deref(),
30414            Some(WORKER_PROTOCOL_VERSION)
30415        );
30416        assert_eq!(
30417            server
30418                .worker_protocol_for("/api/worker/query-tasks/poll")
30419                .as_deref(),
30420            Some(WORKER_PROTOCOL_VERSION)
30421        );
30422    }
30423
30424    #[tokio::test]
30425    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
30426        let server = MockWorkerServer::reject_query_protocol();
30427        let client = Client::builder(server.base_url())
30428            .timeout(Duration::from_secs(2))
30429            .build()
30430            .expect("client");
30431        let mut worker = Worker::new(client, "rust-workers")
30432            .worker_id("baseline-worker")
30433            .poll_timeout(Duration::from_millis(10));
30434
30435        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
30436            Ok(Value::Null)
30437        });
30438
30439        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
30440        assert_eq!(
30441            server
30442                .worker_protocol_for("/api/worker/workflow-tasks/poll")
30443                .as_deref(),
30444            Some(WORKER_PROTOCOL_VERSION)
30445        );
30446        assert_eq!(
30447            server.worker_protocol_for("/api/worker/query-tasks/poll"),
30448            None,
30449            "a worker without query handlers must not use the query-task endpoint"
30450        );
30451    }
30452
30453    #[tokio::test]
30454    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
30455        let server = MockWorkerServer::reject_query_completion();
30456        let client = Client::builder(server.base_url())
30457            .timeout(Duration::from_secs(2))
30458            .build()
30459            .expect("client");
30460
30461        let error = client
30462            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
30463            .await
30464            .expect_err("expired completion must be rejected");
30465        let Error::QueryFailed(failure) = error else {
30466            panic!("expected typed query failure");
30467        };
30468        assert_eq!(failure.status, 409);
30469        assert_eq!(failure.reason, "query_task_timed_out");
30470
30471        let mut worker = Worker::new(client, "rust-workers")
30472            .worker_id("late-worker")
30473            .poll_timeout(Duration::from_millis(10));
30474        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
30475        worker.register_query(
30476            "counter",
30477            "current",
30478            |_ctx, _args| async move { Ok(json!(8)) },
30479        );
30480
30481        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
30482        assert_eq!(
30483            worker
30484                .run_once()
30485                .await
30486                .expect("worker continues after late completion"),
30487            0
30488        );
30489        assert_eq!(
30490            server.request_count("/api/worker/query-tasks/query-late/complete"),
30491            2
30492        );
30493        assert_eq!(
30494            server.request_count("/api/worker/query-tasks/query-late/fail"),
30495            0,
30496            "a server completion rejection must not be reported as an encoding failure"
30497        );
30498    }
30499
30500    #[tokio::test]
30501    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
30502        let server = MockWorkerServer::start();
30503        let client = Client::builder(server.base_url())
30504            .timeout(Duration::from_secs(2))
30505            .build()
30506            .expect("client");
30507        let mut worker = Worker::new(client, "rust-workers")
30508            .worker_id("joined-worker")
30509            .poll_timeout(Duration::from_millis(10));
30510        worker.register_workflow(
30511            "joined.workflow",
30512            |_ctx, _input| async move { Ok(Value::Null) },
30513        );
30514        worker.register_activity(
30515            "joined.activity",
30516            |_ctx, _input| async move { Ok(Value::Null) },
30517        );
30518        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
30519            Ok(Value::Null)
30520        });
30521
30522        worker
30523            .run_until(tokio::time::sleep(Duration::from_millis(20)))
30524            .await
30525            .expect("normal shutdown");
30526
30527        let deregistration_path = "/api/worker/registrations/mock-worker";
30528        assert_eq!(server.request_count(deregistration_path), 1);
30529        for poll_path in [
30530            "/api/worker/workflow-tasks/poll",
30531            "/api/worker/activity-tasks/poll",
30532            "/api/worker/query-tasks/poll",
30533        ] {
30534            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
30535        }
30536        assert_eq!(
30537            server.captured_paths().last().map(String::as_str),
30538            Some(deregistration_path),
30539            "deregistration must start only after every poller has joined"
30540        );
30541    }
30542
30543    #[tokio::test]
30544    async fn registration_failure_does_not_deregister() {
30545        let server = MockWorkerServer::rejected_registration();
30546        let client = Client::builder(server.base_url())
30547            .timeout(Duration::from_secs(2))
30548            .build()
30549            .expect("client");
30550        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
30551
30552        let error = worker
30553            .run_until(async {})
30554            .await
30555            .expect_err("registration must fail");
30556        assert!(matches!(
30557            error,
30558            Error::Http {
30559                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30560                ..
30561            }
30562        ));
30563        assert!(server
30564            .captured_paths()
30565            .iter()
30566            .all(|path| !path.starts_with("/api/worker/registrations/")));
30567    }
30568
30569    #[tokio::test]
30570    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
30571        let server = MockWorkerServer::rejected_registration_protocol();
30572        let client = Client::builder(server.base_url())
30573            .timeout(Duration::from_secs(2))
30574            .build()
30575            .expect("client");
30576        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
30577
30578        let error = worker
30579            .run_until(async {})
30580            .await
30581            .expect_err("a protocol 1.16 server must reject this worker");
30582        let Error::Protocol(failure) = error else {
30583            panic!("expected typed protocol rejection");
30584        };
30585        assert_eq!(failure.reason, "unsupported_protocol_version");
30586        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
30587        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
30588        assert_eq!(
30589            server
30590                .worker_protocol_for("/api/worker/register")
30591                .as_deref(),
30592            Some(WORKER_PROTOCOL_VERSION)
30593        );
30594    }
30595
30596    #[tokio::test]
30597    async fn declined_registration_does_not_deregister() {
30598        let server = MockWorkerServer::declined_registration();
30599        let client = Client::builder(server.base_url())
30600            .timeout(Duration::from_secs(2))
30601            .build()
30602            .expect("client");
30603        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
30604
30605        let error = worker
30606            .run_until(async {})
30607            .await
30608            .expect_err("declined registration must fail");
30609        assert!(matches!(error, Error::WorkerLoop(_)));
30610        assert!(error.to_string().contains("was not accepted"));
30611        assert!(server
30612            .captured_paths()
30613            .iter()
30614            .all(|path| !path.starts_with("/api/worker/registrations/")));
30615    }
30616
30617    #[tokio::test]
30618    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
30619        let server = MockWorkerServer::rejected_deregistration();
30620        let client = Client::builder(server.base_url())
30621            .timeout(Duration::from_secs(2))
30622            .build()
30623            .expect("client");
30624        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
30625
30626        let error = worker
30627            .run_until(async {})
30628            .await
30629            .expect_err("deregistration must fail");
30630        assert!(matches!(
30631            error,
30632            Error::Http {
30633                status: reqwest::StatusCode::FORBIDDEN,
30634                ..
30635            }
30636        ));
30637        assert_eq!(
30638            server.request_count("/api/worker/registrations/mock-worker"),
30639            1
30640        );
30641    }
30642
30643    #[tokio::test]
30644    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
30645        let server = MockWorkerServer::rejected_deregistration_protocol();
30646        let client = Client::builder(server.base_url())
30647            .timeout(Duration::from_secs(2))
30648            .build()
30649            .expect("client");
30650        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
30651
30652        let error = worker
30653            .run_until(async {})
30654            .await
30655            .expect_err("protocol rejection must fail shutdown");
30656        let Error::Protocol(failure) = error else {
30657            panic!("expected typed protocol failure");
30658        };
30659        assert_eq!(failure.reason, "unsupported_protocol_version");
30660        assert_eq!(
30661            failure.requested_version.as_deref(),
30662            Some(WORKER_PROTOCOL_VERSION)
30663        );
30664        assert_eq!(
30665            server.request_count("/api/worker/registrations/mock-worker"),
30666            1
30667        );
30668    }
30669
30670    #[tokio::test]
30671    async fn primary_poller_error_retains_deregistration_failure_context() {
30672        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
30673        let client = Client::builder(server.base_url())
30674            .timeout(Duration::from_secs(2))
30675            .build()
30676            .expect("client");
30677        let mut worker = Worker::new(client, "rust-workers")
30678            .worker_id("combined-failure")
30679            .poll_timeout(Duration::from_millis(10));
30680        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
30681            Ok(Value::Null)
30682        });
30683
30684        let error = worker
30685            .run()
30686            .await
30687            .expect_err("worker and cleanup must fail");
30688        let summary = error.to_string();
30689        assert!(summary.contains("authentication_failed"));
30690        assert!(summary.contains("worker cannot deregister"));
30691        let Error::WorkerShutdown {
30692            primary,
30693            deregistration,
30694        } = error
30695        else {
30696            panic!("expected combined worker shutdown error");
30697        };
30698        assert!(matches!(
30699            *primary,
30700            Error::Http {
30701                status: reqwest::StatusCode::UNAUTHORIZED,
30702                ..
30703            }
30704        ));
30705        assert!(matches!(
30706            *deregistration,
30707            Error::Http {
30708                status: reqwest::StatusCode::FORBIDDEN,
30709                ..
30710            }
30711        ));
30712        assert_eq!(
30713            server.request_count("/api/worker/registrations/mock-worker"),
30714            1
30715        );
30716    }
30717
30718    #[tokio::test]
30719    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
30720        let server = MockWorkerServer::start();
30721        let client = Client::builder(server.base_url())
30722            .timeout(Duration::from_secs(2))
30723            .build()
30724            .expect("client");
30725        let mut worker = Worker::new(client, "rust-workers")
30726            .worker_id("activity-only-worker")
30727            .poll_timeout(Duration::from_millis(10));
30728
30729        worker.register_activity(
30730            "activity.only",
30731            |_ctx, _args| async move { Ok(Value::Null) },
30732        );
30733
30734        worker.run_until(async {}).await.expect("run worker");
30735    }
30736
30737    #[tokio::test]
30738    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
30739        let server = MockWorkerServer::start();
30740        let client = Client::builder(server.base_url())
30741            .timeout(Duration::from_secs(2))
30742            .build()
30743            .expect("client");
30744        let mut worker = Worker::new(client, "rust-workers")
30745            .worker_id("workflow-only-worker")
30746            .poll_timeout(Duration::from_millis(10));
30747
30748        worker.register_workflow(
30749            "workflow.only",
30750            |_ctx, _input| async move { Ok(Value::Null) },
30751        );
30752
30753        worker.run_until(async {}).await.expect("run worker");
30754    }
30755
30756    #[tokio::test]
30757    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
30758        let server = MockWorkerServer::start();
30759        let client = Client::builder(server.base_url())
30760            .timeout(Duration::from_secs(2))
30761            .build()
30762            .expect("client");
30763        let observations = Arc::new(Mutex::new(Vec::new()));
30764        let observed = Arc::clone(&observations);
30765        let mut worker = Worker::new(client, "rust-workers")
30766            .worker_id("observed-heartbeat-worker")
30767            .poll_timeout(Duration::from_millis(10))
30768            .on_worker_heartbeat(move |observation| {
30769                observed
30770                    .lock()
30771                    .expect("heartbeat observations")
30772                    .push(observation.clone());
30773            });
30774
30775        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
30776            Ok(Value::Null)
30777        });
30778        let acknowledged = Arc::clone(&observations);
30779        worker
30780            .run_until(async move {
30781                tokio::time::timeout(Duration::from_secs(2), async move {
30782                    loop {
30783                        if !acknowledged
30784                            .lock()
30785                            .expect("heartbeat observations")
30786                            .is_empty()
30787                        {
30788                            break;
30789                        }
30790                        tokio::time::sleep(Duration::from_millis(1)).await;
30791                    }
30792                })
30793                .await
30794                .expect("heartbeat acknowledgement within timeout");
30795            })
30796            .await
30797            .expect("run worker");
30798
30799        let observations = observations.lock().expect("heartbeat observations");
30800        let first = observations.first().expect("heartbeat acknowledgement");
30801        assert_eq!(first.worker_id, "observed-heartbeat-worker");
30802        assert_eq!(first.task_queue, "rust-workers");
30803        assert!(first.acknowledged_at_unix_millis > 0);
30804        assert_eq!(first.acknowledgement, json!({}));
30805    }
30806
30807    #[tokio::test]
30808    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
30809        let server = MockWorkerServer::delayed_heartbeat_worker();
30810        let client = Client::builder(server.base_url())
30811            .timeout(Duration::from_secs(3))
30812            .build()
30813            .expect("client");
30814        let observations = Arc::new(Mutex::new(Vec::new()));
30815        let observed = Arc::clone(&observations);
30816        let mut worker = Worker::new(client, "rust-snapshot-workers")
30817            .max_concurrent_workflow_tasks(1)
30818            .max_concurrent_activity_tasks(1)
30819            .worker_id("rust-snapshot-worker")
30820            .poll_timeout(Duration::from_millis(10))
30821            .on_worker_heartbeat(move |observation| {
30822                observed
30823                    .lock()
30824                    .expect("heartbeat observations")
30825                    .push(observation.clone());
30826            });
30827
30828        worker.register_workflow("snapshot", |ctx, _input| async move {
30829            ctx.wait_signal("finish").await?;
30830            Ok(json!({"status": "finished"}))
30831        });
30832        worker.register_query("snapshot", "current", |ctx, _args| async move {
30833            Ok(json!(ctx
30834                .signals("increment")
30835                .iter()
30836                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
30837                .sum::<i64>()))
30838        });
30839        worker.register_activity("cancel-aware", |_ctx, _args| async move {
30840            Ok(json!({"late": "completion"}))
30841        });
30842
30843        worker
30844            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
30845            .await
30846            .expect("delayed heartbeat must allow a clean worker shutdown");
30847
30848        let observations = observations.lock().expect("heartbeat observations");
30849        assert!(
30850            observations.len() >= 3,
30851            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
30852        );
30853        assert!(
30854            observations.windows(2).all(|pair| {
30855                pair[1].acknowledged_at_unix_millis
30856                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
30857                    >= 850
30858            }),
30859            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
30860        );
30861        drop(observations);
30862
30863        let heartbeat_times = server.request_times("/api/worker/heartbeat");
30864        let delayed_request_at = *heartbeat_times
30865            .get(1)
30866            .expect("intentionally delayed heartbeat request");
30867        let delay_window_start = delayed_request_at + Duration::from_millis(100);
30868        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
30869        for path in [
30870            "/api/worker/workflow-tasks/poll",
30871            "/api/worker/activity-tasks/poll",
30872            "/api/worker/query-tasks/poll",
30873        ] {
30874            assert!(
30875                server
30876                    .request_times(path)
30877                    .iter()
30878                    .any(|received_at| *received_at >= delay_window_start
30879                        && *received_at <= delay_window_end),
30880                "{path} must keep polling while a heartbeat acknowledgement is delayed"
30881            );
30882        }
30883        assert!(
30884            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
30885            "workflow work must be settled"
30886        );
30887        assert!(
30888            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
30889            "activity work must be settled"
30890        );
30891        assert!(
30892            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
30893            "query work must be settled"
30894        );
30895    }
30896
30897    #[tokio::test]
30898    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
30899        let server = MockWorkerServer::heartbeat_retry_worker();
30900        let client = Client::builder(server.base_url())
30901            .timeout(Duration::from_secs(2))
30902            .build()
30903            .expect("client");
30904        let observations = Arc::new(Mutex::new(Vec::new()));
30905        let observed = Arc::clone(&observations);
30906        let worker = Worker::new(client, "rust-workers")
30907            .worker_id("heartbeat-retry-worker")
30908            .retry_policy(WorkerRetryPolicy {
30909                max_retries: 1,
30910                initial_backoff: Duration::from_millis(300),
30911                max_backoff: Duration::from_millis(300),
30912            })
30913            .on_worker_heartbeat(move |observation| {
30914                observed
30915                    .lock()
30916                    .expect("heartbeat observations")
30917                    .push(observation.clone());
30918            });
30919
30920        worker
30921            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
30922            .await
30923            .expect("retryable heartbeat failure must remain bounded and recover");
30924
30925        let observations = observations.lock().expect("heartbeat observations");
30926        assert!(observations.len() >= 3, "heartbeat retry must recover");
30927        assert!(
30928            observations.windows(2).all(|pair| {
30929                pair[1]
30930                    .acknowledged_at_unix_millis
30931                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
30932                    >= 850
30933            }),
30934            "a successful retry must start a fresh advertised cadence: {observations:?}"
30935        );
30936        assert_eq!(
30937            server.request_count("/api/worker/heartbeat"),
30938            observations.len() + 1,
30939            "one retryable failure must add exactly one bounded request"
30940        );
30941    }
30942
30943    #[tokio::test]
30944    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
30945        let server = MockWorkerServer::waiting_query_worker();
30946        let client = Client::builder(server.base_url())
30947            .timeout(Duration::from_secs(2))
30948            .build()
30949            .expect("client");
30950        let observations = Arc::new(Mutex::new(Vec::new()));
30951        let observed = Arc::clone(&observations);
30952        let mut worker = Worker::new(client, "rust-snapshot-workers")
30953            .worker_id("rust-snapshot-worker")
30954            .poll_timeout(Duration::from_millis(10))
30955            .on_worker_heartbeat(move |observation| {
30956                observed
30957                    .lock()
30958                    .expect("heartbeat observations")
30959                    .push(observation.clone());
30960            });
30961
30962        worker.register_workflow("snapshot", |ctx, _input| async move {
30963            ctx.wait_signal("finish").await?;
30964            Ok(json!({"status": "finished"}))
30965        });
30966        worker.register_query("snapshot", "current", |ctx, _args| async move {
30967            let current = ctx
30968                .signals("increment")
30969                .iter()
30970                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
30971                .sum::<i64>();
30972            Ok(json!(current))
30973        });
30974        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
30975        worker
30976            .declare_workflow_signals("snapshot", &["finish"])
30977            .expect("declare finish signal");
30978
30979        worker
30980            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
30981            .await
30982            .expect("pending workflow and query poller must remain live until shutdown");
30983
30984        assert!(
30985            observations.lock().expect("heartbeat observations").len() >= 4,
30986            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
30987        );
30988        assert!(
30989            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
30990            "workflow polling must continue after empty replay acknowledgements"
30991        );
30992        assert!(
30993            server.request_count("/api/worker/query-tasks/poll") >= 2,
30994            "query polling must continue after serving the current query"
30995        );
30996        assert_eq!(
30997            server.request_body("/api/worker/register")["capabilities"],
30998            json!([
30999                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
31000                "workflow_entry_arguments_validation",
31001                DURABLE_SELECTION_CAPABILITY,
31002                MEMO_UPSERTS_CAPABILITY,
31003                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
31004                QUERY_TASKS_CAPABILITY,
31005                WORKFLOW_UPDATES_CAPABILITY,
31006                MESSAGE_STREAMS_CAPABILITY
31007            ])
31008        );
31009        assert_eq!(
31010            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
31011            json!({
31012                "queries": ["current"],
31013                "query_contracts": [{
31014                    "name": "current",
31015                    "parameters": [{
31016                        "name": "args", "position": 0, "required": false,
31017                        "variadic": true, "type": null, "allows_null": true,
31018                        "default_available": false, "default": null,
31019                    }],
31020                }],
31021                "signals": ["finish"],
31022                "signal_contracts": [{
31023                    "name": "finish",
31024                    "parameters": [{
31025                        "name": "args", "position": 0, "required": false,
31026                        "variadic": true, "type": null, "allows_null": true,
31027                        "default_available": false, "default": null,
31028                    }],
31029                }],
31030                "updates": ["replace"],
31031                "update_contracts": [{
31032                    "name": "replace",
31033                    "parameters": [{
31034                        "name": "args", "position": 0, "required": false,
31035                        "variadic": true, "type": null, "allows_null": true,
31036                        "default_available": false, "default": null,
31037                    }],
31038                }],
31039                "update_validators": [],
31040            })
31041        );
31042
31043        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
31044        assert_eq!(
31045            opened["commands"],
31046            json!([{
31047                "type": "open_signal_wait",
31048                "signal_name": "finish",
31049            }])
31050        );
31051
31052        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
31053            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
31054            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
31055            let failure = server.request_body(&fail_path);
31056            assert_eq!(
31057                failure["failure"]["type"],
31058                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
31059            );
31060            assert_eq!(server.request_count(&completion_path), 0);
31061        }
31062
31063        let query_completion =
31064            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
31065        assert_eq!(query_completion["result"], json!(8));
31066
31067        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
31068        assert_eq!(
31069            server.request_count(terminal_path),
31070            1,
31071            "the matching signal must settle the workflow exactly once"
31072        );
31073        let terminal = server.request_body(terminal_path);
31074        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
31075        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
31076        assert_eq!(
31077            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
31078                .expect("terminal workflow result"),
31079            json!({"status": "finished"})
31080        );
31081    }
31082
31083    #[tokio::test]
31084    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
31085        let server = MockWorkerServer::transient_worker_failures();
31086        let client = Client::builder(server.base_url())
31087            .timeout(Duration::from_secs(2))
31088            .build()
31089            .expect("client");
31090        let mut worker = Worker::new(client, "rust-workers")
31091            .max_concurrent_workflow_tasks(1)
31092            .max_concurrent_activity_tasks(1)
31093            .worker_id("retry-worker")
31094            .poll_timeout(Duration::from_millis(10))
31095            .retry_policy(WorkerRetryPolicy {
31096                max_retries: 2,
31097                initial_backoff: Duration::from_millis(1),
31098                max_backoff: Duration::from_millis(1),
31099            });
31100        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31101        worker.register_activity(
31102            "counter.activity",
31103            |_ctx, _input| async move { Ok(Value::Null) },
31104        );
31105        worker.register_query(
31106            "counter",
31107            "current",
31108            |_ctx, _args| async move { Ok(json!(8)) },
31109        );
31110
31111        worker
31112            .run_until(tokio::time::sleep(Duration::from_millis(75)))
31113            .await
31114            .expect("transient failures must not stop the worker");
31115
31116        for path in [
31117            "/api/worker/heartbeat",
31118            "/api/worker/workflow-tasks/poll",
31119            "/api/worker/activity-tasks/poll",
31120            "/api/worker/query-tasks/poll",
31121        ] {
31122            assert!(
31123                server.request_count(path) >= 2,
31124                "{path} must continue after its transient failure"
31125            );
31126        }
31127    }
31128
31129    #[tokio::test]
31130    async fn worker_continues_after_long_poll_capacity_backpressure() {
31131        let server = MockWorkerServer::capacity_limited_activity_poll();
31132        let client = Client::builder(server.base_url())
31133            .timeout(Duration::from_secs(2))
31134            .build()
31135            .expect("client");
31136        let mut worker = Worker::new(client, "rust-workers")
31137            .worker_id("capacity-worker")
31138            .poll_timeout(Duration::from_millis(10))
31139            .retry_policy(WorkerRetryPolicy {
31140                max_retries: 0,
31141                initial_backoff: Duration::from_millis(1),
31142                max_backoff: Duration::from_millis(1),
31143            });
31144        worker.register_activity("capacity.activity", |_ctx, _input| async move {
31145            Ok(json!({"handled": true}))
31146        });
31147
31148        worker
31149            .run_until(tokio::time::sleep(Duration::from_millis(50)))
31150            .await
31151            .expect("capacity backpressure must not stop the worker");
31152
31153        assert!(
31154            server.request_count("/api/worker/activity-tasks/poll") >= 2,
31155            "the activity poller must continue after capacity backpressure"
31156        );
31157        assert_eq!(
31158            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
31159            1,
31160            "the worker must complete work returned after capacity recovers"
31161        );
31162    }
31163
31164    #[test]
31165    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
31166        let capacity = Error::Http {
31167            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31168            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
31169        };
31170        assert_eq!(
31171            worker_poll_capacity_retry_after(&capacity),
31172            Some(Duration::from_secs(3))
31173        );
31174
31175        let rejected_capacity = Error::Http {
31176            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31177            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
31178        };
31179        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
31180        assert!(!worker_operation_is_retryable(&rejected_capacity));
31181
31182        let ordinary_rate_limit = Error::Http {
31183            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31184            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
31185                .to_string(),
31186        };
31187        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
31188        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
31189    }
31190
31191    #[tokio::test]
31192    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
31193        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31194            poll_failures_per_path: 8,
31195            heartbeat_failures: 8,
31196            ..MockWorkerBehavior::default()
31197        });
31198        let client = Client::builder(server.base_url())
31199            .timeout(Duration::from_secs(2))
31200            .build()
31201            .expect("client");
31202        let acknowledgements = Arc::new(AtomicUsize::new(0));
31203        let observed = Arc::clone(&acknowledgements);
31204        let mut worker = Worker::new(client, "rust-workers")
31205            .max_concurrent_workflow_tasks(1)
31206            .max_concurrent_activity_tasks(1)
31207            .recover_transient_outages(true)
31208            .poll_timeout(Duration::from_millis(10))
31209            .retry_policy(WorkerRetryPolicy {
31210                max_retries: 2,
31211                initial_backoff: Duration::from_millis(2),
31212                max_backoff: Duration::from_millis(5),
31213            })
31214            .on_worker_heartbeat(move |_| {
31215                observed.fetch_add(1, Ordering::SeqCst);
31216            });
31217        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31218        worker.register_activity(
31219            "counter.activity",
31220            |_ctx, _input| async move { Ok(Value::Null) },
31221        );
31222        worker.register_query("counter", "current", |_ctx, _args| async move {
31223            Ok(Value::Null)
31224        });
31225
31226        worker
31227            .run_until(tokio::time::sleep(Duration::from_millis(500)))
31228            .await
31229            .expect("a recoverable outage must not stop the service worker");
31230
31231        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
31232        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
31233        for path in [
31234            "/api/worker/workflow-tasks/poll",
31235            "/api/worker/activity-tasks/poll",
31236            "/api/worker/query-tasks/poll",
31237        ] {
31238            let bodies = server.request_bodies(path);
31239            assert!(bodies.len() >= 10, "{path} must resume after recovery");
31240            let first = &bodies[0]["poll_request_id"];
31241            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
31242            for body in &bodies[..9] {
31243                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
31244            }
31245            assert_ne!(&bodies[9]["poll_request_id"], first);
31246            let times = server.request_times(path);
31247            for pair in times[..9].windows(2) {
31248                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
31249            }
31250        }
31251    }
31252
31253    #[tokio::test]
31254    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
31255        for heartbeat_outage in [false, true] {
31256            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31257                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
31258                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
31259                ..MockWorkerBehavior::default()
31260            });
31261            let client = Client::builder(server.base_url()).build().expect("client");
31262            let mut worker = Worker::new(client, "rust-workers")
31263                .max_concurrent_workflow_tasks(1)
31264                .max_concurrent_activity_tasks(1)
31265                .recover_transient_outages(true)
31266                .retry_policy(WorkerRetryPolicy {
31267                    max_retries: 1,
31268                    initial_backoff: Duration::from_secs(5),
31269                    max_backoff: Duration::from_secs(5),
31270                });
31271            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31272            let started = Instant::now();
31273            worker
31274                .run_until(tokio::time::sleep(Duration::from_millis(200)))
31275                .await
31276                .expect("shutdown during an outage is a normal stop");
31277            assert!(started.elapsed() < Duration::from_secs(1));
31278            let path = if heartbeat_outage {
31279                "/api/worker/heartbeat"
31280            } else {
31281                "/api/worker/workflow-tasks/poll"
31282            };
31283            assert_eq!(server.request_count(path), 1);
31284            assert_eq!(
31285                server.request_count("/api/worker/registrations/mock-worker"),
31286                1
31287            );
31288        }
31289    }
31290
31291    #[tokio::test]
31292    async fn worker_outage_recovery_keeps_run_once_bounded() {
31293        let server = MockWorkerServer::unavailable_polls();
31294        let client = Client::builder(server.base_url()).build().expect("client");
31295        let mut worker = Worker::new(client, "rust-workers")
31296            .recover_transient_outages(true)
31297            .retry_policy(WorkerRetryPolicy {
31298                max_retries: 2,
31299                initial_backoff: Duration::from_millis(1),
31300                max_backoff: Duration::from_millis(1),
31301            });
31302        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31303        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
31304        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
31305    }
31306
31307    #[tokio::test]
31308    async fn worker_outage_recovery_respects_disabled_retries() {
31309        let server = MockWorkerServer::unavailable_polls();
31310        let client = Client::builder(server.base_url()).build().expect("client");
31311        let mut worker = Worker::new(client, "rust-workers")
31312            .max_concurrent_workflow_tasks(1)
31313            .max_concurrent_activity_tasks(1)
31314            .recover_transient_outages(true)
31315            .retry_policy(WorkerRetryPolicy {
31316                max_retries: 0,
31317                ..WorkerRetryPolicy::default()
31318            });
31319        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31320        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
31321        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
31322    }
31323
31324    #[tokio::test]
31325    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
31326        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31327            heartbeat_failures: usize::MAX,
31328            unauthorized_polls: true,
31329            ..MockWorkerBehavior::default()
31330        });
31331        let client = Client::builder(server.base_url()).build().expect("client");
31332        let mut worker = Worker::new(client, "rust-workers")
31333            .max_concurrent_workflow_tasks(1)
31334            .max_concurrent_activity_tasks(1)
31335            .recover_transient_outages(true)
31336            .retry_policy(WorkerRetryPolicy {
31337                max_retries: 1,
31338                initial_backoff: Duration::from_secs(5),
31339                max_backoff: Duration::from_secs(5),
31340            });
31341        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31342        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
31343            .await
31344            .expect("fatal poll errors must interrupt heartbeat recovery")
31345            .expect_err("authentication failure is terminal");
31346        assert!(
31347            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
31348        );
31349        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
31350    }
31351
31352    #[tokio::test]
31353    async fn worker_bounds_transport_retries() {
31354        let server = MockWorkerServer::unavailable_polls();
31355        let client = Client::builder(server.base_url())
31356            .timeout(Duration::from_secs(2))
31357            .build()
31358            .expect("client");
31359        let mut worker = Worker::new(client, "rust-workers")
31360            .max_concurrent_workflow_tasks(1)
31361            .max_concurrent_activity_tasks(1)
31362            .worker_id("bounded-retry-worker")
31363            .poll_timeout(Duration::from_millis(10))
31364            .retry_policy(WorkerRetryPolicy {
31365                max_retries: 2,
31366                initial_backoff: Duration::from_millis(1),
31367                max_backoff: Duration::from_millis(1),
31368            });
31369        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31370
31371        let error = worker.run().await.expect_err("retry bound must terminate");
31372        assert!(matches!(error, Error::Transport(_)));
31373        assert_eq!(
31374            server.request_count("/api/worker/workflow-tasks/poll"),
31375            3,
31376            "one initial request plus exactly two retries"
31377        );
31378    }
31379
31380    #[tokio::test]
31381    async fn worker_retry_policy_can_disable_poll_retries() {
31382        let server = MockWorkerServer::unavailable_polls();
31383        let client = Client::builder(server.base_url())
31384            .timeout(Duration::from_secs(2))
31385            .build()
31386            .expect("client");
31387        let mut worker = Worker::new(client, "rust-workers")
31388            .worker_id("no-retry-worker")
31389            .poll_timeout(Duration::from_millis(10))
31390            .retry_policy(WorkerRetryPolicy {
31391                max_retries: 0,
31392                initial_backoff: Duration::from_millis(1),
31393                max_backoff: Duration::from_millis(1),
31394            });
31395        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31396
31397        let error = worker
31398            .run_once()
31399            .await
31400            .expect_err("disabled retries must return the first transport failure");
31401        assert!(matches!(error, Error::Transport(_)));
31402        assert_eq!(
31403            server.request_count("/api/worker/workflow-tasks/poll"),
31404            1,
31405            "max_retries=0 must send only the initial request"
31406        );
31407    }
31408
31409    #[tokio::test]
31410    async fn worker_does_not_retry_authentication_failures() {
31411        let server = MockWorkerServer::unauthorized_polls();
31412        let client = Client::builder(server.base_url())
31413            .timeout(Duration::from_secs(2))
31414            .build()
31415            .expect("client");
31416        let mut worker = Worker::new(client, "rust-workers")
31417            .max_concurrent_workflow_tasks(1)
31418            .max_concurrent_activity_tasks(1)
31419            .worker_id("unauthorized-worker")
31420            .recover_transient_outages(true)
31421            .poll_timeout(Duration::from_millis(10));
31422        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31423
31424        let error = worker
31425            .run()
31426            .await
31427            .expect_err("authentication must terminate");
31428        let Error::Http { status, body } = error else {
31429            panic!("expected stable HTTP authentication error");
31430        };
31431        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
31432        assert!(body.contains("authentication_failed"));
31433        assert_eq!(
31434            server.request_count("/api/worker/workflow-tasks/poll"),
31435            1,
31436            "authentication failures must not be retried"
31437        );
31438    }
31439
31440    #[test]
31441    fn duplicate_registration_keeps_the_original_workflow() {
31442        let client = Client::new("http://127.0.0.1:9").expect("client");
31443        let mut worker = Worker::new(client, "registration-tests");
31444        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
31445        let original = Arc::clone(&worker.workflows["same"].execute);
31446        worker
31447            .set_workflow_definition_sources("same", &["first workflow source"])
31448            .expect("source identity");
31449        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
31450        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
31451        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
31452        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
31453    }
31454
31455    #[test]
31456    fn duplicate_registration_keeps_the_original_activity() {
31457        let client = Client::new("http://127.0.0.1:9").expect("client");
31458        let mut worker = Worker::new(client, "registration-tests");
31459        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
31460        let original = Arc::clone(&worker.activities["same"]);
31461        worker.register_activity_avro_value("same", |_ctx, _input| async {
31462            Ok(AvroValue::String("second".into()))
31463        });
31464        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
31465    }
31466
31467    #[test]
31468    fn duplicate_registration_keeps_original_query_and_update_handlers() {
31469        let client = Client::new("http://127.0.0.1:9").expect("client");
31470        let mut worker = Worker::new(client, "registration-tests");
31471        worker.register_query("orders", "same", |_ctx, _input| async {
31472            Ok(json!("first"))
31473        });
31474        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
31475            panic!("snapshot query");
31476        };
31477        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
31478            Ok(json!("second"))
31479        });
31480        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
31481            panic!("duplicate replaced the query adapter");
31482        };
31483        assert!(Arc::ptr_eq(&original, retained));
31484        worker.register_update("orders", "same", |_ctx, _input| async {
31485            Ok(json!("first"))
31486        });
31487        let original = Arc::clone(&worker.updates["orders"]["same"]);
31488        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
31489            Ok(AvroValue::Null)
31490        });
31491        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
31492    }
31493
31494    #[tokio::test]
31495    async fn duplicate_registration_fails_before_server_contact() {
31496        let server = MockWorkerServer::start();
31497        let client = Client::builder(server.base_url()).build().expect("client");
31498        let mut worker =
31499            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
31500        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
31501        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
31502        let error = worker
31503            .run_once()
31504            .await
31505            .expect_err("ambiguous worker must not poll");
31506        assert!(
31507            error.to_string().contains("duplicate_registration"),
31508            "{error}"
31509        );
31510        assert!(server.requests.lock().expect("requests").is_empty());
31511    }
31512
31513    #[derive(Clone, Debug)]
31514    struct CapturedRequest {
31515        headers: String,
31516        method: String,
31517        path: String,
31518        authorization: Option<String>,
31519        namespace: Option<String>,
31520        worker_protocol: Option<String>,
31521        control_protocol: Option<String>,
31522        body: String,
31523        received_at: Instant,
31524    }
31525
31526    struct MockWorkerServer {
31527        addr: SocketAddr,
31528        stop: Arc<AtomicBool>,
31529        requests: Arc<Mutex<Vec<CapturedRequest>>>,
31530        thread: Option<thread::JoinHandle<()>>,
31531    }
31532
31533    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
31534
31535    #[derive(Clone, Copy, Default)]
31536    struct MockWorkerBehavior {
31537        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
31538        request_override: Option<RequestOverride>,
31539        /// Close the connection after reading the request, without any response.
31540        drop_request: Option<fn(&str, usize) -> bool>,
31541        storage_refusals: usize,
31542        storage_path: Option<&'static str>,
31543        storage_unavailable: bool,
31544        storage_mid_poll: bool,
31545        storage_activity: bool,
31546        storage_query: bool,
31547        storage_wrong_poll_id: bool,
31548        reject_query_protocol: bool,
31549        reject_query_completion: bool,
31550        waiting_query_worker: bool,
31551        decline_registration: bool,
31552        complete_named_signal: bool,
31553        poll_failures_per_path: usize,
31554        long_poll_capacity_responses_per_path: usize,
31555        heartbeat_failures: usize,
31556        heartbeat_failure_request: Option<usize>,
31557        delayed_heartbeat_request: Option<usize>,
31558        heartbeat_response_delay: Duration,
31559        concurrent_requests: bool,
31560        unauthorized_polls: bool,
31561        reject_registration: bool,
31562        reject_registration_protocol: bool,
31563        reject_deregistration: bool,
31564        reject_deregistration_protocol: bool,
31565        cancelled_activity: bool,
31566        draining_polls: bool,
31567        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
31568        workflow_completion_status: Option<&'static str>,
31569        workflow_completion_body: Option<&'static str>,
31570    }
31571
31572    impl MockWorkerServer {
31573        fn start() -> Self {
31574            Self::start_with_behavior(MockWorkerBehavior::default())
31575        }
31576
31577        fn reject_query_protocol() -> Self {
31578            Self::start_with_behavior(MockWorkerBehavior {
31579                reject_query_protocol: true,
31580                ..MockWorkerBehavior::default()
31581            })
31582        }
31583
31584        fn reject_query_completion() -> Self {
31585            Self::start_with_behavior(MockWorkerBehavior {
31586                reject_query_completion: true,
31587                ..MockWorkerBehavior::default()
31588            })
31589        }
31590
31591        fn waiting_query_worker() -> Self {
31592            Self::start_with_behavior(MockWorkerBehavior {
31593                waiting_query_worker: true,
31594                complete_named_signal: true,
31595                ..MockWorkerBehavior::default()
31596            })
31597        }
31598
31599        fn transient_worker_failures() -> Self {
31600            Self::start_with_behavior(MockWorkerBehavior {
31601                poll_failures_per_path: 1,
31602                heartbeat_failures: 1,
31603                ..MockWorkerBehavior::default()
31604            })
31605        }
31606
31607        fn consecutive_poll_failures(count: usize) -> Self {
31608            Self::start_with_behavior(MockWorkerBehavior {
31609                poll_failures_per_path: count,
31610                ..MockWorkerBehavior::default()
31611            })
31612        }
31613
31614        fn capacity_limited_activity_poll() -> Self {
31615            Self::start_with_behavior(MockWorkerBehavior {
31616                long_poll_capacity_responses_per_path: 1,
31617                ..MockWorkerBehavior::default()
31618            })
31619        }
31620
31621        fn delayed_heartbeat_worker() -> Self {
31622            Self::start_with_behavior(MockWorkerBehavior {
31623                waiting_query_worker: true,
31624                delayed_heartbeat_request: Some(2),
31625                heartbeat_response_delay: Duration::from_millis(1_500),
31626                concurrent_requests: true,
31627                cancelled_activity: true,
31628                ..MockWorkerBehavior::default()
31629            })
31630        }
31631
31632        fn heartbeat_retry_worker() -> Self {
31633            Self::start_with_behavior(MockWorkerBehavior {
31634                waiting_query_worker: true,
31635                heartbeat_failure_request: Some(2),
31636                concurrent_requests: true,
31637                ..MockWorkerBehavior::default()
31638            })
31639        }
31640
31641        fn unavailable_polls() -> Self {
31642            Self::start_with_behavior(MockWorkerBehavior {
31643                poll_failures_per_path: usize::MAX,
31644                ..MockWorkerBehavior::default()
31645            })
31646        }
31647
31648        fn unauthorized_polls() -> Self {
31649            Self::start_with_behavior(MockWorkerBehavior {
31650                unauthorized_polls: true,
31651                ..MockWorkerBehavior::default()
31652            })
31653        }
31654
31655        fn rejected_registration() -> Self {
31656            Self::start_with_behavior(MockWorkerBehavior {
31657                reject_registration: true,
31658                ..MockWorkerBehavior::default()
31659            })
31660        }
31661
31662        fn rejected_registration_protocol() -> Self {
31663            Self::start_with_behavior(MockWorkerBehavior {
31664                reject_registration_protocol: true,
31665                ..MockWorkerBehavior::default()
31666            })
31667        }
31668
31669        fn declined_registration() -> Self {
31670            Self::start_with_behavior(MockWorkerBehavior {
31671                decline_registration: true,
31672                ..MockWorkerBehavior::default()
31673            })
31674        }
31675
31676        fn rejected_deregistration() -> Self {
31677            Self::start_with_behavior(MockWorkerBehavior {
31678                reject_deregistration: true,
31679                ..MockWorkerBehavior::default()
31680            })
31681        }
31682
31683        fn rejected_deregistration_protocol() -> Self {
31684            Self::start_with_behavior(MockWorkerBehavior {
31685                reject_deregistration_protocol: true,
31686                ..MockWorkerBehavior::default()
31687            })
31688        }
31689
31690        fn unauthorized_polls_and_rejected_deregistration() -> Self {
31691            Self::start_with_behavior(MockWorkerBehavior {
31692                unauthorized_polls: true,
31693                reject_deregistration: true,
31694                ..MockWorkerBehavior::default()
31695            })
31696        }
31697
31698        fn cancelled_activity() -> Self {
31699            Self::start_with_behavior(MockWorkerBehavior {
31700                cancelled_activity: true,
31701                ..MockWorkerBehavior::default()
31702            })
31703        }
31704
31705        fn draining_polls() -> Self {
31706            Self::start_with_behavior(MockWorkerBehavior {
31707                draining_polls: true,
31708                ..MockWorkerBehavior::default()
31709            })
31710        }
31711
31712        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
31713            Self::start_with_behavior(MockWorkerBehavior {
31714                invalid_task_payload_codec: Some(codec),
31715                ..MockWorkerBehavior::default()
31716            })
31717        }
31718
31719        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
31720            Self::start_with_behavior(MockWorkerBehavior {
31721                workflow_completion_status: Some(status),
31722                workflow_completion_body: Some(body),
31723                ..MockWorkerBehavior::default()
31724            })
31725        }
31726
31727        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
31728            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
31729            listener
31730                .set_nonblocking(true)
31731                .expect("configure mock listener");
31732            let addr = listener.local_addr().expect("mock server address");
31733            let stop = Arc::new(AtomicBool::new(false));
31734            let server_stop = Arc::clone(&stop);
31735            let requests = Arc::new(Mutex::new(Vec::new()));
31736            let server_requests = Arc::clone(&requests);
31737            let thread = thread::spawn(move || {
31738                let mut request_threads = Vec::new();
31739                while !server_stop.load(Ordering::SeqCst) {
31740                    match listener.accept() {
31741                        Ok((mut stream, _)) => {
31742                            if behavior.concurrent_requests {
31743                                let requests = Arc::clone(&server_requests);
31744                                request_threads.push(thread::spawn(move || {
31745                                    handle_mock_worker_request(&mut stream, &requests, behavior)
31746                                }));
31747                            } else {
31748                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
31749                            }
31750                        }
31751                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
31752                            let mut index = 0;
31753                            while index < request_threads.len() {
31754                                if request_threads[index].is_finished() {
31755                                    request_threads
31756                                        .swap_remove(index)
31757                                        .join()
31758                                        .expect("join mock request");
31759                                } else {
31760                                    index += 1;
31761                                }
31762                            }
31763                            thread::sleep(Duration::from_millis(5));
31764                        }
31765                        Err(_) => break,
31766                    }
31767                }
31768                for request_thread in request_threads {
31769                    request_thread.join().expect("join mock request");
31770                }
31771            });
31772
31773            Self {
31774                addr,
31775                stop,
31776                requests,
31777                thread: Some(thread),
31778            }
31779        }
31780
31781        fn base_url(&self) -> String {
31782            format!("http://{}", self.addr)
31783        }
31784
31785        fn worker_protocol_for(&self, path: &str) -> Option<String> {
31786            self.requests
31787                .lock()
31788                .expect("captured requests")
31789                .iter()
31790                .find(|request| request.path == path)
31791                .and_then(|request| request.worker_protocol.clone())
31792        }
31793
31794        fn control_protocol_for(&self, path: &str) -> Option<String> {
31795            self.requests
31796                .lock()
31797                .expect("captured requests")
31798                .iter()
31799                .find(|request| request.path == path)
31800                .and_then(|request| request.control_protocol.clone())
31801        }
31802
31803        fn method_for(&self, path: &str) -> Option<String> {
31804            self.requests
31805                .lock()
31806                .expect("captured requests")
31807                .iter()
31808                .find(|request| request.path == path)
31809                .map(|request| request.method.clone())
31810        }
31811
31812        fn authorization_for(&self, path: &str) -> Option<String> {
31813            self.requests
31814                .lock()
31815                .expect("captured requests")
31816                .iter()
31817                .find(|request| request.path == path)
31818                .and_then(|request| request.authorization.clone())
31819        }
31820
31821        fn namespace_for(&self, path: &str) -> Option<String> {
31822            self.requests
31823                .lock()
31824                .expect("captured requests")
31825                .iter()
31826                .find(|request| request.path == path)
31827                .and_then(|request| request.namespace.clone())
31828        }
31829
31830        fn request_count(&self, path: &str) -> usize {
31831            self.requests
31832                .lock()
31833                .expect("captured requests")
31834                .iter()
31835                .filter(|request| request.path == path)
31836                .count()
31837        }
31838
31839        fn captured_paths(&self) -> Vec<String> {
31840            self.requests
31841                .lock()
31842                .expect("captured requests")
31843                .iter()
31844                .map(|request| request.path.clone())
31845                .collect()
31846        }
31847
31848        fn request_times(&self, path: &str) -> Vec<Instant> {
31849            self.requests
31850                .lock()
31851                .expect("captured requests")
31852                .iter()
31853                .filter(|request| request.path == path)
31854                .map(|request| request.received_at)
31855                .collect()
31856        }
31857
31858        fn request_body(&self, path: &str) -> Value {
31859            let requests = self.requests.lock().expect("captured requests");
31860            let body = &requests
31861                .iter()
31862                .find(|request| request.path == path)
31863                .unwrap_or_else(|| panic!("missing request for {path}"))
31864                .body;
31865            serde_json::from_str(body).unwrap_or_else(|error| {
31866                panic!("invalid JSON request body for {path}: {error}: {body:?}")
31867            })
31868        }
31869
31870        fn request_bodies(&self, path: &str) -> Vec<Value> {
31871            self.requests
31872                .lock()
31873                .expect("captured requests")
31874                .iter()
31875                .filter(|request| request.path == path)
31876                .map(|request| {
31877                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
31878                        panic!(
31879                            "invalid JSON request body for {path}: {error}: {:?}",
31880                            request.body
31881                        )
31882                    })
31883                })
31884                .collect()
31885        }
31886
31887        fn request_headers(&self, path: &str) -> Vec<String> {
31888            self.requests
31889                .lock()
31890                .expect("captured requests")
31891                .iter()
31892                .filter(|request| request.path == path)
31893                .map(|request| request.headers.clone())
31894                .collect()
31895        }
31896    }
31897
31898    impl Drop for MockWorkerServer {
31899        fn drop(&mut self) {
31900            self.stop.store(true, Ordering::SeqCst);
31901            let _ = TcpStream::connect(self.addr);
31902
31903            if let Some(thread) = self.thread.take() {
31904                thread.join().expect("join mock server");
31905            }
31906        }
31907    }
31908
31909    #[test]
31910    fn closed_mock_connection_is_not_a_worker_request() {
31911        let listener = TcpListener::bind("127.0.0.1:0").expect("bind closed connection control");
31912        let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
31913        let (mut stream, _) = listener.accept().unwrap();
31914        drop(client);
31915        let requests = Arc::new(Mutex::new(Vec::new()));
31916        handle_mock_worker_request(
31917            &mut stream,
31918            &requests,
31919            MockWorkerBehavior {
31920                request_override: Some(|_, _, _| {
31921                    panic!("closed connection cannot invoke an HTTP handler")
31922                }),
31923                ..MockWorkerBehavior::default()
31924            },
31925        );
31926        assert!(requests.lock().unwrap().is_empty());
31927    }
31928
31929    fn handle_mock_worker_request(
31930        stream: &mut TcpStream,
31931        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
31932        behavior: MockWorkerBehavior,
31933    ) {
31934        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
31935        let mut buffer = [0_u8; 8192];
31936        let mut request = Vec::new();
31937
31938        loop {
31939            match stream.read(&mut buffer) {
31940                Ok(0) => break,
31941                Ok(read) => {
31942                    request.extend_from_slice(&buffer[..read]);
31943                    if mock_request_is_complete(&request) {
31944                        break;
31945                    }
31946                }
31947                Err(error)
31948                    if matches!(
31949                        error.kind(),
31950                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
31951                    ) =>
31952                {
31953                    break;
31954                }
31955                Err(_) => return,
31956            }
31957        }
31958
31959        if !mock_request_is_complete(&request) {
31960            return;
31961        }
31962
31963        let request = String::from_utf8_lossy(&request);
31964        let body = request
31965            .split_once("\r\n\r\n")
31966            .map(|(_, body)| body)
31967            .unwrap_or_default();
31968        let path = request
31969            .lines()
31970            .next()
31971            .and_then(|line| line.split_whitespace().nth(1))
31972            .unwrap_or_default();
31973        let method = request
31974            .lines()
31975            .next()
31976            .and_then(|line| line.split_whitespace().next())
31977            .unwrap_or_default();
31978        let authorization = request.lines().find_map(|line| {
31979            let (name, value) = line.split_once(':')?;
31980            name.eq_ignore_ascii_case("Authorization")
31981                .then(|| value.trim().to_string())
31982        });
31983        let namespace = request.lines().find_map(|line| {
31984            let (name, value) = line.split_once(':')?;
31985            name.eq_ignore_ascii_case("X-Namespace")
31986                .then(|| value.trim().to_string())
31987        });
31988        let worker_protocol = request.lines().find_map(|line| {
31989            let (name, value) = line.split_once(':')?;
31990            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
31991                .then(|| value.trim().to_string())
31992        });
31993        let control_protocol = request.lines().find_map(|line| {
31994            let (name, value) = line.split_once(':')?;
31995            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
31996                .then(|| value.trim().to_string())
31997        });
31998        let request_number = {
31999            let mut requests = requests.lock().expect("captured requests");
32000            requests.push(CapturedRequest {
32001                headers: request
32002                    .split_once("\r\n\r\n")
32003                    .map_or("", |(headers, _)| headers)
32004                    .to_owned(),
32005                method: method.to_string(),
32006                path: path.to_string(),
32007                authorization,
32008                namespace,
32009                worker_protocol: worker_protocol.clone(),
32010                control_protocol,
32011                body: body.to_string(),
32012                received_at: Instant::now(),
32013            });
32014            requests
32015                .iter()
32016                .filter(|request| request.path == path)
32017                .count()
32018        };
32019
32020        if behavior
32021            .drop_request
32022            .is_some_and(|dropped| dropped(path, request_number))
32023        {
32024            return;
32025        }
32026        if let Some(response) = behavior
32027            .request_override
32028            .and_then(|handler| handler(path, body, request_number))
32029        {
32030            write_mock_response(stream, response.0, &response.1);
32031            return;
32032        }
32033        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
32034            write_mock_response(stream, response.0, &response.1);
32035            return;
32036        }
32037        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
32038            return;
32039        }
32040        let pressure_path = behavior
32041            .storage_path
32042            .is_some_and(|part| path.contains(part));
32043        let prior_failures = if path.ends_with("/poll") {
32044            behavior.poll_failures_per_path
32045        } else {
32046            0
32047        };
32048        if pressure_path
32049            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
32050        {
32051            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
32052            let poll_id = path
32053                .ends_with("/poll")
32054                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
32055            let mut refusal = storage_refusal(
32056                poll_id,
32057                behavior.storage_unavailable,
32058                behavior.storage_mid_poll,
32059            );
32060            if behavior.storage_wrong_poll_id {
32061                refusal["poll_request_id"] = json!("wrong-poll");
32062            }
32063            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
32064            return;
32065        }
32066        if path.contains("/storage-task/")
32067            || path.contains("/storage-activity/")
32068            || path.contains("/storage-query/")
32069        {
32070            write_mock_response(stream, "200 OK", "{}");
32071            return;
32072        }
32073        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
32074            write_mock_response(stream, "200 OK", &json!({"task":{
32075                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
32076                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
32077                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32078                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32079                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
32080            }}).to_string());
32081            return;
32082        }
32083        if behavior.storage_activity
32084            && path == "/api/worker/activity-tasks/poll"
32085            && request_number == 1
32086        {
32087            write_mock_response(stream, "200 OK", &json!({"task":{
32088                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
32089                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32090                "attempt_number":7, "lease_owner":"storage-worker"
32091            }}).to_string());
32092            return;
32093        }
32094
32095        if path == "/api/worker/register" {
32096            if behavior.reject_registration_protocol {
32097                write_mock_response(
32098                    stream,
32099                    "400 Bad Request",
32100                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
32101                );
32102                return;
32103            }
32104            if behavior.reject_registration {
32105                write_mock_response(
32106                    stream,
32107                    "503 Service Unavailable",
32108                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
32109                );
32110                return;
32111            }
32112        }
32113
32114        if path.starts_with("/api/worker/registrations/") {
32115            if behavior.reject_deregistration_protocol {
32116                write_mock_response(
32117                    stream,
32118                    "400 Bad Request",
32119                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
32120                );
32121            } else if behavior.reject_deregistration {
32122                write_mock_response(
32123                    stream,
32124                    "403 Forbidden",
32125                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
32126                );
32127            } else {
32128                write_mock_response(
32129                    stream,
32130                    "200 OK",
32131                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
32132                );
32133            }
32134            return;
32135        }
32136
32137        let is_poll = matches!(
32138            path,
32139            "/api/worker/workflow-tasks/poll"
32140                | "/api/worker/activity-tasks/poll"
32141                | "/api/worker/query-tasks/poll"
32142        );
32143        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
32144            write_mock_response(
32145                stream,
32146                "429 Too Many Requests",
32147                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
32148            );
32149            return;
32150        }
32151        if is_poll && request_number <= behavior.poll_failures_per_path {
32152            return;
32153        }
32154        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
32155            return;
32156        }
32157        if path == "/api/worker/heartbeat"
32158            && behavior.heartbeat_failure_request == Some(request_number)
32159        {
32160            return;
32161        }
32162        if path == "/api/worker/heartbeat"
32163            && behavior.delayed_heartbeat_request == Some(request_number)
32164        {
32165            thread::sleep(behavior.heartbeat_response_delay);
32166        }
32167        if behavior.unauthorized_polls && is_poll {
32168            write_mock_response(
32169                stream,
32170                "401 Unauthorized",
32171                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
32172            );
32173            return;
32174        }
32175        if behavior.draining_polls && is_poll {
32176            write_mock_response(
32177                stream,
32178                "409 Conflict",
32179                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
32180            );
32181            return;
32182        }
32183
32184        if let Some(codec_case) = behavior.invalid_task_payload_codec {
32185            if is_poll && request_number == 1 {
32186                let mut task = match path {
32187                    "/api/worker/workflow-tasks/poll" => json!({
32188                        "task_id": "codec-workflow",
32189                        "workflow_type": "codec.workflow",
32190                        "payload_codec": DEFAULT_CODEC,
32191                        "workflow_task_attempt": 1,
32192                        "lease_owner": "codec-worker"
32193                    }),
32194                    "/api/worker/activity-tasks/poll" => json!({
32195                        "task_id": "codec-activity",
32196                        "activity_attempt_id": "codec-activity-attempt",
32197                        "activity_type": "codec.activity",
32198                        "payload_codec": DEFAULT_CODEC,
32199                        "attempt_number": 1,
32200                        "lease_owner": "codec-worker"
32201                    }),
32202                    "/api/worker/query-tasks/poll" => json!({
32203                        "query_task_id": "codec-query",
32204                        "query_task_attempt": 1,
32205                        "workflow_type": "codec.workflow",
32206                        "query_name": "known",
32207                        "payload_codec": DEFAULT_CODEC,
32208                        "lease_owner": "codec-worker"
32209                    }),
32210                    _ => unreachable!("is_poll limits task codec probe paths"),
32211                };
32212                codec_case.apply(&mut task);
32213                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
32214                return;
32215            }
32216
32217            if matches!(
32218                path,
32219                "/api/worker/workflow-tasks/codec-workflow/fail"
32220                    | "/api/worker/activity-tasks/codec-activity/fail"
32221                    | "/api/worker/query-tasks/codec-query/fail"
32222            ) {
32223                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
32224                return;
32225            }
32226        }
32227
32228        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
32229            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
32230            let body = format!(
32231                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
32232            );
32233            write_mock_response(stream, "400 Bad Request", &body);
32234            return;
32235        }
32236
32237        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
32238        {
32239            write_mock_response(
32240                stream,
32241                "409 Conflict",
32242                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
32243            );
32244            return;
32245        }
32246
32247        if behavior.workflow_completion_status.is_some()
32248            && path == "/api/worker/workflow-tasks/poll"
32249            && request_number == 1
32250        {
32251            write_mock_response(
32252                stream,
32253                "200 OK",
32254                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"}}"#,
32255            );
32256            return;
32257        }
32258
32259        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
32260            if let (Some(status), Some(body)) = (
32261                behavior.workflow_completion_status,
32262                behavior.workflow_completion_body,
32263            ) {
32264                write_mock_response(stream, status, body);
32265                return;
32266            }
32267        }
32268
32269        if behavior.waiting_query_worker {
32270            if behavior.complete_named_signal
32271                && path == "/api/worker/workflow-tasks/poll"
32272                && request_number == 1
32273            {
32274                let body = json!({
32275                    "task": {
32276                        "task_id": "snapshot-open",
32277                        "workflow_id": "snapshot-1",
32278                        "run_id": "snapshot-run-1",
32279                        "workflow_type": "snapshot",
32280                        "payload_codec": DEFAULT_CODEC,
32281                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32282                            .expect("Avro workflow arguments"),
32283                        "history_events": [],
32284                        "workflow_task_attempt": 1,
32285                        "lease_owner": "rust-snapshot-worker"
32286                    }
32287                })
32288                .to_string();
32289                write_mock_response(stream, "200 OK", &body);
32290                return;
32291            }
32292
32293            let signal_request = request_number - usize::from(behavior.complete_named_signal);
32294            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
32295            if path == "/api/worker/workflow-tasks/poll"
32296                && signal_request >= 1
32297                && signal_request <= signal_request_limit
32298            {
32299                let finish = behavior.complete_named_signal && signal_request == 3;
32300                let amounts = if signal_request == 1 {
32301                    vec![3]
32302                } else {
32303                    vec![3, 5]
32304                };
32305                let task_id = if signal_request == 1 {
32306                    "snapshot-wait-3"
32307                } else if finish {
32308                    "snapshot-finish"
32309                } else {
32310                    "snapshot-wait-5"
32311                };
32312                let mut history_events = std::iter::once(json!({
32313                    "event_type": "SignalWaitOpened",
32314                    "payload": {"sequence": 1, "signal_name": "finish"}
32315                }))
32316                .chain(amounts.iter().enumerate().map(|(index, amount)| {
32317                    json!({
32318                        "event_type": "SignalReceived",
32319                        "payload": {
32320                            "signal_id": format!("increment-{amount}"),
32321                            "signal_name": "increment",
32322                            "workflow_sequence": index + 2,
32323                            "payload_codec": DEFAULT_CODEC,
32324                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32325                                .expect("Avro signal envelope")
32326                        }
32327                    })
32328                }))
32329                .collect::<Vec<_>>();
32330                let (resume_id, resume_name, resume_arguments) = if finish {
32331                    history_events.push(json!({
32332                        "event_type": "SignalReceived",
32333                        "payload": {
32334                            "signal_id": "finish",
32335                            "signal_name": "finish",
32336                            "workflow_sequence": 4,
32337                            "payload_codec": DEFAULT_CODEC,
32338                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32339                                .expect("Avro finish signal envelope")
32340                        }
32341                    }));
32342                    (
32343                        "finish".to_string(),
32344                        "finish".to_string(),
32345                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
32346                            .expect("Avro finish resume signal"),
32347                    )
32348                } else {
32349                    let amount = amounts.last().expect("amount");
32350                    (
32351                        format!("increment-{amount}"),
32352                        "increment".to_string(),
32353                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32354                            .expect("Avro increment resume signal"),
32355                    )
32356                };
32357                let body = json!({
32358                    "task": {
32359                        "task_id": task_id,
32360                        "workflow_id": "snapshot-1",
32361                        "run_id": "snapshot-run-1",
32362                        "workflow_type": "snapshot",
32363                        "payload_codec": DEFAULT_CODEC,
32364                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32365                            .expect("Avro workflow arguments"),
32366                        "history_events": history_events,
32367                        "workflow_task_attempt": 1,
32368                        "workflow_signal_id": resume_id,
32369                        "signal_name": resume_name,
32370                        "signal_arguments": resume_arguments,
32371                        "lease_owner": "rust-snapshot-worker"
32372                    }
32373                })
32374                .to_string();
32375                write_mock_response(stream, "200 OK", &body);
32376                return;
32377            }
32378
32379            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
32380                let history_events = [3, 5]
32381                    .into_iter()
32382                    .enumerate()
32383                    .map(|(index, amount)| {
32384                        json!({
32385                            "event_type": "SignalReceived",
32386                            "payload": {
32387                                "signal_id": format!("increment-{amount}"),
32388                                "signal_name": "increment",
32389                                "workflow_sequence": index + 2,
32390                                "payload_codec": DEFAULT_CODEC,
32391                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32392                                    .expect("Avro query signal envelope")
32393                            }
32394                        })
32395                    })
32396                    .collect::<Vec<_>>();
32397                let body = json!({
32398                    "task": {
32399                        "query_task_id": "snapshot-current",
32400                        "query_task_attempt": 1,
32401                        "lease_owner": "rust-snapshot-worker",
32402                        "workflow_id": "snapshot-1",
32403                        "run_id": "snapshot-run-1",
32404                        "workflow_type": "snapshot",
32405                        "query_name": "current",
32406                        "payload_codec": DEFAULT_CODEC,
32407                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32408                            .expect("Avro workflow arguments"),
32409                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32410                            .expect("Avro query arguments"),
32411                        "history_events": history_events,
32412                        "run_status": "waiting"
32413                    }
32414                })
32415                .to_string();
32416                write_mock_response(stream, "200 OK", &body);
32417                return;
32418            }
32419
32420            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
32421                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
32422            {
32423                write_mock_response(
32424                    stream,
32425                    "200 OK",
32426                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
32427                );
32428                return;
32429            }
32430
32431            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
32432                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
32433                return;
32434            }
32435
32436            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
32437                write_mock_response(
32438                    stream,
32439                    "200 OK",
32440                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
32441                );
32442                return;
32443            }
32444
32445            if path == "/api/worker/query-tasks/snapshot-current/complete" {
32446                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
32447                return;
32448            }
32449        }
32450
32451        if matches!(
32452            path,
32453            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
32454        ) {
32455            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
32456                .expect("typed mock result");
32457            let body = json!({
32458                "result": typed_fidelity_probe().into_json().expect("result projection"),
32459                "result_envelope": result,
32460            })
32461            .to_string();
32462            write_mock_response(stream, "200 OK", &body);
32463            return;
32464        }
32465
32466        if path == "/api/workflows/typed-1" {
32467            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
32468                .expect("typed mock result");
32469            let body = json!({
32470                "workflow_id": "typed-1",
32471                "run_id": "run-typed-1",
32472                "workflow_type": "typed.echo",
32473                "status": "completed",
32474                "output": typed_fidelity_probe().into_json().expect("output projection"),
32475                "output_envelope": result,
32476            })
32477            .to_string();
32478            write_mock_response(stream, "200 OK", &body);
32479            return;
32480        }
32481
32482        let (status, body) = match path {
32483            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
32484            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
32485            "/api/workflows" => (
32486                "201 Created",
32487                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
32488            ),
32489            "/api/worker/register" if behavior.decline_registration => (
32490                "200 OK",
32491                r#"{"worker_id":"declined-worker","registered":false}"#,
32492            ),
32493            "/api/worker/register" if behavior.waiting_query_worker => (
32494                "200 OK",
32495                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
32496            ),
32497            "/api/worker/register" => (
32498                "200 OK",
32499                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
32500            ),
32501            "/api/worker/heartbeat" => ("200 OK", "{}"),
32502            "/api/worker/activity-tasks/poll"
32503                if behavior.cancelled_activity && request_number == 1 =>
32504            {
32505                (
32506                    "200 OK",
32507                    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"}}"#,
32508                )
32509            }
32510            "/api/worker/activity-tasks/poll"
32511                if behavior.long_poll_capacity_responses_per_path > 0
32512                    && request_number
32513                        == behavior
32514                            .long_poll_capacity_responses_per_path
32515                            .saturating_add(1) =>
32516            {
32517                (
32518                    "200 OK",
32519                    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"}}"#,
32520                )
32521            }
32522            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
32523                ("200 OK", r#"{"task":null}"#)
32524            }
32525            "/api/worker/query-tasks/poll"
32526                if behavior.reject_query_completion && request_number == 1 =>
32527            {
32528                (
32529                    "200 OK",
32530                    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"}}"#,
32531                )
32532            }
32533            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
32534            "/api/worker/query-tasks/query-capture/complete"
32535            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
32536            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
32537                "200 OK",
32538                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
32539            ),
32540            "/api/worker/activity-tasks/activity-cancel/complete" => (
32541                "409 Conflict",
32542                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
32543            ),
32544            "/api/worker/activity-tasks/activity-typed/complete"
32545            | "/api/worker/activity-tasks/activity-typed/fail"
32546            | "/api/worker/activity-tasks/capacity-activity/complete"
32547            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
32548            "/api/workflows/counter-1/query/current" => (
32549                "200 OK",
32550                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
32551            ),
32552            "/api/workflows/counter-1/query/missing" => (
32553                "404 Not Found",
32554                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
32555            ),
32556            "/api/workflows/wf-lifecycle/cancel" => (
32557                "200 OK",
32558                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
32559            ),
32560            "/api/workflows/wf-lifecycle/terminate" => (
32561                "200 OK",
32562                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
32563            ),
32564            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
32565                "200 OK",
32566                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
32567            ),
32568            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
32569                "200 OK",
32570                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
32571            ),
32572            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
32573                "202 Accepted",
32574                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
32575            ),
32576            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
32577                "200 OK",
32578                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}"#,
32579            ),
32580            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
32581                "409 Conflict",
32582                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
32583            ),
32584            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
32585            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
32586                "409 Conflict",
32587                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
32588            ),
32589            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
32590                "200 OK",
32591                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"}]}}"#,
32592            ),
32593            "/api/workflows/wf-cancelled" => (
32594                "200 OK",
32595                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
32596            ),
32597            "/api/workflows/wf-terminated" => (
32598                "200 OK",
32599                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
32600            ),
32601            "/api/workflows/wf-timed-out" => (
32602                "200 OK",
32603                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
32604            ),
32605            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
32606                "200 OK",
32607                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
32608            ),
32609            "/api/workflows/wf-selected" => (
32610                "200 OK",
32611                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
32612            ),
32613            "/api/workflows/wf-selected/runs/run-selected" => (
32614                "200 OK",
32615                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
32616            ),
32617            _ => ("404 Not Found", r#"{"message":"not found"}"#),
32618        };
32619        write_mock_response(stream, status, body);
32620    }
32621
32622    fn mock_request_is_complete(request: &[u8]) -> bool {
32623        let Some(header_end) = request
32624            .windows(4)
32625            .position(|window| window == b"\r\n\r\n")
32626            .map(|position| position + 4)
32627        else {
32628            return false;
32629        };
32630        let headers = String::from_utf8_lossy(&request[..header_end]);
32631        let content_length = headers.lines().find_map(|line| {
32632            let (name, value) = line.split_once(':')?;
32633            name.eq_ignore_ascii_case("content-length")
32634                .then(|| value.trim().parse::<usize>().ok())
32635                .flatten()
32636        });
32637
32638        request.len() >= header_end + content_length.unwrap_or(0)
32639    }
32640
32641    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
32642        let response = format!(
32643            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
32644            body.len()
32645        );
32646
32647        let _ = stream.write_all(response.as_bytes());
32648        let _ = stream.flush();
32649    }
32650
32651    fn typed_activity_failure_server(
32652        path: &str,
32653        _body: &str,
32654        request_number: usize,
32655    ) -> Option<(&'static str, String)> {
32656        match path {
32657            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
32658                "200 OK",
32659                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(),
32660            )),
32661            "/api/worker/activity-tasks/typed-failure/fail" => Some(("200 OK", "{}".into())),
32662            _ => None,
32663        }
32664    }
32665
32666    #[tokio::test]
32667    async fn managed_activity_reports_application_type_and_non_retryable_marker() {
32668        for non_retryable in [false, true] {
32669            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32670                request_override: Some(typed_activity_failure_server),
32671                ..MockWorkerBehavior::default()
32672            });
32673            let client = Client::builder(server.base_url()).build().unwrap();
32674            let mut worker = Worker::new(client, "typed-queue").worker_id("typed-worker");
32675            worker.register_activity("typed.failure", move |_, _| async move {
32676                Err(ActivityError::new("PaymentDeclined", "card declined")
32677                    .non_retryable(non_retryable)
32678                    .into())
32679            });
32680            assert_eq!(worker.run_once().await.unwrap(), 1);
32681            assert_eq!(
32682                server.request_body("/api/worker/activity-tasks/typed-failure/fail"),
32683                json!({
32684                    "activity_attempt_id": "typed-attempt",
32685                    "lease_owner": "typed-worker",
32686                    "failure": {"type": "PaymentDeclined", "message": "card declined",
32687                                "non_retryable": non_retryable}
32688                })
32689            );
32690        }
32691    }
32692
32693    fn activity_completion_backend_recovery(
32694        path: &str,
32695        _body: &str,
32696        request_number: usize,
32697    ) -> Option<(&'static str, String)> {
32698        match path {
32699            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
32700                "200 OK",
32701                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(),
32702            )),
32703            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
32704                "503 Service Unavailable",
32705                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(),
32706            )),
32707            "/api/worker/activity-tasks/recover-activity/complete" => Some((
32708                "200 OK",
32709                r#"{"outcome":"completed","recorded":true}"#.to_string(),
32710            )),
32711            _ => None,
32712        }
32713    }
32714
32715    fn workflow_completion_backend_recovery(
32716        path: &str,
32717        _body: &str,
32718        request_number: usize,
32719    ) -> Option<(&'static str, String)> {
32720        match path {
32721            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
32722                "200 OK",
32723                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
32724            )),
32725            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
32726                "503 Service Unavailable",
32727                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(),
32728            )),
32729            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
32730                "200 OK",
32731                r#"{"outcome":"completed","recorded":true}"#.to_string(),
32732            )),
32733            _ => None,
32734        }
32735    }
32736
32737    fn workflow_completion_lock_pressure(
32738        path: &str,
32739        body: &str,
32740        request_number: usize,
32741    ) -> Option<(&'static str, String)> {
32742        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number == 1 {
32743            return Some((
32744                "503 Service Unavailable",
32745                json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
32746                    "outcome":"deferred", "recorded":false, "retryable":true,
32747                    "retry_after_seconds":1, "task_id":"recover-workflow",
32748                    "lease_owner":"recover-worker", "workflow_task_attempt":3,
32749                    "backend":{"driver":"sqlite", "lock_pressure":true}})
32750                .to_string(),
32751            ));
32752        }
32753        workflow_completion_backend_recovery(path, body, request_number)
32754    }
32755
32756    fn workflow_completion_lock_pressure_forever(
32757        path: &str,
32758        body: &str,
32759        request_number: usize,
32760    ) -> Option<(&'static str, String)> {
32761        if path == "/api/worker/workflow-tasks/recover-workflow/complete" {
32762            return workflow_completion_lock_pressure(path, body, 1);
32763        }
32764        workflow_completion_lock_pressure(path, body, request_number)
32765    }
32766
32767    fn workflow_completion_lock_pressure_then_expired(
32768        path: &str,
32769        body: &str,
32770        request_number: usize,
32771    ) -> Option<(&'static str, String)> {
32772        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32773            return Some(("409 Conflict", json!({"reason":"lease_expired", "recorded":false,
32774                "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3}).to_string()));
32775        }
32776        workflow_completion_lock_pressure(path, body, request_number)
32777    }
32778
32779    fn workflow_completion_lock_pressure_then_slow(
32780        path: &str,
32781        body: &str,
32782        request_number: usize,
32783    ) -> Option<(&'static str, String)> {
32784        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32785            thread::sleep(Duration::from_secs(2));
32786        }
32787        workflow_completion_lock_pressure(path, body, request_number)
32788    }
32789
32790    fn workflow_completion_pressure_then_backend_loss(
32791        path: &str,
32792        body: &str,
32793        request_number: usize,
32794    ) -> Option<(&'static str, String)> {
32795        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32796            return Some((
32797                "503 Service Unavailable",
32798                json!({"reason":"backend_unavailable", "operation":"complete_workflow_task",
32799                    "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
32800                    "retryable":true, "retry_after_seconds":3, "task_id":"recover-workflow",
32801                    "lease_owner":"recover-worker", "workflow_task_attempt":3})
32802                .to_string(),
32803            ));
32804        }
32805        workflow_completion_lock_pressure(path, body, request_number)
32806    }
32807
32808    fn completion_deferral_worker(server: &MockWorkerServer, calls: Arc<AtomicUsize>) -> Worker {
32809        let client = Client::builder(server.base_url())
32810            .timeout(Duration::from_secs(4))
32811            .build()
32812            .unwrap();
32813        let mut worker = Worker::new(client, "recover-queue")
32814            .worker_id("recover-worker")
32815            .poll_timeout(Duration::from_millis(10));
32816        worker.register_workflow("recover.workflow", move |_ctx, _args| {
32817            let calls = Arc::clone(&calls);
32818            async move {
32819                calls.fetch_add(1, Ordering::SeqCst);
32820                Ok(json!("done"))
32821            }
32822        });
32823        worker
32824    }
32825
32826    #[tokio::test]
32827    async fn workflow_completion_deferral_stops_at_original_cleanup_budget() {
32828        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32829            request_override: Some(workflow_completion_lock_pressure_forever),
32830            ..MockWorkerBehavior::default()
32831        });
32832        let calls = Arc::new(AtomicUsize::new(0));
32833        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32834            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32835        worker
32836            .client
32837            .worker_storage_admission
32838            .as_mut()
32839            .unwrap()
32840            .workflow_completion_retry_deadline =
32841            Some(tokio::time::Instant::now() + Duration::from_millis(250));
32842        let result = tokio::time::timeout(Duration::from_secs(2), worker.poll_workflow_once())
32843            .await
32844            .unwrap();
32845        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32846        assert_eq!(calls.load(Ordering::SeqCst), 1);
32847        assert_eq!(
32848            server
32849                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32850                .len(),
32851            1
32852        );
32853    }
32854
32855    #[tokio::test]
32856    async fn workflow_completion_deferral_bounds_the_inflight_retry() {
32857        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32858            request_override: Some(workflow_completion_lock_pressure_then_slow),
32859            ..MockWorkerBehavior::default()
32860        });
32861        let calls = Arc::new(AtomicUsize::new(0));
32862        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32863            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32864        let start = tokio::time::Instant::now();
32865        worker
32866            .client
32867            .worker_storage_admission
32868            .as_mut()
32869            .unwrap()
32870            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
32871        assert!(matches!(
32872            worker.poll_workflow_once().await,
32873            Err(Error::Timeout)
32874        ));
32875        assert!(start.elapsed() < Duration::from_secs(2));
32876        assert_eq!(calls.load(Ordering::SeqCst), 1);
32877        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32878        assert_eq!(bodies.len(), 2);
32879        assert_eq!(bodies[0], bodies[1]);
32880    }
32881
32882    #[tokio::test]
32883    async fn workflow_completion_deferral_retains_deadline_when_backend_reason_changes() {
32884        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32885            request_override: Some(workflow_completion_pressure_then_backend_loss),
32886            ..MockWorkerBehavior::default()
32887        });
32888        let calls = Arc::new(AtomicUsize::new(0));
32889        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32890            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32891        let start = tokio::time::Instant::now();
32892        worker
32893            .client
32894            .worker_storage_admission
32895            .as_mut()
32896            .unwrap()
32897            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
32898        let result = worker.poll_workflow_once().await;
32899        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32900        assert!(start.elapsed() < Duration::from_secs(2));
32901        assert_eq!(calls.load(Ordering::SeqCst), 1);
32902        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32903        assert_eq!(bodies.len(), 2);
32904        assert_eq!(bodies[0], bodies[1]);
32905    }
32906
32907    #[tokio::test]
32908    async fn workflow_completion_deferral_shutdown_interrupts_prolonged_pressure() {
32909        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32910            request_override: Some(workflow_completion_lock_pressure_forever),
32911            ..MockWorkerBehavior::default()
32912        });
32913        let calls = Arc::new(AtomicUsize::new(0));
32914        let stop = Arc::new(AtomicBool::new(false));
32915        let worker = completion_deferral_worker(&server, Arc::clone(&calls))
32916            .with_storage_admission(Arc::clone(&stop));
32917        let shutdown = async {
32918            while server
32919                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32920                .is_empty()
32921            {
32922                tokio::time::sleep(Duration::from_millis(10)).await;
32923            }
32924            stop.store(true, Ordering::SeqCst);
32925        };
32926        let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
32927            tokio::join!(worker.poll_workflow_once(), shutdown)
32928        })
32929        .await
32930        .unwrap();
32931        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32932        assert_eq!(calls.load(Ordering::SeqCst), 1);
32933        assert_eq!(
32934            server
32935                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32936                .len(),
32937            1
32938        );
32939    }
32940
32941    #[tokio::test]
32942    async fn workflow_completion_deferral_preserves_later_expiry_refusal() {
32943        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32944            request_override: Some(workflow_completion_lock_pressure_then_expired),
32945            ..MockWorkerBehavior::default()
32946        });
32947        let calls = Arc::new(AtomicUsize::new(0));
32948        let worker = completion_deferral_worker(&server, Arc::clone(&calls));
32949        let result = worker.run_once().await;
32950        assert!(
32951            matches!(result, Err(Error::Http { status, ref body }) if status.as_u16() == 409 && body.contains("lease_expired"))
32952        );
32953        assert_eq!(calls.load(Ordering::SeqCst), 1);
32954        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32955        assert_eq!(bodies.len(), 2);
32956        assert_eq!(bodies[0], bodies[1]);
32957        assert!(server
32958            .request_bodies("/api/worker/workflow-tasks/recover-workflow/fail")
32959            .is_empty());
32960    }
32961
32962    #[tokio::test]
32963    async fn managed_workflow_completion_deferral_preserves_bytes_and_server_delay() {
32964        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32965            request_override: Some(workflow_completion_lock_pressure),
32966            ..MockWorkerBehavior::default()
32967        });
32968        let client = Client::builder(server.base_url())
32969            .timeout(Duration::from_secs(2))
32970            .build()
32971            .unwrap();
32972        let calls = Arc::new(AtomicUsize::new(0));
32973        let mut worker = Worker::new(client, "recover-queue")
32974            .worker_id("recover-worker")
32975            .recover_transient_outages(true)
32976            .poll_timeout(Duration::from_millis(10))
32977            .retry_policy(WorkerRetryPolicy {
32978                max_retries: 1,
32979                initial_backoff: Duration::from_millis(10),
32980                max_backoff: Duration::from_millis(10),
32981            });
32982        worker.register_workflow("recover.workflow", {
32983            let calls = Arc::clone(&calls);
32984            move |_ctx, _args| {
32985                let calls = Arc::clone(&calls);
32986                async move {
32987                    calls.fetch_add(1, Ordering::SeqCst);
32988                    Ok(json!("done"))
32989                }
32990            }
32991        });
32992        let start = tokio::time::Instant::now();
32993        assert_eq!(worker.run_once().await.unwrap(), 1);
32994        assert!(start.elapsed() >= Duration::from_secs(1));
32995        assert_eq!(calls.load(Ordering::SeqCst), 1);
32996        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32997        assert_eq!(bodies.len(), 2);
32998        assert_eq!(bodies[0], bodies[1]);
32999    }
33000
33001    #[test]
33002    fn workflow_completion_deferral_requires_an_exact_unrecorded_fence() {
33003        let path = "/worker/workflow-tasks/recover-workflow/complete";
33004        let request = json!({"lease_owner":"recover-worker", "workflow_task_attempt":3});
33005        let response = json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
33006            "outcome":"deferred", "recorded":false, "retryable":true, "retry_after_seconds":1,
33007            "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3,
33008            "backend":{"driver":"sqlite", "lock_pressure":true}});
33009        let error = |body: Value| Error::Http {
33010            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33011            body: body.to_string(),
33012        };
33013        assert_eq!(
33014            worker_deferred_workflow_completion_retry_after(
33015                &error(response.clone()),
33016                path,
33017                Some(&request)
33018            ),
33019            Some(Duration::from_secs(1))
33020        );
33021        for (field, value) in [
33022            ("reason", json!("backend_unavailable")),
33023            ("operation", json!("complete_activity_task")),
33024            ("task_id", json!("other-task")),
33025            ("lease_owner", json!("other-owner")),
33026            ("workflow_task_attempt", json!(4)),
33027            ("recorded", json!(true)),
33028            ("recorded", Value::Null),
33029            ("recorded", json!("false")),
33030            ("retryable", json!(false)),
33031            ("retry_after_seconds", json!(0)),
33032            ("retry_after_seconds", json!(-1)),
33033            ("retry_after_seconds", json!(1.0)),
33034            ("retry_after_seconds", json!("1")),
33035            ("retry_after_seconds", json!(6)),
33036            ("backend", json!({"lock_pressure":false})),
33037        ] {
33038            let mut invalid = response.clone();
33039            invalid[field] = value;
33040            assert_eq!(
33041                worker_deferred_workflow_completion_retry_after(
33042                    &error(invalid),
33043                    path,
33044                    Some(&request)
33045                ),
33046                None,
33047                "invalid {field}"
33048            );
33049        }
33050        for field in [
33051            "reason",
33052            "operation",
33053            "task_id",
33054            "lease_owner",
33055            "workflow_task_attempt",
33056            "recorded",
33057            "retryable",
33058            "retry_after_seconds",
33059            "backend",
33060        ] {
33061            let mut missing = response.clone();
33062            missing.as_object_mut().unwrap().remove(field);
33063            assert_eq!(
33064                worker_deferred_workflow_completion_retry_after(
33065                    &error(missing),
33066                    path,
33067                    Some(&request)
33068                ),
33069                None,
33070                "missing {field}"
33071            );
33072        }
33073        assert_eq!(
33074            worker_deferred_workflow_completion_retry_after(
33075                &error(response.clone()),
33076                "/worker/activity-tasks/recover-workflow/complete",
33077                Some(&request)
33078            ),
33079            None
33080        );
33081        assert_eq!(
33082            worker_deferred_workflow_completion_retry_after(&error(response.clone()), path, None),
33083            None
33084        );
33085        let wrong_status = Error::Http {
33086            status: reqwest::StatusCode::CONFLICT,
33087            body: response.to_string(),
33088        };
33089        assert_eq!(
33090            worker_deferred_workflow_completion_retry_after(&wrong_status, path, Some(&request)),
33091            None
33092        );
33093    }
33094
33095    fn activity_completion_stale_after_backend_recovery(
33096        path: &str,
33097        body: &str,
33098        request_number: usize,
33099    ) -> Option<(&'static str, String)> {
33100        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
33101            return Some((
33102                "409 Conflict",
33103                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(),
33104            ));
33105        }
33106        activity_completion_backend_recovery(path, body, request_number)
33107    }
33108
33109    fn activity_completion_remains_unavailable(
33110        path: &str,
33111        body: &str,
33112        request_number: usize,
33113    ) -> Option<(&'static str, String)> {
33114        if path == "/api/worker/activity-tasks/recover-activity/complete" {
33115            return activity_completion_backend_recovery(path, body, 1);
33116        }
33117        activity_completion_backend_recovery(path, body, request_number)
33118    }
33119
33120    #[tokio::test]
33121    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
33122        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33123            request_override: Some(activity_completion_backend_recovery),
33124            ..MockWorkerBehavior::default()
33125        });
33126        let client = Client::builder(server.base_url())
33127            .timeout(Duration::from_secs(2))
33128            .build()
33129            .expect("client");
33130        let handler_calls = Arc::new(AtomicUsize::new(0));
33131        let mut worker = Worker::new(client, "recover-queue")
33132            .worker_id("recover-worker")
33133            .poll_timeout(Duration::from_millis(10));
33134        worker.register_activity("recover.activity", {
33135            let handler_calls = Arc::clone(&handler_calls);
33136            move |_ctx, _args| {
33137                let handler_calls = Arc::clone(&handler_calls);
33138                async move {
33139                    handler_calls.fetch_add(1, Ordering::SeqCst);
33140                    Ok(json!("done"))
33141                }
33142            }
33143        });
33144
33145        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
33146        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33147        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
33148        assert_eq!(bodies.len(), 2);
33149        assert_eq!(bodies[0], bodies[1]);
33150    }
33151
33152    #[tokio::test]
33153    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
33154        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33155            request_override: Some(workflow_completion_backend_recovery),
33156            ..MockWorkerBehavior::default()
33157        });
33158        let client = Client::builder(server.base_url())
33159            .timeout(Duration::from_secs(2))
33160            .build()
33161            .expect("client");
33162        let handler_calls = Arc::new(AtomicUsize::new(0));
33163        let mut worker = Worker::new(client, "recover-queue")
33164            .worker_id("recover-worker")
33165            .poll_timeout(Duration::from_millis(10));
33166        worker.register_workflow("recover.workflow", {
33167            let handler_calls = Arc::clone(&handler_calls);
33168            move |_ctx, _args| {
33169                let handler_calls = Arc::clone(&handler_calls);
33170                async move {
33171                    handler_calls.fetch_add(1, Ordering::SeqCst);
33172                    Ok(json!("done"))
33173                }
33174            }
33175        });
33176
33177        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
33178        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33179        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
33180        assert_eq!(bodies.len(), 2);
33181        assert_eq!(bodies[0], bodies[1]);
33182    }
33183
33184    #[tokio::test]
33185    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
33186        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33187            request_override: Some(activity_completion_stale_after_backend_recovery),
33188            ..MockWorkerBehavior::default()
33189        });
33190        let client = Client::builder(server.base_url())
33191            .timeout(Duration::from_secs(2))
33192            .build()
33193            .expect("client");
33194        let handler_calls = Arc::new(AtomicUsize::new(0));
33195        let mut worker = Worker::new(client, "recover-queue")
33196            .worker_id("recover-worker")
33197            .poll_timeout(Duration::from_millis(10));
33198        worker.register_activity("recover.activity", {
33199            let handler_calls = Arc::clone(&handler_calls);
33200            move |_ctx, _args| {
33201                let handler_calls = Arc::clone(&handler_calls);
33202                async move {
33203                    handler_calls.fetch_add(1, Ordering::SeqCst);
33204                    Ok(json!("done"))
33205                }
33206            }
33207        });
33208
33209        assert_eq!(
33210            worker
33211                .run_once()
33212                .await
33213                .expect("authoritative stale outcome"),
33214            1
33215        );
33216        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33217        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
33218        assert_eq!(bodies.len(), 2);
33219        assert_eq!(bodies[0], bodies[1]);
33220    }
33221
33222    #[test]
33223    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
33224        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
33225        let response = json!({
33226            "reason":"backend_unavailable", "operation":"complete_activity_task",
33227            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
33228            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
33229            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
33230        });
33231        let path = "/worker/activity-tasks/recover-activity/complete";
33232        let error = |body: Value| Error::Http {
33233            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33234            body: body.to_string(),
33235        };
33236        assert_eq!(
33237            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
33238            Some(Duration::from_secs(1))
33239        );
33240
33241        for (field, invalid) in [
33242            ("operation", json!("poll_activity_task")),
33243            ("outcome", json!("rejected")),
33244            ("worker_id", json!("another-worker")),
33245            ("task_queue", json!("recover-queue")),
33246            ("retryable", json!(false)),
33247            ("retry_after_seconds", json!(0)),
33248            ("task_id", json!("another-task")),
33249            ("lease_owner", json!("another-worker")),
33250            ("activity_attempt_id", json!("another-attempt")),
33251        ] {
33252            let mut invalid_response = response.clone();
33253            invalid_response[field] = invalid;
33254            assert_eq!(
33255                worker_fenced_completion_retry_after(
33256                    &error(invalid_response),
33257                    path,
33258                    Some(&request)
33259                ),
33260                None,
33261                "must not retry mismatched {field}"
33262            );
33263        }
33264        assert_eq!(
33265            worker_fenced_completion_retry_after(&error(response), path, None),
33266            None
33267        );
33268    }
33269
33270    #[tokio::test]
33271    async fn shutdown_interrupts_fenced_completion_backend_wait() {
33272        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33273            request_override: Some(activity_completion_remains_unavailable),
33274            ..MockWorkerBehavior::default()
33275        });
33276        let client = Client::builder(server.base_url())
33277            .timeout(Duration::from_secs(2))
33278            .build()
33279            .expect("client");
33280        let stop = Arc::new(AtomicBool::new(false));
33281        let worker = Worker::new(client, "recover-queue")
33282            .worker_id("recover-worker")
33283            .with_storage_admission(Arc::clone(&stop));
33284        let completion = tokio::spawn(async move {
33285            worker
33286                .client
33287                .complete_activity_task(
33288                    "recover-activity",
33289                    "recover-attempt",
33290                    "recover-worker",
33291                    json!("done"),
33292                    DEFAULT_CODEC,
33293                )
33294                .await
33295        });
33296        let path = "/api/worker/activity-tasks/recover-activity/complete";
33297        tokio::time::timeout(Duration::from_secs(2), async {
33298            while server.request_count(path) == 0 {
33299                tokio::time::sleep(Duration::from_millis(10)).await;
33300            }
33301        })
33302        .await
33303        .expect("first completion request");
33304        stop.store(true, Ordering::SeqCst);
33305        let error = tokio::time::timeout(Duration::from_secs(1), completion)
33306            .await
33307            .expect("shutdown must interrupt retry wait")
33308            .expect("completion task")
33309            .expect_err("backend is still unavailable");
33310        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
33311        assert_eq!(server.request_count(path), 1);
33312    }
33313}