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            task_queue: self.task_queue.clone(),
10065            worker_id: self.worker_id.clone(),
10066            claim_guard: None,
10067            local_heartbeats: None,
10068            worker_session,
10069        };
10070
10071        let operation = async {
10072            let callback = self.activity_callback(handler, ctx, args, false);
10073            if let Some(session) = session {
10074                tokio::select! {
10075                    biased;
10076                    _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
10077                    result = callback => if session.active() { result } else {
10078                        Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
10079                    },
10080                }
10081            } else {
10082                callback.await
10083            }
10084        };
10085        #[cfg(feature = "telemetry")]
10086        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
10087            self.client
10088                .observability_context_supported
10089                .load(Ordering::SeqCst)
10090        }) {
10091            return telemetry
10092                .run_observed(
10093                    "durable.activity.task",
10094                    fields,
10095                    false,
10096                    observations,
10097                    operation,
10098                )
10099                .await;
10100        }
10101        operation.await
10102    }
10103
10104    fn activity_callback(
10105        &self,
10106        handler: &ActivityHandler,
10107        context: ActivityContext,
10108        args: AvroValue,
10109        local: bool,
10110    ) -> ActivityFuture {
10111        #[cfg(feature = "telemetry")]
10112        if let Some(telemetry) = &self.telemetry {
10113            let telemetry = telemetry.clone();
10114            let fields = self.callback_telemetry_fields(&context, local);
10115            let handler = handler.clone();
10116            let name = if local {
10117                "durable.local_activity.attempt"
10118            } else {
10119                "durable.activity.attempt"
10120            };
10121            return Box::pin(async move {
10122                telemetry
10123                    .run(
10124                        name,
10125                        fields,
10126                        true,
10127                        async move { handler(context, args).await },
10128                    )
10129                    .await
10130            });
10131        }
10132        #[cfg(not(feature = "telemetry"))]
10133        let _ = local;
10134        handler(context, args)
10135    }
10136}
10137
10138fn poller_result(
10139    kind: &str,
10140    result: std::result::Result<Result<()>, tokio::task::JoinError>,
10141) -> Result<()> {
10142    match result {
10143        Ok(result) => result,
10144        Err(error) => Err(Error::WorkerLoop(format!(
10145            "{kind} poller join error: {error}"
10146        ))),
10147    }
10148}
10149
10150fn optional_poller_result(
10151    kind: &str,
10152    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
10153) -> Result<()> {
10154    match result {
10155        Some(result) => poller_result(kind, result),
10156        None => Ok(()),
10157    }
10158}
10159
10160async fn join_pollers(
10161    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10162    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10163    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10164) -> Result<()> {
10165    let mut first_error = None;
10166
10167    if let Some(handle) = workflow_poller {
10168        if let Err(error) = poller_result("workflow", handle.await) {
10169            first_error.get_or_insert(error);
10170        }
10171    }
10172
10173    if let Some(handle) = activity_poller {
10174        if let Err(error) = poller_result("activity", handle.await) {
10175            first_error.get_or_insert(error);
10176        }
10177    }
10178
10179    if let Some(handle) = query_poller {
10180        if let Err(error) = poller_result("query", handle.await) {
10181            first_error.get_or_insert(error);
10182        }
10183    }
10184
10185    if let Some(error) = first_error {
10186        Err(error)
10187    } else {
10188        Ok(())
10189    }
10190}
10191
10192fn default_worker_id() -> String {
10193    let millis = SystemTime::now()
10194        .duration_since(UNIX_EPOCH)
10195        .unwrap_or_default()
10196        .as_millis();
10197    format!("rust-worker-{}-{millis}", std::process::id())
10198}
10199
10200fn percent_encode_path_segment(segment: &str) -> String {
10201    const HEX: &[u8; 16] = b"0123456789ABCDEF";
10202    let mut encoded = String::with_capacity(segment.len());
10203
10204    for byte in segment.bytes() {
10205        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
10206            encoded.push(char::from(byte));
10207        } else {
10208            encoded.push('%');
10209            encoded.push(char::from(HEX[(byte >> 4) as usize]));
10210            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
10211        }
10212    }
10213
10214    encoded
10215}
10216
10217fn unique_request_id(prefix: &str) -> String {
10218    let nanos = SystemTime::now()
10219        .duration_since(UNIX_EPOCH)
10220        .unwrap_or_default()
10221        .as_nanos();
10222    format!("{prefix}-{}-{nanos}", std::process::id())
10223}
10224
10225#[derive(Debug)]
10226struct QueryTaskExecutionFailure {
10227    reason: String,
10228    message: String,
10229    failure_type: String,
10230}
10231
10232impl QueryTaskExecutionFailure {
10233    fn new(
10234        reason: impl Into<String>,
10235        message: impl Into<String>,
10236        failure_type: impl Into<String>,
10237    ) -> Self {
10238        Self {
10239            reason: reason.into(),
10240            message: message.into(),
10241            failure_type: failure_type.into(),
10242        }
10243    }
10244}
10245
10246/// Typed local state owned by one deterministic workflow invocation.
10247///
10248/// Use [`WorkflowInstance::update`] for the same state transitions during
10249/// ordinary execution and replay. A replayed query receives a detached
10250/// immutable `Arc<S>` rather than this mutation-capable handle.
10251#[derive(Clone, Debug)]
10252pub struct WorkflowInstance<S> {
10253    state: Arc<Mutex<S>>,
10254}
10255
10256impl<S> WorkflowInstance<S> {
10257    fn new(state: S) -> Self {
10258        Self {
10259            state: Arc::new(Mutex::new(state)),
10260        }
10261    }
10262
10263    /// Read the current workflow-instance state without changing it.
10264    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
10265        let state = self
10266            .state
10267            .lock()
10268            .map_err(|_| Error::WorkflowStatePoisoned)?;
10269        Ok(reader(&state))
10270    }
10271
10272    /// Apply one deterministic workflow-instance state transition.
10273    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
10274        let mut state = self
10275            .state
10276            .lock()
10277            .map_err(|_| Error::WorkflowStatePoisoned)?;
10278        Ok(transition(&mut state))
10279    }
10280}
10281
10282impl<S: Clone> WorkflowInstance<S> {
10283    fn snapshot(&self) -> Result<S> {
10284        self.read(Clone::clone)
10285    }
10286}
10287
10288#[derive(Clone, Debug, PartialEq)]
10289pub struct MessageStreamMessage {
10290    pub stream_name: String,
10291    pub message_id: String,
10292    pub position: u64,
10293    pub arguments: Vec<AvroValue>,
10294}
10295
10296#[derive(Clone, Debug)]
10297pub struct MessageStream {
10298    ctx: WorkflowContext,
10299    name: String,
10300}
10301
10302impl MessageStream {
10303    /// Wait for one message, then return a bounded currently-available batch.
10304    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
10305        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
10306            return Err(Error::Codec(format!(
10307                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
10308            )));
10309        }
10310        loop {
10311            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
10312                return Ok(batch);
10313            }
10314
10315            self.ctx.record_message_stream_wait(&self.name)?;
10316            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
10317            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
10318            self.ctx.buffer_message_stream_delivery(arguments)?;
10319            if let Some(sequence) = replay_wait_sequence {
10320                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
10321            }
10322        }
10323    }
10324
10325    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
10326        self.receive(1)
10327            .await?
10328            .into_iter()
10329            .next()
10330            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
10331    }
10332}
10333
10334#[derive(Clone, Debug)]
10335pub struct WorkflowContext {
10336    state: Arc<Mutex<WorkflowState>>,
10337    cancellation_scope_id: String,
10338}
10339
10340fn valid_memo_key(key: &str) -> bool {
10341    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
10342
10343    !key.is_empty()
10344        && key.len() <= 64
10345        && (numeric_candidate.is_empty()
10346            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
10347        && key
10348            .bytes()
10349            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
10350}
10351
10352fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
10353    BASE64
10354        .decode(encode_avro_value(value)?.blob)
10355        .map(|bytes| bytes.len())
10356        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
10357}
10358
10359fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
10360    let AvroValue::Map(entries) = value else {
10361        return Err(Error::InvalidMemoUpdate(
10362            "entries must serialize to an Avro string-keyed map".to_string(),
10363        ));
10364    };
10365    if require_entries && entries.is_empty() {
10366        return Err(Error::InvalidMemoUpdate(
10367            "at least one entry is required".to_string(),
10368        ));
10369    }
10370    if entries.len() > MAX_MEMO_ENTRIES {
10371        return Err(Error::InvalidMemoUpdate(format!(
10372            "at most {MAX_MEMO_ENTRIES} entries are allowed"
10373        )));
10374    }
10375
10376    for (key, value) in &entries {
10377        if !valid_memo_key(&key) {
10378            return Err(Error::InvalidMemoUpdate(
10379                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
10380            ));
10381        }
10382        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
10383            return Err(Error::InvalidMemoUpdate(format!(
10384                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
10385            )));
10386        }
10387    }
10388
10389    let value = AvroValue::Map(entries);
10390    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
10391        return Err(Error::InvalidMemoUpdate(format!(
10392            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
10393        )));
10394    }
10395    Ok(value)
10396}
10397
10398fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
10399    let object = envelope.as_object().ok_or_else(|| {
10400        Error::InvalidMemoUpdate(
10401            "history field must use the public {codec, blob} payload envelope".to_string(),
10402        )
10403    })?;
10404    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
10405        return Err(Error::InvalidMemoUpdate(
10406            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
10407        ));
10408    }
10409
10410    canonical_memo_entries(
10411        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
10412        require_entries,
10413    )
10414}
10415
10416impl WorkflowContext {
10417    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
10418        let name = name.into();
10419        if name.is_empty()
10420            || name.len() > 128
10421            || !name.bytes().all(|byte| {
10422                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
10423            })
10424        {
10425            return Err(Error::Codec(
10426                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
10427                    .to_string(),
10428            ));
10429        }
10430        Ok(MessageStream {
10431            ctx: self.clone(),
10432            name,
10433        })
10434    }
10435
10436    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
10437        let mut state = self
10438            .state
10439            .lock()
10440            .map_err(|_| Error::WorkflowStatePoisoned)?;
10441        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
10442        state
10443            .message_stream_waits
10444            .insert(name.to_string(), position);
10445        Ok(())
10446    }
10447
10448    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
10449        let mut state = self
10450            .state
10451            .lock()
10452            .map_err(|_| Error::WorkflowStatePoisoned)?;
10453        let cursor = state
10454            .message_stream_cursors
10455            .get(&message.stream_name)
10456            .copied()
10457            .unwrap_or(0);
10458        if message.position <= cursor {
10459            return Ok(());
10460        }
10461        let pending = state
10462            .message_stream_messages
10463            .entry(message.stream_name.clone())
10464            .or_default();
10465        if pending.iter().any(|candidate| {
10466            candidate.position == message.position || candidate.message_id == message.message_id
10467        }) {
10468            return Ok(());
10469        }
10470        pending.push(message);
10471        pending.sort_by_key(|candidate| candidate.position);
10472        Ok(())
10473    }
10474
10475    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
10476        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
10477            match delivery {
10478                MessageStreamDelivery::Message(message) => {
10479                    let stream_name = message.stream_name.clone();
10480                    self.buffer_message_stream(message)?;
10481                    return Ok(Some(stream_name));
10482                }
10483                MessageStreamDelivery::Cursor {
10484                    stream_name,
10485                    through_position,
10486                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
10487            }
10488        }
10489        Ok(None)
10490    }
10491
10492    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
10493        let state = self
10494            .state
10495            .lock()
10496            .map_err(|_| Error::WorkflowStatePoisoned)?;
10497        Ok(match state.recorded_commands.get(state.command_cursor) {
10498            Some(RecordedCommand::SignalWait {
10499                sequence,
10500                signal_name,
10501                ..
10502            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
10503            _ => None,
10504        })
10505    }
10506
10507    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
10508        let (history, payload_codec) = {
10509            let state = self
10510                .state
10511                .lock()
10512                .map_err(|_| Error::WorkflowStatePoisoned)?;
10513            (
10514                Arc::clone(&state.history_events),
10515                state.payload_codec.clone(),
10516            )
10517        };
10518
10519        let Some(opened_index) = history.iter().position(|event| {
10520            event.event_type == "SignalWaitOpened"
10521                && durable_event_sequence(event) == Some(wait_sequence)
10522                && event.payload.get("signal_name").and_then(Value::as_str)
10523                    == Some(MESSAGE_STREAM_SIGNAL)
10524        }) else {
10525            return Ok(());
10526        };
10527        let boundary_index = history
10528            .iter()
10529            .enumerate()
10530            .skip(opened_index + 1)
10531            .find_map(|(index, event)| {
10532                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
10533                    && is_authored_command_open_event(event))
10534                .then_some(index)
10535            })
10536            .unwrap_or(history.len());
10537
10538        for event in history[opened_index + 1..boundary_index]
10539            .iter()
10540            .filter(|event| {
10541                event.event_type == "SignalReceived"
10542                    && event.payload.get("signal_name").and_then(Value::as_str)
10543                        == Some(MESSAGE_STREAM_SIGNAL)
10544            })
10545        {
10546            let arguments = decode_signal_event_arguments(event, &payload_codec)?
10547                .into_iter()
10548                .map(AvroValue::into_json)
10549                .collect::<Result<Vec<_>>>()?;
10550            self.buffer_message_stream_delivery(arguments)?;
10551        }
10552        Ok(())
10553    }
10554
10555    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
10556        let mut state = self
10557            .state
10558            .lock()
10559            .map_err(|_| Error::WorkflowStatePoisoned)?;
10560        let cursor = state
10561            .message_stream_cursors
10562            .entry(name.to_string())
10563            .or_default();
10564        *cursor = (*cursor).max(through_position);
10565        if let Some(pending) = state.message_stream_messages.get_mut(name) {
10566            pending.retain(|message| message.position > through_position);
10567        }
10568        Ok(())
10569    }
10570
10571    fn take_message_stream_batch(
10572        &self,
10573        name: &str,
10574        max_items: usize,
10575    ) -> Result<Option<Vec<MessageStreamMessage>>> {
10576        let mut state = self
10577            .state
10578            .lock()
10579            .map_err(|_| Error::WorkflowStatePoisoned)?;
10580        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
10581        let pending = state
10582            .message_stream_messages
10583            .entry(name.to_string())
10584            .or_default();
10585        let count = contiguous_message_stream_count(pending, cursor, max_items);
10586        if count == 0 {
10587            return Ok(None);
10588        }
10589        let batch = pending.drain(..count).collect::<Vec<_>>();
10590        let position = batch.last().map(|message| message.position).unwrap_or(0);
10591        state
10592            .message_stream_cursors
10593            .insert(name.to_string(), position);
10594        state.message_stream_waits.remove(name);
10595        Ok(Some(batch))
10596    }
10597
10598    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
10599        let state = self
10600            .state
10601            .lock()
10602            .map_err(|_| Error::WorkflowStatePoisoned)?;
10603        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
10604        cursors.sort_by_key(|(name, _)| *name);
10605        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
10606        waits.sort_by_key(|(name, _)| *name);
10607        Ok((
10608            cursors
10609                .into_iter()
10610                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
10611                .collect(),
10612            waits
10613                .into_iter()
10614                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
10615                .collect(),
10616        ))
10617    }
10618    /// Identity of the parent workflow currently being replayed.
10619    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
10620        let state = self
10621            .state
10622            .lock()
10623            .map_err(|_| Error::WorkflowStatePoisoned)?;
10624        Ok(WorkflowIdentity {
10625            workflow_id: state.workflow_id.clone(),
10626            run_id: state.run_id.clone(),
10627        })
10628    }
10629
10630    /// Return the server-published history budget for this workflow task.
10631    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
10632        let state = self
10633            .state
10634            .lock()
10635            .map_err(|_| Error::WorkflowStatePoisoned)?;
10636        Ok(state.history_budget.clone())
10637    }
10638
10639    /// Continue this workflow instance as a fresh run with replacement arguments.
10640    ///
10641    /// Return this value directly from the workflow handler. The worker converts
10642    /// it to the terminal protocol command only after replay has consumed every
10643    /// recorded durable command.
10644    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
10645        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
10646    }
10647
10648    /// Continue as new with optional workflow-type and task-queue overrides.
10649    pub fn continue_as_new_with_options<T: Serialize>(
10650        &self,
10651        options: ContinueAsNewOptions,
10652        args: T,
10653    ) -> Result<Value> {
10654        options.validate()?;
10655        Err(Error::ContinueAsNew(ContinueAsNewRequest {
10656            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
10657            options,
10658        }))
10659    }
10660
10661    pub fn activity<T: Serialize>(
10662        &self,
10663        activity_type: impl Into<String>,
10664        args: T,
10665    ) -> ActivityCall {
10666        self.activity_with_options(activity_type, ActivityOptions::new(), args)
10667    }
10668
10669    pub fn activity_on_queue<T, Q>(
10670        &self,
10671        activity_type: impl Into<String>,
10672        task_queue: Option<Q>,
10673        args: T,
10674    ) -> ActivityCall
10675    where
10676        T: Serialize,
10677        Q: Into<String>,
10678    {
10679        let mut options = ActivityOptions::new();
10680        options.task_queue = task_queue.map(Into::into);
10681        self.activity_with_options(activity_type, options, args)
10682    }
10683
10684    /// Schedule one durable activity with retry, routing, and timeout options.
10685    ///
10686    /// Options are validated before the command is emitted. Once the command is
10687    /// recorded, replay consumes the same activity lifecycle at this command
10688    /// position and never emits a duplicate schedule.
10689    ///
10690    /// ```no_run
10691    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
10692    /// # use std::time::Duration;
10693    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
10694    /// let result = ctx
10695    ///     .activity_with_options(
10696    ///         "charge-card",
10697    ///         ActivityOptions::new()
10698    ///             .task_queue("payments")
10699    ///             .retry_policy(
10700    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
10701    ///                     Duration::from_secs(1),
10702    ///                     2,
10703    ///                     Some(Duration::from_secs(30)),
10704    ///                 ),
10705    ///             )
10706    ///             .start_to_close_timeout(Duration::from_secs(60))
10707    ///             .schedule_to_close_timeout(Duration::from_secs(180))
10708    ///             .heartbeat_timeout(Duration::from_secs(15)),
10709    ///         json!([{"order_id": "order-42"}]),
10710    ///     )
10711    ///     .await;
10712    /// match result {
10713    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
10714    ///         "reason": failure.reason,
10715    ///         "timeout_kind": failure.timeout_kind,
10716    ///     })),
10717    ///     other => other,
10718    /// }
10719    /// # }
10720    /// ```
10721    pub fn activity_with_options<T: Serialize>(
10722        &self,
10723        activity_type: impl Into<String>,
10724        options: ActivityOptions,
10725        args: T,
10726    ) -> ActivityCall {
10727        ActivityCall {
10728            ctx: self.clone(),
10729            activity_type: activity_type.into(),
10730            options,
10731            worker_session: None,
10732            args: Some(AvroValue::from_serialize(&args)),
10733            scheduled: false,
10734            local: false,
10735            local_result: None,
10736            parallel_group_path: Vec::new(),
10737        }
10738    }
10739
10740    pub async fn activity_avro_value<T: Serialize>(
10741        &self,
10742        activity_type: impl Into<String>,
10743        args: T,
10744    ) -> Result<AvroValue> {
10745        let mut call = self.activity(activity_type, args);
10746        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10747    }
10748
10749    pub async fn activity_avro_value_with_options<T: Serialize>(
10750        &self,
10751        activity_type: impl Into<String>,
10752        options: ActivityOptions,
10753        args: T,
10754    ) -> Result<AvroValue> {
10755        let mut call = self.activity_with_options(activity_type, options, args);
10756        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10757    }
10758
10759    /// Schedule an activity with a Serde request and decode its Serde result.
10760    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
10761    where
10762        I: Serialize,
10763        O: DeserializeOwned,
10764    {
10765        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
10766            .await
10767    }
10768
10769    /// Schedule an activity with options and decode its result into `O`.
10770    ///
10771    /// Both directions use the fixed Avro Value codec. In particular, this
10772    /// method does not deserialize the JSON-safe inspection projection returned
10773    /// by the dynamic [`ActivityCall`] future.
10774    pub async fn activity_typed_with_options<I, O>(
10775        &self,
10776        activity_type: impl Into<String>,
10777        options: ActivityOptions,
10778        args: I,
10779    ) -> Result<O>
10780    where
10781        I: Serialize,
10782        O: DeserializeOwned,
10783    {
10784        let activity_type = activity_type.into();
10785        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
10786            handler_type_error::<I>(
10787                HandlerKind::Activity,
10788                &activity_type,
10789                HandlerValueKind::Input,
10790                error.to_string(),
10791            )
10792        });
10793        let mut call = ActivityCall {
10794            ctx: self.clone(),
10795            activity_type: activity_type.clone(),
10796            options,
10797            worker_session: None,
10798            args: Some(encoded),
10799            scheduled: false,
10800            local: false,
10801            local_result: None,
10802            parallel_group_path: Vec::new(),
10803        };
10804        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
10805        decode_handler_result(result, HandlerKind::Activity, &activity_type)
10806    }
10807
10808    /// Schedule and join a deterministic activity/child/timer group.
10809    ///
10810    /// Nested groups retain their input shape. Every durable leaf is scheduled
10811    /// before this future yields, results are assembled by declaration order,
10812    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
10813    /// declaration path, stable group metadata, and completed siblings.
10814    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10815        ParallelCall::new(self.clone(), operations)
10816    }
10817
10818    /// Alias for [`WorkflowContext::parallel`].
10819    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
10820        self.parallel(operations)
10821    }
10822
10823    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
10824    pub async fn parallel_avro_value(
10825        &self,
10826        operations: Vec<ParallelOperation>,
10827    ) -> Result<Vec<ParallelAvroResult>> {
10828        let mut call = self.parallel(operations);
10829        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10830    }
10831
10832    /// Start every durable operation and resume from the one winner persisted
10833    /// by Server. Non-winning operations continue and remain addressable.
10834    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
10835        let operations = operations
10836            .into_iter()
10837            .enumerate()
10838            .map(|(index, operation)| (SelectionKey::Index(index), operation))
10839            .collect();
10840        SelectCall::new(self.clone(), operations)
10841    }
10842
10843    /// Named-key variant of [`WorkflowContext::select`].
10844    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
10845    where
10846        K: Into<SelectionKey>,
10847    {
10848        SelectCall::new(
10849            self.clone(),
10850            operations
10851                .into_iter()
10852                .map(|(key, operation)| (key.into(), operation))
10853                .collect(),
10854        )
10855    }
10856
10857    /// Create a workflow-local deterministic compensation registry.
10858    pub fn saga(&self) -> Saga {
10859        Saga::new(self.clone())
10860    }
10861
10862    /// Whether cancellation has reached this replay's authored boundary.
10863    ///
10864    /// Server's current `/cancel` route is terminal and does not set this flag.
10865    /// A canonical service request remains pending until its committed delivery
10866    /// is consumed. Request observation alone does not authorize an exception.
10867    pub fn is_cancellation_requested(&self) -> Result<bool> {
10868        let state = self
10869            .state
10870            .lock()
10871            .map_err(|_| Error::WorkflowStatePoisoned)?;
10872        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10873            return Ok(state
10874                .scope_delivery
10875                .as_ref()
10876                .unwrap()
10877                .contexts
10878                .contains_key(&self.cancellation_scope_id));
10879        }
10880        Ok(state.cancel_requested
10881            || state
10882                .scope_delivery
10883                .as_ref()
10884                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
10885    }
10886
10887    /// Raise a typed cooperative cancellation at an author-controlled point.
10888    ///
10889    /// Passing this result to [`Saga::finish`] compensates already registered
10890    /// forward steps before the cancellation remains the initiating outcome.
10891    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
10892        let mut state = self
10893            .state
10894            .lock()
10895            .map_err(|_| Error::WorkflowStatePoisoned)?;
10896        if state.cancellation_shield_depth == 0 {
10897            if let Some(replay) = &state.scope_delivery {
10898                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
10899                    let delivered = replay
10900                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
10901                        .ok_or_else(|| {
10902                            Error::InvalidCooperativeCancellation(
10903                                "scoped request lacks its consumed original delivery".into(),
10904                            )
10905                        })?;
10906                    return Err(Error::CancellationScopeRequested(
10907                        CancellationScopeRequested {
10908                            context: context
10909                                .clone()
10910                                .with_replay(Some(Arc::downgrade(&self.state))),
10911                            delivery: delivered.boundary.clone(),
10912                        },
10913                    ));
10914                }
10915            }
10916        }
10917        if state.cancel_requested && state.cancellation_shield_depth == 0 {
10918            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
10919                return Ok(());
10920            }
10921            return Err(state.cancellation_error());
10922        }
10923        Ok(())
10924    }
10925
10926    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10927        SignalCall {
10928            ctx: self.clone(),
10929            signal_name: signal_name.into(),
10930            runtime_reserved_allowed: false,
10931            opened_wait: false,
10932            matched_pending: false,
10933            parallel_group_path: Vec::new(),
10934        }
10935    }
10936
10937    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
10938        SignalCall {
10939            ctx: self.clone(),
10940            signal_name: signal_name.into(),
10941            runtime_reserved_allowed: true,
10942            opened_wait: false,
10943            matched_pending: false,
10944            parallel_group_path: Vec::new(),
10945        }
10946    }
10947
10948    pub async fn wait_signal_avro_value(
10949        &self,
10950        signal_name: impl Into<String>,
10951    ) -> Result<Vec<AvroValue>> {
10952        let mut call = self.wait_signal(signal_name);
10953        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
10954    }
10955
10956    /// Return every committed signal argument list with the given name.
10957    ///
10958    /// This history-backed view is deterministic and is intended for
10959    /// condition predicates that must be re-evaluated after a signal while the
10960    /// workflow is blocked on [`WorkflowContext::wait_condition`].
10961    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
10962        self.signals_avro_value(signal_name)?
10963            .into_iter()
10964            .map(|arguments| {
10965                arguments
10966                    .into_iter()
10967                    .map(AvroValue::into_json)
10968                    .collect::<Result<Vec<_>>>()
10969            })
10970            .collect()
10971    }
10972
10973    /// Lossless fixed Avro Value view of committed signals with the given name.
10974    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
10975        let state = self
10976            .state
10977            .lock()
10978            .map_err(|_| Error::WorkflowStatePoisoned)?;
10979        state
10980            .history_events
10981            .iter()
10982            .filter(|event| {
10983                event.event_type == "SignalReceived"
10984                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
10985            })
10986            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
10987            .collect()
10988    }
10989
10990    /// Return every committed update argument list with the given name.
10991    ///
10992    /// Accepted and applied records for the same update ID are de-duplicated.
10993    /// A Server task created after an update therefore replays the workflow and
10994    /// re-evaluates an open condition without application polling.
10995    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
10996        self.updates_avro_value(update_name)?
10997            .into_iter()
10998            .map(|arguments| {
10999                arguments
11000                    .into_iter()
11001                    .map(AvroValue::into_json)
11002                    .collect::<Result<Vec<_>>>()
11003            })
11004            .collect()
11005    }
11006
11007    /// Lossless fixed Avro Value view of committed updates with the given name.
11008    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
11009        let state = self
11010            .state
11011            .lock()
11012            .map_err(|_| Error::WorkflowStatePoisoned)?;
11013        let mut seen = Vec::new();
11014        let mut updates = Vec::new();
11015        for event in state.history_events.iter() {
11016            if !matches!(
11017                event.event_type.as_str(),
11018                "UpdateAccepted" | "UpdateApplied"
11019            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
11020                || event.payload.get("arguments").is_none()
11021            {
11022                continue;
11023            }
11024            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
11025                if seen.iter().any(|recorded| recorded == update_id) {
11026                    continue;
11027                }
11028                seen.push(update_id.to_string());
11029            }
11030            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
11031        }
11032        Ok(updates)
11033    }
11034
11035    /// Wait for a deterministic predicate to become true or for its durable
11036    /// timeout to elapse.
11037    ///
11038    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
11039    /// predicate tokens automatically change the recorded definition
11040    /// fingerprint. Direct callers must provide an equally stable identity in
11041    /// [`ConditionWaitOptions`].
11042    pub fn wait_condition<F>(
11043        &self,
11044        options: ConditionWaitOptions,
11045        predicate: F,
11046    ) -> ConditionWaitCall
11047    where
11048        F: Fn() -> Result<bool> + Send + 'static,
11049    {
11050        ConditionWaitCall {
11051            ctx: self.clone(),
11052            options,
11053            predicate: Box::new(predicate),
11054            occurrence_id: None,
11055            opened_wait: false,
11056            parallel_group_path: Vec::new(),
11057        }
11058    }
11059
11060    /// Wait for server-backed durable time without blocking the worker executor.
11061    ///
11062    /// Polling this future emits one `start_timer` command and yields. The
11063    /// server records the deadline, so neither worker nor server restarts reset
11064    /// the wait. Replay resolves the future only from a `TimerScheduled` and
11065    /// `TimerFired` pair at the same position in the shared durable-command
11066    /// stream, with matching sequence, timer identity, and delay. Sub-second
11067    /// durations round up because protocol deadlines use whole seconds.
11068    ///
11069    /// ```no_run
11070    /// # use durable_workflow::{json, Client, Worker};
11071    /// # use std::time::Duration;
11072    /// # fn configure(client: Client) {
11073    /// let mut worker = Worker::new(client, "rust-workers");
11074    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
11075    ///     ctx.sleep(Duration::from_secs(5)).await?;
11076    ///     Ok(json!({"status": "timer fired"}))
11077    /// });
11078    /// # }
11079    /// ```
11080    pub fn sleep(&self, duration: Duration) -> TimerCall {
11081        let delay_seconds = duration
11082            .as_secs()
11083            .checked_add(u64::from(duration.subsec_nanos() > 0));
11084        TimerCall {
11085            ctx: self.clone(),
11086            delay_seconds,
11087            scheduled: false,
11088            matched_pending: false,
11089            parallel_group_path: Vec::new(),
11090        }
11091    }
11092
11093    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
11094    pub fn start_timer(&self, duration: Duration) -> TimerCall {
11095        self.sleep(duration)
11096    }
11097
11098    /// Evaluate a non-deterministic callback once and durably record its typed value.
11099    ///
11100    /// On replay the callback is not invoked: the value is decoded from the
11101    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
11102    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
11103    /// small values that must remain fixed for the lifetime of a workflow run.
11104    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
11105    where
11106        T: Serialize + DeserializeOwned,
11107        F: FnOnce() -> T,
11108    {
11109        {
11110            let mut state = self
11111                .state
11112                .lock()
11113                .map_err(|_| Error::WorkflowStatePoisoned)?;
11114            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11115                return match recorded {
11116                    RecordedCommand::SideEffect { sequence, value } => {
11117                        state.command_cursor += 1;
11118                        value.deserialize().map_err(|error| {
11119                            Error::NonDeterministicReplay(ReplayFailure::new(
11120                                "side_effect_type_mismatch",
11121                                Some(sequence),
11122                                Some(std::any::type_name::<T>().to_string()),
11123                                Some(error.to_string()),
11124                                "recorded side-effect value is incompatible with the requested Rust type",
11125                            ))
11126                        })
11127                    }
11128                    other => Err(command_mismatch(&other, "side effect")),
11129                };
11130            }
11131        }
11132
11133        let value = callback();
11134        let avro_value = AvroValue::from_serialize(&value)?;
11135        let mut state = self
11136            .state
11137            .lock()
11138            .map_err(|_| Error::WorkflowStatePoisoned)?;
11139        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
11140        state.commands.push(json!({
11141            "type": "record_side_effect",
11142            "result": result,
11143        }));
11144        Ok(value)
11145    }
11146
11147    /// Record or replay a lossless fixed Avro Value side effect.
11148    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
11149    where
11150        F: FnOnce() -> AvroValue,
11151    {
11152        {
11153            let mut state = self
11154                .state
11155                .lock()
11156                .map_err(|_| Error::WorkflowStatePoisoned)?;
11157            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11158                return match recorded {
11159                    RecordedCommand::SideEffect { value, .. } => {
11160                        state.command_cursor += 1;
11161                        Ok(value)
11162                    }
11163                    other => Err(command_mismatch(&other, "side effect")),
11164                };
11165            }
11166        }
11167
11168        let value = callback();
11169        let mut state = self
11170            .state
11171            .lock()
11172            .map_err(|_| Error::WorkflowStatePoisoned)?;
11173        let result = encode_typed_envelope(&value, &state.payload_codec)?;
11174        state.commands.push(json!({
11175            "type": "record_side_effect",
11176            "result": result,
11177        }));
11178        Ok(value)
11179    }
11180
11181    /// Append output items at a deterministic workflow command boundary.
11182    ///
11183    /// Stable idempotency keys are derived from the server-provided durable
11184    /// workflow command identity, command ordinal, and item index. Replay
11185    /// consumes the recorded side effect and never emits another append.
11186    pub fn append_workflow_stream(
11187        &self,
11188        stream_name: impl Into<String>,
11189        items: &[WorkflowStreamAppendItem],
11190        max_pending_items: Option<u64>,
11191    ) -> Result<()> {
11192        if items.is_empty() {
11193            return Err(Error::Codec(
11194                "workflow_stream_items_empty: append requires at least one item".to_string(),
11195            ));
11196        }
11197        if max_pending_items == Some(0) {
11198            return Err(Error::Codec(
11199                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
11200                    .to_string(),
11201            ));
11202        }
11203        let stream_name = stream_name.into();
11204        if stream_name.is_empty() {
11205            return Err(Error::Codec(
11206                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11207            ));
11208        }
11209
11210        let mut state = self
11211            .state
11212            .lock()
11213            .map_err(|_| Error::WorkflowStatePoisoned)?;
11214        let command_ordinal = state.workflow_stream_command_counter;
11215        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11216            state.workflow_stream_command_counter += 1;
11217            return match recorded {
11218                RecordedCommand::SideEffect { .. } => {
11219                    state.command_cursor += 1;
11220                    Ok(())
11221                }
11222                other => Err(command_mismatch(&other, "workflow stream append")),
11223            };
11224        }
11225
11226        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11227        state.workflow_stream_command_counter += 1;
11228        let wire_items = items
11229            .iter()
11230            .enumerate()
11231            .map(|(item_index, item)| {
11232                item.wire_value(Some(format!(
11233                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
11234                )))
11235            })
11236            .collect::<Vec<_>>();
11237        let mut directive = json!({
11238            "operation": "append",
11239            "stream_name": stream_name,
11240            "command_identity": identity,
11241            "command_ordinal": command_ordinal,
11242            "items": wire_items,
11243        });
11244        if let Some(max_pending_items) = max_pending_items {
11245            directive["max_pending_items"] = json!(max_pending_items);
11246        }
11247        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11248        state.commands.push(json!({
11249            "type": "record_side_effect",
11250            "result": result,
11251            "workflow_stream": directive,
11252        }));
11253        Ok(())
11254    }
11255
11256    /// Close a run-scoped output stream at a deterministic command boundary.
11257    pub fn close_workflow_stream(
11258        &self,
11259        stream_name: impl Into<String>,
11260        retention_seconds: Option<u64>,
11261    ) -> Result<()> {
11262        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
11263    }
11264
11265    /// Mark a run-scoped output stream errored at a deterministic command boundary.
11266    pub fn error_workflow_stream(
11267        &self,
11268        stream_name: impl Into<String>,
11269        error_reason: impl Into<String>,
11270        retention_seconds: Option<u64>,
11271    ) -> Result<()> {
11272        let error_reason = error_reason.into();
11273        if error_reason.is_empty() {
11274            return Err(Error::Codec(
11275                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
11276            ));
11277        }
11278        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
11279    }
11280
11281    fn finish_workflow_stream(
11282        &self,
11283        stream_name: String,
11284        error_reason: Option<String>,
11285        retention_seconds: Option<u64>,
11286    ) -> Result<()> {
11287        if stream_name.is_empty() {
11288            return Err(Error::Codec(
11289                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11290            ));
11291        }
11292        if retention_seconds == Some(0) {
11293            return Err(Error::Codec(
11294                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
11295            ));
11296        }
11297        let mut state = self
11298            .state
11299            .lock()
11300            .map_err(|_| Error::WorkflowStatePoisoned)?;
11301        let command_ordinal = state.workflow_stream_command_counter;
11302        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11303            state.workflow_stream_command_counter += 1;
11304            return match recorded {
11305                RecordedCommand::SideEffect { .. } => {
11306                    state.command_cursor += 1;
11307                    Ok(())
11308                }
11309                other => Err(command_mismatch(&other, "workflow stream close")),
11310            };
11311        }
11312        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11313        state.workflow_stream_command_counter += 1;
11314        let mut directive = json!({
11315            "operation": if error_reason.is_some() { "error" } else { "close" },
11316            "stream_name": stream_name,
11317            "command_identity": identity,
11318            "command_ordinal": command_ordinal,
11319        });
11320        if let Some(error_reason) = error_reason {
11321            directive["error_reason"] = json!(error_reason);
11322        }
11323        if let Some(retention_seconds) = retention_seconds {
11324            directive["retention_seconds"] = json!(retention_seconds);
11325        }
11326        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11327        state.commands.push(json!({
11328            "type": "record_side_effect",
11329            "result": result,
11330            "workflow_stream": directive,
11331        }));
11332        Ok(())
11333    }
11334
11335    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
11336        let identity = state.workflow_command_identity.as_str();
11337        if identity.is_empty() {
11338            return Err(Error::MissingWorkflowCommandIdentity);
11339        }
11340        Ok(identity)
11341    }
11342
11343    /// Validate, emit, or replay a typed workflow search-attribute update.
11344    ///
11345    /// The command is non-blocking within a workflow decision, but its
11346    /// `SearchAttributesUpserted` event occupies the same deterministic command
11347    /// stream as activities, timers, conditions, and other durable operations.
11348    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
11349        update.validate()?;
11350        let (attributes, attribute_types) = update.into_wire_parts();
11351        let mut state = self
11352            .state
11353            .lock()
11354            .map_err(|_| Error::WorkflowStatePoisoned)?;
11355
11356        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11357            return match recorded {
11358                RecordedCommand::SearchAttributes {
11359                    sequence,
11360                    attributes: recorded_attributes,
11361                    attribute_types: recorded_attribute_types,
11362                } => {
11363                    if recorded_attributes != attributes {
11364                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11365                            "search_attribute_value_mismatch",
11366                            Some(sequence),
11367                            Some(recorded_attributes.to_string()),
11368                            Some(attributes.to_string()),
11369                            "search-attribute values differ from the recorded durable command",
11370                        )));
11371                    }
11372                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
11373                        if recorded_types != attribute_types {
11374                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11375                                "search_attribute_type_mismatch",
11376                                Some(sequence),
11377                                Some(json!(recorded_types).to_string()),
11378                                Some(json!(attribute_types).to_string()),
11379                                "search-attribute declared types differ from the recorded durable command",
11380                            )));
11381                        }
11382                    }
11383                    state.command_cursor += 1;
11384                    Ok(())
11385                }
11386                other => Err(command_mismatch(&other, "search-attribute update")),
11387            };
11388        }
11389
11390        let mut command = serde_json::Map::from_iter([
11391            ("type".to_string(), json!("upsert_search_attributes")),
11392            ("attributes".to_string(), attributes),
11393        ]);
11394        if !attribute_types.is_empty() {
11395            command.insert("attribute_types".to_string(), json!(attribute_types));
11396        }
11397        state.commands.push(Value::Object(command));
11398        Ok(())
11399    }
11400
11401    /// Record a UUIDv4 once and return the same UUID on every replay.
11402    pub fn uuid_v4(&self) -> Result<Uuid> {
11403        self.side_effect(Uuid::new_v4)
11404    }
11405
11406    /// Select the newest supported version for a change, or replay the version
11407    /// already committed for that stable change ID.
11408    ///
11409    /// An unmarked old history that reached its next durable operation, or
11410    /// already completed, selects `-1` when that version is supported. This
11411    /// leaves the original operation available and writes no additional marker.
11412    /// Consistent markers written by older workers retain their original ordered
11413    /// positions. Repeated calls consume a matching marker at the current cursor.
11414    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
11415    pub fn get_version(
11416        &self,
11417        change_id: impl Into<String>,
11418        min_supported: i32,
11419        max_supported: i32,
11420    ) -> Result<i32> {
11421        let change_id = change_id.into();
11422        if change_id.trim().is_empty() {
11423            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11424                "version_change_id_invalid",
11425                None,
11426                Some("non-empty change ID".to_string()),
11427                Some(change_id),
11428                "version markers require a stable non-empty change ID",
11429            )));
11430        }
11431        if min_supported > max_supported {
11432            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11433                "version_range_invalid",
11434                None,
11435                Some("min_supported <= max_supported".to_string()),
11436                Some(format!("{min_supported}..={max_supported}")),
11437                "version marker supported range is invalid",
11438            )));
11439        }
11440
11441        let mut state = self
11442            .state
11443            .lock()
11444            .map_err(|_| Error::WorkflowStatePoisoned)?;
11445        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
11446            if let Some(RecordedCommand::VersionMarker {
11447                sequence: alias_sequence,
11448                change_id: alias_change_id,
11449                version: alias_version,
11450            }) = state.recorded_commands.get(state.command_cursor)
11451            {
11452                if alias_change_id == &change_id {
11453                    if *alias_version != version {
11454                        return Err(invalid_recorded_history(
11455                            "version_marker_conflict",
11456                            *alias_sequence,
11457                            &format!("selected version {version} for change ID {change_id:?}"),
11458                            &format!("recorded version {alias_version}"),
11459                            "recorded marker conflicts with the decision already selected during replay",
11460                        ));
11461                    }
11462                    ensure_version_supported(
11463                        &change_id,
11464                        version,
11465                        min_supported,
11466                        max_supported,
11467                        *alias_sequence,
11468                    )?;
11469                    // Older workers could record the same decision again. Keep
11470                    // each physical boundary without skipping intervening work.
11471                    state.command_cursor += 1;
11472                    return Ok(version);
11473                }
11474            }
11475            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
11476            return Ok(version);
11477        }
11478
11479        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11480            return match recorded {
11481                RecordedCommand::VersionMarker {
11482                    sequence,
11483                    change_id: recorded_change_id,
11484                    version,
11485                    ..
11486                } => {
11487                    if recorded_change_id != change_id {
11488                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11489                            "version_change_id_mismatch",
11490                            Some(sequence),
11491                            Some(recorded_change_id),
11492                            Some(change_id),
11493                            "recorded version marker change ID differs from current workflow code",
11494                        )));
11495                    }
11496                    ensure_version_supported(
11497                        &change_id,
11498                        version,
11499                        min_supported,
11500                        max_supported,
11501                        sequence,
11502                    )?;
11503                    state.command_cursor += 1;
11504                    state.version_markers.insert(change_id, (version, sequence));
11505                    Ok(version)
11506                }
11507                other => {
11508                    let version = -1;
11509                    let sequence = other.sequence();
11510                    ensure_version_supported(
11511                        &change_id,
11512                        version,
11513                        min_supported,
11514                        max_supported,
11515                        sequence,
11516                    )?;
11517                    // The existing operation proves this patch site was reached
11518                    // before its marker existed. Keep its original cursor.
11519                    state.version_markers.insert(change_id, (version, sequence));
11520                    Ok(version)
11521                }
11522            };
11523        }
11524
11525        if state
11526            .history_events
11527            .iter()
11528            .any(|event| event.event_type == "WorkflowCompleted")
11529        {
11530            let version = -1;
11531            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
11532            state.version_markers.insert(change_id, (version, 0));
11533            return Ok(version);
11534        }
11535
11536        let version = max_supported;
11537        state.commands.push(json!({
11538            "type": "record_version_marker",
11539            "change_id": change_id,
11540            "version": version,
11541            "min_supported": min_supported,
11542            "max_supported": max_supported,
11543        }));
11544        // Sequence numbers are assigned by the server. Zero identifies a marker
11545        // selected in this uncommitted decision batch for duplicate-call checks.
11546        state.version_markers.insert(change_id, (version, 0));
11547        Ok(version)
11548    }
11549
11550    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
11551    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
11552        Ok(self.get_version(change_id, -1, 1)? == 1)
11553    }
11554
11555    /// Keep a patch marker in history after the legacy branch has been removed.
11556    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
11557        self.get_version(change_id, -1, 1).map(|_| ())
11558    }
11559
11560    /// Merge non-indexed workflow memo metadata through durable history.
11561    ///
11562    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
11563    /// public Avro payload envelope consumed by Server and Cloud runtimes.
11564    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
11565        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
11566        let mut state = self
11567            .state
11568            .lock()
11569            .map_err(|_| Error::WorkflowStatePoisoned)?;
11570
11571        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11572            return match recorded {
11573                RecordedCommand::Memo {
11574                    sequence,
11575                    entries: recorded_entries,
11576                } => {
11577                    if recorded_entries != entries {
11578                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11579                            "memo_update_mismatch",
11580                            Some(sequence),
11581                            Some(format!("{recorded_entries:?}")),
11582                            Some(format!("{entries:?}")),
11583                            "recorded memo entries differ from the current workflow update",
11584                        )));
11585                    }
11586                    state.command_cursor += 1;
11587                    Ok(())
11588                }
11589                other => Err(command_mismatch(&other, "memo upsert")),
11590            };
11591        }
11592
11593        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
11594        state.commands.push(json!({
11595            "type": "upsert_memo",
11596            "entries": entries_envelope,
11597        }));
11598        Ok(())
11599    }
11600
11601    /// Start a named durable child on an explicit queue and await its result.
11602    ///
11603    /// The command is recorded in the parent's sequence-ordered durable command
11604    /// stream. Replay keeps a scheduled child pending without emitting another
11605    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
11606    /// values preserve the history payload codec and include both sides of the
11607    /// durable relationship; failures are returned as
11608    /// [`Error::ChildWorkflowFailed`].
11609    ///
11610    /// ```no_run
11611    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
11612    /// # fn configure(client: Client) {
11613    /// let mut worker = Worker::new(client, "parent-workers");
11614    /// worker.register_workflow("order-parent", |ctx, _input| async move {
11615    ///     let child = ctx
11616    ///         .start_child_workflow(
11617    ///             "fulfil-order",
11618    ///             ChildWorkflowOptions::new("fulfilment-workers")
11619    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
11620    ///             json!([{"order_id": "order-42"}]),
11621    ///         )
11622    ///         .await?;
11623    ///     Ok(child.result)
11624    /// });
11625    /// # }
11626    /// ```
11627    pub fn start_child_workflow<T: Serialize>(
11628        &self,
11629        workflow_type: impl Into<String>,
11630        options: ChildWorkflowOptions,
11631        args: T,
11632    ) -> ChildWorkflowCall {
11633        ChildWorkflowCall {
11634            ctx: self.clone(),
11635            workflow_type: workflow_type.into(),
11636            options,
11637            args: Some(AvroValue::from_serialize(&args)),
11638            scheduled: false,
11639            matched_pending: false,
11640            parallel_group_path: Vec::new(),
11641        }
11642    }
11643
11644    pub async fn start_child_workflow_avro_value<T: Serialize>(
11645        &self,
11646        workflow_type: impl Into<String>,
11647        options: ChildWorkflowOptions,
11648        args: T,
11649    ) -> Result<ChildWorkflowAvroResult> {
11650        let mut call = self.start_child_workflow(workflow_type, options, args);
11651        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
11652    }
11653
11654    fn take_commands(&self) -> Result<Vec<Value>> {
11655        let mut state = self
11656            .state
11657            .lock()
11658            .map_err(|_| Error::WorkflowStatePoisoned)?;
11659        Ok(std::mem::take(&mut state.commands))
11660    }
11661
11662    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
11663        let mut state = self
11664            .state
11665            .lock()
11666            .map_err(|_| Error::WorkflowStatePoisoned)?;
11667
11668        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11669            return Err(command_mismatch(&recorded, "continue as new"));
11670        }
11671        if state.recorded_continue_as_new_sequence.is_some() {
11672            state.continue_as_new_consumed = true;
11673            return Ok(None);
11674        }
11675
11676        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
11677        let mut command = serde_json::Map::from_iter([
11678            ("type".to_string(), json!("continue_as_new")),
11679            ("arguments".to_string(), arguments),
11680            ("queue".to_string(), json!(state.task_queue.clone())),
11681        ]);
11682        if let Some(workflow_type) = request.options.workflow_type {
11683            command.insert("workflow_type".to_string(), json!(workflow_type));
11684        }
11685        if let Some(task_queue) = request.options.task_queue {
11686            command.insert("queue".to_string(), json!(task_queue));
11687        }
11688        Ok(Some(Value::Object(command)))
11689    }
11690
11691    fn matched_recorded_pending(&self) -> Result<bool> {
11692        let state = self
11693            .state
11694            .lock()
11695            .map_err(|_| Error::WorkflowStatePoisoned)?;
11696        Ok(state.matched_recorded_pending)
11697    }
11698
11699    fn ensure_history_consumed(&self) -> Result<()> {
11700        let state = self
11701            .state
11702            .lock()
11703            .map_err(|_| Error::WorkflowStatePoisoned)?;
11704        if let Some(replay) = &state.scope_delivery {
11705            if let Some((&sequence, _)) = replay
11706                .canonical
11707                .deliveries
11708                .iter()
11709                .find(|(sequence, _)| !replay.consumed.contains(sequence))
11710            {
11711                return Err(invalid_recorded_history(
11712                    "cancellation_scope_delivery_unconsumed",
11713                    sequence,
11714                    "original scoped delivery",
11715                    "workflow completion",
11716                    "workflow completed without consuming its committed scope delivery",
11717                ));
11718            }
11719        }
11720        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
11721            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11722                "recorded_commands_unconsumed",
11723                Some(command.sequence()),
11724                Some(command.shape().to_string()),
11725                Some("workflow completion".to_string()),
11726                "workflow completed before consuming all recorded durable commands",
11727            )));
11728        }
11729        if let Some(delivery) = state
11730            .cancellation_history
11731            .delivery
11732            .as_ref()
11733            .filter(|_| !state.cancellation_consumed)
11734        {
11735            return Err(invalid_recorded_history(
11736                "cooperative_cancellation_unconsumed",
11737                delivery.sequence,
11738                "committed cancellation call",
11739                "workflow completion",
11740                "workflow completed without reaching its committed cancellation boundary",
11741            ));
11742        }
11743        if let Some(sequence) = state
11744            .recorded_continue_as_new_sequence
11745            .filter(|_| !state.continue_as_new_consumed)
11746        {
11747            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11748                "recorded_continue_as_new_unconsumed",
11749                Some(sequence),
11750                Some("continue as new".to_string()),
11751                Some("workflow completion".to_string()),
11752                "workflow completed without consuming its recorded continue-as-new transition",
11753            )));
11754        }
11755        Ok(())
11756    }
11757}
11758
11759fn contiguous_message_stream_count(
11760    pending: &[MessageStreamMessage],
11761    cursor: u64,
11762    max_items: usize,
11763) -> usize {
11764    pending
11765        .iter()
11766        .take(max_items)
11767        .enumerate()
11768        .take_while(|(offset, message)| {
11769            u64::try_from(*offset)
11770                .ok()
11771                .and_then(|offset| cursor.checked_add(offset + 1))
11772                == Some(message.position)
11773        })
11774        .count()
11775}
11776
11777fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
11778    matches!(
11779        event.event_type.as_str(),
11780        "ActivityScheduled"
11781            | "TimerScheduled"
11782            | "ChildWorkflowScheduled"
11783            | "SignalWaitOpened"
11784            | "ConditionWaitOpened"
11785            | "SearchAttributesUpserted"
11786            | "SideEffectRecorded"
11787            | "VersionMarkerRecorded"
11788            | "MemoUpserted"
11789            | "WorkflowContinuedAsNew"
11790    )
11791}
11792
11793#[derive(Debug)]
11794struct WorkflowState {
11795    workflow_id: Option<String>,
11796    run_id: Option<String>,
11797    task_queue: String,
11798    payload_codec: String,
11799    history_events: Arc<Vec<HistoryEvent>>,
11800    history_budget: WorkflowHistoryBudget,
11801    cancel_requested: bool,
11802    cancellation_history: CancellationHistory,
11803    cancellation_consumed: bool,
11804    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
11805    cancellation_shield_depth: u64,
11806    cancellation_delivery_enabled: bool,
11807    cancellation_delivery_intent: Option<CancellationDelivery>,
11808    cancellation_delivery_command_count: usize,
11809    allow_cancellation_scope_authoring: bool,
11810    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
11811    cancellation_scope_memberships: BTreeMap<u64, String>,
11812    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
11813    resume_signal: Option<ResumeSignal>,
11814    recorded_commands: Vec<RecordedCommand>,
11815    selection_markers: Vec<SelectionMarker>,
11816    selection_marker_cursor: usize,
11817    cancelled_selection_members: Vec<SelectionCancellation>,
11818    recorded_continue_as_new_sequence: Option<u64>,
11819    continue_as_new_consumed: bool,
11820    command_cursor: usize,
11821    condition_wait_occurrence_counter: u64,
11822    matched_recorded_pending: bool,
11823    version_markers: HashMap<String, (i32, u64)>,
11824    workflow_command_identity: String,
11825    workflow_stream_command_counter: u64,
11826    commands: Vec<Value>,
11827    local_activity_requests: Vec<local_activity::Request>,
11828    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
11829    message_stream_cursors: HashMap<String, u64>,
11830    message_stream_waits: HashMap<String, u64>,
11831}
11832
11833impl WorkflowState {
11834    #[cfg(test)]
11835    fn new(
11836        history: Vec<HistoryEvent>,
11837        task_queue: String,
11838        payload_codec: String,
11839        resume_signal: Option<ResumeSignal>,
11840    ) -> Result<Self> {
11841        Self::new_with_identity(
11842            history,
11843            None,
11844            None,
11845            task_queue,
11846            payload_codec,
11847            resume_signal,
11848        )
11849    }
11850
11851    fn new_with_identity(
11852        history: Vec<HistoryEvent>,
11853        workflow_id: Option<String>,
11854        run_id: Option<String>,
11855        task_queue: String,
11856        payload_codec: String,
11857        resume_signal: Option<ResumeSignal>,
11858    ) -> Result<Self> {
11859        Self::new_with_identity_and_scopes(
11860            history,
11861            workflow_id,
11862            run_id,
11863            task_queue,
11864            payload_codec,
11865            resume_signal,
11866            false,
11867        )
11868    }
11869
11870    fn new_with_identity_and_scopes(
11871        history: Vec<HistoryEvent>,
11872        workflow_id: Option<String>,
11873        run_id: Option<String>,
11874        task_queue: String,
11875        payload_codec: String,
11876        resume_signal: Option<ResumeSignal>,
11877        allow_cancellation_scope_authoring: bool,
11878    ) -> Result<Self> {
11879        Self::new_with_identity_and_scope_delivery(
11880            history,
11881            workflow_id,
11882            run_id,
11883            task_queue,
11884            payload_codec,
11885            resume_signal,
11886            allow_cancellation_scope_authoring,
11887            false,
11888        )
11889    }
11890
11891    fn new_with_identity_and_scope_delivery(
11892        history: Vec<HistoryEvent>,
11893        workflow_id: Option<String>,
11894        run_id: Option<String>,
11895        task_queue: String,
11896        payload_codec: String,
11897        resume_signal: Option<ResumeSignal>,
11898        allow_cancellation_scope_authoring: bool,
11899        allow_cancellation_scope_delivery: bool,
11900    ) -> Result<Self> {
11901        cooperative_cancellation::assert_cancellation_scope_replay_supported(
11902            &history,
11903            allow_cancellation_scope_authoring,
11904            allow_cancellation_scope_delivery,
11905        )?;
11906        let scopes = if allow_cancellation_scope_authoring {
11907            cancellation_scope::CancellationScopeHistory::read(
11908                &history,
11909                run_id.as_deref().unwrap_or_default(),
11910            )?
11911        } else {
11912            cancellation_scope::CancellationScopeHistory::default()
11913        };
11914        let cancellation_history = CancellationHistory::from_events(
11915            &history,
11916            run_id.as_deref().unwrap_or_default(),
11917            None,
11918        )?;
11919        if allow_cancellation_scope_authoring
11920            && cancellation_history.request.is_some()
11921            && !allow_cancellation_scope_delivery
11922        {
11923            return Err(Error::CancellationScopeExecutionUnavailable);
11924        }
11925        let scope_delivery = if allow_cancellation_scope_delivery {
11926            Some(cancellation_scope_replay::ScopeReplay::read(
11927                &history,
11928                &scopes,
11929                run_id.as_deref().unwrap_or_default(),
11930                workflow_id.as_deref().unwrap_or_default(),
11931            )?)
11932        } else {
11933            None
11934        };
11935        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
11936            &history,
11937            &payload_codec,
11938            WorkflowIdentity {
11939                workflow_id: workflow_id.clone(),
11940                run_id: run_id.clone(),
11941            },
11942        )?)?;
11943        for (sequence, opening) in &scopes.openings {
11944            if recorded_commands
11945                .iter()
11946                .any(|command| command.sequence() == *sequence)
11947            {
11948                return Err(invalid_recorded_history(
11949                    "invalid_cancellation_scope_history",
11950                    *sequence,
11951                    "distinct authored scope opening",
11952                    "operation collision",
11953                    "scope opening collides with a command",
11954                ));
11955            }
11956            recorded_commands.push(RecordedCommand::CancellationScope {
11957                sequence: *sequence,
11958                scope_id: opening.scope_id.clone(),
11959                parent_scope_id: opening.parent_scope_id.clone(),
11960                shield_parent: opening.shield_parent,
11961            });
11962        }
11963        recorded_commands.sort_by_key(RecordedCommand::sequence);
11964        if let Some(replay) = &scope_delivery {
11965            replay.bind_commands(&mut recorded_commands)?;
11966        }
11967        let selection_markers = recorded_selection_markers(&history)?;
11968        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
11969        let recorded_continue_as_new = history
11970            .iter()
11971            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
11972            .collect::<Vec<_>>();
11973        if recorded_continue_as_new.len() > 1 {
11974            return Err(invalid_recorded_history(
11975                "duplicate_continue_as_new_transition",
11976                recorded_continue_as_new
11977                    .last()
11978                    .and_then(|event| durable_event_sequence(event))
11979                    .unwrap_or(0),
11980                "one WorkflowContinuedAsNew event",
11981                &format!(
11982                    "{} WorkflowContinuedAsNew events",
11983                    recorded_continue_as_new.len()
11984                ),
11985                "workflow history records one continue-as-new transition more than once",
11986            ));
11987        }
11988        let recorded_continue_as_new_sequence = recorded_continue_as_new
11989            .first()
11990            .map(|event| {
11991                durable_event_sequence(event).ok_or_else(|| {
11992                    Error::NonDeterministicReplay(ReplayFailure::new(
11993                        "continue_as_new_sequence_missing",
11994                        None,
11995                        Some("recorded transition sequence".to_string()),
11996                        Some("missing sequence".to_string()),
11997                        "WorkflowContinuedAsNew history is missing its recorded sequence",
11998                    ))
11999                })
12000            })
12001            .transpose()?;
12002        let mut message_stream_cursors = HashMap::new();
12003        for event in &history {
12004            if !matches!(
12005                event.event_type.as_str(),
12006                "SignalReceived" | "SignalApplied"
12007            ) || event.payload.get("signal_name").and_then(Value::as_str)
12008                != Some(MESSAGE_STREAM_SIGNAL)
12009            {
12010                continue;
12011            }
12012            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
12013            if arguments.len() != 1 {
12014                continue;
12015            }
12016            let envelope = arguments[0].clone().into_json()?;
12017            let Some(envelope) = envelope.as_object() else {
12018                continue;
12019            };
12020            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
12021            {
12022                continue;
12023            }
12024            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
12025                continue;
12026            };
12027            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
12028            else {
12029                continue;
12030            };
12031            let cursor = message_stream_cursors
12032                .entry(stream_name.to_string())
12033                .or_insert(0);
12034            *cursor = (*cursor).max(through_position);
12035        }
12036        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
12037        let cancel_requested = history.iter().any(|event| {
12038            matches!(
12039                event.event_type.as_str(),
12040                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
12041            )
12042        });
12043        let cancellation_clock = cancellation_history
12044            .request
12045            .as_ref()
12046            .and_then(|request| request.context.as_ref())
12047            .map(|_| {
12048                cancellation_replay_clock::ReplayClock::new(
12049                    &history,
12050                    &recorded_commands,
12051                    cancellation_history.delivery_index,
12052                )
12053            })
12054            .or_else(|| {
12055                scope_delivery.as_ref().map(|_| {
12056                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
12057                })
12058            });
12059        Ok(Self {
12060            workflow_command_identity: String::new(),
12061            workflow_stream_command_counter: 0,
12062            workflow_id,
12063            run_id,
12064            task_queue,
12065            payload_codec,
12066            history_events: Arc::new(history),
12067            history_budget: WorkflowHistoryBudget {
12068                event_count,
12069                ..WorkflowHistoryBudget::default()
12070            },
12071            cancel_requested,
12072            cancellation_history,
12073            cancellation_consumed: false,
12074            cancellation_clock,
12075            cancellation_shield_depth: 0,
12076            cancellation_delivery_enabled: false,
12077            cancellation_delivery_intent: None,
12078            cancellation_delivery_command_count: 0,
12079            allow_cancellation_scope_authoring,
12080            cancellation_scope_opening: None,
12081            cancellation_scope_memberships: scopes.memberships,
12082            scope_delivery,
12083            resume_signal,
12084            recorded_commands,
12085            selection_markers,
12086            selection_marker_cursor: 0,
12087            cancelled_selection_members,
12088            recorded_continue_as_new_sequence,
12089            continue_as_new_consumed: false,
12090            command_cursor: 0,
12091            condition_wait_occurrence_counter: 0,
12092            matched_recorded_pending: false,
12093            version_markers: HashMap::new(),
12094            commands: Vec::new(),
12095            local_activity_requests: Vec::new(),
12096            message_stream_messages: HashMap::new(),
12097            message_stream_cursors,
12098            message_stream_waits: HashMap::new(),
12099        })
12100    }
12101}
12102
12103enum MessageStreamDelivery {
12104    Message(MessageStreamMessage),
12105    Cursor {
12106        stream_name: String,
12107        through_position: u64,
12108    },
12109}
12110
12111fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
12112    if arguments.len() != 1 {
12113        return Ok(None);
12114    }
12115    let envelope = arguments
12116        .into_iter()
12117        .next()
12118        .expect("one argument was checked");
12119    let Some(envelope) = envelope.as_object() else {
12120        return Ok(None);
12121    };
12122    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
12123        return Ok(None);
12124    };
12125    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
12126        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
12127        else {
12128            return Ok(None);
12129        };
12130        return Ok(Some(MessageStreamDelivery::Cursor {
12131            stream_name: stream_name.to_string(),
12132            through_position,
12133        }));
12134    }
12135    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
12136        return Ok(None);
12137    }
12138    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
12139        return Ok(None);
12140    };
12141    let Some(position) = envelope
12142        .get("position")
12143        .and_then(Value::as_u64)
12144        .filter(|value| *value > 0)
12145    else {
12146        return Ok(None);
12147    };
12148    let Some(payload_envelope) = envelope.get("payload_envelope") else {
12149        return Ok(None);
12150    };
12151    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
12152    else {
12153        return Ok(None);
12154    };
12155    let decoded = decode_avro_value(&payload_envelope)?;
12156    let AvroValue::Array(values) = decoded else {
12157        return Ok(None);
12158    };
12159    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
12160        stream_name: stream_name.to_string(),
12161        message_id: message_id.to_string(),
12162        position,
12163        arguments: values,
12164    })))
12165}
12166
12167#[derive(Clone, Debug)]
12168enum RecordedCommand {
12169    ServiceOperation {
12170        sequence: u64,
12171        call: nexus::RecordedServiceCall,
12172    },
12173    CancellationScope {
12174        sequence: u64,
12175        scope_id: String,
12176        parent_scope_id: String,
12177        shield_parent: bool,
12178    },
12179    CancellationGroup {
12180        sequence: u64,
12181        span: u64,
12182        original: Vec<RecordedCommand>,
12183    },
12184    CancellationBoundary {
12185        sequence: u64,
12186        call_kind: CancellationCallKind,
12187        original: Option<Box<RecordedCommand>>,
12188    },
12189    Activity {
12190        sequence: u64,
12191        activity_type: Option<String>,
12192        cancellation_policy: String,
12193        options: Option<RecordedActivityOptions>,
12194        outcome: Option<ActivityOutcome>,
12195        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12196    },
12197    Timer {
12198        sequence: u64,
12199        delay_seconds: u64,
12200        fired: bool,
12201        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12202    },
12203    ChildWorkflow {
12204        sequence: u64,
12205        workflow_type: Option<String>,
12206        policies: RecordedChildPolicies,
12207        outcome: Option<ChildWorkflowOutcome>,
12208        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12209    },
12210    SignalWait {
12211        sequence: u64,
12212        signal_name: String,
12213        value: Option<Vec<AvroValue>>,
12214        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12215    },
12216    ConditionWait {
12217        sequence: u64,
12218        occurrence_id: String,
12219        condition_key: Option<String>,
12220        predicate_identity: String,
12221        timeout_seconds: Option<u64>,
12222        result: Option<ConditionWaitResult>,
12223        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12224    },
12225    SearchAttributes {
12226        sequence: u64,
12227        attributes: Value,
12228        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
12229    },
12230    SideEffect {
12231        sequence: u64,
12232        value: AvroValue,
12233    },
12234    VersionMarker {
12235        sequence: u64,
12236        change_id: String,
12237        version: i32,
12238    },
12239    Memo {
12240        sequence: u64,
12241        entries: AvroValue,
12242    },
12243}
12244
12245#[derive(Clone, Debug, PartialEq, Eq)]
12246struct SelectionMarker {
12247    selection_group_id: String,
12248    selection_group_base_sequence: u64,
12249    selection_group_size: usize,
12250    member_key: SelectionKey,
12251    member_index: usize,
12252    member_base_sequence: u64,
12253    member_size: usize,
12254    operation_kind: String,
12255    operation_identity: String,
12256    outcome: String,
12257    resolution_event_id: String,
12258    resolution_event_type: String,
12259}
12260
12261#[derive(Clone, Debug, PartialEq, Eq)]
12262struct SelectionCancellation {
12263    selection_group_id: String,
12264    member_key: SelectionKey,
12265    member_index: usize,
12266    member_base_sequence: u64,
12267    member_size: usize,
12268    operation_kind: String,
12269    operation_identity: String,
12270}
12271
12272fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
12273    let mut markers: Vec<SelectionMarker> = Vec::new();
12274    for event in events
12275        .iter()
12276        .filter(|event| event.event_type == "SelectionResolved")
12277    {
12278        let payload = &event.payload;
12279        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
12280        let group_size = required_selection_usize(payload, "selection_group_size")?;
12281        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
12282        let member_size = required_selection_usize(payload, "member_size")?;
12283        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
12284        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
12285            invalid_recorded_history(
12286                "selection_marker_invalid",
12287                base_sequence,
12288                "non-empty selection_group_id",
12289                &payload.to_string(),
12290                "selection winner history is missing its durable group identity",
12291            )
12292        })?;
12293        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
12294        if group_id != expected_group_id {
12295            return Err(invalid_recorded_history(
12296                "selection_marker_invalid",
12297                base_sequence,
12298                &expected_group_id,
12299                &group_id,
12300                "selection winner history contains an incompatible group identity",
12301            ));
12302        }
12303        let group_end = base_sequence
12304            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
12305            .unwrap_or(u64::MAX);
12306        let member_end = member_base_sequence
12307            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
12308            .unwrap_or(u64::MAX);
12309        if member_index >= group_size
12310            || member_base_sequence < base_sequence
12311            || member_end > group_end
12312        {
12313            return Err(invalid_recorded_history(
12314                "selection_marker_invalid",
12315                base_sequence,
12316                "winner member within selection group bounds",
12317                &payload.to_string(),
12318                "selection winner history contains an invalid member range",
12319            ));
12320        }
12321        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
12322            invalid_recorded_history(
12323                "selection_marker_invalid",
12324                base_sequence,
12325                "selection operation kind",
12326                &payload.to_string(),
12327                "selection winner history is missing its operation kind",
12328            )
12329        })?;
12330        if !matches!(
12331            operation_kind.as_str(),
12332            "activity" | "child" | "timer" | "signal" | "condition" | "group"
12333        ) {
12334            return Err(invalid_recorded_history(
12335                "selection_marker_invalid",
12336                base_sequence,
12337                "activity, child, timer, signal, condition, or group",
12338                &operation_kind,
12339                "selection winner history contains an unsupported operation kind",
12340            ));
12341        }
12342        let operation_identity =
12343            payload_string(payload, "operation_identity").ok_or_else(|| {
12344                invalid_recorded_history(
12345                    "selection_marker_invalid",
12346                    base_sequence,
12347                    "non-empty operation identity",
12348                    &payload.to_string(),
12349                    "selection winner history is missing its durable operation identity",
12350                )
12351            })?;
12352        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
12353            invalid_recorded_history(
12354                "selection_marker_invalid",
12355                base_sequence,
12356                "completed or failed selection outcome",
12357                &payload.to_string(),
12358                "selection winner history is missing its outcome",
12359            )
12360        })?;
12361        if !matches!(outcome.as_str(), "completed" | "failed") {
12362            return Err(invalid_recorded_history(
12363                "selection_marker_invalid",
12364                base_sequence,
12365                "completed or failed selection outcome",
12366                &outcome,
12367                "selection winner history contains an unsupported outcome",
12368            ));
12369        }
12370        let marker = SelectionMarker {
12371            selection_group_id: group_id,
12372            selection_group_base_sequence: base_sequence,
12373            selection_group_size: group_size,
12374            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
12375            member_index,
12376            member_base_sequence,
12377            member_size,
12378            operation_kind,
12379            operation_identity,
12380            outcome,
12381            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
12382                || {
12383                    invalid_recorded_history(
12384                        "selection_marker_invalid",
12385                        base_sequence,
12386                        "durable resolution_event_id",
12387                        &payload.to_string(),
12388                        "selection winner history is missing its terminal event identity",
12389                    )
12390                },
12391            )?,
12392            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
12393                || {
12394                    invalid_recorded_history(
12395                        "selection_marker_invalid",
12396                        base_sequence,
12397                        "durable resolution_event_type",
12398                        &payload.to_string(),
12399                        "selection winner history is missing its terminal event type",
12400                    )
12401                },
12402            )?,
12403        };
12404        if let Some(existing) = markers
12405            .iter()
12406            .find(|existing| existing.selection_group_id == marker.selection_group_id)
12407        {
12408            if existing != &marker {
12409                return Err(invalid_recorded_history(
12410                    "selection_marker_conflict",
12411                    base_sequence,
12412                    &format!("one winner for {}", marker.selection_group_id),
12413                    &payload.to_string(),
12414                    "selection history records conflicting winners for one durable group",
12415                ));
12416            }
12417            continue;
12418        }
12419        markers.push(marker);
12420    }
12421    Ok(markers)
12422}
12423
12424fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
12425    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
12426    for event in events
12427        .iter()
12428        .filter(|event| event.event_type == "SelectionOperationCancelled")
12429    {
12430        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
12431            invalid_recorded_history(
12432                "selection_cancellation_invalid",
12433                0,
12434                "non-empty selection_group_id",
12435                &event.payload.to_string(),
12436                "selection cancellation history is missing its group identity",
12437            )
12438        })?;
12439        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
12440        let marker = SelectionCancellation {
12441            selection_group_id: group_id,
12442            member_key: selection_key_from_value(
12443                event.payload.get("member_key"),
12444                member_base_sequence,
12445            )?,
12446            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
12447            member_base_sequence,
12448            member_size: required_selection_usize(&event.payload, "member_size")?,
12449            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
12450                invalid_recorded_history(
12451                    "selection_cancellation_invalid",
12452                    member_base_sequence,
12453                    "selection operation kind",
12454                    &event.payload.to_string(),
12455                    "selection cancellation is missing its operation kind",
12456                )
12457            })?,
12458            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
12459                || {
12460                    invalid_recorded_history(
12461                        "selection_cancellation_invalid",
12462                        member_base_sequence,
12463                        "selection operation identity",
12464                        &event.payload.to_string(),
12465                        "selection cancellation is missing its operation identity",
12466                    )
12467                },
12468            )?,
12469        };
12470        if let Some(existing) = cancelled.iter().find(|recorded| {
12471            recorded.selection_group_id == marker.selection_group_id
12472                && recorded.member_base_sequence == marker.member_base_sequence
12473        }) {
12474            if existing != &marker {
12475                return Err(invalid_recorded_history(
12476                    "selection_cancellation_conflict",
12477                    member_base_sequence,
12478                    "one stable SelectionOperationCancelled marker",
12479                    &event.payload.to_string(),
12480                    "selection cancellation history contains conflicting member metadata",
12481                ));
12482            }
12483        } else {
12484            cancelled.push(marker);
12485        }
12486    }
12487    Ok(cancelled)
12488}
12489
12490fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
12491    payload
12492        .get(field)
12493        .and_then(value_as_u64)
12494        .filter(|value| *value > 0)
12495        .ok_or_else(|| {
12496            invalid_recorded_history(
12497                "selection_marker_invalid",
12498                0,
12499                &format!("positive integer {field}"),
12500                &payload.to_string(),
12501                "selection history contains invalid durable identity metadata",
12502            )
12503        })
12504}
12505
12506fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
12507    required_selection_usize_allow_zero(payload, field).and_then(|value| {
12508        if value > 0 {
12509            Ok(value)
12510        } else {
12511            Err(invalid_recorded_history(
12512                "selection_marker_invalid",
12513                0,
12514                &format!("positive integer {field}"),
12515                &payload.to_string(),
12516                "selection history contains invalid durable identity metadata",
12517            ))
12518        }
12519    })
12520}
12521
12522fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
12523    payload
12524        .get(field)
12525        .and_then(value_as_u64)
12526        .and_then(|value| usize::try_from(value).ok())
12527        .ok_or_else(|| {
12528            invalid_recorded_history(
12529                "selection_marker_invalid",
12530                0,
12531                &format!("non-negative integer {field}"),
12532                &payload.to_string(),
12533                "selection history contains invalid durable identity metadata",
12534            )
12535        })
12536}
12537
12538#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12539struct RecordedActivityOptions {
12540    task_queue: RecordedSnapshotValue<Option<String>>,
12541    execution_mode: RecordedSnapshotValue<Option<String>>,
12542    retry_policy: ActivityRetrySnapshot,
12543    worker_session: Option<Value>,
12544}
12545
12546#[derive(Clone, Debug)]
12547struct RecordedChildPolicies {
12548    parent_close_policy: String,
12549    cancellation_policy: String,
12550}
12551
12552fn recorded_activity_cancellation_policy(
12553    events: &[&HistoryEvent],
12554    sequence: u64,
12555) -> Result<String> {
12556    let mut policy: Option<String> = None;
12557    for event in events.iter().filter(|event| {
12558        matches!(
12559            event.event_type.as_str(),
12560            "ActivityScheduled"
12561                | "ActivityStarted"
12562                | "ActivityCompleted"
12563                | "ActivityFailed"
12564                | "ActivityTimedOut"
12565                | "ActivityCancelled"
12566        )
12567    }) {
12568        for source in [Some(&event.payload), event.payload.get("activity")]
12569            .into_iter()
12570            .flatten()
12571        {
12572            let Some(value) = source.get("cancellation_policy") else {
12573                continue;
12574            };
12575            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
12576                value.as_str()
12577            else {
12578                return Err(invalid_recorded_history(
12579                    "invalid_activity_cancellation_policy_history",
12580                    sequence,
12581                    "supported Activity cancellation policy",
12582                    &value.to_string(),
12583                    "Activity history contains an invalid cancellation policy",
12584                ));
12585            };
12586            if let Some(previous) = policy.as_deref() {
12587                if previous != incoming {
12588                    return Err(invalid_recorded_history(
12589                        "activity_cancellation_policy_history_conflict",
12590                        sequence,
12591                        previous,
12592                        incoming,
12593                        "Activity cancellation policy changed between history events",
12594                    ));
12595                }
12596            }
12597            policy = Some(incoming.to_string());
12598        }
12599        policy.get_or_insert_with(|| "try_cancel".to_string());
12600    }
12601    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
12602}
12603
12604fn recorded_child_policy_value<'a>(
12605    payload: &'a Value,
12606    field: &str,
12607    sequence: u64,
12608) -> Result<Option<&'a str>> {
12609    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
12610        return Ok(None);
12611    };
12612    let valid = match (field, value.as_str()) {
12613        (
12614            "parent_close_policy",
12615            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
12616        ) => true,
12617        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
12618            true
12619        }
12620        _ => false,
12621    };
12622    if !valid {
12623        return Err(invalid_recorded_history(
12624            "invalid_child_workflow_policy_history",
12625            sequence,
12626            "supported child workflow policy",
12627            &value.to_string(),
12628            "child workflow history contains an invalid policy",
12629        ));
12630    }
12631    Ok(value.as_str())
12632}
12633
12634fn recorded_child_policies(
12635    events: &[&HistoryEvent],
12636    scheduled: &HistoryEvent,
12637    sequence: u64,
12638) -> Result<RecordedChildPolicies> {
12639    let parent_close_policy =
12640        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
12641            .unwrap_or("abandon")
12642            .to_string();
12643    let cancellation_policy =
12644        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
12645            .unwrap_or("abandon")
12646            .to_string();
12647    for event in events {
12648        for (field, expected) in [
12649            ("parent_close_policy", parent_close_policy.as_str()),
12650            ("cancellation_policy", cancellation_policy.as_str()),
12651        ] {
12652            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
12653                if actual != expected {
12654                    return Err(invalid_recorded_history(
12655                        "child_workflow_policy_history_conflict",
12656                        sequence,
12657                        expected,
12658                        actual,
12659                        "child workflow policy changed between history events",
12660                    ));
12661                }
12662            }
12663        }
12664    }
12665    Ok(RecordedChildPolicies {
12666        parent_close_policy,
12667        cancellation_policy,
12668    })
12669}
12670
12671fn ensure_child_policies_match(
12672    sequence: u64,
12673    recorded: &RecordedChildPolicies,
12674    current: &ChildWorkflowOptions,
12675) -> Result<()> {
12676    for (field, expected, actual) in [
12677        (
12678            "parent_close_policy",
12679            recorded.parent_close_policy.as_str(),
12680            current.parent_close_policy.as_str(),
12681        ),
12682        (
12683            "cancellation_policy",
12684            recorded.cancellation_policy.as_str(),
12685            current.cancellation_policy.as_str(),
12686        ),
12687    ] {
12688        if expected != actual {
12689            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
12690                "child_workflow_policy_changed",
12691                Some(sequence),
12692                Some(expected.to_string()),
12693                Some(actual.to_string()),
12694                format!("child workflow {field} changed during replay"),
12695            )));
12696        }
12697    }
12698    Ok(())
12699}
12700
12701#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12702enum RecordedSnapshotValue<T> {
12703    /// Older history did not persist this field, so it cannot constrain replay.
12704    Unknown,
12705    Known(T),
12706}
12707
12708impl<T: PartialEq> RecordedSnapshotValue<T> {
12709    fn matches_current(&self, current: &Self) -> bool {
12710        match self {
12711            Self::Unknown => true,
12712            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
12713        }
12714    }
12715}
12716
12717#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
12718struct ActivityRetrySnapshot {
12719    snapshot_version: RecordedSnapshotValue<Option<u64>>,
12720    max_attempts: RecordedSnapshotValue<Option<u64>>,
12721    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
12722    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12723    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
12724    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
12725    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
12726    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
12727}
12728
12729impl ActivityRetrySnapshot {
12730    fn matches_current(&self, current: &Self) -> bool {
12731        self.snapshot_version
12732            .matches_current(&current.snapshot_version)
12733            && self.max_attempts.matches_current(&current.max_attempts)
12734            && self
12735                .backoff_seconds
12736                .matches_current(&current.backoff_seconds)
12737            && self
12738                .start_to_close_timeout
12739                .matches_current(&current.start_to_close_timeout)
12740            && self
12741                .schedule_to_start_timeout
12742                .matches_current(&current.schedule_to_start_timeout)
12743            && self
12744                .schedule_to_close_timeout
12745                .matches_current(&current.schedule_to_close_timeout)
12746            && self
12747                .heartbeat_timeout
12748                .matches_current(&current.heartbeat_timeout)
12749            && self
12750                .non_retryable_error_types
12751                .matches_current(&current.non_retryable_error_types)
12752    }
12753}
12754
12755fn recorded_optional_u64(
12756    object: Option<&serde_json::Map<String, Value>>,
12757    field: &str,
12758) -> RecordedSnapshotValue<Option<u64>> {
12759    match object.and_then(|object| object.get(field)) {
12760        None => RecordedSnapshotValue::Unknown,
12761        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12762        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
12763    }
12764}
12765
12766fn recorded_optional_string(
12767    object: &serde_json::Map<String, Value>,
12768    field: &str,
12769) -> RecordedSnapshotValue<Option<String>> {
12770    match object.get(field) {
12771        None => RecordedSnapshotValue::Unknown,
12772        Some(Value::Null) => RecordedSnapshotValue::Known(None),
12773        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
12774    }
12775}
12776
12777fn recorded_activity_execution_mode(
12778    events: &[&HistoryEvent],
12779    sequence: u64,
12780) -> Result<RecordedSnapshotValue<Option<String>>> {
12781    let mut recorded = RecordedSnapshotValue::Unknown;
12782    for event in events {
12783        for object in [
12784            event.payload.as_object(),
12785            event.payload.get("activity").and_then(Value::as_object),
12786        ]
12787        .into_iter()
12788        .flatten()
12789        {
12790            let mode = match object.get("execution_mode") {
12791                None => None,
12792                Some(Value::Null) => Some(None),
12793                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
12794                Some(_) => {
12795                    return Err(invalid_recorded_history(
12796                        "activity_execution_mode_invalid",
12797                        sequence,
12798                        "null or a non-empty execution mode",
12799                        "invalid execution_mode",
12800                        "activity history contains an invalid execution mode",
12801                    ))
12802                }
12803            };
12804            let legacy_mode = match object.get("local_activity") {
12805                None => None,
12806                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
12807                Some(_) => {
12808                    return Err(invalid_recorded_history(
12809                        "activity_execution_mode_invalid",
12810                        sequence,
12811                        "boolean local_activity",
12812                        "invalid local_activity",
12813                        "activity history contains an invalid local-activity marker",
12814                    ))
12815                }
12816            };
12817            for mode in [mode, legacy_mode].into_iter().flatten() {
12818                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
12819                {
12820                    return Err(invalid_recorded_history(
12821                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
12822                        "activity lifecycle events at one workflow sequence disagree on execution mode",
12823                    ));
12824                }
12825                recorded = RecordedSnapshotValue::Known(mode);
12826            }
12827        }
12828    }
12829    Ok(recorded)
12830}
12831
12832fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
12833    let policy = policy.and_then(Value::as_object);
12834    let backoff_seconds = policy
12835        .and_then(|policy| policy.get("backoff_seconds"))
12836        .and_then(Value::as_array)
12837        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12838        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
12839    let mut non_retryable_error_types = Vec::new();
12840    for error_type in policy
12841        .and_then(|policy| policy.get("non_retryable_error_types"))
12842        .and_then(Value::as_array)
12843        .into_iter()
12844        .flatten()
12845        .filter_map(Value::as_str)
12846        .map(str::trim)
12847        .filter(|error_type| !error_type.is_empty())
12848    {
12849        if !non_retryable_error_types
12850            .iter()
12851            .any(|recorded| recorded == error_type)
12852        {
12853            non_retryable_error_types.push(error_type.to_string());
12854        }
12855    }
12856
12857    ActivityRetrySnapshot {
12858        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
12859        max_attempts: recorded_optional_u64(policy, "max_attempts"),
12860        backoff_seconds,
12861        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
12862        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
12863        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
12864        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
12865        non_retryable_error_types: if policy
12866            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
12867        {
12868            RecordedSnapshotValue::Known(non_retryable_error_types)
12869        } else {
12870            RecordedSnapshotValue::Unknown
12871        },
12872    }
12873}
12874
12875fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
12876    let policy = options.retry_policy.as_ref();
12877    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
12878        Some(Value::Null) => None,
12879        Some(value) => value_as_u64(value),
12880        None => Some(1),
12881    };
12882    let backoff_seconds = policy
12883        .and_then(|policy| policy.get("backoff_seconds"))
12884        .and_then(Value::as_array)
12885        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
12886        .unwrap_or_default();
12887    let non_retryable_error_types = policy
12888        .and_then(|policy| policy.get("non_retryable_error_types"))
12889        .and_then(Value::as_array)
12890        .into_iter()
12891        .flatten()
12892        .filter_map(Value::as_str)
12893        .map(str::to_string)
12894        .collect();
12895
12896    ActivityRetrySnapshot {
12897        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
12898        max_attempts: RecordedSnapshotValue::Known(max_attempts),
12899        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
12900        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
12901        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
12902        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
12903        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
12904        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
12905    }
12906}
12907
12908fn activity_options_description(options: &RecordedActivityOptions) -> String {
12909    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
12910}
12911
12912impl RecordedCommand {
12913    fn sequence(&self) -> u64 {
12914        match self {
12915            Self::CancellationGroup { sequence, .. }
12916            | Self::CancellationScope { sequence, .. }
12917            | Self::CancellationBoundary { sequence, .. }
12918            | Self::Activity { sequence, .. }
12919            | Self::Timer { sequence, .. }
12920            | Self::ChildWorkflow { sequence, .. }
12921            | Self::SignalWait { sequence, .. }
12922            | Self::ConditionWait { sequence, .. }
12923            | Self::SearchAttributes { sequence, .. }
12924            | Self::SideEffect { sequence, .. }
12925            | Self::VersionMarker { sequence, .. }
12926            | Self::Memo { sequence, .. } => *sequence,
12927            Self::ServiceOperation { sequence, .. } => *sequence,
12928        }
12929    }
12930
12931    fn shape(&self) -> &'static str {
12932        match self {
12933            Self::CancellationScope { .. } => "cancellation scope",
12934            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
12935                "cooperative cancellation"
12936            }
12937            Self::Activity { .. } => "activity",
12938            Self::Timer { .. } => "timer",
12939            Self::ChildWorkflow { .. } => "child workflow",
12940            Self::SignalWait { .. } => "signal wait",
12941            Self::ConditionWait { .. } => "condition wait",
12942            Self::SearchAttributes { .. } => "search-attribute update",
12943            Self::SideEffect { .. } => "side effect",
12944            Self::VersionMarker { .. } => "version marker",
12945            Self::Memo { .. } => "memo upsert",
12946            Self::ServiceOperation { .. } => "service operation",
12947        }
12948    }
12949}
12950
12951fn ensure_version_supported(
12952    change_id: &str,
12953    version: i32,
12954    min_supported: i32,
12955    max_supported: i32,
12956    sequence: u64,
12957) -> Result<()> {
12958    if (min_supported..=max_supported).contains(&version) {
12959        return Ok(());
12960    }
12961    Err(Error::NonDeterministicReplay(ReplayFailure::new(
12962        "version_marker_incompatible_range",
12963        (sequence != 0).then_some(sequence),
12964        Some(format!("{min_supported}..={max_supported}")),
12965        Some(format!("{change_id}:{version}")),
12966        "recorded workflow version is outside the range supported by current code",
12967    )))
12968}
12969
12970#[derive(Clone, Debug)]
12971struct ResumeSignal {
12972    signal_name: String,
12973    arguments: Vec<AvroValue>,
12974}
12975
12976const MAX_PARALLEL_OPERATIONS: usize = 1000;
12977
12978fn parallel_group_prefix(kind: &str) -> &'static str {
12979    match kind {
12980        "activity" => "parallel-activities",
12981        "child" => "parallel-children",
12982        "timer" => "parallel-timers",
12983        _ => "parallel-calls",
12984    }
12985}
12986
12987fn parallel_group_entry(
12988    base_sequence: u64,
12989    size: usize,
12990    index: usize,
12991    kind: &str,
12992) -> ParallelGroupMetadata {
12993    ParallelGroupMetadata {
12994        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
12995        parallel_group_kind: kind.to_string(),
12996        parallel_group_base_sequence: base_sequence,
12997        parallel_group_size: size,
12998        parallel_group_index: index,
12999        parallel_group_mode: None,
13000        selection_member_key: None,
13001        selection_member_index: None,
13002        selection_member_base_sequence: None,
13003        selection_member_size: None,
13004        selection_member_kind: None,
13005    }
13006}
13007
13008struct SelectionMemberMetadata {
13009    key: SelectionKey,
13010    index: usize,
13011    base_sequence: u64,
13012    size: usize,
13013    kind: String,
13014}
13015
13016fn selection_group_entry(
13017    base_sequence: u64,
13018    size: usize,
13019    index: usize,
13020    kind: &str,
13021    member: &SelectionMemberMetadata,
13022) -> ParallelGroupMetadata {
13023    ParallelGroupMetadata {
13024        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
13025        parallel_group_kind: kind.to_string(),
13026        parallel_group_base_sequence: base_sequence,
13027        parallel_group_size: size,
13028        parallel_group_index: index,
13029        parallel_group_mode: Some("select".to_string()),
13030        selection_member_key: Some(member.key.clone()),
13031        selection_member_index: Some(member.index),
13032        selection_member_base_sequence: Some(member.base_sequence),
13033        selection_member_size: Some(member.size),
13034        selection_member_kind: Some(member.kind.clone()),
13035    }
13036}
13037
13038fn apply_parallel_group_path(
13039    command: &mut serde_json::Map<String, Value>,
13040    path: &[ParallelGroupMetadata],
13041) {
13042    let Some(inner) = path.last() else {
13043        return;
13044    };
13045    command.insert(
13046        "parallel_group_id".to_string(),
13047        json!(inner.parallel_group_id),
13048    );
13049    command.insert(
13050        "parallel_group_kind".to_string(),
13051        json!(inner.parallel_group_kind),
13052    );
13053    command.insert(
13054        "parallel_group_base_sequence".to_string(),
13055        json!(inner.parallel_group_base_sequence),
13056    );
13057    command.insert(
13058        "parallel_group_size".to_string(),
13059        json!(inner.parallel_group_size),
13060    );
13061    command.insert(
13062        "parallel_group_index".to_string(),
13063        json!(inner.parallel_group_index),
13064    );
13065    if let Some(mode) = &inner.parallel_group_mode {
13066        command.insert("parallel_group_mode".to_string(), json!(mode));
13067    }
13068    if let Some(key) = &inner.selection_member_key {
13069        command.insert("selection_member_key".to_string(), json!(key));
13070    }
13071    if let Some(index) = inner.selection_member_index {
13072        command.insert("selection_member_index".to_string(), json!(index));
13073    }
13074    if let Some(base_sequence) = inner.selection_member_base_sequence {
13075        command.insert(
13076            "selection_member_base_sequence".to_string(),
13077            json!(base_sequence),
13078        );
13079    }
13080    if let Some(size) = inner.selection_member_size {
13081        command.insert("selection_member_size".to_string(), json!(size));
13082    }
13083    if let Some(kind) = &inner.selection_member_kind {
13084        command.insert("selection_member_kind".to_string(), json!(kind));
13085    }
13086    command.insert("parallel_group_path".to_string(), json!(path));
13087}
13088
13089fn ensure_parallel_path_matches(
13090    sequence: u64,
13091    recorded: Option<&[ParallelGroupMetadata]>,
13092    expected: &[ParallelGroupMetadata],
13093) -> Result<()> {
13094    match (recorded, expected.is_empty()) {
13095        (None, true) => Ok(()),
13096        (Some(recorded), false) if recorded == expected => Ok(()),
13097        (None, false) => Err(invalid_recorded_history(
13098            "parallel_group_metadata_missing",
13099            sequence,
13100            &serde_json::to_string(expected).unwrap_or_default(),
13101            "<missing>",
13102            "recorded parallel member is missing its durable group path",
13103        )),
13104        (Some(recorded), true) => Err(invalid_recorded_history(
13105            "parallel_group_shape_mismatch",
13106            sequence,
13107            "sequential command",
13108            &serde_json::to_string(recorded).unwrap_or_default(),
13109            "recorded command belonged to a parallel group but current code schedules it sequentially",
13110        )),
13111        (Some(recorded), false) => Err(invalid_recorded_history(
13112            "parallel_group_shape_mismatch",
13113            sequence,
13114            &serde_json::to_string(recorded).unwrap_or_default(),
13115            &serde_json::to_string(expected).unwrap_or_default(),
13116            "recorded parallel-group identity or path changed during replay",
13117        )),
13118    }
13119}
13120
13121#[derive(Clone, Debug)]
13122enum ParallelShape {
13123    Leaf,
13124    Group(Vec<ParallelShape>),
13125}
13126
13127struct ParallelDescriptor {
13128    operation: ParallelOperation,
13129    offset: usize,
13130    member_path: Vec<usize>,
13131    group_path: Vec<ParallelGroupMetadata>,
13132}
13133
13134fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
13135    operations
13136        .iter()
13137        .map(|operation| match operation {
13138            ParallelOperation::Group(children) => parallel_leaf_count(children),
13139            _ => 1,
13140        })
13141        .sum()
13142}
13143
13144fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
13145    match operation {
13146        ParallelOperation::Activity { .. } => Some("activity"),
13147        ParallelOperation::ChildWorkflow { .. } => Some("child"),
13148        ParallelOperation::Timer(_) => Some("timer"),
13149        ParallelOperation::Signal(_) => Some("signal"),
13150        ParallelOperation::Condition { .. } => Some("condition"),
13151        ParallelOperation::Group(children) => parallel_group_kind(children),
13152    }
13153}
13154
13155fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
13156    let mut kind = None;
13157    for operation in operations {
13158        let Some(operation_kind) = parallel_operation_kind(operation) else {
13159            continue;
13160        };
13161        match kind {
13162            None => kind = Some(operation_kind),
13163            Some(current) if current == operation_kind => {}
13164            Some(_) => return Some("mixed"),
13165        }
13166    }
13167    kind
13168}
13169
13170fn validate_parallel_operations(
13171    operations: &[ParallelOperation],
13172    member_path: &mut Vec<usize>,
13173    root: bool,
13174) -> Result<()> {
13175    let leaves = parallel_leaf_count(operations);
13176    if leaves > MAX_PARALLEL_OPERATIONS {
13177        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13178            reason: "fan_out_limit_exceeded",
13179            member_path: member_path.clone(),
13180            message: format!(
13181                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13182            ),
13183        }));
13184    }
13185    if !root && operations.is_empty() {
13186        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13187            reason: "nested_group_empty",
13188            member_path: member_path.clone(),
13189            message: "a nested group must contain at least one durable leaf".to_string(),
13190        }));
13191    }
13192
13193    for (index, operation) in operations.iter().enumerate() {
13194        member_path.push(index);
13195        match operation {
13196            ParallelOperation::Activity {
13197                options, arguments, ..
13198            } => {
13199                options
13200                    .validate()
13201                    .map_err(|error| Error::InvalidActivityOptions(error))?;
13202                if let Err(error) = arguments {
13203                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13204                        reason: "arguments_invalid",
13205                        member_path: member_path.clone(),
13206                        message: error.to_string(),
13207                    }));
13208                }
13209            }
13210            ParallelOperation::ChildWorkflow {
13211                options, arguments, ..
13212            } => {
13213                validate_parallel_child_options(options)?;
13214                if let Err(error) = arguments {
13215                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13216                        reason: "arguments_invalid",
13217                        member_path: member_path.clone(),
13218                        message: error.to_string(),
13219                    }));
13220                }
13221            }
13222            ParallelOperation::Timer(duration)
13223                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
13224            {
13225                return Err(Error::TimerDurationOverflow);
13226            }
13227            ParallelOperation::Timer(_) => {}
13228            ParallelOperation::Signal(signal_name) => {
13229                validate_user_signal_name(signal_name)?;
13230                if signal_name.trim().is_empty() {
13231                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13232                        reason: "signal_name_empty",
13233                        member_path: member_path.clone(),
13234                        message: "signal wait name must not be empty".to_string(),
13235                    }));
13236                }
13237            }
13238            ParallelOperation::Condition { options, .. } => {
13239                options.validate()?;
13240            }
13241            ParallelOperation::Group(children) => {
13242                validate_parallel_operations(children, member_path, false)?;
13243            }
13244        }
13245        member_path.pop();
13246    }
13247    Ok(())
13248}
13249
13250fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
13251    if options.task_queue.trim().is_empty() {
13252        return Err(Error::InvalidChildWorkflowOptions(
13253            "task_queue must not be empty".to_string(),
13254        ));
13255    }
13256    for (name, value) in [
13257        (
13258            "execution_timeout_seconds",
13259            options.execution_timeout_seconds,
13260        ),
13261        ("run_timeout_seconds", options.run_timeout_seconds),
13262    ] {
13263        if value == Some(0) {
13264            return Err(Error::InvalidChildWorkflowOptions(format!(
13265                "{name} must be at least 1"
13266            )));
13267        }
13268    }
13269    if options
13270        .retry_policy
13271        .as_ref()
13272        .is_some_and(|policy| policy.max_attempts == Some(0))
13273    {
13274        return Err(Error::InvalidChildWorkflowOptions(
13275            "retry_policy.max_attempts must be at least 1".to_string(),
13276        ));
13277    }
13278    Ok(())
13279}
13280
13281fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
13282    ParallelShape::Group(
13283        operations
13284            .iter()
13285            .map(|operation| match operation {
13286                ParallelOperation::Group(children) => parallel_shape(children),
13287                _ => ParallelShape::Leaf,
13288            })
13289            .collect(),
13290    )
13291}
13292
13293fn parallel_descriptors(
13294    operations: Vec<ParallelOperation>,
13295    base_sequence: u64,
13296) -> Result<Vec<ParallelDescriptor>> {
13297    let size = parallel_leaf_count(&operations);
13298    let kind = parallel_group_kind(&operations).unwrap_or("activity");
13299    let mut descriptors = Vec::with_capacity(size);
13300    let mut cursor = 0;
13301
13302    for (index, operation) in operations.into_iter().enumerate() {
13303        match operation {
13304            ParallelOperation::Group(children) => {
13305                let child_base = base_sequence
13306                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13307                    .ok_or(Error::TimerDurationOverflow)?;
13308                for mut descriptor in parallel_descriptors(children, child_base)? {
13309                    let outer_index = cursor + descriptor.offset;
13310                    descriptor.group_path.insert(
13311                        0,
13312                        parallel_group_entry(base_sequence, size, outer_index, kind),
13313                    );
13314                    descriptor.member_path.insert(0, index);
13315                    descriptor.offset = outer_index;
13316                    descriptors.push(descriptor);
13317                }
13318                cursor = descriptors.len();
13319            }
13320            operation => {
13321                descriptors.push(ParallelDescriptor {
13322                    operation,
13323                    offset: cursor,
13324                    member_path: vec![index],
13325                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
13326                });
13327                cursor += 1;
13328            }
13329        }
13330    }
13331    Ok(descriptors)
13332}
13333
13334enum ParallelLeafCall {
13335    Activity(ActivityCall),
13336    ChildWorkflow(ChildWorkflowCall),
13337    Timer(TimerCall),
13338    Signal(SignalCall),
13339    Condition(ConditionWaitCall),
13340}
13341
13342fn parallel_leaf_call(
13343    ctx: &WorkflowContext,
13344    operation: ParallelOperation,
13345    parallel_group_path: Vec<ParallelGroupMetadata>,
13346) -> ParallelLeafCall {
13347    match operation {
13348        ParallelOperation::Activity {
13349            activity_type,
13350            options,
13351            arguments,
13352        } => ParallelLeafCall::Activity(ActivityCall {
13353            ctx: ctx.clone(),
13354            activity_type,
13355            options,
13356            worker_session: None,
13357            args: Some(arguments),
13358            scheduled: false,
13359            local: false,
13360            local_result: None,
13361            parallel_group_path,
13362        }),
13363        ParallelOperation::ChildWorkflow {
13364            workflow_type,
13365            options,
13366            arguments,
13367        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
13368            ctx: ctx.clone(),
13369            workflow_type,
13370            options,
13371            args: Some(arguments),
13372            scheduled: false,
13373            matched_pending: false,
13374            parallel_group_path,
13375        }),
13376        ParallelOperation::Timer(duration) => {
13377            let delay_seconds = duration
13378                .as_secs()
13379                .checked_add(u64::from(duration.subsec_nanos() > 0));
13380            ParallelLeafCall::Timer(TimerCall {
13381                ctx: ctx.clone(),
13382                delay_seconds,
13383                scheduled: false,
13384                matched_pending: false,
13385                parallel_group_path,
13386            })
13387        }
13388        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
13389            ctx: ctx.clone(),
13390            signal_name,
13391            runtime_reserved_allowed: false,
13392            opened_wait: false,
13393            matched_pending: false,
13394            parallel_group_path,
13395        }),
13396        ParallelOperation::Condition { options, predicate } => {
13397            ParallelLeafCall::Condition(ConditionWaitCall {
13398                ctx: ctx.clone(),
13399                options,
13400                predicate,
13401                occurrence_id: None,
13402                opened_wait: false,
13403                parallel_group_path,
13404            })
13405        }
13406        ParallelOperation::Group(_) => {
13407            unreachable!("parallel descriptors contain only durable leaves")
13408        }
13409    }
13410}
13411
13412impl ParallelLeafCall {
13413    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
13414        match self {
13415            Self::Activity(call) => Pin::new(call)
13416                .poll_avro_value(cx)
13417                .map_ok(ParallelAvroResult::Activity),
13418            Self::ChildWorkflow(call) => Pin::new(call)
13419                .poll_avro_value(cx)
13420                .map_ok(ParallelAvroResult::ChildWorkflow),
13421            Self::Timer(call) => Pin::new(call)
13422                .poll(cx)
13423                .map_ok(|()| ParallelAvroResult::Timer),
13424            Self::Signal(call) => Pin::new(call)
13425                .poll_avro_value(cx)
13426                .map_ok(ParallelAvroResult::Signal),
13427            Self::Condition(call) => Pin::new(call)
13428                .poll(cx)
13429                .map_ok(ParallelAvroResult::Condition),
13430        }
13431    }
13432}
13433
13434struct ParallelLeaf {
13435    call: ParallelLeafCall,
13436    sequence: u64,
13437    member_path: Vec<usize>,
13438    group_path: Vec<ParallelGroupMetadata>,
13439    result: Option<ParallelAvroResult>,
13440}
13441
13442/// Future returned by [`WorkflowContext::parallel`].
13443pub struct ParallelCall {
13444    ctx: WorkflowContext,
13445    operations: Option<Vec<ParallelOperation>>,
13446    shape: Option<ParallelShape>,
13447    leaves: Vec<ParallelLeaf>,
13448    pending_scope_delivery: bool,
13449    worker_session: Option<WorkerSessionOptions>,
13450}
13451
13452impl ParallelCall {
13453    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
13454        Self {
13455            ctx,
13456            operations: Some(operations),
13457            shape: None,
13458            leaves: Vec::new(),
13459            pending_scope_delivery: false,
13460            worker_session: None,
13461        }
13462    }
13463
13464    fn initialize(&mut self) -> Result<()> {
13465        if let Some(session) = &self.worker_session {
13466            session.to_wire()?;
13467        }
13468        let operations = self.operations.take().unwrap_or_default();
13469        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
13470        self.shape = Some(parallel_shape(&operations));
13471        if operations.is_empty() {
13472            return Ok(());
13473        }
13474
13475        let base_sequence = {
13476            let state = self
13477                .ctx
13478                .state
13479                .lock()
13480                .map_err(|_| Error::WorkflowStatePoisoned)?;
13481            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
13482                recorded.sequence()
13483            } else {
13484                let last = state
13485                    .recorded_commands
13486                    .last()
13487                    .map(RecordedCommand::sequence)
13488                    .unwrap_or(0);
13489                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
13490                    .and_then(|sequence| sequence.checked_add(1))
13491                    .ok_or_else(|| {
13492                        Error::InvalidParallelGroup(ParallelGroupError {
13493                            reason: "sequence_overflow",
13494                            member_path: Vec::new(),
13495                            message: "parallel group sequence identity overflowed u64".to_string(),
13496                        })
13497                    })?
13498            }
13499        };
13500
13501        let descriptors = parallel_descriptors(operations, base_sequence)?;
13502        {
13503            let mut state = self
13504                .ctx
13505                .state
13506                .lock()
13507                .map_err(|_| Error::WorkflowStatePoisoned)?;
13508            let cursor = state.command_cursor;
13509            self.ctx.validate_scope_membership(&mut state, cursor)?;
13510            if state.prepare_parallel_scope_cancellation(&descriptors)? {
13511                self.pending_scope_delivery = true;
13512                return Ok(());
13513            }
13514            state.expand_cancellation_group(&descriptors)?;
13515            state.prepare_group_cancellation(&descriptors)?;
13516        }
13517        self.leaves = descriptors
13518            .into_iter()
13519            .map(|descriptor| {
13520                let mut call = parallel_leaf_call(
13521                    &self.ctx,
13522                    descriptor.operation,
13523                    descriptor.group_path.clone(),
13524                );
13525                if let (Some(session), ParallelLeafCall::Activity(activity)) =
13526                    (&self.worker_session, &mut call)
13527                {
13528                    activity.worker_session = Some(session.clone());
13529                }
13530                ParallelLeaf {
13531                    call,
13532                    sequence: base_sequence + descriptor.offset as u64,
13533                    member_path: descriptor.member_path,
13534                    group_path: descriptor.group_path,
13535                    result: None,
13536                }
13537            })
13538            .collect();
13539        Ok(())
13540    }
13541
13542    fn poll_avro_value(
13543        mut self: Pin<&mut Self>,
13544        cx: &mut TaskContext<'_>,
13545    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
13546        if self.operations.is_some() {
13547            if let Err(error) = self.initialize() {
13548                return Poll::Ready(Err(error));
13549            }
13550        }
13551        if self.pending_scope_delivery {
13552            return Poll::Pending;
13553        }
13554        if self.leaves.is_empty() {
13555            return Poll::Ready(Ok(Vec::new()));
13556        }
13557
13558        let mut failures = Vec::new();
13559        let mut pending = false;
13560        for (index, leaf) in self.leaves.iter_mut().enumerate() {
13561            if leaf.result.is_some() {
13562                continue;
13563            }
13564            match leaf.call.poll_avro_value(cx) {
13565                Poll::Ready(Ok(result)) => leaf.result = Some(result),
13566                Poll::Ready(Err(error)) => failures.push((index, error)),
13567                Poll::Pending => pending = true,
13568            }
13569        }
13570
13571        if !failures.is_empty() {
13572            if let Some(position) = failures
13573                .iter()
13574                .position(|(_, error)| workflow_task_integrity_error(error))
13575            {
13576                return Poll::Ready(Err(failures.remove(position).1));
13577            }
13578            if self
13579                .ctx
13580                .state
13581                .lock()
13582                .map_err(|_| Error::WorkflowStatePoisoned)?
13583                .cancellation_delivery_intent
13584                .is_some()
13585            {
13586                return Poll::Pending;
13587            }
13588            if let Some(position) = failures
13589                .iter()
13590                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
13591            {
13592                return Poll::Ready(Err(failures.remove(position).1));
13593            }
13594            failures.sort_by_key(|(index, _)| *index);
13595            let (failed_index, cause) = failures.remove(0);
13596            let failed = &self.leaves[failed_index];
13597            let completed = self
13598                .leaves
13599                .iter()
13600                .filter_map(|leaf| {
13601                    leaf.result
13602                        .clone()
13603                        .and_then(|result| result.into_json_result().ok())
13604                        .map(|result| ParallelCompletion {
13605                            member_path: leaf.member_path.clone(),
13606                            result,
13607                        })
13608                })
13609                .collect();
13610            let group_id = failed
13611                .group_path
13612                .first()
13613                .map(|entry| entry.parallel_group_id.clone())
13614                .unwrap_or_default();
13615            let sequences = self
13616                .leaves
13617                .iter()
13618                .map(|leaf| leaf.sequence)
13619                .collect::<Vec<_>>();
13620            self.ctx
13621                .state
13622                .lock()
13623                .map_err(|_| Error::WorkflowStatePoisoned)?
13624                .advance_cancellation_sequences(&sequences, Some(failed.sequence));
13625            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
13626                group_id,
13627                member_path: failed.member_path.clone(),
13628                group_path: failed.group_path.clone(),
13629                completed,
13630                cause: Box::new(cause),
13631            })));
13632        }
13633        if pending
13634            || self
13635                .ctx
13636                .state
13637                .lock()
13638                .map_err(|_| Error::WorkflowStatePoisoned)?
13639                .cancellation_delivery_intent
13640                .is_some()
13641        {
13642            return Poll::Pending;
13643        }
13644
13645        let mut flat_results = self
13646            .leaves
13647            .iter_mut()
13648            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
13649            .collect::<Vec<_>>()
13650            .into_iter();
13651        let results = parallel_results_for_shape(
13652            self.shape.as_ref().expect("initialized parallel shape"),
13653            &mut flat_results,
13654        );
13655        let sequences = self
13656            .leaves
13657            .iter()
13658            .map(|leaf| leaf.sequence)
13659            .collect::<Vec<_>>();
13660        self.ctx
13661            .state
13662            .lock()
13663            .map_err(|_| Error::WorkflowStatePoisoned)?
13664            .advance_cancellation_sequences(&sequences, None);
13665        Poll::Ready(Ok(match results {
13666            ParallelAvroResult::Group(results) => results,
13667            ParallelAvroResult::Activity(_)
13668            | ParallelAvroResult::ChildWorkflow(_)
13669            | ParallelAvroResult::Timer
13670            | ParallelAvroResult::Signal(_)
13671            | ParallelAvroResult::Condition(_) => {
13672                unreachable!("root parallel shape is a group")
13673            }
13674        }))
13675    }
13676}
13677
13678fn parallel_results_for_shape(
13679    shape: &ParallelShape,
13680    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
13681) -> ParallelAvroResult {
13682    match shape {
13683        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
13684        ParallelShape::Group(children) => ParallelAvroResult::Group(
13685            children
13686                .iter()
13687                .map(|child| parallel_results_for_shape(child, flat_results))
13688                .collect(),
13689        ),
13690    }
13691}
13692
13693impl Future for ParallelCall {
13694    type Output = Result<Vec<ParallelResult>>;
13695
13696    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
13697        self.poll_avro_value(cx)
13698            .map_ok(|results| {
13699                results
13700                    .into_iter()
13701                    .map(ParallelAvroResult::into_json_result)
13702                    .collect::<Result<Vec<_>>>()
13703            })
13704            .map_ok(|result| result)
13705            .flatten_result()
13706    }
13707}
13708
13709#[derive(Clone, Debug)]
13710struct SelectionMemberPlan {
13711    key: SelectionKey,
13712    index: usize,
13713    base_sequence: u64,
13714    size: usize,
13715    kind: String,
13716    shape: ParallelShape,
13717    leaf_start: usize,
13718}
13719
13720fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
13721    match operation {
13722        ParallelOperation::Activity { .. } => "activity",
13723        ParallelOperation::ChildWorkflow { .. } => "child",
13724        ParallelOperation::Timer(_) => "timer",
13725        ParallelOperation::Signal(_) => "signal",
13726        ParallelOperation::Condition { .. } => "condition",
13727        ParallelOperation::Group(_) => "group",
13728    }
13729}
13730
13731fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
13732    match operation {
13733        ParallelOperation::Group(children) => parallel_shape(children),
13734        _ => ParallelShape::Leaf,
13735    }
13736}
13737
13738fn selection_descriptors(
13739    operations: Vec<(SelectionKey, ParallelOperation)>,
13740    base_sequence: u64,
13741) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
13742    if operations.is_empty() {
13743        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13744            reason: "selection_empty",
13745            member_path: Vec::new(),
13746            message: "durable selection requires at least one operation".to_string(),
13747        }));
13748    }
13749    let operation_refs = operations
13750        .iter()
13751        .map(|(_, operation)| operation)
13752        .collect::<Vec<_>>();
13753    let total_size = operation_refs
13754        .iter()
13755        .map(|operation| match operation {
13756            ParallelOperation::Group(children) => parallel_leaf_count(children),
13757            _ => 1,
13758        })
13759        .sum::<usize>();
13760    if total_size > MAX_PARALLEL_OPERATIONS {
13761        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13762            reason: "fan_out_limit_exceeded",
13763            member_path: Vec::new(),
13764            message: format!(
13765                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13766            ),
13767        }));
13768    }
13769    let group_kind = {
13770        let mut kind = None;
13771        for operation in &operation_refs {
13772            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
13773            match kind {
13774                None => kind = Some(operation_kind),
13775                Some(current) if current == operation_kind => {}
13776                Some(_) => {
13777                    kind = Some("mixed");
13778                    break;
13779                }
13780            }
13781        }
13782        kind.unwrap_or("mixed")
13783    };
13784
13785    let mut descriptors = Vec::with_capacity(total_size);
13786    let mut members = Vec::with_capacity(operations.len());
13787    let mut cursor = 0usize;
13788    let mut seen_keys: Vec<SelectionKey> = Vec::new();
13789    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
13790        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
13791            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13792                reason: "selection_key_invalid",
13793                member_path: vec![member_index],
13794                message: "selection member keys must be non-empty strings or non-negative integers"
13795                    .to_string(),
13796            }));
13797        }
13798        if seen_keys.contains(&key) {
13799            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13800                reason: "selection_key_duplicate",
13801                member_path: vec![member_index],
13802                message: format!("selection member key {key:?} is duplicated"),
13803            }));
13804        }
13805        seen_keys.push(key.clone());
13806        let member_size = match &operation {
13807            ParallelOperation::Group(children) => parallel_leaf_count(children),
13808            _ => 1,
13809        };
13810        if member_size == 0 {
13811            return Err(Error::InvalidParallelGroup(ParallelGroupError {
13812                reason: "selection_member_empty",
13813                member_path: vec![member_index],
13814                message: "a selection member must contain at least one durable leaf".to_string(),
13815            }));
13816        }
13817        let member_base = base_sequence
13818            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13819            .ok_or(Error::TimerDurationOverflow)?;
13820        let member_kind = selection_operation_kind(&operation).to_string();
13821        let member_shape = selection_operation_shape(&operation);
13822        let leaf_start = descriptors.len();
13823        match operation {
13824            ParallelOperation::Group(children) => {
13825                validate_parallel_operations(&children, &mut vec![member_index], false)?;
13826                for mut descriptor in parallel_descriptors(children, member_base)? {
13827                    let flat_index = cursor + descriptor.offset;
13828                    descriptor.group_path.insert(
13829                        0,
13830                        selection_group_entry(
13831                            base_sequence,
13832                            total_size,
13833                            flat_index,
13834                            group_kind,
13835                            &SelectionMemberMetadata {
13836                                key: key.clone(),
13837                                index: member_index,
13838                                base_sequence: member_base,
13839                                size: member_size,
13840                                kind: member_kind.clone(),
13841                            },
13842                        ),
13843                    );
13844                    descriptor.member_path.insert(0, member_index);
13845                    descriptor.offset = flat_index;
13846                    descriptors.push(descriptor);
13847                }
13848            }
13849            operation => {
13850                validate_parallel_operations(
13851                    std::slice::from_ref(&operation),
13852                    &mut Vec::new(),
13853                    true,
13854                )?;
13855                descriptors.push(ParallelDescriptor {
13856                    operation,
13857                    offset: cursor,
13858                    member_path: vec![member_index],
13859                    group_path: vec![selection_group_entry(
13860                        base_sequence,
13861                        total_size,
13862                        cursor,
13863                        group_kind,
13864                        &SelectionMemberMetadata {
13865                            key: key.clone(),
13866                            index: member_index,
13867                            base_sequence: member_base,
13868                            size: member_size,
13869                            kind: member_kind.clone(),
13870                        },
13871                    )],
13872                });
13873            }
13874        }
13875        members.push(SelectionMemberPlan {
13876            key,
13877            index: member_index,
13878            base_sequence: member_base,
13879            size: member_size,
13880            kind: member_kind,
13881            shape: member_shape,
13882            leaf_start,
13883        });
13884        cursor += member_size;
13885    }
13886    Ok((descriptors, members))
13887}
13888
13889struct SelectionLeaf {
13890    call: ParallelLeafCall,
13891    outcome: Option<Result<ParallelAvroResult>>,
13892}
13893
13894/// Stable reference to one member of a durable selection group.
13895#[derive(Clone)]
13896pub struct DurableOperationHandle {
13897    ctx: WorkflowContext,
13898    pub key: SelectionKey,
13899    pub index: usize,
13900    pub kind: String,
13901    pub identity: String,
13902    pub base_sequence: u64,
13903    pub size: usize,
13904    pub selection_group_id: String,
13905    shape: ParallelShape,
13906}
13907
13908impl std::fmt::Debug for DurableOperationHandle {
13909    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13910        formatter
13911            .debug_struct("DurableOperationHandle")
13912            .field("key", &self.key)
13913            .field("index", &self.index)
13914            .field("kind", &self.kind)
13915            .field("identity", &self.identity)
13916            .field("base_sequence", &self.base_sequence)
13917            .field("size", &self.size)
13918            .field("selection_group_id", &self.selection_group_id)
13919            .finish()
13920    }
13921}
13922
13923impl DurableOperationHandle {
13924    /// Await this member after another member has already won the selection.
13925    pub fn await_result(&self) -> DurableOperationAwaitCall {
13926        DurableOperationAwaitCall {
13927            handle: self.clone(),
13928        }
13929    }
13930
13931    /// Request cancellation without affecting siblings. The future resolves
13932    /// to unit; only `SelectionOperationCancelled` history proves cancellation
13933    /// beat a concurrently committed terminal result.
13934    pub fn cancel(&self) -> CancelDurableOperationCall {
13935        CancelDurableOperationCall {
13936            handle: self.clone(),
13937            emitted: false,
13938        }
13939    }
13940}
13941
13942/// The one winner committed for a durable selection group.
13943#[derive(Debug)]
13944pub struct SelectionResult {
13945    pub key: SelectionKey,
13946    pub index: usize,
13947    pub kind: String,
13948    pub identity: String,
13949    pub value: Option<ParallelResult>,
13950    pub failure: Option<Error>,
13951    pub winner: DurableOperationHandle,
13952    pub handles: Vec<DurableOperationHandle>,
13953}
13954
13955impl SelectionResult {
13956    pub fn succeeded(&self) -> bool {
13957        self.failure.is_none()
13958    }
13959
13960    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
13961        self.handles.iter().find(|handle| &handle.key == key)
13962    }
13963
13964    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
13965        self.handles
13966            .iter()
13967            .filter(|handle| handle.index != self.index)
13968            .collect()
13969    }
13970
13971    pub fn into_result(self) -> Result<ParallelResult> {
13972        match (self.value, self.failure) {
13973            (Some(value), None) => Ok(value),
13974            (_, Some(error)) => Err(error),
13975            _ => Err(Error::WorkerLoop(
13976                "selection result contained neither a value nor a failure".to_string(),
13977            )),
13978        }
13979    }
13980}
13981
13982/// Future returned by [`WorkflowContext::select`].
13983pub struct SelectCall {
13984    ctx: WorkflowContext,
13985    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
13986    members: Vec<SelectionMemberPlan>,
13987    leaves: Vec<SelectionLeaf>,
13988    group_id: Option<String>,
13989}
13990
13991impl SelectCall {
13992    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
13993        Self {
13994            ctx,
13995            operations: Some(operations),
13996            members: Vec::new(),
13997            leaves: Vec::new(),
13998            group_id: None,
13999        }
14000    }
14001
14002    fn initialize(&mut self) -> Result<()> {
14003        let operations = self.operations.take().unwrap_or_default();
14004        let base_sequence = {
14005            let state = self
14006                .ctx
14007                .state
14008                .lock()
14009                .map_err(|_| Error::WorkflowStatePoisoned)?;
14010            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
14011                state.recorded_commands.get(state.command_cursor)
14012            {
14013                *sequence
14014            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
14015            {
14016                marker.selection_group_base_sequence
14017            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
14018                recorded.sequence()
14019            } else {
14020                let last = state
14021                    .recorded_commands
14022                    .last()
14023                    .map(RecordedCommand::sequence)
14024                    .unwrap_or(0);
14025                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
14026                    .and_then(|sequence| sequence.checked_add(1))
14027                    .ok_or(Error::TimerDurationOverflow)?
14028            }
14029        };
14030        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
14031        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
14032        {
14033            let mut state = self
14034                .ctx
14035                .state
14036                .lock()
14037                .map_err(|_| Error::WorkflowStatePoisoned)?;
14038            state.expand_cancellation_group(&descriptors)?;
14039            state.prepare_group_cancellation(&descriptors)?;
14040        }
14041        self.leaves = descriptors
14042            .into_iter()
14043            .map(|descriptor| SelectionLeaf {
14044                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
14045                outcome: None,
14046            })
14047            .collect();
14048        self.members = members;
14049        self.group_id = Some(group_id);
14050        Ok(())
14051    }
14052}
14053
14054impl Future for SelectCall {
14055    type Output = Result<SelectionResult>;
14056
14057    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14058        if self.operations.is_some() {
14059            if let Err(error) = self.initialize() {
14060                return Poll::Ready(Err(error));
14061            }
14062        }
14063
14064        for leaf in &mut self.leaves {
14065            if leaf.outcome.is_some() {
14066                continue;
14067            }
14068            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
14069                if outcome
14070                    .as_ref()
14071                    .err()
14072                    .is_some_and(workflow_task_integrity_error)
14073                {
14074                    return Poll::Ready(outcome.map(|_| unreachable!()));
14075                }
14076                leaf.outcome = Some(outcome);
14077            }
14078        }
14079
14080        if self
14081            .ctx
14082            .state
14083            .lock()
14084            .map_err(|_| Error::WorkflowStatePoisoned)?
14085            .cancellation_delivery_intent
14086            .is_some()
14087        {
14088            return Poll::Pending;
14089        }
14090
14091        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
14092            matches!(
14093                leaf.outcome,
14094                Some(Err(Error::CooperativeCancellationRequested(_)))
14095            )
14096        }) {
14097            return Poll::Ready(
14098                leaf.outcome
14099                    .take()
14100                    .expect("matched cancellation")
14101                    .map(|_| unreachable!()),
14102            );
14103        }
14104
14105        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
14106        let selection_member_range = self
14107            .members
14108            .first()
14109            .map(|member| member.base_sequence)
14110            .zip(self.leaves.len().try_into().ok())
14111            .map(|(base_sequence, size): (u64, u64)| {
14112                base_sequence..base_sequence.saturating_add(size)
14113            });
14114        let marker = {
14115            let mut state = match self.ctx.state.lock() {
14116                Ok(state) => state,
14117                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14118            };
14119            let marker = state
14120                .selection_markers
14121                .get(state.selection_marker_cursor)
14122                .cloned();
14123            if marker.is_none()
14124                && all_members_terminal
14125                && selection_member_range.as_ref().is_some_and(|member_range| {
14126                    state
14127                        .recorded_commands
14128                        .iter()
14129                        .any(|command| member_range.contains(&command.sequence()))
14130                })
14131            {
14132                // Terminal member history can be committed before the server's
14133                // SelectionResolved marker becomes visible to this task. That
14134                // marker is the durable barrier the selection is still waiting
14135                // on, so an otherwise commandless replay remains legitimately
14136                // pending instead of failing as an untracked yield.
14137                state.matched_recorded_pending = true;
14138            }
14139            marker
14140        };
14141        let Some(marker) = marker else {
14142            return Poll::Pending;
14143        };
14144        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
14145            || marker.selection_group_size != self.leaves.len()
14146            || self.members.first().map(|member| member.base_sequence)
14147                != Some(marker.selection_group_base_sequence)
14148        {
14149            return Poll::Ready(Err(invalid_recorded_history(
14150                "selection_group_shape_mismatch",
14151                marker.selection_group_base_sequence,
14152                self.group_id
14153                    .as_deref()
14154                    .unwrap_or("initialized selection group"),
14155                &marker.selection_group_id,
14156                "recorded selection group differs from current workflow code",
14157            )));
14158        }
14159        let Some(member_position) = self.members.iter().position(|member| {
14160            member.key == marker.member_key
14161                && member.index == marker.member_index
14162                && member.base_sequence == marker.member_base_sequence
14163                && member.size == marker.member_size
14164                && member.kind == marker.operation_kind
14165        }) else {
14166            return Poll::Ready(Err(invalid_recorded_history(
14167                "selection_member_shape_mismatch",
14168                marker.member_base_sequence,
14169                "winner member matching current workflow code",
14170                &format!("{:?}", marker.member_key),
14171                "recorded selection winner differs from the authored member identity",
14172            )));
14173        };
14174        let member = self.members[member_position].clone();
14175        let (handles, resolution_sequence) = {
14176            let mut state = match self.ctx.state.lock() {
14177                Ok(state) => state,
14178                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14179            };
14180            let identities = self
14181                .members
14182                .iter()
14183                .map(|candidate| {
14184                    selection_operation_identity(
14185                        &state,
14186                        &candidate.kind,
14187                        candidate.base_sequence,
14188                        candidate.size,
14189                    )
14190                })
14191                .collect::<Vec<_>>();
14192            if let Some((position, missing)) = identities
14193                .iter()
14194                .enumerate()
14195                .find(|(_, identity)| identity.is_empty())
14196                .map(|(position, identity)| (position, identity.clone()))
14197            {
14198                let candidate = &self.members[position];
14199                return Poll::Ready(Err(invalid_recorded_history(
14200                    "selection_operation_identity_missing",
14201                    candidate.base_sequence,
14202                    &format!(
14203                        "durable {} resource identity from scheduled/open history",
14204                        candidate.kind
14205                    ),
14206                    &missing,
14207                    "selection member history is missing its canonical durable identity",
14208                )));
14209            }
14210            let expected_winner_identity = &identities[member_position];
14211            let resolution_sequence = match validated_selection_resolution_sequence(
14212                &state,
14213                &marker,
14214                &member,
14215                expected_winner_identity,
14216            ) {
14217                Ok(sequence) => sequence,
14218                Err(error) => return Poll::Ready(Err(error)),
14219            };
14220            let handles = self
14221                .members
14222                .iter()
14223                .zip(identities)
14224                .map(|(member, identity)| DurableOperationHandle {
14225                    ctx: self.ctx.clone(),
14226                    key: member.key.clone(),
14227                    index: member.index,
14228                    kind: member.kind.clone(),
14229                    identity,
14230                    base_sequence: member.base_sequence,
14231                    size: member.size,
14232                    selection_group_id: marker.selection_group_id.clone(),
14233                    shape: member.shape.clone(),
14234                })
14235                .collect::<Vec<_>>();
14236            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
14237                return Poll::Ready(Err(error));
14238            }
14239            state.selection_marker_cursor += 1;
14240            (handles, resolution_sequence)
14241        };
14242
14243        let mut winner_failure = None;
14244        let mut flat_results = Vec::with_capacity(member.size);
14245        if marker.outcome == "failed" {
14246            let resolution_offset = match resolution_sequence
14247                .checked_sub(member.base_sequence)
14248                .and_then(|offset| usize::try_from(offset).ok())
14249            {
14250                Some(offset) if offset < member.size => offset,
14251                _ => {
14252                    return Poll::Ready(Err(invalid_recorded_history(
14253                        "selection_resolution_event_mismatch",
14254                        member.base_sequence,
14255                        "failure event within selected member bounds",
14256                        &resolution_sequence.to_string(),
14257                        "selection failure event is outside the authored member",
14258                    )))
14259                }
14260            };
14261            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
14262            match leaf.outcome.take() {
14263                Some(Err(error)) => winner_failure = Some(error),
14264                _ => {
14265                    return Poll::Ready(Err(invalid_recorded_history(
14266                        "selection_winner_outcome_mismatch",
14267                        member.base_sequence,
14268                        "exact failed terminal history referenced by SelectionResolved",
14269                        "missing or successful resolution event",
14270                        "selection winner marker disagrees with terminal operation history",
14271                    )))
14272                }
14273            }
14274        } else {
14275            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
14276                match leaf.outcome.take() {
14277                    Some(Ok(result)) => flat_results.push(result),
14278                    Some(Err(_)) => {
14279                        return Poll::Ready(Err(invalid_recorded_history(
14280                            "selection_winner_outcome_mismatch",
14281                            member.base_sequence,
14282                            "fully completed nested selection member",
14283                            "failed durable leaf",
14284                            "completed selection winner contains a failed leaf",
14285                        )))
14286                    }
14287                    None => {
14288                        return Poll::Ready(Err(invalid_recorded_history(
14289                            "selection_winner_unresolved",
14290                            member.base_sequence,
14291                            "terminal history for every completed winner leaf",
14292                            "pending member history",
14293                            "completed SelectionResolved member has an unfinished durable barrier",
14294                        )))
14295                    }
14296                }
14297            }
14298        }
14299        let value = if winner_failure.is_none() {
14300            let mut flat_results = flat_results.into_iter();
14301            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
14302            match value.into_json_result() {
14303                Ok(value) => Some(value),
14304                Err(error) => return Poll::Ready(Err(error)),
14305            }
14306        } else {
14307            None
14308        };
14309        let winner = handles[member_position].clone();
14310        self.ctx
14311            .state
14312            .lock()
14313            .map_err(|_| Error::WorkflowStatePoisoned)?
14314            .advance_cancellation_selection(&marker.selection_group_id);
14315        Poll::Ready(Ok(SelectionResult {
14316            key: winner.key.clone(),
14317            index: winner.index,
14318            kind: winner.kind.clone(),
14319            identity: winner.identity.clone(),
14320            value,
14321            failure: winner_failure,
14322            winner,
14323            handles,
14324        }))
14325    }
14326}
14327
14328fn selection_operation_identity(
14329    state: &WorkflowState,
14330    kind: &str,
14331    base_sequence: u64,
14332    size: usize,
14333) -> String {
14334    if kind == "group" {
14335        return format!("group:{base_sequence}:{size}");
14336    }
14337    let fields: &[&str] = match kind {
14338        "activity" => &["activity_execution_id"],
14339        "child" => &["child_workflow_run_id"],
14340        "timer" => &["timer_id"],
14341        "signal" => &["signal_wait_id"],
14342        "condition" => &["condition_wait_id"],
14343        _ => &[],
14344    };
14345    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
14346        for event in state
14347            .history_events
14348            .iter()
14349            .filter(|event| durable_event_sequence(event) == Some(sequence))
14350        {
14351            for field in fields {
14352                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
14353                    if !identity.is_empty() {
14354                        return identity.to_string();
14355                    }
14356                }
14357            }
14358        }
14359    }
14360    String::new()
14361}
14362
14363fn validated_selection_resolution_sequence(
14364    state: &WorkflowState,
14365    marker: &SelectionMarker,
14366    member: &SelectionMemberPlan,
14367    expected_identity: &str,
14368) -> Result<u64> {
14369    if expected_identity.is_empty() {
14370        return Err(invalid_recorded_history(
14371            "selection_operation_identity_missing",
14372            member.base_sequence,
14373            &format!(
14374                "durable {} resource identity from scheduled/open history",
14375                member.kind
14376            ),
14377            "missing operation identity",
14378            "selection member history is missing its canonical durable identity",
14379        ));
14380    }
14381    if marker.operation_identity != expected_identity {
14382        return Err(invalid_recorded_history(
14383            "selection_operation_identity_mismatch",
14384            member.base_sequence,
14385            expected_identity,
14386            &marker.operation_identity,
14387            "selection winner identity does not match durable scheduled/open history",
14388        ));
14389    }
14390
14391    let failure_types = [
14392        "ActivityFailed",
14393        "ActivityCancelled",
14394        "ActivityTimedOut",
14395        "ChildRunFailed",
14396        "ChildRunCancelled",
14397        "ChildRunTerminated",
14398    ];
14399    let success_types = [
14400        "ActivityCompleted",
14401        "ChildRunCompleted",
14402        "TimerFired",
14403        "SignalApplied",
14404        "ConditionWaitSatisfied",
14405        "ConditionWaitTimedOut",
14406    ];
14407    let terminal_types: &[&str] = if marker.outcome == "failed" {
14408        &failure_types
14409    } else {
14410        &success_types
14411    };
14412    let mut candidates = Vec::new();
14413    let member_commands = (member.base_sequence
14414        ..member.base_sequence.saturating_add(member.size as u64))
14415        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
14416        .map(|command| (command.sequence(), command))
14417        .collect::<BTreeMap<_, _>>();
14418    let mut resolved_conditions = BTreeSet::new();
14419    for event in state.history_events.iter() {
14420        let Some(sequence) = durable_event_sequence(event) else {
14421            continue;
14422        };
14423        let Some(command) = member_commands.get(&sequence) else {
14424            continue;
14425        };
14426        if !terminal_types.contains(&event.event_type.as_str()) {
14427            continue;
14428        }
14429        if matches!(command, RecordedCommand::ConditionWait { .. }) {
14430            if !matches!(
14431                event.event_type.as_str(),
14432                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
14433            ) && !(event.event_type == "TimerFired"
14434                && event.payload.get("timer_kind").and_then(Value::as_str)
14435                    == Some("condition_timeout"))
14436            {
14437                continue;
14438            }
14439            if !resolved_conditions.insert(sequence) {
14440                continue;
14441            }
14442        }
14443        let event_id = event
14444            .raw
14445            .get("id")
14446            .or_else(|| event.raw.get("event_id"))
14447            .and_then(Value::as_str)
14448            .filter(|value| !value.is_empty())
14449            .ok_or_else(|| {
14450                invalid_recorded_history(
14451                    "selection_resolution_event_id_missing",
14452                    member.base_sequence,
14453                    "terminal selection history with a durable event id",
14454                    &event.payload.to_string(),
14455                    "selection terminal history cannot be bound to its winner marker",
14456                )
14457            })?;
14458        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
14459    }
14460    let resolution = if marker.outcome == "failed" {
14461        candidates.first()
14462    } else {
14463        candidates.last()
14464    };
14465    let Some((event_id, event_type, sequence)) = resolution else {
14466        return Err(invalid_recorded_history(
14467            "selection_resolution_event_missing",
14468            member.base_sequence,
14469            "terminal history for the selected member",
14470            &format!("{:?}", marker.member_key),
14471            "selection winner marker has no matching durable terminal event",
14472        ));
14473    };
14474    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
14475        return Err(invalid_recorded_history(
14476            "selection_resolution_event_mismatch",
14477            member.base_sequence,
14478            &format!("{event_type}:{event_id}"),
14479            &format!(
14480                "{}:{}",
14481                marker.resolution_event_type, marker.resolution_event_id
14482            ),
14483            "selection winner marker does not reference the event that made its member terminal",
14484        ));
14485    }
14486    Ok(*sequence)
14487}
14488
14489fn selection_member_recorded_command(
14490    state: &WorkflowState,
14491    authored_sequence: u64,
14492) -> Option<&RecordedCommand> {
14493    let original = state
14494        .recorded_commands
14495        .iter()
14496        .find(|command| command.sequence() == authored_sequence)?;
14497    let RecordedCommand::ConditionWait {
14498        occurrence_id,
14499        parallel_group_path: Some(_),
14500        ..
14501    } = original
14502    else {
14503        return Some(original);
14504    };
14505    // Decoding proves each physical reopen has the same authored identity and
14506    // group path after a satisfied predecessor. Only its latest wait can make
14507    // this logical member terminal.
14508    state
14509        .recorded_commands
14510        .iter()
14511        .filter(|command| {
14512            matches!(command, RecordedCommand::ConditionWait {
14513                occurrence_id: candidate, ..
14514            } if candidate == occurrence_id)
14515        })
14516        .max_by_key(|command| command.sequence())
14517}
14518
14519fn recorded_selection_member_outcome(
14520    state: &WorkflowState,
14521    handle: &DurableOperationHandle,
14522) -> Result<Option<ParallelResult>> {
14523    for event in state.history_events.iter() {
14524        let Some(sequence) = durable_event_sequence(event) else {
14525            continue;
14526        };
14527        if sequence < handle.base_sequence
14528            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
14529            || !matches!(
14530                event.event_type.as_str(),
14531                "ActivityFailed"
14532                    | "ActivityCancelled"
14533                    | "ActivityTimedOut"
14534                    | "ChildRunFailed"
14535                    | "ChildRunCancelled"
14536                    | "ChildRunTerminated"
14537            )
14538        {
14539            continue;
14540        }
14541        let Some(command) = state
14542            .recorded_commands
14543            .iter()
14544            .find(|command| command.sequence() == sequence)
14545        else {
14546            continue;
14547        };
14548        match command {
14549            RecordedCommand::Activity {
14550                outcome: Some(Err(failure)),
14551                ..
14552            } => return Err(Error::ActivityFailed(failure.clone())),
14553            RecordedCommand::ChildWorkflow {
14554                outcome: Some(Err(failure)),
14555                ..
14556            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
14557            _ => {}
14558        }
14559    }
14560
14561    let mut results = Vec::with_capacity(handle.size);
14562    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
14563        let Some(command) = selection_member_recorded_command(state, sequence) else {
14564            return Ok(None);
14565        };
14566        let result = match command {
14567            RecordedCommand::Activity { outcome, .. } => match outcome {
14568                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
14569                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
14570                None => return Ok(None),
14571            },
14572            RecordedCommand::Timer { fired, .. } => {
14573                if !fired {
14574                    return Ok(None);
14575                }
14576                ParallelAvroResult::Timer
14577            }
14578            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
14579                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
14580                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
14581                None => return Ok(None),
14582            },
14583            RecordedCommand::SignalWait { value, .. } => match value {
14584                Some(value) => ParallelAvroResult::Signal(value.clone()),
14585                None => return Ok(None),
14586            },
14587            RecordedCommand::ConditionWait { result, .. } => match result {
14588                Some(result) => ParallelAvroResult::Condition(*result),
14589                None => return Ok(None),
14590            },
14591            other => {
14592                return Err(command_mismatch(
14593                    other,
14594                    format!("selected {} member", handle.kind),
14595                ))
14596            }
14597        };
14598        results.push(result);
14599    }
14600    let mut results = results.into_iter();
14601    parallel_results_for_shape(&handle.shape, &mut results)
14602        .into_json_result()
14603        .map(Some)
14604}
14605
14606fn recorded_selection_member_is_terminal(
14607    state: &WorkflowState,
14608    handle: &DurableOperationHandle,
14609) -> bool {
14610    let mut completed = 0usize;
14611    let mut all_completed = true;
14612    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
14613        let Some(command) = selection_member_recorded_command(state, sequence) else {
14614            all_completed = false;
14615            continue;
14616        };
14617        let terminal = match command {
14618            RecordedCommand::Activity {
14619                outcome: Some(Err(_)),
14620                ..
14621            }
14622            | RecordedCommand::ChildWorkflow {
14623                outcome: Some(Err(_)),
14624                ..
14625            } => return true,
14626            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
14627            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
14628            RecordedCommand::Timer { fired, .. } => *fired,
14629            RecordedCommand::SignalWait { value, .. } => value.is_some(),
14630            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
14631            RecordedCommand::SearchAttributes { .. }
14632            | RecordedCommand::CancellationScope { .. }
14633            | RecordedCommand::SideEffect { .. }
14634            | RecordedCommand::VersionMarker { .. }
14635            | RecordedCommand::Memo { .. }
14636            | RecordedCommand::CancellationBoundary { .. }
14637            | RecordedCommand::CancellationGroup { .. } => false,
14638            RecordedCommand::ServiceOperation { .. } => false,
14639        };
14640        if !terminal {
14641            all_completed = false;
14642            continue;
14643        }
14644        completed += 1;
14645    }
14646    all_completed && completed == handle.size
14647}
14648
14649fn selection_cancellation_for_handle(
14650    state: &WorkflowState,
14651    handle: &DurableOperationHandle,
14652) -> Result<bool> {
14653    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
14654        recorded.selection_group_id == handle.selection_group_id
14655            && recorded.member_base_sequence == handle.base_sequence
14656    }) else {
14657        return Ok(false);
14658    };
14659    validate_selection_cancellation_marker(marker, handle)?;
14660    Ok(true)
14661}
14662
14663fn validate_selection_cancellations_for_handles(
14664    state: &WorkflowState,
14665    handles: &[DurableOperationHandle],
14666) -> Result<()> {
14667    let Some(group_id) = handles
14668        .first()
14669        .map(|handle| handle.selection_group_id.as_str())
14670    else {
14671        return Ok(());
14672    };
14673    for marker in state
14674        .cancelled_selection_members
14675        .iter()
14676        .filter(|marker| marker.selection_group_id == group_id)
14677    {
14678        let Some(handle) = handles
14679            .iter()
14680            .find(|handle| handle.base_sequence == marker.member_base_sequence)
14681        else {
14682            return Err(invalid_recorded_history(
14683                "selection_cancellation_member_mismatch",
14684                marker.member_base_sequence,
14685                "SelectionOperationCancelled matching an authored selection handle",
14686                &format!("{marker:?}"),
14687                "selection cancellation member base does not name an authored member",
14688            ));
14689        };
14690        validate_selection_cancellation_marker(marker, handle)?;
14691    }
14692    Ok(())
14693}
14694
14695fn validate_selection_cancellation_marker(
14696    marker: &SelectionCancellation,
14697    handle: &DurableOperationHandle,
14698) -> Result<()> {
14699    if marker.selection_group_id != handle.selection_group_id
14700        || marker.member_key != handle.key
14701        || marker.member_index != handle.index
14702        || marker.member_base_sequence != handle.base_sequence
14703        || marker.member_size != handle.size
14704        || marker.operation_kind != handle.kind
14705        || marker.operation_identity != handle.identity
14706    {
14707        return Err(invalid_recorded_history(
14708            "selection_cancellation_member_mismatch",
14709            handle.base_sequence,
14710            "SelectionOperationCancelled matching the authored selection handle",
14711            &format!("{marker:?}"),
14712            "selection cancellation history targets different authored member metadata",
14713        ));
14714    }
14715    Ok(())
14716}
14717
14718/// Future returned by [`DurableOperationHandle::await_result`].
14719pub struct DurableOperationAwaitCall {
14720    handle: DurableOperationHandle,
14721}
14722
14723impl Future for DurableOperationAwaitCall {
14724    type Output = Result<ParallelResult>;
14725
14726    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14727        let mut state = match self.handle.ctx.state.lock() {
14728            Ok(state) => state,
14729            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14730        };
14731        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
14732            return Poll::Ready(Err(error));
14733        }
14734        match state.prepare_selection_handle_cancellation(&self.handle) {
14735            Ok(true) => return Poll::Pending,
14736            Ok(false) => {}
14737            Err(error) => return Poll::Ready(Err(error)),
14738        }
14739        match selection_cancellation_for_handle(&state, &self.handle) {
14740            Err(error) => return Poll::Ready(Err(error)),
14741            Ok(false) => {}
14742            Ok(true) => {
14743                state.advance_cancellation_receipt(
14744                    &self.handle.selection_group_id,
14745                    self.handle.base_sequence,
14746                );
14747                return Poll::Ready(Err(Error::DurableOperationCancelled(
14748                    DurableOperationCancelled {
14749                        selection_group_id: self.handle.selection_group_id.clone(),
14750                        member_key: self.handle.key.clone(),
14751                        member_index: self.handle.index,
14752                        operation_kind: self.handle.kind.clone(),
14753                        operation_identity: self.handle.identity.clone(),
14754                    },
14755                )));
14756            }
14757        }
14758        match recorded_selection_member_outcome(&state, &self.handle) {
14759            Ok(Some(result)) => {
14760                state.advance_cancellation_handle(&self.handle, false);
14761                Poll::Ready(Ok(result))
14762            }
14763            Ok(None) => Poll::Pending,
14764            Err(error) => {
14765                if !workflow_task_integrity_error(&error) {
14766                    state.advance_cancellation_handle(&self.handle, true);
14767                }
14768                Poll::Ready(Err(error))
14769            }
14770        }
14771    }
14772}
14773
14774fn validate_selection_delivery_handle(
14775    state: &WorkflowState,
14776    handle: &DurableOperationHandle,
14777) -> Result<()> {
14778    let path = state
14779        .recorded_commands
14780        .iter()
14781        .find(|command| command.sequence() == handle.base_sequence)
14782        .and_then(|command| match command {
14783            RecordedCommand::Activity {
14784                parallel_group_path,
14785                ..
14786            }
14787            | RecordedCommand::ChildWorkflow {
14788                parallel_group_path,
14789                ..
14790            }
14791            | RecordedCommand::Timer {
14792                parallel_group_path,
14793                ..
14794            }
14795            | RecordedCommand::SignalWait {
14796                parallel_group_path,
14797                ..
14798            }
14799            | RecordedCommand::ConditionWait {
14800                parallel_group_path,
14801                ..
14802            } => parallel_group_path.as_ref(),
14803            _ => None,
14804        })
14805        .and_then(|path| path.first());
14806    let matches = path.is_some_and(|entry| {
14807        entry.parallel_group_mode.as_deref() == Some("select")
14808            && entry.parallel_group_id == handle.selection_group_id
14809            && entry.selection_member_key.as_ref() == Some(&handle.key)
14810            && entry.selection_member_index == Some(handle.index)
14811            && entry.selection_member_base_sequence == Some(handle.base_sequence)
14812            && entry.selection_member_size == Some(handle.size)
14813            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
14814    });
14815    if !matches
14816        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
14817            != handle.identity
14818    {
14819        return Err(invalid_recorded_history(
14820            "cooperative_cancellation_call_mismatch",
14821            handle.base_sequence,
14822            "selection handle matching its authored durable identity",
14823            &format!("{handle:?}"),
14824            "selection handle identity or member metadata changed before cancellation replay",
14825        ));
14826    }
14827    Ok(())
14828}
14829
14830/// Future returned by [`DurableOperationHandle::cancel`].
14831pub struct CancelDurableOperationCall {
14832    handle: DurableOperationHandle,
14833    emitted: bool,
14834}
14835
14836impl Future for CancelDurableOperationCall {
14837    type Output = Result<()>;
14838
14839    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14840        let ctx = self.handle.ctx.clone();
14841        let mut state = match ctx.state.lock() {
14842            Ok(state) => state,
14843            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14844        };
14845        match selection_cancellation_for_handle(&state, &self.handle) {
14846            Err(error) => return Poll::Ready(Err(error)),
14847            Ok(true) => {
14848                state.advance_cancellation_receipt(
14849                    &self.handle.selection_group_id,
14850                    self.handle.base_sequence,
14851                );
14852                return Poll::Ready(Ok(()));
14853            }
14854            Ok(false) => {}
14855        }
14856        if recorded_selection_member_is_terminal(&state, &self.handle) {
14857            return Poll::Ready(Ok(()));
14858        }
14859        if !self.emitted {
14860            state.commands.push(json!({
14861                "type": "cancel_selection_operation",
14862                "selection_group_id": self.handle.selection_group_id,
14863                "member_key": self.handle.key,
14864                "member_index": self.handle.index,
14865                "member_base_sequence": self.handle.base_sequence,
14866                "member_size": self.handle.size,
14867                "operation_kind": self.handle.kind,
14868                "operation_identity": self.handle.identity,
14869            }));
14870            self.emitted = true;
14871        }
14872        // Unit completes the request, not the member's outcome. Following
14873        // workflow commands commit atomically with this cancellation request.
14874        // Waiting here would need another workflow task that cancellation
14875        // alone does not create. await_result still requires recorded history.
14876        Poll::Ready(Ok(()))
14877    }
14878}
14879
14880trait PollNestedResultExt<T> {
14881    fn flatten_result(self) -> Poll<Result<T>>;
14882}
14883
14884impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
14885    fn flatten_result(self) -> Poll<Result<T>> {
14886        match self {
14887            Poll::Ready(Ok(result)) => Poll::Ready(result),
14888            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
14889            Poll::Pending => Poll::Pending,
14890        }
14891    }
14892}
14893
14894struct SagaCompensation {
14895    activity_type: String,
14896    options: ActivityOptions,
14897    arguments: AvroValue,
14898    registration_order: usize,
14899}
14900
14901/// Workflow-local deterministic saga compensation helper.
14902///
14903/// Register each compensation only after its forward step succeeds. Passing
14904/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
14905/// reverse registration order after any failure, including cooperative
14906/// cancellation. Each compensation is an ordinary durable activity, so replay,
14907/// duplicate delivery, and worker restart use existing history semantics.
14908pub struct Saga {
14909    ctx: WorkflowContext,
14910    compensations: Vec<SagaCompensation>,
14911}
14912
14913impl Saga {
14914    fn new(ctx: WorkflowContext) -> Self {
14915        Self {
14916            ctx,
14917            compensations: Vec::new(),
14918        }
14919    }
14920
14921    pub fn add_compensation<T: Serialize>(
14922        &mut self,
14923        activity_type: impl Into<String>,
14924        args: T,
14925    ) -> Result<&mut Self> {
14926        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
14927    }
14928
14929    pub fn add_compensation_with_options<T: Serialize>(
14930        &mut self,
14931        activity_type: impl Into<String>,
14932        options: ActivityOptions,
14933        args: T,
14934    ) -> Result<&mut Self> {
14935        let activity_type = activity_type.into();
14936        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
14937            return Err(Error::Codec(
14938                "saga compensation activity type must be non-empty without surrounding whitespace"
14939                    .to_string(),
14940            ));
14941        }
14942        options.validate().map_err(Error::InvalidActivityOptions)?;
14943        let arguments = AvroValue::from_serialize(&args)?;
14944        let registration_order = self.compensations.len() + 1;
14945        self.compensations.push(SagaCompensation {
14946            activity_type,
14947            options,
14948            arguments,
14949            registration_order,
14950        });
14951        Ok(self)
14952    }
14953
14954    /// Compensate `initiating_failure` and return the failure that must remain.
14955    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
14956        let _shield = match self.ctx.cancellation_shield() {
14957            Ok(shield) => shield,
14958            Err(error) => return error,
14959        };
14960        while let Some(compensation) = self.compensations.pop() {
14961            if let Err(compensation_failure) = self
14962                .ctx
14963                .activity_with_options(
14964                    compensation.activity_type.clone(),
14965                    compensation.options,
14966                    compensation.arguments,
14967                )
14968                .await
14969            {
14970                if workflow_task_integrity_error(&compensation_failure) {
14971                    return compensation_failure;
14972                }
14973                return Error::SagaCompensationFailed(SagaCompensationFailure {
14974                    initiating_failure: Box::new(initiating_failure),
14975                    compensation_failure: Box::new(compensation_failure),
14976                    compensation_activity_type: compensation.activity_type,
14977                    compensation_registration_order: compensation.registration_order,
14978                });
14979            }
14980        }
14981        initiating_failure
14982    }
14983
14984    /// Return a successful forward value or compensate and preserve its failure.
14985    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
14986        match outcome {
14987            Ok(value) => Ok(value),
14988            Err(error) => Err(self.compensate(error).await),
14989        }
14990    }
14991}
14992
14993pub struct ActivityCall {
14994    ctx: WorkflowContext,
14995    activity_type: String,
14996    options: ActivityOptions,
14997    worker_session: Option<WorkerSessionOptions>,
14998    args: Option<Result<AvroValue>>,
14999    scheduled: bool,
15000    local: bool,
15001    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
15002    parallel_group_path: Vec<ParallelGroupMetadata>,
15003}
15004
15005impl ActivityCall {
15006    fn poll_avro_value(
15007        mut self: Pin<&mut Self>,
15008        _cx: &mut TaskContext<'_>,
15009    ) -> Poll<Result<AvroValue>> {
15010        let ctx = self.ctx.clone();
15011        let mut state = match ctx.state.lock() {
15012            Ok(state) => state,
15013            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15014        };
15015
15016        if let Some(result) = &self.local_result {
15017            return match result.lock() {
15018                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
15019                    Poll::Ready(result.map_err(Error::ActivityFailed))
15020                }),
15021                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15022            };
15023        }
15024        if self.scheduled {
15025            return Poll::Pending;
15026        }
15027
15028        let options = match self.options.validate() {
15029            Ok(options) => options,
15030            Err(error) => {
15031                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
15032            }
15033        };
15034        if self.local {
15035            if self.worker_session.is_some() {
15036                return Poll::Ready(Err(Error::WorkerLoop(
15037                    "local activities cannot use worker-session routing".into(),
15038                )));
15039            }
15040            if let Err(error) = local_activity::validate(&options) {
15041                return Poll::Ready(Err(error));
15042            }
15043        }
15044        let session = match self
15045            .worker_session
15046            .as_ref()
15047            .map(WorkerSessionOptions::to_wire)
15048            .transpose()
15049        {
15050            Ok(value) => value,
15051            Err(error) => return Poll::Ready(Err(error)),
15052        };
15053        let session_queue = session
15054            .as_ref()
15055            .and_then(|session| session["queue"].as_str());
15056        let task_queue = options
15057            .task_queue
15058            .clone()
15059            .or_else(|| session_queue.map(str::to_owned))
15060            .unwrap_or_else(|| state.task_queue.clone());
15061        if session_queue.is_some_and(|queue| queue != task_queue) {
15062            return Poll::Ready(Err(Error::WorkerLoop(
15063                "worker-session queue must match the activity task queue".into(),
15064            )));
15065        }
15066        let current_recorded_options = RecordedActivityOptions {
15067            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
15068            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
15069            retry_policy: current_activity_retry_snapshot(&options),
15070            worker_session: session,
15071        };
15072
15073        let cursor = state.command_cursor;
15074        let call_kind = if self.local {
15075            CancellationCallKind::LocalActivity
15076        } else {
15077            CancellationCallKind::Activity
15078        };
15079        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15080            return Poll::Ready(Err(error));
15081        }
15082        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
15083            Ok(recorded) => recorded,
15084            Err(error) => return Poll::Ready(Err(error)),
15085        };
15086        if let Some(recorded) = recorded {
15087            let sequence = recorded.sequence();
15088            match recorded {
15089                RecordedCommand::Activity {
15090                    activity_type,
15091                    cancellation_policy,
15092                    options: recorded_options,
15093                    outcome,
15094                    parallel_group_path,
15095                    ..
15096                } => {
15097                    let current_policy = options
15098                        .cancellation_policy
15099                        .unwrap_or(CancellationPolicy::TryCancel)
15100                        .as_str();
15101                    if cancellation_policy != current_policy {
15102                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15103                            ReplayFailure::new(
15104                                "activity_cancellation_policy_changed",
15105                                Some(sequence),
15106                                Some(cancellation_policy),
15107                                Some(current_policy.to_string()),
15108                                "Activity cancellation policy changed during replay",
15109                            ),
15110                        )));
15111                    }
15112                    if let Err(error) = ensure_parallel_path_matches(
15113                        sequence,
15114                        parallel_group_path.as_deref(),
15115                        &self.parallel_group_path,
15116                    ) {
15117                        return Poll::Ready(Err(error));
15118                    }
15119                    if let Some(recorded_type) = activity_type {
15120                        if recorded_type != self.activity_type {
15121                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15122                                ReplayFailure::new(
15123                                    "recorded_command_detail_mismatch",
15124                                    Some(sequence),
15125                                    Some(format!("activity:{recorded_type}")),
15126                                    Some(format!("activity:{}", self.activity_type)),
15127                                    "recorded activity type differs from the current workflow command",
15128                                ),
15129                            )));
15130                        }
15131                    }
15132                    if let Some(recorded_options) = recorded_options {
15133                        if recorded_options.worker_session
15134                            != current_recorded_options.worker_session
15135                        {
15136                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15137                                "activity_worker_session_mismatch", Some(sequence),
15138                                Some(activity_options_description(&recorded_options)),
15139                                Some(activity_options_description(&current_recorded_options)),
15140                                "recorded worker-session routing differs from the current activity",
15141                            ))));
15142                        }
15143                        if !recorded_options
15144                            .task_queue
15145                            .matches_current(&current_recorded_options.task_queue)
15146                        {
15147                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15148                                ReplayFailure::new(
15149                                    "activity_task_queue_mismatch",
15150                                    Some(sequence),
15151                                    Some(activity_options_description(&recorded_options)),
15152                                    Some(activity_options_description(&current_recorded_options)),
15153                                    "recorded activity task queue differs from the current workflow command",
15154                                ),
15155                            )));
15156                        }
15157                        if (self.local
15158                            && matches!(
15159                                recorded_options.execution_mode,
15160                                RecordedSnapshotValue::Unknown
15161                            ))
15162                            || !recorded_options
15163                                .execution_mode
15164                                .matches_current(&current_recorded_options.execution_mode)
15165                        {
15166                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15167                                ReplayFailure::new(
15168                                    "activity_execution_mode_mismatch",
15169                                    Some(sequence),
15170                                    Some(activity_options_description(&recorded_options)),
15171                                    Some(activity_options_description(&current_recorded_options)),
15172                                    "recorded activity execution mode differs from the current workflow command",
15173                                ),
15174                            )));
15175                        }
15176                        if !recorded_options
15177                            .retry_policy
15178                            .matches_current(&current_recorded_options.retry_policy)
15179                        {
15180                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15181                                ReplayFailure::new(
15182                                    "activity_retry_policy_mismatch",
15183                                    Some(sequence),
15184                                    Some(activity_options_description(&recorded_options)),
15185                                    Some(activity_options_description(&current_recorded_options)),
15186                                    "recorded activity retry policy differs from the current workflow command",
15187                                ),
15188                            )));
15189                        }
15190                    }
15191                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
15192                        return Poll::Ready(Err(error));
15193                    }
15194                    match state.prepare_scalar_cancellation(
15195                        cursor,
15196                        call_kind,
15197                        &self.parallel_group_path,
15198                    ) {
15199                        Ok(true) => {
15200                            self.scheduled = true;
15201                            return Poll::Pending;
15202                        }
15203                        Ok(false) => {}
15204                        Err(error) => return Poll::Ready(Err(error)),
15205                    }
15206                    state.command_cursor += 1;
15207                    if let Some(outcome) = outcome {
15208                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15209                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
15210                    }
15211                    state.matched_recorded_pending = true;
15212                    self.scheduled = true;
15213                    return Poll::Pending;
15214                }
15215                other => {
15216                    return Poll::Ready(Err(command_mismatch(
15217                        &other,
15218                        format!("activity:{}", self.activity_type),
15219                    )));
15220                }
15221            }
15222        }
15223
15224        if !self.scheduled {
15225            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15226                Ok(args) => args,
15227                Err(error) => return Poll::Ready(Err(error)),
15228            };
15229            let arguments = normalize_avro_arguments(args);
15230            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
15231                Ok(envelope) => envelope,
15232                Err(error) => return Poll::Ready(Err(error)),
15233            };
15234
15235            let mut command = serde_json::Map::from_iter([
15236                (
15237                    "type".to_string(),
15238                    json!(if self.local {
15239                        "record_local_activity"
15240                    } else {
15241                        "schedule_activity"
15242                    }),
15243                ),
15244                (
15245                    "activity_type".to_string(),
15246                    json!(self.activity_type.clone()),
15247                ),
15248                ("queue".to_string(), json!(task_queue)),
15249                ("arguments".to_string(), envelope),
15250            ]);
15251            for (field, value) in [
15252                ("start_to_close_timeout", options.start_to_close_timeout),
15253                (
15254                    "schedule_to_start_timeout",
15255                    options.schedule_to_start_timeout,
15256                ),
15257                (
15258                    "schedule_to_close_timeout",
15259                    options.schedule_to_close_timeout,
15260                ),
15261                ("heartbeat_timeout", options.heartbeat_timeout),
15262            ] {
15263                if let Some(value) = value {
15264                    command.insert(field.to_string(), json!(value));
15265                }
15266            }
15267            if let Some(retry_policy) = &options.retry_policy {
15268                command.insert("retry_policy".to_string(), retry_policy.clone());
15269            }
15270            if let Some(policy) = options.cancellation_policy {
15271                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
15272            }
15273            if let Some(session) = current_recorded_options.worker_session {
15274                command.insert("worker_session".into(), session);
15275            }
15276            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15277            ctx.apply_scope_membership(&mut command);
15278            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
15279                Ok(true) => {
15280                    self.scheduled = true;
15281                    return Poll::Pending;
15282                }
15283                Ok(false) => {}
15284                Err(error) => return Poll::Ready(Err(error)),
15285            }
15286            if self.local {
15287                command.remove("queue");
15288                command.insert("execution_mode".into(), json!("local"));
15289                let result = Arc::new(Mutex::new(None));
15290                let command_index = state.commands.len();
15291                state.local_activity_requests.push(local_activity::Request {
15292                    command_index,
15293                    options,
15294                    arguments,
15295                    result: result.clone(),
15296                });
15297                self.local_result = Some(result);
15298            }
15299            state.commands.push(Value::Object(command));
15300            self.scheduled = true;
15301        }
15302
15303        Poll::Pending
15304    }
15305}
15306
15307impl Future for ActivityCall {
15308    type Output = Result<Value>;
15309
15310    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15311        match self.poll_avro_value(cx) {
15312            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
15313            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15314            Poll::Pending => Poll::Pending,
15315        }
15316    }
15317}
15318
15319/// Future returned by [`WorkflowContext::sleep`].
15320pub struct TimerCall {
15321    ctx: WorkflowContext,
15322    delay_seconds: Option<u64>,
15323    scheduled: bool,
15324    matched_pending: bool,
15325    parallel_group_path: Vec<ParallelGroupMetadata>,
15326}
15327
15328impl Future for TimerCall {
15329    type Output = Result<()>;
15330
15331    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15332        if self.matched_pending {
15333            return Poll::Pending;
15334        }
15335
15336        let ctx = self.ctx.clone();
15337        let Some(requested_delay) = self.delay_seconds else {
15338            return Poll::Ready(Err(Error::TimerDurationOverflow));
15339        };
15340        let mut state = match ctx.state.lock() {
15341            Ok(state) => state,
15342            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15343        };
15344
15345        let cursor = state.command_cursor;
15346        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15347            return Poll::Ready(Err(error));
15348        }
15349        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
15350        {
15351            Ok(recorded) => recorded,
15352            Err(error) => return Poll::Ready(Err(error)),
15353        };
15354        if let Some(recorded) = recorded {
15355            match recorded {
15356                RecordedCommand::Timer {
15357                    sequence,
15358                    delay_seconds,
15359                    fired,
15360                    parallel_group_path,
15361                    ..
15362                } => {
15363                    if let Err(error) =
15364                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
15365                    {
15366                        return Poll::Ready(Err(error));
15367                    }
15368                    if let Err(error) = ensure_parallel_path_matches(
15369                        sequence,
15370                        parallel_group_path.as_deref(),
15371                        &self.parallel_group_path,
15372                    ) {
15373                        return Poll::Ready(Err(error));
15374                    }
15375                    if delay_seconds != requested_delay {
15376                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15377                            ReplayFailure::new(
15378                                "timer_delay_mismatch",
15379                                Some(sequence),
15380                                Some(format!("timer:{delay_seconds}s")),
15381                                Some(format!("timer:{requested_delay}s")),
15382                                "recorded timer delay differs from the current workflow command",
15383                            ),
15384                        )));
15385                    }
15386                    if let Err(error) =
15387                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
15388                    {
15389                        return Poll::Ready(Err(error));
15390                    }
15391                    match state.prepare_scalar_cancellation(
15392                        cursor,
15393                        CancellationCallKind::Timer,
15394                        &self.parallel_group_path,
15395                    ) {
15396                        Ok(true) => {
15397                            self.scheduled = true;
15398                            self.matched_pending = true;
15399                            return Poll::Pending;
15400                        }
15401                        Ok(false) => {}
15402                        Err(error) => return Poll::Ready(Err(error)),
15403                    }
15404                    state.command_cursor += 1;
15405                    if fired {
15406                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15407                        return Poll::Ready(Ok(()));
15408                    }
15409                    state.matched_recorded_pending = true;
15410                    self.scheduled = true;
15411                    self.matched_pending = true;
15412                    return Poll::Pending;
15413                }
15414                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
15415            }
15416        }
15417
15418        if !self.scheduled {
15419            let mut command = serde_json::Map::from_iter([
15420                ("type".to_string(), json!("start_timer")),
15421                ("delay_seconds".to_string(), json!(requested_delay)),
15422            ]);
15423            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
15424                Ok(Some(proof)) => {
15425                    command.insert("cancellation_cleanup".into(), proof);
15426                }
15427                Ok(None) => {}
15428                Err(error) => return Poll::Ready(Err(error)),
15429            }
15430            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15431            ctx.apply_scope_membership(&mut command);
15432            match state.prepare_scalar_cancellation(
15433                cursor,
15434                CancellationCallKind::Timer,
15435                &self.parallel_group_path,
15436            ) {
15437                Ok(true) => {
15438                    self.scheduled = true;
15439                    self.matched_pending = true;
15440                    return Poll::Pending;
15441                }
15442                Ok(false) => {}
15443                Err(error) => return Poll::Ready(Err(error)),
15444            }
15445            state.commands.push(Value::Object(command));
15446            self.scheduled = true;
15447        }
15448
15449        Poll::Pending
15450    }
15451}
15452
15453/// Future returned by [`WorkflowContext::wait_condition`].
15454pub struct ConditionWaitCall {
15455    ctx: WorkflowContext,
15456    options: ConditionWaitOptions,
15457    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
15458    occurrence_id: Option<String>,
15459    opened_wait: bool,
15460    parallel_group_path: Vec<ParallelGroupMetadata>,
15461}
15462
15463impl Future for ConditionWaitCall {
15464    type Output = Result<ConditionWaitResult>;
15465
15466    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15467        if self.opened_wait {
15468            return Poll::Pending;
15469        }
15470
15471        let options = match self.options.validate() {
15472            Ok(options) => options,
15473            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
15474        };
15475        let ctx = self.ctx.clone();
15476        let occurrence_id = match self.occurrence_id.as_ref() {
15477            Some(occurrence_id) => occurrence_id.clone(),
15478            None => {
15479                let mut state = match ctx.state.lock() {
15480                    Ok(state) => state,
15481                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15482                };
15483                let ordinal = state.condition_wait_occurrence_counter;
15484                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
15485                    Some(next) => next,
15486                    None => {
15487                        return Poll::Ready(Err(Error::WorkerLoop(
15488                            "condition wait occurrence counter overflowed".to_string(),
15489                        )))
15490                    }
15491                };
15492                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
15493                drop(state);
15494                self.occurrence_id = Some(occurrence_id.clone());
15495                occurrence_id
15496            }
15497        };
15498
15499        let recorded_result = {
15500            let mut state = match ctx.state.lock() {
15501                Ok(state) => state,
15502                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15503            };
15504            let initial_cursor = state.command_cursor;
15505            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
15506                return Poll::Ready(Err(error));
15507            }
15508            let recorded = match state
15509                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
15510            {
15511                Ok(recorded) => recorded,
15512                Err(error) => return Poll::Ready(Err(error)),
15513            };
15514            let Some(recorded) = recorded else {
15515                drop(state);
15516                return self.poll_new_condition(options);
15517            };
15518            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
15519                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
15520            }
15521
15522            let mut cursor = state.command_cursor;
15523            let mut result = None;
15524            let mut pending_delivery = false;
15525            loop {
15526                if cursor > initial_cursor
15527                    && matches!(
15528                        state.recorded_commands.get(cursor),
15529                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
15530                    )
15531                {
15532                    break;
15533                }
15534                let recorded = match state
15535                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
15536                {
15537                    Ok(recorded) => recorded,
15538                    Err(error) => return Poll::Ready(Err(error)),
15539                };
15540                let Some(RecordedCommand::ConditionWait {
15541                    sequence,
15542                    occurrence_id: ref recorded_occurrence_id,
15543                    ref condition_key,
15544                    ref predicate_identity,
15545                    timeout_seconds,
15546                    result: recorded_result,
15547                    ref parallel_group_path,
15548                    ..
15549                }) = recorded
15550                else {
15551                    break;
15552                };
15553
15554                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
15555                    break;
15556                }
15557                if let Err(error) = ensure_parallel_path_matches(
15558                    sequence,
15559                    parallel_group_path.as_deref(),
15560                    &self.parallel_group_path,
15561                ) {
15562                    return Poll::Ready(Err(error));
15563                }
15564                if let Err(error) = validate_recorded_condition_wait(
15565                    sequence,
15566                    recorded_occurrence_id,
15567                    condition_key.as_deref(),
15568                    predicate_identity,
15569                    timeout_seconds,
15570                    &occurrence_id,
15571                    &options,
15572                ) {
15573                    return Poll::Ready(Err(error));
15574                }
15575                if result == Some(ConditionWaitResult::TimedOut) {
15576                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15577                        "condition_wait_reopened_after_timeout",
15578                        Some(sequence),
15579                        Some("timed-out condition is terminal".to_string()),
15580                        Some("another physical wait-open".to_string()),
15581                        "condition history reopened one logical wait after its durable timeout",
15582                    ))));
15583                }
15584                if let Err(error) =
15585                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
15586                {
15587                    return Poll::Ready(Err(error));
15588                }
15589                match state.prepare_scalar_cancellation(
15590                    cursor,
15591                    CancellationCallKind::Condition,
15592                    &self.parallel_group_path,
15593                ) {
15594                    Ok(pending) => pending_delivery |= pending,
15595                    Err(error) => return Poll::Ready(Err(error)),
15596                }
15597                result = recorded_result;
15598                if result.is_some() {
15599                    state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15600                }
15601                cursor += 1;
15602            }
15603            state.command_cursor = cursor;
15604            if pending_delivery {
15605                self.opened_wait = true;
15606                return Poll::Pending;
15607            }
15608            result
15609        };
15610
15611        if let Some(result) = recorded_result {
15612            return Poll::Ready(Ok(result));
15613        }
15614
15615        self.poll_open_condition(options, true)
15616    }
15617}
15618
15619impl ConditionWaitCall {
15620    fn poll_new_condition(
15621        self: Pin<&mut Self>,
15622        options: ValidatedConditionWaitOptions,
15623    ) -> Poll<Result<ConditionWaitResult>> {
15624        self.poll_open_condition(options, false)
15625    }
15626
15627    fn poll_open_condition(
15628        mut self: Pin<&mut Self>,
15629        options: ValidatedConditionWaitOptions,
15630        recorded_wait: bool,
15631    ) -> Poll<Result<ConditionWaitResult>> {
15632        {
15633            let ctx = self.ctx.clone();
15634            let mut state = match ctx.state.lock() {
15635                Ok(state) => state,
15636                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15637            };
15638            let cursor = state.command_cursor;
15639            match state.prepare_scalar_cancellation(
15640                cursor,
15641                CancellationCallKind::Condition,
15642                &self.parallel_group_path,
15643            ) {
15644                Ok(true) => {
15645                    self.opened_wait = true;
15646                    return Poll::Pending;
15647                }
15648                Ok(false) => {}
15649                Err(error) => return Poll::Ready(Err(error)),
15650            }
15651        }
15652        let selection_member = self
15653            .parallel_group_path
15654            .first()
15655            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
15656        match (self.predicate)() {
15657            Ok(true) if !selection_member || recorded_wait => {
15658                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
15659            }
15660            Ok(_) => {}
15661            Err(error) => return Poll::Ready(Err(error)),
15662        }
15663        if options.timeout_seconds == Some(0) && !selection_member {
15664            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
15665        }
15666
15667        let ctx = self.ctx.clone();
15668        let mut state = match ctx.state.lock() {
15669            Ok(state) => state,
15670            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15671        };
15672        let mut command = serde_json::Map::from_iter([
15673            ("type".to_string(), json!("open_condition_wait")),
15674            (
15675                "condition_wait_occurrence_id".to_string(),
15676                json!(self.occurrence_id.as_deref().unwrap_or_default()),
15677            ),
15678            ("condition_key".to_string(), json!(options.condition_key)),
15679            (
15680                "condition_definition_fingerprint".to_string(),
15681                json!(options.predicate_identity),
15682            ),
15683        ]);
15684        if let Some(timeout_seconds) = options.timeout_seconds {
15685            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
15686        }
15687        apply_parallel_group_path(&mut command, &self.parallel_group_path);
15688        ctx.apply_scope_membership(&mut command);
15689        state.commands.push(Value::Object(command));
15690        drop(state);
15691        self.opened_wait = true;
15692        Poll::Pending
15693    }
15694}
15695
15696fn validate_recorded_condition_wait(
15697    sequence: u64,
15698    recorded_occurrence_id: &str,
15699    recorded_key: Option<&str>,
15700    recorded_predicate_identity: &str,
15701    recorded_timeout_seconds: Option<u64>,
15702    current_occurrence_id: &str,
15703    current: &ValidatedConditionWaitOptions,
15704) -> Result<()> {
15705    if recorded_occurrence_id != current_occurrence_id {
15706        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15707            "condition_wait_occurrence_mismatch",
15708            Some(sequence),
15709            Some(recorded_occurrence_id.to_string()),
15710            Some(current_occurrence_id.to_string()),
15711            "recorded condition occurrence differs from the current authored wait position",
15712        )));
15713    }
15714    if recorded_key != Some(current.condition_key.as_str()) {
15715        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15716            "condition_wait_key_mismatch",
15717            Some(sequence),
15718            recorded_key.map(str::to_string),
15719            Some(current.condition_key.clone()),
15720            "recorded condition identity differs from the current workflow wait",
15721        )));
15722    }
15723    if recorded_predicate_identity != current.predicate_identity {
15724        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15725            "condition_wait_predicate_mismatch",
15726            Some(sequence),
15727            Some(recorded_predicate_identity.to_string()),
15728            Some(current.predicate_identity.clone()),
15729            "recorded condition predicate behavior differs from current workflow code",
15730        )));
15731    }
15732    if recorded_timeout_seconds != current.timeout_seconds {
15733        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
15734            "condition_wait_timeout_mismatch",
15735            Some(sequence),
15736            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
15737            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
15738            "recorded condition timeout differs from the current workflow wait",
15739        )));
15740    }
15741    Ok(())
15742}
15743
15744/// Future returned by [`WorkflowContext::start_child_workflow`].
15745pub struct ChildWorkflowCall {
15746    ctx: WorkflowContext,
15747    workflow_type: String,
15748    options: ChildWorkflowOptions,
15749    args: Option<Result<AvroValue>>,
15750    scheduled: bool,
15751    matched_pending: bool,
15752    parallel_group_path: Vec<ParallelGroupMetadata>,
15753}
15754
15755impl ChildWorkflowCall {
15756    fn poll_avro_value(
15757        mut self: Pin<&mut Self>,
15758        _cx: &mut TaskContext<'_>,
15759    ) -> Poll<Result<ChildWorkflowAvroResult>> {
15760        if self.matched_pending {
15761            return Poll::Pending;
15762        }
15763
15764        let ctx = self.ctx.clone();
15765        let mut state = match ctx.state.lock() {
15766            Ok(state) => state,
15767            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15768        };
15769
15770        let cursor = state.command_cursor;
15771        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15772            return Poll::Ready(Err(error));
15773        }
15774        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
15775        {
15776            Ok(recorded) => recorded,
15777            Err(error) => return Poll::Ready(Err(error)),
15778        };
15779        if let Some(recorded) = recorded {
15780            let sequence = recorded.sequence();
15781            match recorded {
15782                RecordedCommand::ChildWorkflow {
15783                    workflow_type,
15784                    policies,
15785                    outcome,
15786                    parallel_group_path,
15787                    ..
15788                } => {
15789                    if let Err(error) = ensure_parallel_path_matches(
15790                        sequence,
15791                        parallel_group_path.as_deref(),
15792                        &self.parallel_group_path,
15793                    ) {
15794                        return Poll::Ready(Err(error));
15795                    }
15796                    if let Some(recorded_type) = workflow_type {
15797                        if recorded_type != self.workflow_type {
15798                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15799                                ReplayFailure::new(
15800                                    "recorded_command_detail_mismatch",
15801                                    Some(sequence),
15802                                    Some(format!("child workflow:{recorded_type}")),
15803                                    Some(format!("child workflow:{}", self.workflow_type)),
15804                                    "recorded child workflow type differs from the current workflow command",
15805                                ),
15806                            )));
15807                        }
15808                    }
15809                    if let Err(error) =
15810                        ensure_child_policies_match(sequence, &policies, &self.options)
15811                    {
15812                        return Poll::Ready(Err(error));
15813                    }
15814                    if let Err(error) =
15815                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
15816                    {
15817                        return Poll::Ready(Err(error));
15818                    }
15819                    match state.prepare_scalar_cancellation(
15820                        cursor,
15821                        CancellationCallKind::Child,
15822                        &self.parallel_group_path,
15823                    ) {
15824                        Ok(true) => {
15825                            self.scheduled = true;
15826                            self.matched_pending = true;
15827                            return Poll::Pending;
15828                        }
15829                        Ok(false) => {}
15830                        Err(error) => return Poll::Ready(Err(error)),
15831                    }
15832                    state.command_cursor += 1;
15833                    if let Some(outcome) = outcome {
15834                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
15835                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
15836                    }
15837                    state.matched_recorded_pending = true;
15838                    self.scheduled = true;
15839                    self.matched_pending = true;
15840                    return Poll::Pending;
15841                }
15842                other => {
15843                    return Poll::Ready(Err(command_mismatch(
15844                        &other,
15845                        format!("child workflow:{}", self.workflow_type),
15846                    )));
15847                }
15848            }
15849        }
15850
15851        if !self.scheduled {
15852            if self.options.task_queue.trim().is_empty() {
15853                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15854                    "task_queue must not be empty".to_string(),
15855                )));
15856            }
15857            for (name, value) in [
15858                (
15859                    "execution_timeout_seconds",
15860                    self.options.execution_timeout_seconds,
15861                ),
15862                ("run_timeout_seconds", self.options.run_timeout_seconds),
15863            ] {
15864                if value == Some(0) {
15865                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
15866                        "{name} must be at least 1"
15867                    ))));
15868                }
15869            }
15870
15871            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15872                Ok(args) => args,
15873                Err(error) => return Poll::Ready(Err(error)),
15874            };
15875            let arguments = match encode_typed_envelope(
15876                &normalize_avro_arguments(args),
15877                &state.payload_codec,
15878            ) {
15879                Ok(arguments) => arguments,
15880                Err(error) => return Poll::Ready(Err(error)),
15881            };
15882            let mut command = json!({
15883                "type": "start_child_workflow",
15884                "workflow_type": self.workflow_type,
15885                "queue": self.options.task_queue,
15886                "parent_close_policy": self.options.parent_close_policy.as_str(),
15887                "arguments": arguments,
15888            });
15889            let object = command
15890                .as_object_mut()
15891                .expect("child workflow command is always an object");
15892            if self.options.cancellation_policy != CancellationPolicy::Abandon {
15893                object.insert(
15894                    "cancellation_policy".to_string(),
15895                    json!(self.options.cancellation_policy.as_str()),
15896                );
15897            }
15898            if let Some(policy) = &self.options.retry_policy {
15899                let mut retry_policy = serde_json::Map::new();
15900                if let Some(max_attempts) = policy.max_attempts {
15901                    if max_attempts == 0 {
15902                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15903                            "retry_policy.max_attempts must be at least 1".to_string(),
15904                        )));
15905                    }
15906                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
15907                }
15908                if !policy.backoff_seconds.is_empty() {
15909                    retry_policy
15910                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
15911                }
15912                if !policy.non_retryable_error_types.is_empty() {
15913                    retry_policy.insert(
15914                        "non_retryable_error_types".to_string(),
15915                        json!(policy.non_retryable_error_types),
15916                    );
15917                }
15918                if retry_policy.is_empty() {
15919                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
15920                        "retry_policy must configure at least one field".to_string(),
15921                    )));
15922                }
15923                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
15924            }
15925            if let Some(seconds) = self.options.execution_timeout_seconds {
15926                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
15927            }
15928            if let Some(seconds) = self.options.run_timeout_seconds {
15929                object.insert("run_timeout_seconds".to_string(), json!(seconds));
15930            }
15931            apply_parallel_group_path(object, &self.parallel_group_path);
15932            ctx.apply_scope_membership(object);
15933            match state.prepare_scalar_cancellation(
15934                cursor,
15935                CancellationCallKind::Child,
15936                &self.parallel_group_path,
15937            ) {
15938                Ok(true) => {
15939                    self.scheduled = true;
15940                    self.matched_pending = true;
15941                    return Poll::Pending;
15942                }
15943                Ok(false) => {}
15944                Err(error) => return Poll::Ready(Err(error)),
15945            }
15946            state.commands.push(command);
15947            self.scheduled = true;
15948        }
15949
15950        Poll::Pending
15951    }
15952}
15953
15954impl Future for ChildWorkflowCall {
15955    type Output = Result<ChildWorkflowResult>;
15956
15957    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15958        match self.poll_avro_value(cx) {
15959            Poll::Ready(Ok(result)) => match result.result.into_json() {
15960                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
15961                    parent: result.parent,
15962                    child: result.child,
15963                    child_workflow_type: result.child_workflow_type,
15964                    result: projected,
15965                })),
15966                Err(error) => Poll::Ready(Err(error)),
15967            },
15968            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15969            Poll::Pending => Poll::Pending,
15970        }
15971    }
15972}
15973
15974fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
15975    Error::NonDeterministicReplay(ReplayFailure::new(
15976        "recorded_command_mismatch",
15977        Some(recorded.sequence()),
15978        Some(recorded.shape().to_string()),
15979        Some(actual.into()),
15980        "current workflow command does not match the recorded durable command sequence",
15981    ))
15982}
15983
15984pub struct SignalCall {
15985    ctx: WorkflowContext,
15986    signal_name: String,
15987    runtime_reserved_allowed: bool,
15988    opened_wait: bool,
15989    matched_pending: bool,
15990    parallel_group_path: Vec<ParallelGroupMetadata>,
15991}
15992
15993impl SignalCall {
15994    fn poll_avro_value(
15995        mut self: Pin<&mut Self>,
15996        _cx: &mut TaskContext<'_>,
15997    ) -> Poll<Result<Vec<AvroValue>>> {
15998        if self.matched_pending {
15999            return Poll::Pending;
16000        }
16001        if !self.runtime_reserved_allowed {
16002            if let Err(error) = validate_user_signal_name(&self.signal_name) {
16003                return Poll::Ready(Err(error));
16004            }
16005        }
16006
16007        let ctx = self.ctx.clone();
16008        let mut state = match ctx.state.lock() {
16009            Ok(state) => state,
16010            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16011        };
16012
16013        let cursor = state.command_cursor;
16014        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
16015            return Poll::Ready(Err(error));
16016        }
16017        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
16018        {
16019            Ok(recorded) => recorded,
16020            Err(error) => return Poll::Ready(Err(error)),
16021        };
16022        if let Some(recorded) = recorded {
16023            match recorded {
16024                RecordedCommand::SignalWait {
16025                    sequence,
16026                    signal_name,
16027                    value,
16028                    parallel_group_path,
16029                } => {
16030                    if let Err(error) = ensure_parallel_path_matches(
16031                        sequence,
16032                        parallel_group_path.as_deref(),
16033                        &self.parallel_group_path,
16034                    ) {
16035                        return Poll::Ready(Err(error));
16036                    }
16037                    if signal_name != self.signal_name {
16038                        return Poll::Ready(Err(Error::NonDeterministicReplay(
16039                            ReplayFailure::new(
16040                                "recorded_command_detail_mismatch",
16041                                Some(sequence),
16042                                Some(format!("signal wait:{signal_name}")),
16043                                Some(format!("signal wait:{}", self.signal_name)),
16044                                "recorded signal name differs from the current workflow command",
16045                            ),
16046                        )));
16047                    }
16048
16049                    if let Err(error) =
16050                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
16051                    {
16052                        return Poll::Ready(Err(error));
16053                    }
16054                    match state.prepare_scalar_cancellation(
16055                        cursor,
16056                        CancellationCallKind::Signal,
16057                        &self.parallel_group_path,
16058                    ) {
16059                        Ok(true) => {
16060                            self.opened_wait = true;
16061                            self.matched_pending = true;
16062                            return Poll::Pending;
16063                        }
16064                        Ok(false) => {}
16065                        Err(error) => return Poll::Ready(Err(error)),
16066                    }
16067                    state.command_cursor += 1;
16068                    if let Some(value) = value {
16069                        state.advance_cancellation_sequence(sequence, &self.parallel_group_path);
16070                        return Poll::Ready(Ok(value));
16071                    }
16072                    if state
16073                        .resume_signal
16074                        .as_ref()
16075                        .is_some_and(|signal| signal.signal_name == self.signal_name)
16076                    {
16077                        let signal = state
16078                            .resume_signal
16079                            .take()
16080                            .expect("matching resume signal is present");
16081                        state.unavailable_cancellation_boundary(&self.parallel_group_path);
16082                        return Poll::Ready(Ok(signal.arguments));
16083                    }
16084
16085                    state.matched_recorded_pending = true;
16086                    self.opened_wait = true;
16087                    self.matched_pending = true;
16088                    return Poll::Pending;
16089                }
16090                other => {
16091                    return Poll::Ready(Err(command_mismatch(
16092                        &other,
16093                        format!("signal wait:{}", self.signal_name),
16094                    )));
16095                }
16096            }
16097        }
16098
16099        match state.prepare_scalar_cancellation(
16100            cursor,
16101            CancellationCallKind::Signal,
16102            &self.parallel_group_path,
16103        ) {
16104            Ok(true) => {
16105                self.opened_wait = true;
16106                self.matched_pending = true;
16107                return Poll::Pending;
16108            }
16109            Ok(false) => {}
16110            Err(error) => return Poll::Ready(Err(error)),
16111        }
16112
16113        if state
16114            .resume_signal
16115            .as_ref()
16116            .is_some_and(|signal| signal.signal_name == self.signal_name)
16117        {
16118            let signal = state
16119                .resume_signal
16120                .take()
16121                .expect("matching resume signal is present");
16122            state.unavailable_cancellation_boundary(&self.parallel_group_path);
16123            return Poll::Ready(Ok(signal.arguments));
16124        }
16125
16126        if !self.opened_wait {
16127            let mut command = serde_json::Map::from_iter([
16128                ("type".to_string(), json!("open_signal_wait")),
16129                ("signal_name".to_string(), json!(self.signal_name)),
16130            ]);
16131            apply_parallel_group_path(&mut command, &self.parallel_group_path);
16132            ctx.apply_scope_membership(&mut command);
16133            state.commands.push(Value::Object(command));
16134            self.opened_wait = true;
16135        }
16136
16137        Poll::Pending
16138    }
16139}
16140
16141impl Future for SignalCall {
16142    type Output = Result<Vec<Value>>;
16143
16144    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
16145        match self.poll_avro_value(cx) {
16146            Poll::Ready(Ok(values)) => Poll::Ready(
16147                values
16148                    .into_iter()
16149                    .map(AvroValue::into_json)
16150                    .collect::<Result<Vec<_>>>(),
16151            ),
16152            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
16153            Poll::Pending => Poll::Pending,
16154        }
16155    }
16156}
16157
16158#[derive(Clone, Debug)]
16159pub struct ActivityContext {
16160    client: Client,
16161    pub task_id: String,
16162    pub activity_attempt_id: String,
16163    pub lease_owner: String,
16164    pub activity_type: String,
16165    pub attempt_number: u64,
16166    retry_info: ActivityRetryInfo,
16167    pub task_queue: String,
16168    pub worker_id: String,
16169    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
16170    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
16171    worker_session: Option<WorkerSession>,
16172}
16173
16174impl ActivityContext {
16175    /// Immutable original attempt identity and received retry policy.
16176    pub fn retry_info(&self) -> &ActivityRetryInfo {
16177        &self.retry_info
16178    }
16179
16180    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
16181        if let Some(heartbeats) = &self.local_heartbeats {
16182            return heartbeats
16183                .lock()
16184                .map_err(|_| Error::WorkflowStatePoisoned)?
16185                .record(details);
16186        }
16187        if let Some(guard) = &self.claim_guard {
16188            return guard.heartbeat(self, details).await;
16189        }
16190        if let Some(session) = &self.worker_session {
16191            if !session.active() {
16192                return Err(Error::ActivityExecutionAbandoned(
16193                    "worker-session lease or TTL is no longer active".into(),
16194                ));
16195            }
16196            let result = self
16197                .client
16198                .heartbeat_activity_task_value(
16199                    &self.task_id,
16200                    &self.activity_attempt_id,
16201                    &self.lease_owner,
16202                    details,
16203                )
16204                .await;
16205            return worker_session::settle_activity_heartbeat(
16206                session,
16207                result,
16208                &self.task_id,
16209                &self.activity_attempt_id,
16210                &self.lease_owner,
16211            );
16212        }
16213        self.client
16214            .heartbeat_activity_task(
16215                &self.task_id,
16216                &self.activity_attempt_id,
16217                &self.lease_owner,
16218                details,
16219            )
16220            .await
16221    }
16222}
16223
16224fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
16225    validate_payload_codec(codec)?;
16226    match value {
16227        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
16228            value, codec,
16229        )?)),
16230        None => Ok(AvroValue::Array(Vec::new())),
16231    }
16232}
16233
16234fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
16235    let Some(signal_name) = task
16236        .signal_name
16237        .as_deref()
16238        .filter(|value| !value.is_empty())
16239    else {
16240        return Ok(None);
16241    };
16242    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
16243    let AvroValue::Array(arguments) = decoded else {
16244        unreachable!("normalize_avro_arguments always returns an array");
16245    };
16246
16247    Ok(Some(ResumeSignal {
16248        signal_name: signal_name.to_string(),
16249        arguments,
16250    }))
16251}
16252
16253fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
16254    validate_payload_codec(&task.payload_codec)?;
16255    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
16256    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
16257    for event in &task.history_events {
16258        validate_history_event_payloads(event, &task.payload_codec)?;
16259    }
16260    Ok(())
16261}
16262
16263fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
16264    validate_payload_codec(&task.payload_codec)?;
16265    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
16266}
16267
16268fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
16269    validate_payload_codec(&task.payload_codec)?;
16270    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
16271    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
16272    for event in &task.history_events {
16273        validate_history_event_payloads(event, &task.payload_codec)?;
16274    }
16275
16276    let Some(export) = task.history_export.as_ref() else {
16277        return Ok(());
16278    };
16279    let export_codec = match export.get("payloads") {
16280        Some(payloads) => declared_payload_codec(payloads, "codec")?,
16281        None => None,
16282    }
16283    .unwrap_or(&task.payload_codec);
16284    validate_payload_codec(export_codec)?;
16285
16286    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
16287        for event in events {
16288            let event_type = event
16289                .get("event_type")
16290                .or_else(|| event.get("type"))
16291                .and_then(Value::as_str)
16292                .unwrap_or_default();
16293            if let Some(payload) = event.get("payload") {
16294                validate_history_payloads(event_type, payload, export_codec)?;
16295            }
16296        }
16297    }
16298    for signal in export
16299        .get("signals")
16300        .and_then(Value::as_array)
16301        .into_iter()
16302        .flatten()
16303    {
16304        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
16305        validate_payload_codec(codec)?;
16306        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
16307    }
16308    for activity in export
16309        .get("activities")
16310        .and_then(Value::as_array)
16311        .into_iter()
16312        .flatten()
16313    {
16314        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
16315        validate_payload_codec(codec)?;
16316        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
16317        validate_optional_inbound_payload(activity.get("result"), codec)?;
16318    }
16319    Ok(())
16320}
16321
16322fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
16323    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
16324}
16325
16326fn validate_history_payloads(
16327    event_type: &str,
16328    payload: &Value,
16329    fallback_codec: &str,
16330) -> Result<()> {
16331    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
16332    validate_payload_codec(codec)?;
16333    for field in history_payload_fields(event_type) {
16334        validate_optional_inbound_payload(payload.get(*field), codec)?;
16335    }
16336    Ok(())
16337}
16338
16339const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
16340
16341fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
16342    match event_type {
16343        "ActivityCompleted" => &["result"],
16344        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
16345        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
16346        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
16347        "ChildRunCompleted" => &["result", "output"],
16348        "WorkflowCompleted" => &["output"],
16349        "ServiceCallStarted"
16350        | "ServiceCallCompleted"
16351        | "ServiceCallFailed"
16352        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
16353        _ => &[],
16354    }
16355}
16356
16357fn signal_history_payload(payload: &Value) -> Option<&Value> {
16358    SIGNAL_HISTORY_PAYLOAD_FIELDS
16359        .iter()
16360        .find_map(|field| payload.get(*field))
16361}
16362
16363fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
16364    match value.get(field) {
16365        None => Ok(None),
16366        Some(Value::String(codec)) => Ok(Some(codec)),
16367        Some(_) => Err(invalid_payload_envelope()),
16368    }
16369}
16370
16371fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
16372    validate_payload_codec(codec)?;
16373    if let Some(value) = value.filter(|value| !value.is_null()) {
16374        decode_wire_avro_value(value, codec)?;
16375    }
16376    Ok(())
16377}
16378
16379fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
16380    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
16381        invalid_recorded_history(
16382            "parallel_group_metadata_invalid",
16383            sequence,
16384            "non-empty parallel_group_id",
16385            &payload.to_string(),
16386            "parallel-group history is missing its stable identity",
16387        )
16388    })?;
16389    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
16390        invalid_recorded_history(
16391            "parallel_group_metadata_invalid",
16392            sequence,
16393            "activity, child, timer, signal, condition, or mixed group kind",
16394            &payload.to_string(),
16395            "parallel-group history is missing its group kind",
16396        )
16397    })?;
16398    if !matches!(
16399        kind.as_str(),
16400        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
16401    ) {
16402        return Err(invalid_recorded_history(
16403            "parallel_group_metadata_invalid",
16404            sequence,
16405            "activity, child, timer, signal, condition, or mixed group kind",
16406            &kind,
16407            "parallel-group history contains an unsupported group kind",
16408        ));
16409    }
16410    let base_sequence = payload
16411        .get("parallel_group_base_sequence")
16412        .and_then(value_as_u64)
16413        .filter(|value| *value > 0)
16414        .ok_or_else(|| {
16415            invalid_recorded_history(
16416                "parallel_group_metadata_invalid",
16417                sequence,
16418                "positive parallel_group_base_sequence",
16419                &payload.to_string(),
16420                "parallel-group history contains an invalid base sequence",
16421            )
16422        })?;
16423    let size = payload
16424        .get("parallel_group_size")
16425        .and_then(value_as_u64)
16426        .and_then(|value| usize::try_from(value).ok())
16427        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
16428        .ok_or_else(|| {
16429            invalid_recorded_history(
16430                "parallel_group_metadata_invalid",
16431                sequence,
16432                "bounded positive parallel_group_size",
16433                &payload.to_string(),
16434                "parallel-group history contains an invalid group size",
16435            )
16436        })?;
16437    let index = payload
16438        .get("parallel_group_index")
16439        .and_then(value_as_u64)
16440        .and_then(|value| usize::try_from(value).ok())
16441        .filter(|value| *value < size)
16442        .ok_or_else(|| {
16443            invalid_recorded_history(
16444                "parallel_group_metadata_invalid",
16445                sequence,
16446                "parallel_group_index within group bounds",
16447                &payload.to_string(),
16448                "parallel-group history contains an invalid member index",
16449            )
16450        })?;
16451    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
16452        return Err(invalid_recorded_history(
16453            "parallel_group_metadata_invalid",
16454            sequence,
16455            "base sequence plus member index equals workflow sequence",
16456            &payload.to_string(),
16457            "parallel-group path does not preserve durable workflow position",
16458        ));
16459    }
16460    let mode = payload
16461        .get("parallel_group_mode")
16462        .and_then(Value::as_str)
16463        .unwrap_or("all");
16464    if !matches!(mode, "all" | "select") {
16465        return Err(invalid_recorded_history(
16466            "parallel_group_metadata_invalid",
16467            sequence,
16468            "parallel group mode all or select",
16469            mode,
16470            "parallel-group history contains an unsupported group mode",
16471        ));
16472    }
16473    let expected_id = if mode == "select" {
16474        format!("select-calls:{base_sequence}:{size}")
16475    } else {
16476        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
16477    };
16478    if group_id != expected_id {
16479        return Err(invalid_recorded_history(
16480            "parallel_group_metadata_invalid",
16481            sequence,
16482            &expected_id,
16483            &group_id,
16484            "parallel-group history contains an incompatible stable group ID",
16485        ));
16486    }
16487    let selection_member_key = if mode == "select" {
16488        Some(selection_key_from_value(
16489            payload.get("selection_member_key"),
16490            sequence,
16491        )?)
16492    } else {
16493        None
16494    };
16495    let selection_member_index = if mode == "select" {
16496        Some(required_parallel_usize(
16497            payload,
16498            "selection_member_index",
16499            sequence,
16500        )?)
16501    } else {
16502        None
16503    };
16504    let selection_member_base_sequence = if mode == "select" {
16505        Some(
16506            payload
16507                .get("selection_member_base_sequence")
16508                .and_then(value_as_u64)
16509                .filter(|value| *value >= base_sequence)
16510                .ok_or_else(|| {
16511                    invalid_recorded_history(
16512                        "parallel_group_metadata_invalid",
16513                        sequence,
16514                        "selection member base within its group",
16515                        &payload.to_string(),
16516                        "selection history contains an invalid member base sequence",
16517                    )
16518                })?,
16519        )
16520    } else {
16521        None
16522    };
16523    let selection_member_size = if mode == "select" {
16524        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
16525        if member_size == 0 {
16526            return Err(invalid_recorded_history(
16527                "parallel_group_metadata_invalid",
16528                sequence,
16529                "positive selection member size",
16530                &payload.to_string(),
16531                "selection history contains an invalid member size",
16532            ));
16533        }
16534        Some(member_size)
16535    } else {
16536        None
16537    };
16538    let selection_member_kind = if mode == "select" {
16539        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
16540            invalid_recorded_history(
16541                "parallel_group_metadata_invalid",
16542                sequence,
16543                "selection member operation kind",
16544                &payload.to_string(),
16545                "selection history is missing its authored member kind",
16546            )
16547        })?;
16548        if !matches!(
16549            kind.as_str(),
16550            "activity" | "child" | "timer" | "signal" | "condition" | "group"
16551        ) {
16552            return Err(invalid_recorded_history(
16553                "parallel_group_metadata_invalid",
16554                sequence,
16555                "activity, child, timer, signal, condition, or group selection member kind",
16556                &kind,
16557                "selection history contains an unsupported member kind",
16558            ));
16559        }
16560        Some(kind)
16561    } else {
16562        None
16563    };
16564    if let (Some(member_base), Some(member_size)) =
16565        (selection_member_base_sequence, selection_member_size)
16566    {
16567        let member_end = member_base
16568            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
16569            .ok_or_else(|| {
16570                invalid_recorded_history(
16571                    "parallel_group_metadata_invalid",
16572                    sequence,
16573                    "bounded selection member range",
16574                    &payload.to_string(),
16575                    "selection member range overflowed",
16576                )
16577            })?;
16578        let group_end = base_sequence
16579            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
16580            .unwrap_or(u64::MAX);
16581        if sequence < member_base || sequence >= member_end || member_end > group_end {
16582            return Err(invalid_recorded_history(
16583                "parallel_group_metadata_invalid",
16584                sequence,
16585                "workflow sequence within one bounded selection member",
16586                &payload.to_string(),
16587                "selection member range does not contain its durable leaf",
16588            ));
16589        }
16590    }
16591    Ok(ParallelGroupMetadata {
16592        parallel_group_id: group_id,
16593        parallel_group_kind: kind,
16594        parallel_group_base_sequence: base_sequence,
16595        parallel_group_size: size,
16596        parallel_group_index: index,
16597        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
16598        selection_member_key,
16599        selection_member_index,
16600        selection_member_base_sequence,
16601        selection_member_size,
16602        selection_member_kind,
16603    })
16604}
16605
16606fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
16607    payload
16608        .get(field)
16609        .and_then(value_as_u64)
16610        .and_then(|value| usize::try_from(value).ok())
16611        .ok_or_else(|| {
16612            invalid_recorded_history(
16613                "parallel_group_metadata_invalid",
16614                sequence,
16615                &format!("non-negative integer {field}"),
16616                &payload.to_string(),
16617                "selection history contains invalid member metadata",
16618            )
16619        })
16620}
16621
16622fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
16623    match value {
16624        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
16625        Some(value) => value_as_u64(value)
16626            .and_then(|value| usize::try_from(value).ok())
16627            .map(SelectionKey::Index)
16628            .ok_or_else(|| {
16629                invalid_recorded_history(
16630                    "selection_member_key_invalid",
16631                    sequence,
16632                    "non-empty string or non-negative integer member key",
16633                    &value.to_string(),
16634                    "selection history contains an invalid member key",
16635                )
16636            }),
16637        None => Err(invalid_recorded_history(
16638            "selection_member_key_missing",
16639            sequence,
16640            "selection_member_key",
16641            "<missing>",
16642            "selection history is missing its stable member key",
16643        )),
16644    }
16645}
16646
16647fn recorded_parallel_group_path(
16648    events: &[&HistoryEvent],
16649    sequence: u64,
16650) -> Result<Option<Vec<ParallelGroupMetadata>>> {
16651    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
16652    for event in events {
16653        let payload = &event.payload;
16654        let has_metadata = payload.get("parallel_group_path").is_some()
16655            || payload.get("parallel_group_id").is_some()
16656            || payload.get("parallel_group_kind").is_some()
16657            || payload.get("parallel_group_base_sequence").is_some()
16658            || payload.get("parallel_group_size").is_some()
16659            || payload.get("parallel_group_index").is_some()
16660            || payload.get("parallel_group_mode").is_some()
16661            || payload.get("selection_member_key").is_some();
16662        if !has_metadata {
16663            continue;
16664        }
16665
16666        let top_level = recorded_parallel_group_entry(payload, sequence)?;
16667        let path = match payload.get("parallel_group_path") {
16668            None => vec![top_level.clone()],
16669            Some(Value::Array(entries)) if !entries.is_empty() => entries
16670                .iter()
16671                .map(|entry| recorded_parallel_group_entry(entry, sequence))
16672                .collect::<Result<Vec<_>>>()?,
16673            Some(value) => {
16674                return Err(invalid_recorded_history(
16675                    "parallel_group_metadata_invalid",
16676                    sequence,
16677                    "non-empty parallel_group_path list",
16678                    &value.to_string(),
16679                    "parallel-group history contains an invalid group path",
16680                ));
16681            }
16682        };
16683        if path.last() != Some(&top_level) {
16684            return Err(invalid_recorded_history(
16685                "parallel_group_metadata_invalid",
16686                sequence,
16687                &serde_json::to_string(&path.last()).unwrap_or_default(),
16688                &serde_json::to_string(&top_level).unwrap_or_default(),
16689                "parallel-group top-level fields do not match the innermost path entry",
16690            ));
16691        }
16692        if recorded.as_ref().is_some_and(|existing| existing != &path) {
16693            return Err(invalid_recorded_history(
16694                "parallel_group_history_conflict",
16695                sequence,
16696                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
16697                &serde_json::to_string(&path).unwrap_or_default(),
16698                "parallel-group metadata changed between scheduling and resolution history",
16699            ));
16700        }
16701        recorded = Some(path);
16702    }
16703    Ok(recorded)
16704}
16705
16706fn recorded_commands(
16707    events: &[HistoryEvent],
16708    fallback_codec: &str,
16709    parent: WorkflowIdentity,
16710) -> Result<Vec<RecordedCommand>> {
16711    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
16712    let mut last_new_sequence = None;
16713
16714    for event in events {
16715        let is_activity = matches!(
16716            event.event_type.as_str(),
16717            "ActivityScheduled"
16718                | "ActivityStarted"
16719                | "ActivityHeartbeatRecorded"
16720                | "ActivityRetryScheduled"
16721                | "ActivityCompleted"
16722                | "ActivityFailed"
16723                | "ActivityCancelled"
16724                | "ActivityTimedOut"
16725        );
16726        let is_workflow_timer = matches!(
16727            event.event_type.as_str(),
16728            "TimerScheduled" | "TimerCancelled" | "TimerFired"
16729        ) && !is_internal_timer_event(event);
16730        let is_child_workflow = matches!(
16731            event.event_type.as_str(),
16732            "ChildWorkflowScheduled"
16733                | "ChildRunStarted"
16734                | "ChildRunCompleted"
16735                | "ChildRunFailed"
16736                | "ChildRunCancelled"
16737                | "ChildRunTerminated"
16738        );
16739        let is_signal_wait = is_recorded_signal_wait_event(event);
16740        let is_condition_wait = is_recorded_condition_wait_event(event);
16741        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
16742        let is_side_effect = event.event_type == "SideEffectRecorded";
16743        let is_version_marker = event.event_type == "VersionMarkerRecorded";
16744        let is_memo = event.event_type == "MemoUpserted";
16745        let is_service_operation = nexus::is_service_event(event);
16746        if !is_activity
16747            && !is_workflow_timer
16748            && !is_child_workflow
16749            && !is_signal_wait
16750            && !is_condition_wait
16751            && !is_search_attributes
16752            && !is_side_effect
16753            && !is_version_marker
16754            && !is_memo
16755            && !is_service_operation
16756        {
16757            continue;
16758        }
16759
16760        let sequence = durable_event_sequence(event).ok_or_else(|| {
16761            Error::NonDeterministicReplay(ReplayFailure::new(
16762                "durable_command_sequence_missing",
16763                None,
16764                Some("positive workflow sequence".to_string()),
16765                Some(event.event_type.clone()),
16766                "durable command history event has no workflow sequence",
16767            ))
16768        })?;
16769        if sequence == 0 {
16770            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
16771                "durable_command_sequence_invalid",
16772                Some(sequence),
16773                Some("positive workflow sequence".to_string()),
16774                Some(sequence.to_string()),
16775                "durable command history uses an invalid workflow sequence",
16776            )));
16777        }
16778        if !events_by_sequence.contains_key(&sequence) {
16779            if let Some(previous) = last_new_sequence {
16780                if sequence < previous {
16781                    return Err(invalid_recorded_history(
16782                        "durable_command_sequence_mismatch",
16783                        sequence,
16784                        &format!("workflow sequence greater than {previous}"),
16785                        &sequence.to_string(),
16786                        "durable commands are not strictly ordered by their recorded workflow sequence",
16787                    ));
16788                }
16789            }
16790            last_new_sequence = Some(sequence);
16791        }
16792        events_by_sequence.entry(sequence).or_default().push(event);
16793    }
16794
16795    let commands: Vec<RecordedCommand> = events_by_sequence
16796        .into_iter()
16797        .map(|(sequence, sequence_events)| {
16798            let activity_events: Vec<_> = sequence_events
16799                .iter()
16800                .copied()
16801                .filter(|event| event.event_type.starts_with("Activity"))
16802                .collect();
16803            let timer_events: Vec<_> = sequence_events
16804                .iter()
16805                .copied()
16806                .filter(|event| event.event_type.starts_with("Timer"))
16807                .collect();
16808            let child_events: Vec<_> = sequence_events
16809                .iter()
16810                .copied()
16811                .filter(|event| {
16812                    event.event_type == "ChildWorkflowScheduled"
16813                        || event.event_type.starts_with("ChildRun")
16814                })
16815                .collect();
16816            let signal_wait_events: Vec<_> = sequence_events
16817                .iter()
16818                .copied()
16819                .filter(|event| is_recorded_signal_wait_event(event))
16820                .collect();
16821            let condition_wait_events: Vec<_> = sequence_events
16822                .iter()
16823                .copied()
16824                .filter(|event| is_recorded_condition_wait_event(event))
16825                .collect();
16826            let search_attribute_events: Vec<_> = sequence_events
16827                .iter()
16828                .copied()
16829                .filter(|event| event.event_type == "SearchAttributesUpserted")
16830                .collect();
16831            let side_effect_events: Vec<_> = sequence_events
16832                .iter()
16833                .copied()
16834                .filter(|event| event.event_type == "SideEffectRecorded")
16835                .collect();
16836            let version_marker_events: Vec<_> = sequence_events
16837                .iter()
16838                .copied()
16839                .filter(|event| event.event_type == "VersionMarkerRecorded")
16840                .collect();
16841            let memo_events: Vec<_> = sequence_events
16842                .iter()
16843                .copied()
16844                .filter(|event| event.event_type == "MemoUpserted")
16845                .collect();
16846            let service_events: Vec<_> = sequence_events.iter().copied()
16847                .filter(|event| nexus::is_service_event(event)).collect();
16848
16849            let command_kind_count = usize::from(!activity_events.is_empty())
16850                + usize::from(!timer_events.is_empty())
16851                + usize::from(!child_events.is_empty())
16852                + usize::from(!signal_wait_events.is_empty())
16853                + usize::from(!condition_wait_events.is_empty())
16854                + usize::from(!search_attribute_events.is_empty())
16855                + usize::from(!side_effect_events.is_empty())
16856                + usize::from(!version_marker_events.is_empty())
16857                + usize::from(!memo_events.is_empty())
16858                + usize::from(!service_events.is_empty());
16859            if command_kind_count > 1 {
16860                let actual = [
16861                    (!activity_events.is_empty()).then_some("activity"),
16862                    (!timer_events.is_empty()).then_some("timer"),
16863                    (!child_events.is_empty()).then_some("child workflow"),
16864                    (!signal_wait_events.is_empty()).then_some("signal wait"),
16865                    (!condition_wait_events.is_empty()).then_some("condition wait"),
16866                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
16867                    (!side_effect_events.is_empty()).then_some("side effect"),
16868                    (!version_marker_events.is_empty()).then_some("version marker"),
16869                    (!memo_events.is_empty()).then_some("memo upsert"),
16870                    (!service_events.is_empty()).then_some("service operation"),
16871                ]
16872                .into_iter()
16873                .flatten()
16874                .collect::<Vec<_>>()
16875                .join(" and ");
16876                return Err(invalid_recorded_history(
16877                    "durable_command_sequence_collision",
16878                    sequence,
16879                    "one durable command kind",
16880                    &actual,
16881                    "one workflow sequence records more than one durable command kind",
16882                ));
16883            }
16884
16885            if !service_events.is_empty() {
16886                return Ok(RecordedCommand::ServiceOperation {
16887                    sequence, call: nexus::recorded_call(&service_events, sequence, fallback_codec, &parent)?,
16888                });
16889            }
16890
16891            if !activity_events.is_empty() {
16892                let parallel_group_path =
16893                    recorded_parallel_group_path(&activity_events, sequence)?;
16894                let scheduled_count = activity_events
16895                    .iter()
16896                    .filter(|event| event.event_type == "ActivityScheduled")
16897                    .count();
16898                if scheduled_count > 1 {
16899                    return Err(invalid_recorded_history(
16900                        "duplicate_activity_schedule",
16901                        sequence,
16902                        "at most one ActivityScheduled event",
16903                        "multiple ActivityScheduled events",
16904                        "activity history schedules more than one command at one workflow sequence",
16905                    ));
16906                }
16907                let activity_type = activity_events.iter().find_map(|event| {
16908                    event
16909                        .payload
16910                        .get("activity_type")
16911                        .or_else(|| event.payload.get("activity_name"))
16912                        .and_then(Value::as_str)
16913                        .map(str::to_string)
16914                });
16915                if activity_events.iter().filter_map(|event| {
16916                    event
16917                        .payload
16918                        .get("activity_type")
16919                        .or_else(|| event.payload.get("activity_name"))
16920                        .and_then(Value::as_str)
16921                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
16922                    return Err(invalid_recorded_history(
16923                        "activity_identity_mismatch",
16924                        sequence,
16925                        activity_type.as_deref().unwrap_or("one activity identity"),
16926                        "conflicting activity identities",
16927                        "activity lifecycle events at one workflow sequence disagree on identity",
16928                    ));
16929                }
16930                let terminal: Vec<_> = activity_events
16931                    .iter()
16932                    .copied()
16933                    .filter(|event| {
16934                        matches!(
16935                            event.event_type.as_str(),
16936                            "ActivityCompleted"
16937                                | "ActivityFailed"
16938                                | "ActivityCancelled"
16939                                | "ActivityTimedOut"
16940                        )
16941                    })
16942                    .collect();
16943                let duplicate_delivery = terminal.first().is_some_and(|first| {
16944                    terminal.iter().all(|event| {
16945                        event.event_type == first.event_type && event.payload == first.payload
16946                    })
16947                });
16948                if terminal.len() > 1 && !duplicate_delivery {
16949                    return Err(invalid_recorded_history(
16950                        "duplicate_activity_terminal_event",
16951                        sequence,
16952                        "at most one terminal activity event",
16953                        "multiple terminal activity events",
16954                        "activity history settles one command more than once",
16955                    ));
16956                }
16957                let outcome = terminal
16958                    .first()
16959                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
16960                    .transpose()?;
16961                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
16962                let activity_snapshot = activity_events
16963                    .iter()
16964                    .find(|event| event.event_type == "ActivityScheduled")
16965                    .and_then(|event| event.payload.get("activity"))
16966                    .and_then(Value::as_object);
16967                let options = Some(match activity_snapshot {
16968                    Some(activity) => RecordedActivityOptions {
16969                        task_queue: recorded_optional_string(activity, "queue"),
16970                        execution_mode,
16971                        retry_policy: recorded_activity_retry_snapshot(
16972                            activity.get("retry_policy"),
16973                        ),
16974                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16975                    },
16976                    None => RecordedActivityOptions {
16977                        task_queue: RecordedSnapshotValue::Unknown,
16978                        execution_mode,
16979                        retry_policy: recorded_activity_retry_snapshot(None),
16980                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
16981                    },
16982                });
16983                return Ok(RecordedCommand::Activity {
16984                    sequence,
16985                    activity_type,
16986                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
16987                    options,
16988                    outcome,
16989                    parallel_group_path,
16990                });
16991            }
16992
16993            if !child_events.is_empty() {
16994                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
16995                let scheduled: Vec<_> = child_events
16996                    .iter()
16997                    .copied()
16998                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
16999                    .collect();
17000                if scheduled.len() != 1 {
17001                    return Err(invalid_recorded_history(
17002                        "child_workflow_schedule_missing_or_duplicate",
17003                        sequence,
17004                        "one ChildWorkflowScheduled event",
17005                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
17006                        "child workflow replay requires exactly one recorded schedule event",
17007                    ));
17008                }
17009                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
17010                let workflow_type = child_events.iter().find_map(|event| {
17011                    event
17012                        .payload
17013                        .get("child_workflow_type")
17014                        .or_else(|| event.payload.get("workflow_type"))
17015                        .and_then(Value::as_str)
17016                        .filter(|value| !value.is_empty())
17017                        .map(str::to_string)
17018                });
17019                if child_events
17020                    .iter()
17021                    .filter_map(|event| {
17022                        event
17023                            .payload
17024                            .get("child_workflow_type")
17025                            .or_else(|| event.payload.get("workflow_type"))
17026                            .and_then(Value::as_str)
17027                    })
17028                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
17029                {
17030                    return Err(invalid_recorded_history(
17031                        "child_workflow_identity_mismatch",
17032                        sequence,
17033                        workflow_type
17034                            .as_deref()
17035                            .unwrap_or("one child workflow type"),
17036                        "conflicting child workflow types",
17037                        "child workflow lifecycle events at one sequence disagree on type",
17038                    ));
17039                }
17040                let mut outcomes = child_workflow_outcomes(
17041                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
17042                    fallback_codec,
17043                    parent.clone(),
17044                )?;
17045                let terminal_events = child_events
17046                    .iter()
17047                    .copied()
17048                    .filter(|event| event.event_type.starts_with("ChildRun"))
17049                    .collect::<Vec<_>>();
17050                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
17051                    terminal_events.iter().all(|event| {
17052                        event.event_type == first.event_type && event.payload == first.payload
17053                    })
17054                });
17055                if outcomes.len() > 1 && !duplicate_delivery {
17056                    return Err(invalid_recorded_history(
17057                        "duplicate_child_workflow_terminal_event",
17058                        sequence,
17059                        "at most one terminal child event",
17060                        "multiple terminal child events",
17061                        "child workflow history settles one command more than once",
17062                    ));
17063                }
17064                return Ok(RecordedCommand::ChildWorkflow {
17065                    sequence,
17066                    workflow_type,
17067                    policies,
17068                    outcome: outcomes.pop(),
17069                    parallel_group_path,
17070                });
17071            }
17072
17073            if !signal_wait_events.is_empty() {
17074                let opened: Vec<_> = signal_wait_events
17075                    .iter()
17076                    .copied()
17077                    .filter(|event| event.event_type == "SignalWaitOpened")
17078                    .collect();
17079                if opened.len() != 1 {
17080                    return Err(invalid_recorded_history(
17081                        "signal_wait_open_missing_or_duplicate",
17082                        sequence,
17083                        "one SignalWaitOpened event",
17084                        &format!("{} SignalWaitOpened events", opened.len()),
17085                        "signal replay requires exactly one canonical wait-open event",
17086                    ));
17087                }
17088
17089                let applied: Vec<_> = signal_wait_events
17090                    .iter()
17091                    .copied()
17092                    .filter(|event| event.event_type == "SignalApplied")
17093                    .collect();
17094                if applied.len() > 1 {
17095                    return Err(invalid_recorded_history(
17096                        "duplicate_signal_wait_apply",
17097                        sequence,
17098                        "at most one SignalApplied event",
17099                        "multiple SignalApplied events",
17100                        "signal history applies one durable wait more than once",
17101                    ));
17102                }
17103
17104                let signal_names = signal_wait_events
17105                    .iter()
17106                    .map(|event| required_signal_wait_name(event, sequence))
17107                    .collect::<Result<Vec<_>>>()?;
17108                let signal_name = signal_names
17109                    .first()
17110                    .expect("signal wait events are not empty")
17111                    .clone();
17112                if signal_names.iter().any(|candidate| candidate != &signal_name) {
17113                    return Err(invalid_recorded_history(
17114                        "signal_wait_identity_mismatch",
17115                        sequence,
17116                        &signal_name,
17117                        "conflicting signal names",
17118                        "signal wait lifecycle events at one workflow sequence disagree on identity",
17119                    ));
17120                }
17121                let value = applied
17122                    .first()
17123                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
17124                    .transpose()?;
17125                return Ok(RecordedCommand::SignalWait {
17126                    sequence,
17127                    signal_name,
17128                    value,
17129                    parallel_group_path: recorded_parallel_group_path(
17130                        &signal_wait_events,
17131                        sequence,
17132                    )?,
17133                });
17134            }
17135
17136            if !condition_wait_events.is_empty() {
17137                return recorded_condition_wait(
17138                    sequence,
17139                    &condition_wait_events,
17140                    events,
17141                );
17142            }
17143
17144            if !search_attribute_events.is_empty() {
17145                if search_attribute_events.len() != 1 {
17146                    return Err(invalid_recorded_history(
17147                        "duplicate_search_attribute_update",
17148                        sequence,
17149                        "one SearchAttributesUpserted event",
17150                        &format!(
17151                            "{} SearchAttributesUpserted events",
17152                            search_attribute_events.len()
17153                        ),
17154                        "search-attribute history records one workflow command more than once",
17155                    ));
17156                }
17157                let payload = &search_attribute_events[0].payload;
17158                let attributes = payload
17159                    .get("attributes")
17160                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
17161                    .cloned()
17162                    .ok_or_else(|| {
17163                        invalid_recorded_history(
17164                            "search_attribute_update_missing",
17165                            sequence,
17166                            "non-empty attributes object",
17167                            "missing or invalid attributes",
17168                            "search-attribute history is missing its recorded mutation",
17169                        )
17170                    })?;
17171                let attribute_types =
17172                    recorded_search_attribute_types(payload, &attributes, sequence)?;
17173                return Ok(RecordedCommand::SearchAttributes {
17174                    sequence,
17175                    attributes,
17176                    attribute_types,
17177                });
17178            }
17179
17180            if !side_effect_events.is_empty() {
17181                if side_effect_events.len() != 1 {
17182                    return Err(invalid_recorded_history(
17183                        "duplicate_side_effect_record",
17184                        sequence,
17185                        "one SideEffectRecorded event",
17186                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
17187                        "side-effect history records one workflow command more than once",
17188                    ));
17189                }
17190                let event = side_effect_events[0];
17191                let result = event.payload.get("result").ok_or_else(|| {
17192                    invalid_recorded_history(
17193                        "side_effect_result_missing",
17194                        sequence,
17195                        "recorded result payload",
17196                        "missing result",
17197                        "side-effect history is missing its recorded value",
17198                    )
17199                })?;
17200                let has_published_envelope = result.as_str().is_some()
17201                    || result.as_object().is_some_and(|envelope| {
17202                        envelope.get("codec").and_then(Value::as_str).is_some()
17203                            && envelope.get("blob").and_then(Value::as_str).is_some()
17204                    });
17205                if !has_published_envelope {
17206                    return Err(invalid_recorded_history(
17207                        "side_effect_payload_malformed",
17208                        sequence,
17209                        "payload blob or {codec, blob} envelope",
17210                        &result.to_string(),
17211                        "side-effect history result does not use a published payload envelope",
17212                    ));
17213                }
17214                let codec = event
17215                    .payload
17216                    .get("payload_codec")
17217                    .and_then(Value::as_str)
17218                    .unwrap_or(fallback_codec);
17219                let value = decode_wire_avro_value(result, codec).map_err(|error| {
17220                    if error.to_string().contains("unsupported_payload_codec") {
17221                        return error;
17222                    }
17223
17224                    invalid_recorded_history(
17225                        "side_effect_payload_incompatible",
17226                        sequence,
17227                        &format!("valid {codec} payload envelope"),
17228                        &error.to_string(),
17229                        "side-effect history payload cannot be decoded with its recorded codec",
17230                    )
17231                })?;
17232                return Ok(RecordedCommand::SideEffect { sequence, value });
17233            }
17234
17235            if !version_marker_events.is_empty() {
17236                if version_marker_events.len() != 1 {
17237                    return Err(invalid_recorded_history(
17238                        "duplicate_version_marker_record",
17239                        sequence,
17240                        "one VersionMarkerRecorded event",
17241                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
17242                        "version-marker history records one workflow command more than once",
17243                    ));
17244                }
17245                let payload = &version_marker_events[0].payload;
17246                let change_id = payload
17247                    .get("change_id")
17248                    .and_then(Value::as_str)
17249                    .filter(|value| !value.is_empty())
17250                    .map(str::to_string)
17251                    .ok_or_else(|| {
17252                        invalid_recorded_history(
17253                            "version_marker_field_missing",
17254                            sequence,
17255                            "non-empty change_id",
17256                            "missing or invalid change_id",
17257                            "version-marker history is missing its stable change ID",
17258                        )
17259                    })?;
17260                let version = required_version_i32(payload, "version", sequence)?;
17261                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
17262                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
17263                if min_supported > max_supported || version < min_supported || version > max_supported {
17264                    return Err(invalid_recorded_history(
17265                        "version_marker_history_range_invalid",
17266                        sequence,
17267                        "min_supported <= version <= max_supported",
17268                        &format!("{min_supported} <= {version} <= {max_supported}"),
17269                        "recorded version marker contains an internally incompatible range",
17270                    ));
17271                }
17272                return Ok(RecordedCommand::VersionMarker {
17273                    sequence,
17274                    change_id,
17275                    version,
17276                });
17277            }
17278
17279            if !memo_events.is_empty() {
17280                if memo_events.len() != 1 {
17281                    return Err(invalid_recorded_history(
17282                        "duplicate_memo_upsert_record",
17283                        sequence,
17284                        "one MemoUpserted event",
17285                        &format!("{} MemoUpserted events", memo_events.len()),
17286                        "memo history records one workflow update more than once",
17287                    ));
17288                }
17289                let payload = &memo_events[0].payload;
17290                let entries = payload.get("entries").cloned().ok_or_else(|| {
17291                    invalid_recorded_history(
17292                        "memo_entries_missing",
17293                        sequence,
17294                        "memo entries object",
17295                        "missing entries",
17296                        "MemoUpserted history is missing replay identity entries",
17297                    )
17298                })?;
17299                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
17300                    invalid_recorded_history(
17301                        "memo_entries_invalid",
17302                        sequence,
17303                        "valid canonical memo entries",
17304                        &error.to_string(),
17305                        "MemoUpserted history contains invalid replay identity entries",
17306                    )
17307                })?;
17308                let merged = payload.get("merged").cloned().ok_or_else(|| {
17309                    invalid_recorded_history(
17310                        "memo_merged_projection_missing",
17311                        sequence,
17312                        "merged memo projection",
17313                        "missing merged",
17314                        "MemoUpserted history is missing its merged projection",
17315                    )
17316                })?;
17317                decode_memo_history_map(&merged, false).map_err(|error| {
17318                    invalid_recorded_history(
17319                        "memo_merged_projection_invalid",
17320                        sequence,
17321                        "valid merged memo projection",
17322                        &error.to_string(),
17323                        "MemoUpserted history contains an invalid merged projection",
17324                    )
17325                })?;
17326
17327                return Ok(RecordedCommand::Memo { sequence, entries });
17328            }
17329            let scheduled: Vec<_> = timer_events
17330                .iter()
17331                .copied()
17332                .filter(|event| event.event_type == "TimerScheduled")
17333                .collect();
17334            let fired: Vec<_> = timer_events
17335                .iter()
17336                .copied()
17337                .filter(|event| event.event_type == "TimerFired")
17338                .collect();
17339            if scheduled.len() != 1 {
17340                return Err(invalid_recorded_history(
17341                    "timer_schedule_missing_or_duplicate",
17342                    sequence,
17343                    "one TimerScheduled event",
17344                    &format!("{} TimerScheduled events", scheduled.len()),
17345                    "timer replay requires exactly one recorded schedule event",
17346                ));
17347            }
17348            if fired.len() > 1 {
17349                return Err(invalid_recorded_history(
17350                    "duplicate_timer_fire",
17351                    sequence,
17352                    "at most one TimerFired event",
17353                    "multiple TimerFired events",
17354                    "timer history contains more than one fire event for a workflow sequence",
17355                ));
17356            }
17357
17358            let scheduled = scheduled[0];
17359            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
17360            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
17361            if let Some(fired) = fired.first() {
17362                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
17363                if fired_timer_id != timer_id {
17364                    return Err(invalid_recorded_history(
17365                        "timer_identity_mismatch",
17366                        sequence,
17367                        &timer_id,
17368                        &fired_timer_id,
17369                        "TimerFired does not correspond to the recorded TimerScheduled event",
17370                    ));
17371                }
17372                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
17373                if fired_delay != delay_seconds {
17374                    return Err(invalid_recorded_history(
17375                        "timer_history_delay_mismatch",
17376                        sequence,
17377                        &delay_seconds.to_string(),
17378                        &fired_delay.to_string(),
17379                        "TimerScheduled and TimerFired record different delays",
17380                    ));
17381                }
17382            }
17383
17384            Ok(RecordedCommand::Timer {
17385                sequence,
17386                delay_seconds,
17387                fired: !fired.is_empty(),
17388                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
17389            })
17390        })
17391        .collect::<Result<_>>()?;
17392
17393    let mut marker_decisions = HashMap::new();
17394    for command in &commands {
17395        if let RecordedCommand::VersionMarker {
17396            sequence,
17397            change_id,
17398            version,
17399        } = command
17400        {
17401            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
17402                if version != first_version {
17403                    return Err(invalid_recorded_history(
17404                        "version_marker_conflict",
17405                        *sequence,
17406                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
17407                        &format!("version {version} at sequence {sequence}"),
17408                        "workflow history contains conflicting decisions for one stable change ID",
17409                    ));
17410                }
17411            } else {
17412                marker_decisions.insert(change_id.clone(), (*version, *sequence));
17413            }
17414        }
17415    }
17416
17417    Ok(commands)
17418}
17419
17420fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
17421    payload
17422        .get(field)
17423        .and_then(Value::as_i64)
17424        .and_then(|value| i32::try_from(value).ok())
17425        .ok_or_else(|| {
17426            invalid_recorded_history(
17427                "version_marker_field_missing",
17428                sequence,
17429                &format!("integer {field}"),
17430                "missing or out-of-range integer",
17431                "version-marker history is missing a required integer field",
17432            )
17433        })
17434}
17435
17436fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
17437    event
17438        .payload
17439        .get("sequence")
17440        .or_else(|| event.payload.get("workflow_sequence"))
17441        .or_else(|| event.raw.get("sequence"))
17442        .or_else(|| event.raw.get("workflow_sequence"))
17443        .and_then(value_as_u64)
17444}
17445
17446fn is_internal_timer_event(event: &HistoryEvent) -> bool {
17447    matches!(
17448        event
17449            .payload
17450            .get("timer_kind")
17451            .or_else(|| event.raw.get("timer_kind"))
17452            .and_then(Value::as_str),
17453        Some("condition_timeout" | "signal_timeout")
17454    )
17455}
17456
17457fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
17458    matches!(
17459        event.event_type.as_str(),
17460        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
17461    )
17462}
17463
17464fn recorded_condition_wait(
17465    sequence: u64,
17466    condition_events: &[&HistoryEvent],
17467    all_events: &[HistoryEvent],
17468) -> Result<RecordedCommand> {
17469    let opened = condition_events
17470        .iter()
17471        .copied()
17472        .filter(|event| event.event_type == "ConditionWaitOpened")
17473        .collect::<Vec<_>>();
17474    if opened.len() != 1 {
17475        return Err(invalid_recorded_history(
17476            "condition_wait_open_missing_or_duplicate",
17477            sequence,
17478            "one ConditionWaitOpened event",
17479            &format!("{} ConditionWaitOpened events", opened.len()),
17480            "condition replay requires exactly one canonical wait-open event",
17481        ));
17482    }
17483    let terminal = condition_events
17484        .iter()
17485        .copied()
17486        .filter(|event| {
17487            matches!(
17488                event.event_type.as_str(),
17489                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
17490            )
17491        })
17492        .collect::<Vec<_>>();
17493    if terminal.len() > 1 {
17494        return Err(invalid_recorded_history(
17495            "duplicate_condition_wait_terminal_event",
17496            sequence,
17497            "at most one condition terminal event",
17498            "multiple condition terminal events",
17499            "condition history settles one durable wait more than once",
17500        ));
17501    }
17502
17503    let opened = opened[0];
17504    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
17505    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
17506    for event in condition_events
17507        .iter()
17508        .copied()
17509        .filter(|event| !std::ptr::eq(*event, opened))
17510    {
17511        let event_wait_id = required_condition_wait_id(event, sequence)?;
17512        if event_wait_id != condition_wait_id {
17513            return Err(invalid_recorded_history(
17514                "condition_wait_id_mismatch",
17515                sequence,
17516                &condition_wait_id,
17517                &event_wait_id,
17518                "condition lifecycle events at one sequence disagree on wait identity",
17519            ));
17520        }
17521        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
17522        if event_occurrence_id != occurrence_id {
17523            return Err(invalid_recorded_history(
17524                "condition_wait_occurrence_history_mismatch",
17525                sequence,
17526                &occurrence_id,
17527                &event_occurrence_id,
17528                "condition lifecycle events at one sequence disagree on authored occurrence identity",
17529            ));
17530        }
17531    }
17532
17533    let condition_key = optional_non_empty_history_string(opened, "condition_key");
17534    let predicate_identity = opened
17535        .payload
17536        .get("condition_definition_fingerprint")
17537        .and_then(Value::as_str)
17538        .filter(|value| !value.is_empty())
17539        .map(str::to_string)
17540        .ok_or_else(|| {
17541            invalid_recorded_history(
17542                "condition_wait_predicate_fingerprint_missing",
17543                sequence,
17544                "non-empty condition_definition_fingerprint",
17545                &opened.event_type,
17546                "canonical condition history is missing its predicate identity",
17547            )
17548        })?;
17549    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
17550    for event in condition_events
17551        .iter()
17552        .copied()
17553        .filter(|event| !std::ptr::eq(*event, opened))
17554    {
17555        for (field, opened_value) in [
17556            ("condition_key", condition_key.as_deref()),
17557            (
17558                "condition_definition_fingerprint",
17559                Some(predicate_identity.as_str()),
17560            ),
17561        ] {
17562            if let Some(value) = optional_non_empty_history_string(event, field) {
17563                if opened_value.is_some_and(|opened_value| opened_value != value) {
17564                    return Err(invalid_recorded_history(
17565                        "condition_wait_definition_history_mismatch",
17566                        sequence,
17567                        opened_value.unwrap_or_default(),
17568                        &value,
17569                        "condition lifecycle events disagree on the recorded definition",
17570                    ));
17571                }
17572            }
17573        }
17574        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
17575            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
17576                return Err(invalid_recorded_history(
17577                    "condition_wait_definition_history_mismatch",
17578                    sequence,
17579                    &format!("{}s", timeout_seconds.unwrap_or_default()),
17580                    &format!("{event_timeout}s"),
17581                    "condition lifecycle events disagree on the recorded timeout",
17582                ));
17583            }
17584        }
17585    }
17586
17587    let timeout_timer_events = all_events
17588        .iter()
17589        .filter(|event| {
17590            matches!(
17591                event.event_type.as_str(),
17592                "TimerScheduled" | "TimerCancelled" | "TimerFired"
17593            ) && event.payload.get("timer_kind").and_then(Value::as_str)
17594                == Some("condition_timeout")
17595                && event
17596                    .payload
17597                    .get("condition_wait_id")
17598                    .and_then(Value::as_str)
17599                    == Some(condition_wait_id.as_str())
17600        })
17601        .collect::<Vec<_>>();
17602    let scheduled = timeout_timer_events
17603        .iter()
17604        .copied()
17605        .filter(|event| event.event_type == "TimerScheduled")
17606        .collect::<Vec<_>>();
17607    let fired = timeout_timer_events
17608        .iter()
17609        .copied()
17610        .filter(|event| event.event_type == "TimerFired")
17611        .collect::<Vec<_>>();
17612    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
17613        return Err(invalid_recorded_history(
17614            "condition_wait_timeout_history_invalid",
17615            sequence,
17616            "one timeout schedule and at most one fire",
17617            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
17618            "condition timeout history has a missing or duplicate lifecycle event",
17619        ));
17620    }
17621    if let Some(scheduled) = scheduled.first() {
17622        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
17623        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
17624        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
17625            return Err(invalid_recorded_history(
17626                "condition_wait_timeout_delay_mismatch",
17627                sequence,
17628                &format!("{}s", timeout_seconds.unwrap_or_default()),
17629                &format!("{delay_seconds}s"),
17630                "condition timeout timer differs from the wait definition",
17631            ));
17632        }
17633        if let Some(fired) = fired.first() {
17634            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
17635            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
17636            if fired_timer_id != timer_id || fired_delay != delay_seconds {
17637                return Err(invalid_recorded_history(
17638                    "condition_wait_timeout_identity_mismatch",
17639                    sequence,
17640                    &format!("{timer_id}:{delay_seconds}s"),
17641                    &format!("{fired_timer_id}:{fired_delay}s"),
17642                    "condition timeout fire does not match its durable schedule",
17643                ));
17644            }
17645        }
17646    }
17647
17648    let result = terminal.first().map(|event| {
17649        if event.event_type == "ConditionWaitTimedOut" {
17650            ConditionWaitResult::TimedOut
17651        } else {
17652            ConditionWaitResult::Satisfied
17653        }
17654    });
17655    let result = if !fired.is_empty() {
17656        if result == Some(ConditionWaitResult::Satisfied) {
17657            return Err(invalid_recorded_history(
17658                "condition_wait_terminal_conflict",
17659                sequence,
17660                "one satisfied or timed-out outcome",
17661                "satisfied event and fired timeout",
17662                "condition history records conflicting terminal outcomes",
17663            ));
17664        }
17665        Some(ConditionWaitResult::TimedOut)
17666    } else {
17667        result
17668    };
17669
17670    Ok(RecordedCommand::ConditionWait {
17671        sequence,
17672        occurrence_id,
17673        condition_key,
17674        predicate_identity,
17675        timeout_seconds,
17676        result,
17677        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
17678    })
17679}
17680
17681fn recorded_condition_group_path(
17682    condition_events: &[&HistoryEvent],
17683    all_events: &[HistoryEvent],
17684    sequence: u64,
17685) -> Result<Option<Vec<ParallelGroupMetadata>>> {
17686    let opened = condition_events
17687        .iter()
17688        .copied()
17689        .find(|event| event.event_type == "ConditionWaitOpened")
17690        .expect("canonical condition opener is validated first");
17691    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
17692    let previous_events = all_events
17693        .iter()
17694        .take_while(|event| !std::ptr::eq(*event, opened))
17695        .collect::<Vec<_>>();
17696    let originals = previous_events
17697        .iter()
17698        .copied()
17699        .filter(|event| event.event_type == "ConditionWaitOpened")
17700        .filter(|event| {
17701            event
17702                .payload
17703                .get("condition_wait_occurrence_id")
17704                .and_then(Value::as_str)
17705                == Some(occurrence.as_str())
17706        })
17707        .collect::<Vec<_>>();
17708    let Some(original) = originals.first().copied() else {
17709        return recorded_parallel_group_path(condition_events, sequence);
17710    };
17711    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
17712    if authored_sequence == sequence {
17713        return recorded_parallel_group_path(condition_events, sequence);
17714    }
17715    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
17716    if original_path.is_none() {
17717        return recorded_parallel_group_path(condition_events, sequence);
17718    }
17719    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
17720    let identity_matches = [
17721        "condition_key",
17722        "condition_definition_fingerprint",
17723        "timeout_seconds",
17724    ]
17725    .iter()
17726    .all(|field| opened.payload.get(*field) == original.payload.get(*field));
17727    let previous = originals
17728        .iter()
17729        .copied()
17730        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
17731        .max_by_key(|event| durable_event_sequence(event));
17732    let previously_satisfied = previous.is_some_and(|previous| {
17733        previous_events.iter().any(|event| {
17734            event.event_type == "ConditionWaitSatisfied"
17735                && event.payload.get("condition_wait_id")
17736                    == previous.payload.get("condition_wait_id")
17737                && event.payload.get("condition_wait_occurrence_id")
17738                    == previous.payload.get("condition_wait_occurrence_id")
17739                && durable_event_sequence(event) == durable_event_sequence(previous)
17740        })
17741    });
17742    if !identity_matches || reopened_path != original_path || !previously_satisfied {
17743        return Err(invalid_recorded_history(
17744            "condition_wait_group_reopen_mismatch",
17745            sequence,
17746            "same authored condition and group path after a satisfied physical wait",
17747            &opened.payload.to_string(),
17748            "grouped condition reopen has no matching recorded predecessor",
17749        ));
17750    }
17751    Ok(reopened_path)
17752}
17753
17754fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17755    event
17756        .payload
17757        .get("condition_wait_occurrence_id")
17758        .and_then(Value::as_str)
17759        .filter(|value| !value.is_empty())
17760        .map(str::to_string)
17761        .ok_or_else(|| {
17762            invalid_recorded_history(
17763                "condition_wait_occurrence_id_missing",
17764                sequence,
17765                "non-empty condition_wait_occurrence_id",
17766                &event.event_type,
17767                "condition history is missing authored occurrence identity",
17768            )
17769        })
17770}
17771
17772fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
17773    event
17774        .payload
17775        .get("condition_wait_id")
17776        .and_then(Value::as_str)
17777        .filter(|value| !value.is_empty())
17778        .map(str::to_string)
17779        .ok_or_else(|| {
17780            invalid_recorded_history(
17781                "condition_wait_id_missing",
17782                sequence,
17783                "non-empty condition_wait_id",
17784                &event.event_type,
17785                "canonical condition history is missing its durable wait identity",
17786            )
17787        })
17788}
17789
17790fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
17791    event
17792        .payload
17793        .get(field)
17794        .and_then(Value::as_str)
17795        .filter(|value| !value.is_empty())
17796        .map(str::to_string)
17797}
17798
17799fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
17800    match event.payload.get(field) {
17801        None | Some(Value::Null) => Ok(None),
17802        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
17803            invalid_recorded_history(
17804                "condition_wait_definition_invalid",
17805                sequence,
17806                &format!("non-negative integer {field}"),
17807                &value.to_string(),
17808                "condition history contains an invalid numeric definition field",
17809            )
17810        }),
17811    }
17812}
17813
17814fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
17815    event
17816        .payload
17817        .get("signal_name")
17818        .or_else(|| event.raw.get("signal_name"))
17819        .and_then(Value::as_str)
17820        .filter(|value| !value.is_empty())
17821        .map(str::to_string)
17822        .ok_or_else(|| {
17823            invalid_recorded_history(
17824                "signal_wait_name_missing",
17825                sequence,
17826                "non-empty signal_name",
17827                &event.event_type,
17828                "canonical signal-wait history is missing its signal identity",
17829            )
17830        })
17831}
17832
17833fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
17834    // Applying a buffered control-plane signal has no authored call sequence.
17835    // Its outer sequence orders history events and must not become a wait.
17836    if event.event_type == "SignalApplied"
17837        && event
17838            .payload
17839            .get("signal_wait_id")
17840            .and_then(Value::as_str)
17841            .is_some_and(|id| id.starts_with("signal-command:"))
17842        && event.payload.get("sequence").is_none()
17843        && event.payload.get("workflow_sequence").is_none()
17844    {
17845        return false;
17846    }
17847    matches!(
17848        event.event_type.as_str(),
17849        "SignalWaitOpened" | "SignalApplied"
17850    )
17851}
17852
17853fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
17854    event
17855        .payload
17856        .get(field)
17857        .and_then(Value::as_str)
17858        .filter(|value| !value.is_empty())
17859        .map(str::to_string)
17860        .ok_or_else(|| {
17861            invalid_recorded_history(
17862                "timer_history_field_missing",
17863                sequence,
17864                field,
17865                &event.event_type,
17866                "timer history is missing a required identity field",
17867            )
17868        })
17869}
17870
17871fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
17872    event
17873        .payload
17874        .get(field)
17875        .and_then(value_as_u64)
17876        .ok_or_else(|| {
17877            invalid_recorded_history(
17878                "timer_history_field_missing",
17879                sequence,
17880                field,
17881                &event.event_type,
17882                "timer history is missing a required numeric field",
17883            )
17884        })
17885}
17886
17887fn recorded_search_attribute_types(
17888    payload: &Value,
17889    attributes: &Value,
17890    sequence: u64,
17891) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
17892    let Some(raw_types) = payload.get("attribute_types") else {
17893        // This is the explicit compatibility rule for histories recorded
17894        // before typed identity was persisted. Values still constrain replay;
17895        // the unknown type snapshot does not assert a typed match.
17896        return Ok(RecordedSnapshotValue::Unknown);
17897    };
17898    let Some(raw_types) = raw_types.as_object() else {
17899        return Err(invalid_recorded_history(
17900            "search_attribute_types_malformed",
17901            sequence,
17902            "canonical attribute type map",
17903            &raw_types.to_string(),
17904            "search-attribute history contains malformed type identity",
17905        ));
17906    };
17907    let attribute_keys = attributes
17908        .as_object()
17909        .expect("recorded search attributes were validated as an object");
17910    let mut types = BTreeMap::new();
17911    for (key, value) in raw_types {
17912        let Some(attribute_type) = value.as_str() else {
17913            return Err(invalid_recorded_history(
17914                "search_attribute_types_malformed",
17915                sequence,
17916                "canonical string type name",
17917                &value.to_string(),
17918                "search-attribute history contains a non-string type identity",
17919            ));
17920        };
17921        if !attribute_keys.contains_key(key)
17922            || !matches!(
17923                attribute_type,
17924                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
17925            )
17926        {
17927            return Err(invalid_recorded_history(
17928                "search_attribute_types_malformed",
17929                sequence,
17930                "canonical types for keys present in attributes",
17931                &format!("{key}:{attribute_type}"),
17932                "search-attribute history contains unsupported or orphaned type identity",
17933            ));
17934        }
17935        types.insert(key.clone(), attribute_type.to_string());
17936    }
17937    Ok(RecordedSnapshotValue::Known(types))
17938}
17939
17940fn invalid_recorded_history(
17941    reason: &str,
17942    sequence: u64,
17943    expected: &str,
17944    actual: &str,
17945    message: &str,
17946) -> Error {
17947    Error::NonDeterministicReplay(ReplayFailure::new(
17948        reason,
17949        Some(sequence),
17950        Some(expected.to_string()),
17951        Some(actual.to_string()),
17952        message,
17953    ))
17954}
17955
17956type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
17957
17958fn activity_outcome(
17959    event: &HistoryEvent,
17960    fallback_codec: &str,
17961    recorded_activity_type: Option<String>,
17962) -> Result<ActivityOutcome> {
17963    if event.event_type == "ActivityCompleted" {
17964        let codec = event
17965            .payload
17966            .get("payload_codec")
17967            .and_then(Value::as_str)
17968            .unwrap_or(fallback_codec);
17969        return Ok(Ok(decode_wire_avro_value(
17970            event.payload.get("result").unwrap_or(&Value::Null),
17971            codec,
17972        )?));
17973    }
17974
17975    let payload = &event.payload;
17976    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
17977        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
17978        "ActivityCancelled" => (
17979            ActivityFailureKind::Cancelled,
17980            "cancelled",
17981            "activity was cancelled",
17982        ),
17983        "ActivityTimedOut" => (
17984            ActivityFailureKind::TimedOut,
17985            "timeout",
17986            "activity timed out",
17987        ),
17988        _ => unreachable!("activity_outcome is called only for terminal activity events"),
17989    };
17990    let exception = payload
17991        .get("exception")
17992        .filter(|value| !value.is_null())
17993        .cloned();
17994    let failure_category = payload_string(payload, "failure_category");
17995    let timeout_kind = payload_string(payload, "timeout_kind");
17996    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
17997        ActivityFailureKind::Failed => failure_category
17998            .clone()
17999            .unwrap_or_else(|| fallback_reason.to_string()),
18000        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
18001        ActivityFailureKind::TimedOut => timeout_kind
18002            .clone()
18003            .unwrap_or_else(|| fallback_reason.to_string()),
18004    });
18005    let message = payload_string(payload, "message")
18006        .or_else(|| {
18007            exception
18008                .as_ref()
18009                .and_then(|value| payload_string(value, "message"))
18010        })
18011        .unwrap_or_else(|| fallback_message.to_string());
18012
18013    Ok(Err(ActivityFailure {
18014        kind,
18015        reason,
18016        message,
18017        activity_execution_id: payload_string(payload, "activity_execution_id"),
18018        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
18019        activity_type: payload_string(payload, "activity_type")
18020            .or_else(|| payload_string(payload, "activity_name"))
18021            .or(recorded_activity_type),
18022        activity_class: payload_string(payload, "activity_class"),
18023        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
18024        failure_id: payload_string(payload, "failure_id"),
18025        failure_category,
18026        timeout_kind,
18027        non_retryable: payload
18028            .get("non_retryable")
18029            .and_then(Value::as_bool)
18030            .unwrap_or(false),
18031        exception_type: payload_string(payload, "exception_type").or_else(|| {
18032            exception
18033                .as_ref()
18034                .and_then(|value| payload_string(value, "type"))
18035        }),
18036        exception_class: payload_string(payload, "exception_class").or_else(|| {
18037            exception
18038                .as_ref()
18039                .and_then(|value| payload_string(value, "class"))
18040        }),
18041        code: payload
18042            .get("code")
18043            .filter(|value| !value.is_null())
18044            .cloned(),
18045        exception,
18046    }))
18047}
18048
18049type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
18050
18051fn child_workflow_outcomes(
18052    events: &[HistoryEvent],
18053    fallback_codec: &str,
18054    parent: WorkflowIdentity,
18055) -> Result<Vec<ChildWorkflowOutcome>> {
18056    let mut outcomes = Vec::new();
18057
18058    for event in events {
18059        let kind = match event.event_type.as_str() {
18060            "ChildRunCompleted" => None,
18061            "ChildRunFailed" => Some((
18062                ChildWorkflowFailureKind::Failed,
18063                "child_workflow",
18064                "child workflow failed",
18065            )),
18066            "ChildRunCancelled" => Some((
18067                ChildWorkflowFailureKind::Cancelled,
18068                "cancelled",
18069                "child workflow was cancelled",
18070            )),
18071            "ChildRunTerminated" => Some((
18072                ChildWorkflowFailureKind::Terminated,
18073                "terminated",
18074                "child workflow was terminated",
18075            )),
18076            _ => continue,
18077        };
18078        let payload = &event.payload;
18079        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
18080        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
18081        let child_workflow_type = payload_string(payload, "child_workflow_type");
18082
18083        if let Some((kind, reason, fallback_message)) = kind {
18084            let exception = payload
18085                .get("exception")
18086                .filter(|value| !value.is_null())
18087                .cloned();
18088            let message = payload_string(payload, "message")
18089                .or_else(|| {
18090                    exception
18091                        .as_ref()
18092                        .and_then(|value| payload_string(value, "message"))
18093                })
18094                .unwrap_or_else(|| fallback_message.to_string());
18095            let exception_type = payload_string(payload, "exception_type").or_else(|| {
18096                exception
18097                    .as_ref()
18098                    .and_then(|value| payload_string(value, "type"))
18099            });
18100            let exception_class = payload_string(payload, "exception_class").or_else(|| {
18101                exception
18102                    .as_ref()
18103                    .and_then(|value| payload_string(value, "class"))
18104            });
18105            outcomes.push(Err(ChildWorkflowFailure {
18106                kind,
18107                reason: reason.to_string(),
18108                message,
18109                parent_workflow_id: parent.workflow_id.clone(),
18110                parent_workflow_run_id: parent.run_id.clone(),
18111                child_workflow_id,
18112                child_workflow_run_id,
18113                child_workflow_type,
18114                failure_id: payload_string(payload, "failure_id"),
18115                failure_category: payload_string(payload, "failure_category"),
18116                exception_type,
18117                exception_class,
18118                non_retryable: payload
18119                    .get("non_retryable")
18120                    .and_then(Value::as_bool)
18121                    .unwrap_or(false),
18122                code: payload
18123                    .get("code")
18124                    .filter(|value| !value.is_null())
18125                    .cloned(),
18126                exception,
18127            }));
18128            continue;
18129        }
18130
18131        let codec = payload
18132            .get("payload_codec")
18133            .and_then(Value::as_str)
18134            .unwrap_or(fallback_codec);
18135        let result = payload
18136            .get("result")
18137            .or_else(|| payload.get("output"))
18138            .unwrap_or(&Value::Null);
18139        outcomes.push(Ok(ChildWorkflowAvroResult {
18140            parent: parent.clone(),
18141            child: WorkflowIdentity {
18142                workflow_id: child_workflow_id,
18143                run_id: child_workflow_run_id,
18144            },
18145            child_workflow_type,
18146            result: decode_wire_avro_value(result, codec)?,
18147        }));
18148    }
18149
18150    Ok(outcomes)
18151}
18152
18153fn payload_string(payload: &Value, key: &str) -> Option<String> {
18154    payload
18155        .get(key)
18156        .and_then(Value::as_str)
18157        .filter(|value| !value.is_empty())
18158        .map(str::to_string)
18159}
18160
18161fn recorded_activity_failure_boundary(
18162    ctx: &WorkflowContext,
18163    error: &Error,
18164) -> Option<(u64, String)> {
18165    let Error::ActivityFailed(failure) = error else {
18166        return None;
18167    };
18168    if failure.kind != ActivityFailureKind::Failed {
18169        return None;
18170    }
18171    let activity_execution_id = failure
18172        .activity_execution_id
18173        .as_deref()
18174        .filter(|value| !value.is_empty())?;
18175    let state = ctx.state.lock().ok()?;
18176    let mut matches = state.recorded_commands.iter().filter_map(|command| {
18177        let RecordedCommand::Activity {
18178            sequence,
18179            outcome: Some(Err(recorded_failure)),
18180            ..
18181        } = command
18182        else {
18183            return None;
18184        };
18185        (*sequence > 0 && recorded_failure == failure)
18186            .then_some((*sequence, activity_execution_id.to_string()))
18187    });
18188    let boundary = matches.next()?;
18189    matches.next().is_none().then_some(boundary)
18190}
18191
18192fn workflow_failure_command(
18193    error: &Error,
18194    failed_activity_boundary: Option<(u64, String)>,
18195) -> Value {
18196    let (exception_type, exception_class, properties) = match error {
18197        Error::NexusOperationFailed(failure) => (
18198            "NexusOperationFailed",
18199            "durable_workflow::NexusOperationFailure",
18200            json!({"service_call_id":failure.service_call_id, "status":failure.status,
18201                "caller_observed_error_type":failure.exception_type, "service_exception":failure.exception}),
18202        ),
18203        Error::ActivityFailed(failure) => (
18204            match failure.kind {
18205                ActivityFailureKind::Failed => "ActivityFailed",
18206                ActivityFailureKind::Cancelled => "ActivityCancelled",
18207                ActivityFailureKind::TimedOut => "ActivityTimedOut",
18208            },
18209            "durable_workflow::ActivityFailure",
18210            json!({
18211                "reason": failure.reason,
18212                "activity_execution_id": failure.activity_execution_id,
18213                "activity_attempt_id": failure.activity_attempt_id,
18214                "activity_type": failure.activity_type,
18215                "activity_class": failure.activity_class,
18216                "attempt_number": failure.attempt_number,
18217                "failure_id": failure.failure_id,
18218                "failure_category": failure.failure_category,
18219                "timeout_kind": failure.timeout_kind,
18220                "activity_non_retryable": failure.non_retryable,
18221                "activity_exception_type": failure.exception_type,
18222                "activity_exception_class": failure.exception_class,
18223                "activity_code": failure.code,
18224                "activity_exception": failure.exception,
18225            }),
18226        ),
18227        Error::ChildWorkflowFailed(failure) => (
18228            match failure.kind {
18229                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
18230                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
18231                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
18232            },
18233            "durable_workflow::ChildWorkflowFailure",
18234            json!({
18235                "reason": failure.reason,
18236                "parent_workflow_id": failure.parent_workflow_id,
18237                "parent_workflow_run_id": failure.parent_workflow_run_id,
18238                "child_workflow_id": failure.child_workflow_id,
18239                "child_workflow_run_id": failure.child_workflow_run_id,
18240                "child_workflow_type": failure.child_workflow_type,
18241                "failure_id": failure.failure_id,
18242                "failure_category": failure.failure_category,
18243                "child_exception_type": failure.exception_type,
18244                "child_exception_class": failure.exception_class,
18245                "child_non_retryable": failure.non_retryable,
18246                "child_code": failure.code,
18247                "child_exception": failure.exception,
18248            }),
18249        ),
18250        Error::ParallelFailed(failure) => (
18251            "ParallelFailed",
18252            "durable_workflow::ParallelFailure",
18253            json!({
18254                "parallel_group_id": failure.group_id,
18255                "parallel_member_path": failure.member_path,
18256                "parallel_group_path": failure.group_path,
18257                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
18258                "cause_type": workflow_error_type(&failure.cause),
18259                "cause_message": failure.cause.to_string(),
18260            }),
18261        ),
18262        Error::SagaCompensationFailed(failure) => (
18263            "SagaCompensationFailed",
18264            "durable_workflow::SagaCompensationFailure",
18265            json!({
18266                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
18267                "initiating_failure_message": failure.initiating_failure.to_string(),
18268                "compensation_activity_type": failure.compensation_activity_type,
18269                "compensation_registration_order": failure.compensation_registration_order,
18270                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
18271                "compensation_failure_message": failure.compensation_failure.to_string(),
18272            }),
18273        ),
18274        Error::WorkflowCancellationRequested(_) => (
18275            "WorkflowCancellationRequested",
18276            "durable_workflow::WorkflowCancellationRequested",
18277            json!({"reason": "cancelled"}),
18278        ),
18279        Error::CooperativeCancellationRequested(cancellation) => (
18280            "WorkflowCancellationRequested",
18281            "durable_workflow::CooperativeCancellationRequested",
18282            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
18283                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
18284        ),
18285        Error::CancellationScopeRequested(cancellation) => (
18286            "WorkflowCancellationRequested",
18287            "durable_workflow::CancellationScopeRequested",
18288            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
18289                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
18290                "cancellation":cancellation.context.to_value()}),
18291        ),
18292        Error::NonDeterministicReplay(_) => (
18293            "NonDeterministicReplay",
18294            "durable_workflow::Error",
18295            Value::Null,
18296        ),
18297        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
18298    };
18299    let non_retryable = match error {
18300        Error::ActivityFailed(failure) => failure.non_retryable,
18301        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
18302        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
18303        Error::SagaCompensationFailed(failure) => {
18304            workflow_error_non_retryable(&failure.compensation_failure)
18305        }
18306        Error::WorkflowCancellationRequested(_)
18307        | Error::CooperativeCancellationRequested(_)
18308        | Error::CancellationScopeRequested(_) => true,
18309        Error::NonDeterministicReplay(_) => true,
18310        _ => false,
18311    };
18312
18313    let mut command = json!({
18314        "type": "fail_workflow",
18315        "message": error.to_string(),
18316        "exception_type": exception_type,
18317        "exception_class": exception_class,
18318        "non_retryable": non_retryable,
18319        "exception": {
18320            "type": exception_type,
18321            "class": exception_class,
18322            "message": error.to_string(),
18323            "properties": properties,
18324        }
18325    });
18326
18327    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
18328        command["failed_step_sequence"] = json!(sequence);
18329        command["failed_activity_execution_id"] = json!(activity_execution_id);
18330    }
18331
18332    command
18333}
18334
18335fn workflow_error_type(error: &Error) -> &'static str {
18336    match error {
18337        Error::NexusOperationFailed(_) => "NexusOperationFailed",
18338        Error::ActivityFailed(failure) => match failure.kind {
18339            ActivityFailureKind::Failed => "ActivityFailed",
18340            ActivityFailureKind::Cancelled => "ActivityCancelled",
18341            ActivityFailureKind::TimedOut => "ActivityTimedOut",
18342        },
18343        Error::ChildWorkflowFailed(failure) => match failure.kind {
18344            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
18345            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
18346            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
18347        },
18348        Error::ParallelFailed(_) => "ParallelFailed",
18349        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
18350        Error::WorkflowCancellationRequested(_)
18351        | Error::CooperativeCancellationRequested(_)
18352        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
18353        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
18354        _ => "RustWorkflowError",
18355    }
18356}
18357
18358fn workflow_error_non_retryable(error: &Error) -> bool {
18359    match error {
18360        Error::ActivityFailed(failure) => failure.non_retryable,
18361        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
18362        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
18363        Error::SagaCompensationFailed(failure) => {
18364            workflow_error_non_retryable(&failure.compensation_failure)
18365        }
18366        Error::WorkflowCancellationRequested(_)
18367        | Error::CooperativeCancellationRequested(_)
18368        | Error::CancellationScopeRequested(_)
18369        | Error::NonDeterministicReplay(_) => true,
18370        _ => false,
18371    }
18372}
18373
18374fn workflow_task_integrity_error(error: &Error) -> bool {
18375    matches!(
18376        error,
18377        Error::NonDeterministicReplay(_)
18378            | Error::Protocol(_)
18379            | Error::CancellationScopeExecutionUnavailable
18380            | Error::MissingWorkflowCommandIdentity
18381            | Error::WorkflowStatePoisoned
18382    )
18383}
18384
18385fn decode_signal_event_arguments(
18386    event: &HistoryEvent,
18387    fallback_codec: &str,
18388) -> Result<Vec<AvroValue>> {
18389    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
18390    validate_payload_codec(codec)?;
18391    let raw = signal_history_payload(&event.payload);
18392    let decoded = match raw.filter(|value| !value.is_null()) {
18393        Some(value) => decode_wire_avro_value(value, codec)?,
18394        None => AvroValue::Array(Vec::new()),
18395    };
18396    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
18397        unreachable!("normalize_avro_arguments always returns an array");
18398    };
18399    Ok(arguments)
18400}
18401
18402fn decode_update_event_arguments(
18403    event: &HistoryEvent,
18404    fallback_codec: &str,
18405) -> Result<Vec<AvroValue>> {
18406    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
18407    validate_payload_codec(codec)?;
18408    let decoded = match event
18409        .payload
18410        .get("arguments")
18411        .filter(|value| !value.is_null())
18412    {
18413        Some(value) => decode_wire_avro_value(value, codec)?,
18414        None => AvroValue::Array(Vec::new()),
18415    };
18416    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
18417        unreachable!("normalize_avro_arguments always returns an array");
18418    };
18419    Ok(arguments)
18420}
18421
18422fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
18423    let Some(export_events) = task
18424        .history_export
18425        .as_ref()
18426        .and_then(|export| export.get("history_events"))
18427        .and_then(Value::as_array)
18428    else {
18429        return Ok(());
18430    };
18431
18432    if export_events.len() > task.history_events.len() {
18433        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
18434    }
18435
18436    Ok(())
18437}
18438
18439fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
18440    let Some(export) = task.history_export.as_ref() else {
18441        return Ok(());
18442    };
18443    let signals = export
18444        .get("signals")
18445        .and_then(Value::as_array)
18446        .cloned()
18447        .unwrap_or_default();
18448    let activities = export
18449        .get("activities")
18450        .and_then(Value::as_array)
18451        .cloned()
18452        .unwrap_or_default();
18453    let export_codec = export
18454        .get("payloads")
18455        .and_then(|payloads| payloads.get("codec"))
18456        .and_then(Value::as_str)
18457        .unwrap_or(&task.payload_codec)
18458        .to_string();
18459    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
18460
18461    for event in &mut task.history_events {
18462        if event.event_type == "ActivityCompleted" {
18463            let sequence = event
18464                .payload
18465                .get("sequence")
18466                .or_else(|| event.payload.get("workflow_sequence"))
18467                .and_then(value_as_u64);
18468            let Some(activity) = sequence.and_then(|sequence| {
18469                activities.iter().find(|activity| {
18470                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
18471                })
18472            }) else {
18473                continue;
18474            };
18475            let Some(payload) = event.payload.as_object_mut() else {
18476                continue;
18477            };
18478            if missing_payload(payload.get("result")) {
18479                if let Some(result) = activity
18480                    .get("result")
18481                    .filter(|value| !missing_payload(Some(value)))
18482                {
18483                    payload.insert("result".to_string(), result.clone());
18484                }
18485            }
18486            for field in ["payload_codec", "activity_type"] {
18487                if payload
18488                    .get(field)
18489                    .and_then(Value::as_str)
18490                    .unwrap_or_default()
18491                    .is_empty()
18492                {
18493                    if let Some(value) = activity.get(field) {
18494                        payload.insert(field.to_string(), value.clone());
18495                    }
18496                }
18497            }
18498            continue;
18499        }
18500
18501        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
18502            continue;
18503        }
18504        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
18505        let command_id = event
18506            .payload
18507            .get("workflow_command_id")
18508            .or_else(|| event.raw.get("workflow_command_id"))
18509            .and_then(Value::as_str);
18510        let signal_name = event
18511            .payload
18512            .get("signal_name")
18513            .and_then(Value::as_str)
18514            .unwrap_or_default()
18515            .to_string();
18516        let matched = signals
18517            .iter()
18518            .find(|signal| {
18519                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
18520            })
18521            .or_else(|| {
18522                signals.iter().find(|signal| {
18523                    command_id.is_some()
18524                        && signal.get("command_id").and_then(Value::as_str) == command_id
18525                })
18526            })
18527            .or_else(|| {
18528                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
18529                let signal = signals
18530                    .iter()
18531                    .filter(|signal| {
18532                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
18533                    })
18534                    .nth(*offset);
18535                if signal.is_some() {
18536                    *offset += 1;
18537                }
18538                signal
18539            });
18540        let Some(signal) = matched else {
18541            continue;
18542        };
18543        let signal_codec = signal
18544            .get("payload_codec")
18545            .and_then(Value::as_str)
18546            .unwrap_or(&export_codec);
18547        let Some(payload) = event.payload.as_object_mut() else {
18548            continue;
18549        };
18550        if missing_payload(payload.get("arguments")) {
18551            if let Some(arguments) = signal
18552                .get("arguments")
18553                .filter(|value| !missing_payload(Some(value)))
18554            {
18555                let envelope = match arguments {
18556                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
18557                    other => other.clone(),
18558                };
18559                payload.insert("arguments".to_string(), envelope);
18560            }
18561        }
18562        if payload
18563            .get("payload_codec")
18564            .and_then(Value::as_str)
18565            .unwrap_or_default()
18566            .is_empty()
18567        {
18568            payload.insert("payload_codec".to_string(), json!(signal_codec));
18569        }
18570    }
18571
18572    Ok(())
18573}
18574
18575fn missing_payload(value: Option<&Value>) -> bool {
18576    match value {
18577        None | Some(Value::Null) => true,
18578        Some(Value::String(value)) => value.is_empty(),
18579        Some(_) => false,
18580    }
18581}
18582
18583fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
18584    history_signal_events(
18585        &task.history_events,
18586        task.history_export.as_ref(),
18587        &task.payload_codec,
18588    )
18589}
18590
18591fn history_signal_events(
18592    history_events: &[HistoryEvent],
18593    history_export: Option<&Value>,
18594    payload_codec: &str,
18595) -> Result<Vec<QuerySignal>> {
18596    let export_signals = history_export
18597        .and_then(|export| export.get("signals"))
18598        .and_then(Value::as_array)
18599        .cloned()
18600        .unwrap_or_default();
18601    let export_codec = history_export
18602        .and_then(|export| export.get("payloads"))
18603        .and_then(|payloads| payloads.get("codec"))
18604        .and_then(Value::as_str)
18605        .unwrap_or(payload_codec);
18606    let mut name_offsets: HashMap<String, usize> = HashMap::new();
18607    let mut signals: Vec<QuerySignal> = Vec::new();
18608    let mut signal_indices = HashMap::new();
18609    let mut command_indices = HashMap::new();
18610
18611    for event in history_events {
18612        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
18613            continue;
18614        }
18615
18616        let name = event
18617            .payload
18618            .get("signal_name")
18619            .and_then(Value::as_str)
18620            .unwrap_or_default();
18621        if name.is_empty() {
18622            continue;
18623        }
18624        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
18625        let command_id = event
18626            .payload
18627            .get("workflow_command_id")
18628            .or_else(|| event.raw.get("workflow_command_id"))
18629            .and_then(Value::as_str);
18630        let matched_export = export_signals
18631            .iter()
18632            .find(|candidate| {
18633                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
18634            })
18635            .or_else(|| {
18636                export_signals.iter().find(|candidate| {
18637                    command_id.is_some()
18638                        && candidate.get("command_id").and_then(Value::as_str) == command_id
18639                })
18640            })
18641            .or_else(|| {
18642                let offset = name_offsets.entry(name.to_string()).or_default();
18643                let candidate = export_signals
18644                    .iter()
18645                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
18646                    .nth(*offset);
18647                if candidate.is_some() {
18648                    *offset += 1;
18649                }
18650                candidate
18651            });
18652        let codec = event
18653            .payload
18654            .get("payload_codec")
18655            .and_then(Value::as_str)
18656            .or_else(|| {
18657                matched_export
18658                    .and_then(|signal| signal.get("payload_codec"))
18659                    .and_then(Value::as_str)
18660            })
18661            .unwrap_or(export_codec);
18662        let raw_arguments = signal_history_payload(&event.payload)
18663            .filter(|value| !value.is_null())
18664            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
18665        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
18666        let workflow_sequence = event
18667            .payload
18668            .get("workflow_sequence")
18669            .and_then(value_as_u64)
18670            .or_else(|| {
18671                matched_export
18672                    .and_then(|signal| signal.get("workflow_sequence"))
18673                    .and_then(value_as_u64)
18674            });
18675
18676        let id = signal_id.or_else(|| {
18677            matched_export
18678                .and_then(|signal| signal.get("id"))
18679                .and_then(Value::as_str)
18680        });
18681        let command_id = command_id.or_else(|| {
18682            matched_export
18683                .and_then(|signal| signal.get("command_id"))
18684                .and_then(Value::as_str)
18685        });
18686        let duplicate = id
18687            .and_then(|id| signal_indices.get(id))
18688            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
18689            .copied();
18690        let index = duplicate.unwrap_or(signals.len());
18691        if let Some(index) = duplicate {
18692            let original = &mut signals[index];
18693            let same_arguments = if event.event_type == "SignalApplied" {
18694                if let Some(value) = event.payload.get("value") {
18695                    let expected = match original.avro_arguments.as_slice() {
18696                        [] => AvroValue::Boolean(true),
18697                        [value] => value.clone(),
18698                        values => AvroValue::Array(values.to_vec()),
18699                    };
18700                    let applied = decode_wire_avro_value(value, codec)?;
18701                    applied == expected
18702                        || applied == AvroValue::Array(original.avro_arguments.clone())
18703                } else {
18704                    original.avro_arguments == avro_arguments
18705                }
18706            } else {
18707                original.avro_arguments == avro_arguments
18708            };
18709            if original.name != name
18710                || !same_arguments
18711                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
18712            {
18713                return Err(Error::Codec("conflicting committed signal identity".into()));
18714            }
18715            if original.id.is_none() {
18716                original.id = id.map(str::to_string);
18717            }
18718            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
18719        } else {
18720            signals.push(QuerySignal {
18721                id: id.map(str::to_string),
18722                name: name.to_string(),
18723                arguments,
18724                avro_arguments,
18725                workflow_sequence,
18726            });
18727        }
18728        if let Some(id) = id {
18729            signal_indices.insert(id.to_string(), index);
18730        }
18731        if let Some(id) = command_id {
18732            command_indices.insert(id.to_string(), index);
18733        }
18734    }
18735
18736    if signals.is_empty() {
18737        for signal in export_signals {
18738            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
18739                continue;
18740            }
18741            let Some(name) = signal.get("name").and_then(Value::as_str) else {
18742                continue;
18743            };
18744            let codec = signal
18745                .get("payload_codec")
18746                .and_then(Value::as_str)
18747                .unwrap_or(export_codec);
18748            let (arguments, avro_arguments) =
18749                decode_query_signal_arguments(signal.get("arguments"), codec)?;
18750            signals.push(QuerySignal {
18751                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
18752                name: name.to_string(),
18753                arguments,
18754                avro_arguments,
18755                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
18756            });
18757        }
18758        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
18759    }
18760
18761    Ok(signals)
18762}
18763
18764fn decode_query_signal_arguments(
18765    raw: Option<&Value>,
18766    codec: &str,
18767) -> Result<(Vec<Value>, Vec<AvroValue>)> {
18768    validate_payload_codec(codec)?;
18769    let decoded = match raw.filter(|value| !value.is_null()) {
18770        Some(value) => decode_wire_avro_value(value, codec)?,
18771        None => AvroValue::Array(Vec::new()),
18772    };
18773    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
18774        unreachable!("normalize_avro_arguments always returns an array");
18775    };
18776    let arguments = avro_arguments
18777        .iter()
18778        .cloned()
18779        .map(AvroValue::into_json)
18780        .collect::<Result<Vec<_>>>()?;
18781    Ok((arguments, avro_arguments))
18782}
18783
18784fn value_as_u64(value: &Value) -> Option<u64> {
18785    value
18786        .as_u64()
18787        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
18788}
18789
18790#[cfg(test)]
18791mod tests {
18792    use super::*;
18793    #[cfg(feature = "telemetry")]
18794    static OBSERVABILITY_PROPAGATOR_TEST_LOCK: tokio::sync::Mutex<()> =
18795        tokio::sync::Mutex::const_new(());
18796    mod activity_cancellation_policies;
18797    mod activity_lease_worker;
18798    mod cancellation_scope_admission;
18799    mod cancellation_scope_authoring;
18800    mod cancellation_scope_history;
18801    mod cancellation_scope_opening;
18802    mod cancellation_scope_replay;
18803    mod child_workflow_policies;
18804    mod cooperative_cancellation;
18805    mod local_activity;
18806    mod nexus;
18807    mod runtime_payloads;
18808    mod runtime_uploads;
18809    mod version_marker_contract;
18810    mod worker_capacity;
18811    mod worker_session;
18812    use std::{
18813        fs,
18814        io::{Read, Write},
18815        net::{SocketAddr, TcpListener, TcpStream},
18816        process::Command as ProcessCommand,
18817        sync::atomic::AtomicUsize,
18818        thread,
18819    };
18820
18821    #[derive(Clone, Copy, Debug)]
18822    enum InvalidTaskPayloadCodec {
18823        Missing,
18824        Null,
18825        NonString,
18826    }
18827
18828    impl InvalidTaskPayloadCodec {
18829        fn label(self) -> &'static str {
18830            match self {
18831                Self::Missing => "missing",
18832                Self::Null => "null",
18833                Self::NonString => "non-string",
18834            }
18835        }
18836
18837        fn apply(self, task: &mut Value) {
18838            let task = task.as_object_mut().expect("task fixture object");
18839            match self {
18840                Self::Missing => {
18841                    task.remove("payload_codec");
18842                }
18843                Self::Null => {
18844                    task.insert("payload_codec".to_string(), Value::Null);
18845                }
18846                Self::NonString => {
18847                    task.insert("payload_codec".to_string(), json!(42));
18848                }
18849            }
18850        }
18851    }
18852
18853    fn fixture_envelope(value: Value) -> Value {
18854        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
18855    }
18856
18857    fn fixture_blob(value: Value) -> String {
18858        encode_payload(&value, DEFAULT_CODEC)
18859            .expect("encode Avro test fixture")
18860            .blob
18861    }
18862
18863    #[test]
18864    fn client_builder_rejects_the_sdk_owned_api_suffix() {
18865        for base_url in [
18866            "http://127.0.0.1:8080/api",
18867            "http://localhost:8080/api/",
18868            "https://runtime.example.test/namespaces/orders/api",
18869        ] {
18870            let error = Client::builder(base_url)
18871                .build()
18872                .expect_err("SDK-owned /api suffix must be rejected during build");
18873
18874            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
18875            assert!(
18876                error.to_string().contains("SDK appends /api automatically"),
18877                "the validation error must explain how to fix the endpoint"
18878            );
18879        }
18880    }
18881
18882    #[test]
18883    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
18884        for (base_url, expected) in [
18885            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
18886            (
18887                "http://localhost:8080/durable-workflow/",
18888                "http://localhost:8080/durable-workflow",
18889            ),
18890            (
18891                "https://runtime.example.test/namespaces/orders",
18892                "https://runtime.example.test/namespaces/orders",
18893            ),
18894            (
18895                "https://runtime.example.test/gateway/api/namespaces/orders",
18896                "https://runtime.example.test/gateway/api/namespaces/orders",
18897            ),
18898            (
18899                "https://api.example.test/runtime/orders/",
18900                "https://api.example.test/runtime/orders",
18901            ),
18902        ] {
18903            let client = Client::builder(base_url)
18904                .build()
18905                .expect("Server and Cloud runtime base URL must remain valid");
18906
18907            assert_eq!(client.base_url, expected);
18908        }
18909    }
18910
18911    #[test]
18912    fn workflow_completion_uses_the_additive_command_protocol_floor() {
18913        assert_eq!(
18914            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
18915            MINIMUM_WORKER_PROTOCOL_VERSION
18916        );
18917        assert_eq!(
18918            workflow_completion_protocol_version(&[json!({
18919                "type": "upsert_search_attributes",
18920                "attributes": {"OrderStatus": "waiting"},
18921            })]),
18922            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
18923        );
18924        assert_eq!(
18925            workflow_completion_protocol_version(&[json!({
18926                "type": "upsert_search_attributes",
18927                "attributes": {"OrderStatus": "waiting"},
18928                "attribute_types": {"OrderStatus": "keyword"},
18929            })]),
18930            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
18931        );
18932        assert_eq!(
18933            workflow_completion_protocol_version(&[
18934                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
18935                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18936            ]),
18937            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
18938        );
18939        assert_eq!(
18940            workflow_completion_protocol_version(&[
18941                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
18942                json!({"type": "open_condition_wait", "condition_key": "ready"}),
18943            ]),
18944            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
18945        );
18946        assert_eq!(
18947            workflow_completion_protocol_version(&[json!({
18948                "type": "open_condition_wait",
18949                "condition_wait_occurrence_id": "rust:condition-wait:0",
18950                "condition_key": "ready",
18951            })]),
18952            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18953        );
18954        assert_eq!(
18955            workflow_completion_protocol_version_with_message_streams(
18956                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
18957                true,
18958            ),
18959            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
18960        );
18961        assert_eq!(
18962            workflow_completion_protocol_version_with_message_streams(
18963                &[json!({
18964                    "type": "open_condition_wait",
18965                    "condition_wait_occurrence_id": "rust:condition-wait:0",
18966                    "condition_key": "ready",
18967                })],
18968                true,
18969            ),
18970            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
18971        );
18972    }
18973
18974    #[test]
18975    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
18976        let manifest = portable_worker_affinity_capability_manifest();
18977
18978        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
18979            assert_eq!(manifest[capability]["supported"], json!(false));
18980            assert_eq!(
18981                manifest[capability]["minimum_protocol_version"],
18982                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
18983            );
18984            assert!(manifest[capability]["reason"]
18985                .as_str()
18986                .is_some_and(|reason| !reason.is_empty()));
18987        }
18988    }
18989
18990    fn typed_fidelity_probe() -> AvroValue {
18991        AvroValue::Map(BTreeMap::from([
18992            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
18993            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
18994            (
18995                "numeric".to_string(),
18996                AvroValue::Map(BTreeMap::from([
18997                    ("0".to_string(), AvroValue::String("zero".to_string())),
18998                    ("1".to_string(), AvroValue::String("one".to_string())),
18999                ])),
19000            ),
19001            (
19002                "nested".to_string(),
19003                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
19004                    "enabled".to_string(),
19005                    AvroValue::Boolean(true),
19006                )]))]),
19007            ),
19008            (
19009                "projection_collisions".to_string(),
19010                AvroValue::Array(projection_collision_probe()),
19011            ),
19012        ]))
19013    }
19014
19015    fn projection_collision_probe() -> Vec<AvroValue> {
19016        vec![
19017            AvroValue::Map(BTreeMap::from([
19018                ("$type".to_string(), AvroValue::String("bytes".to_string())),
19019                (
19020                    "base64".to_string(),
19021                    AvroValue::String("ordinary user text".to_string()),
19022                ),
19023            ])),
19024            AvroValue::Map(BTreeMap::from([
19025                ("$type".to_string(), AvroValue::String("map".to_string())),
19026                (
19027                    "entries".to_string(),
19028                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
19029                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
19030                        (
19031                            "value".to_string(),
19032                            AvroValue::String("user map".to_string()),
19033                        ),
19034                    ]))]),
19035                ),
19036            ])),
19037        ]
19038    }
19039
19040    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19041    struct TypedContract {
19042        nested: TypedNested,
19043        mode: TypedMode,
19044        optional: Option<String>,
19045        absent: Option<String>,
19046        items: Vec<i64>,
19047        labels: BTreeMap<String, String>,
19048        bytes: serde_bytes::ByteBuf,
19049        signed: i64,
19050        finite: f64,
19051    }
19052
19053    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19054    struct TypedNested {
19055        enabled: bool,
19056    }
19057
19058    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
19059    enum TypedMode {
19060        Detailed { label: String },
19061    }
19062
19063    fn typed_contract() -> TypedContract {
19064        TypedContract {
19065            nested: TypedNested { enabled: true },
19066            mode: TypedMode::Detailed {
19067                label: "compiler-checked".to_string(),
19068            },
19069            optional: Some("present".to_string()),
19070            absent: None,
19071            items: vec![i64::MIN, 0, i64::MAX],
19072            labels: BTreeMap::from([
19073                ("language".to_string(), "rust".to_string()),
19074                ("wire".to_string(), "avro".to_string()),
19075            ]),
19076            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
19077            signed: -9_223_372_036_854_775_000,
19078            finite: 12.5,
19079        }
19080    }
19081
19082    #[derive(Clone, Debug, Default, PartialEq)]
19083    struct ReplayCounterState {
19084        loaded: Option<String>,
19085        count: i64,
19086        finished: bool,
19087    }
19088
19089    fn replay_counter_worker() -> Worker {
19090        let client = Client::new("http://127.0.0.1:8080").expect("client");
19091        let mut worker = Worker::new(client, "rust-workers");
19092        worker.register_replayed_workflow(
19093            "replay-counter",
19094            ReplayCounterState::default,
19095            |ctx, _input, state| async move {
19096                let loaded = ctx.activity("load-counter", json!([])).await?;
19097                state.update(|current| {
19098                    current.loaded = loaded.as_str().map(str::to_string);
19099                })?;
19100                for _ in 0..2 {
19101                    let signal = ctx.wait_signal("increment").await?;
19102                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
19103                    state.update(|current| current.count += amount)?;
19104                }
19105                state.update(|current| current.finished = true)?;
19106                state.read(|current| Ok(json!(current.count)))?
19107            },
19108        );
19109        worker.register_replayed_query::<ReplayCounterState, _, _>(
19110            "replay-counter",
19111            "current",
19112            |_ctx, state, _args| async move {
19113                Ok(json!({
19114                    "loaded": state.loaded,
19115                    "count": state.count,
19116                    "finished": state.finished,
19117                }))
19118            },
19119        );
19120        worker.register_replayed_query::<ReplayCounterState, _, _>(
19121            "replay-counter",
19122            "detached-mutation",
19123            |_ctx, state, _args| async move {
19124                let mut detached = (*state).clone();
19125                detached.count = 999;
19126                Ok(json!(detached.count))
19127            },
19128        );
19129        worker.register_replayed_query::<ReplayCounterState, _, _>(
19130            "replay-counter",
19131            "failed-mutation",
19132            |_ctx, state, _args| async move {
19133                let mut detached = (*state).clone();
19134                detached.count = 999;
19135                Err(Error::WorkerLoop("query refused".to_string()))
19136            },
19137        );
19138        worker
19139    }
19140
19141    fn replay_counter_query(
19142        query_name: &str,
19143        history_events: Value,
19144        run_status: &str,
19145    ) -> QueryTask {
19146        let arguments = fixture_envelope(json!([]));
19147        serde_json::from_value(json!({
19148            "query_task_id": format!("query-{query_name}"),
19149            "workflow_type": "replay-counter",
19150            "query_name": query_name,
19151            "payload_codec": DEFAULT_CODEC,
19152            "workflow_arguments": arguments.clone(),
19153            "query_arguments": arguments,
19154            "history_events": history_events,
19155            "run_status": run_status,
19156        }))
19157        .expect("query task")
19158    }
19159
19160    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
19161        workflow_context_with_codec(history, DEFAULT_CODEC)
19162    }
19163
19164    fn workflow_context_with_codec(
19165        history: Vec<HistoryEvent>,
19166        payload_codec: &str,
19167    ) -> WorkflowContext {
19168        WorkflowContext {
19169            cancellation_scope_id: "root".into(),
19170            state: Arc::new(Mutex::new(
19171                WorkflowState::new_with_identity(
19172                    history,
19173                    None,
19174                    None,
19175                    "rust-workers".to_string(),
19176                    payload_codec.to_string(),
19177                    None,
19178                )
19179                .expect("valid workflow history"),
19180            )),
19181        }
19182    }
19183
19184    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
19185        HistoryEvent {
19186            event_type: event_type.to_string(),
19187            payload,
19188            raw: HashMap::new(),
19189        }
19190    }
19191
19192    fn parallel_path_entry(
19193        kind: &str,
19194        base: u64,
19195        size: usize,
19196        index: usize,
19197    ) -> ParallelGroupMetadata {
19198        parallel_group_entry(base, size, index, kind)
19199    }
19200
19201    fn parallel_history_event(
19202        event_type: &str,
19203        sequence: u64,
19204        identity_field: &str,
19205        identity: &str,
19206        path: Vec<ParallelGroupMetadata>,
19207        result: Option<Value>,
19208    ) -> HistoryEvent {
19209        let mut payload = serde_json::Map::from_iter([
19210            ("sequence".to_string(), json!(sequence)),
19211            (identity_field.to_string(), json!(identity)),
19212        ]);
19213        let inner = path.last().expect("parallel history path");
19214        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
19215        payload.insert("parallel_group_path".to_string(), json!(path));
19216        if let Some(result) = result {
19217            let field = if event_type == "ChildRunCompleted" {
19218                "result"
19219            } else {
19220                "result"
19221            };
19222            payload.insert(field.to_string(), fixture_envelope(result));
19223            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
19224        }
19225        history_event(event_type, Value::Object(payload))
19226    }
19227
19228    fn nested_parallel_operations() -> Vec<ParallelOperation> {
19229        vec![
19230            ParallelOperation::activity("first", json!([])),
19231            ParallelOperation::group(vec![
19232                ParallelOperation::child_workflow(
19233                    "second",
19234                    ChildWorkflowOptions::new("child-workers"),
19235                    json!([]),
19236                ),
19237                ParallelOperation::activity("third", json!([])),
19238            ]),
19239        ]
19240    }
19241
19242    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
19243        let outer = [
19244            parallel_path_entry("mixed", 1, 3, 0),
19245            parallel_path_entry("mixed", 1, 3, 1),
19246            parallel_path_entry("mixed", 1, 3, 2),
19247        ];
19248        [
19249            vec![outer[0].clone()],
19250            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
19251            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
19252        ]
19253    }
19254
19255    #[test]
19256    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
19257        let ctx = workflow_context(Vec::new());
19258        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19259        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19260
19261        assert!(matches!(
19262            call.as_mut().poll(&mut task_context),
19263            Poll::Pending
19264        ));
19265        let commands = ctx.take_commands().expect("parallel commands");
19266        assert_eq!(
19267            commands
19268                .iter()
19269                .map(|command| command["type"].as_str().unwrap_or_default())
19270                .collect::<Vec<_>>(),
19271            [
19272                "schedule_activity",
19273                "start_child_workflow",
19274                "schedule_activity"
19275            ]
19276        );
19277        let paths = nested_parallel_paths();
19278        for (command, path) in commands.iter().zip(paths) {
19279            assert_eq!(command["parallel_group_path"], json!(path));
19280            assert_eq!(
19281                command["parallel_group_id"],
19282                json!(path.last().expect("inner group").parallel_group_id)
19283            );
19284        }
19285    }
19286
19287    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
19288        let paths = nested_parallel_paths();
19289        let third = parallel_history_event(
19290            "ActivityCompleted",
19291            3,
19292            "activity_type",
19293            "third",
19294            paths[2].clone(),
19295            Some(json!("three")),
19296        );
19297        vec![
19298            parallel_history_event(
19299                "ActivityCompleted",
19300                1,
19301                "activity_type",
19302                "first",
19303                paths[0].clone(),
19304                Some(json!("one")),
19305            ),
19306            parallel_history_event(
19307                "ChildWorkflowScheduled",
19308                2,
19309                "child_workflow_type",
19310                "second",
19311                paths[1].clone(),
19312                None,
19313            ),
19314            parallel_history_event(
19315                "ChildRunCompleted",
19316                2,
19317                "child_workflow_type",
19318                "second",
19319                paths[1].clone(),
19320                Some(json!("two")),
19321            ),
19322            third.clone(),
19323            third,
19324        ]
19325    }
19326
19327    #[test]
19328    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
19329        for _restart_or_completed_replay in 0..2 {
19330            let ctx = workflow_context(completed_nested_parallel_history());
19331            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19332            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19333            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
19334                panic!("completed nested parallel history must replay");
19335            };
19336            assert_eq!(
19337                results,
19338                vec![
19339                    ParallelResult::Activity(json!("one")),
19340                    ParallelResult::Group(vec![
19341                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
19342                            parent: WorkflowIdentity {
19343                                workflow_id: None,
19344                                run_id: None,
19345                            },
19346                            child: WorkflowIdentity {
19347                                workflow_id: None,
19348                                run_id: None,
19349                            },
19350                            child_workflow_type: Some("second".to_string()),
19351                            result: json!("two"),
19352                        }),
19353                        ParallelResult::Activity(json!("three")),
19354                    ]),
19355                ]
19356            );
19357            assert!(ctx.take_commands().expect("commands").is_empty());
19358            ctx.ensure_history_consumed().expect("history consumed");
19359        }
19360    }
19361
19362    #[test]
19363    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
19364        let paths = nested_parallel_paths();
19365        let history = vec![
19366            parallel_history_event(
19367                "ActivityCompleted",
19368                1,
19369                "activity_type",
19370                "first",
19371                paths[0].clone(),
19372                Some(json!("one")),
19373            ),
19374            parallel_history_event(
19375                "ChildWorkflowScheduled",
19376                2,
19377                "child_workflow_type",
19378                "second",
19379                paths[1].clone(),
19380                None,
19381            ),
19382            parallel_history_event(
19383                "ChildRunFailed",
19384                2,
19385                "child_workflow_type",
19386                "second",
19387                paths[1].clone(),
19388                None,
19389            ),
19390            parallel_history_event(
19391                "ActivityCompleted",
19392                3,
19393                "activity_type",
19394                "third",
19395                paths[2].clone(),
19396                Some(json!("late")),
19397            ),
19398        ];
19399        let ctx = workflow_context(history);
19400        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19401        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19402        let outcome = call.as_mut().poll(&mut task_context);
19403        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
19404            panic!("one failed child must return a typed partial failure: {outcome:?}");
19405        };
19406        assert_eq!(failure.member_path, [1, 0]);
19407        assert_eq!(failure.group_id, "parallel-calls:1:3");
19408        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
19409        assert_eq!(
19410            failure
19411                .completed
19412                .iter()
19413                .map(|completion| completion.member_path.clone())
19414                .collect::<Vec<_>>(),
19415            [vec![0], vec![1, 1]]
19416        );
19417    }
19418
19419    #[test]
19420    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
19421        let paths = nested_parallel_paths();
19422        let history = vec![
19423            parallel_history_event(
19424                "ActivityScheduled",
19425                1,
19426                "activity_type",
19427                "first",
19428                paths[0].clone(),
19429                None,
19430            ),
19431            parallel_history_event(
19432                "ChildWorkflowScheduled",
19433                2,
19434                "child_workflow_type",
19435                "second",
19436                paths[1].clone(),
19437                None,
19438            ),
19439            parallel_history_event(
19440                "ActivityScheduled",
19441                3,
19442                "activity_type",
19443                "third",
19444                paths[2].clone(),
19445                None,
19446            ),
19447        ];
19448        for _restart in 0..2 {
19449            let ctx = workflow_context(history.clone());
19450            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
19451            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19452            let outcome = call.as_mut().poll(&mut task_context);
19453            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
19454            assert!(ctx.take_commands().expect("commands").is_empty());
19455        }
19456    }
19457
19458    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
19459        vec![selection_group_entry(
19460            1,
19461            2,
19462            index,
19463            "activity",
19464            &SelectionMemberMetadata {
19465                key: SelectionKey::Name(key.to_string()),
19466                index,
19467                base_sequence: index as u64 + 1,
19468                size: 1,
19469                kind: "activity".to_string(),
19470            },
19471        )]
19472    }
19473
19474    fn selection_activity_event(
19475        event_type: &str,
19476        index: usize,
19477        key: &str,
19478        result: Option<Value>,
19479    ) -> HistoryEvent {
19480        let sequence = index as u64 + 1;
19481        let mut event = parallel_history_event(
19482            event_type,
19483            sequence,
19484            "activity_type",
19485            &format!("{key}-activity"),
19486            selection_path(index, key),
19487            result,
19488        );
19489        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
19490        event.raw.insert(
19491            "id".to_string(),
19492            json!(if event_type == "ActivityCompleted" {
19493                format!("event-{key}")
19494            } else {
19495                format!("{event_type}-{key}")
19496            }),
19497        );
19498        event
19499    }
19500
19501    fn selection_winner_marker() -> HistoryEvent {
19502        history_event(
19503            "SelectionResolved",
19504            json!({
19505                "selection_group_id": "select-calls:1:2",
19506                "selection_group_base_sequence": 1,
19507                "selection_group_size": 2,
19508                "member_key": "fast",
19509                "member_index": 1,
19510                "member_base_sequence": 2,
19511                "member_size": 1,
19512                "operation_kind": "activity",
19513                "operation_identity": "activity-fast",
19514                "outcome": "completed",
19515                "resolution_event_id": "event-fast",
19516                "resolution_event_type": "ActivityCompleted",
19517            }),
19518        )
19519    }
19520
19521    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
19522        ctx.select_keyed(vec![
19523            (
19524                "slow",
19525                ParallelOperation::activity_with_options(
19526                    "slow-activity",
19527                    ActivityOptions::new().task_queue("default"),
19528                    json!([]),
19529                ),
19530            ),
19531            (
19532                "fast",
19533                ParallelOperation::activity_with_options(
19534                    "fast-activity",
19535                    ActivityOptions::new().task_queue("default"),
19536                    json!([]),
19537                ),
19538            ),
19539        ])
19540    }
19541
19542    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
19543        let ctx = workflow_context(history);
19544        let mut call = Box::pin(keyed_activity_selection(&ctx));
19545        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19546        let selected = match call.as_mut().poll(&mut task_context) {
19547            Poll::Ready(Ok(selected)) => selected,
19548            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
19549            Poll::Pending => panic!("persisted selection winner must replay without pending"),
19550        };
19551        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
19552        assert_eq!(
19553            selected.value,
19554            Some(ParallelResult::Activity(json!("winner-value")))
19555        );
19556        let slow = selected
19557            .handle(&SelectionKey::Name("slow".to_string()))
19558            .expect("slow handle")
19559            .clone();
19560        let mut await_slow = Box::pin(slow.await_result());
19561        assert!(matches!(
19562            await_slow.as_mut().poll(&mut task_context),
19563            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
19564        ));
19565        assert!(ctx.take_commands().expect("commands").is_empty());
19566    }
19567
19568    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
19569
19570    fn canonical_selection_history() -> Vec<HistoryEvent> {
19571        const FIXTURE: &[u8] =
19572            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
19573        assert_eq!(
19574            format!("{:x}", Sha256::digest(FIXTURE)),
19575            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
19576        );
19577        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
19578
19579        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
19580    }
19581
19582    #[test]
19583    fn selection_fresh_process_entrypoint() {
19584        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
19585            return;
19586        };
19587        let persisted = fs::read(path).expect("persisted selection history");
19588        assert_eq!(
19589            format!("{:x}", Sha256::digest(&persisted)),
19590            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
19591        );
19592        let fixture: Value =
19593            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
19594        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
19595            .expect("valid persisted selection history");
19596
19597        assert_persisted_selection_replay(history);
19598    }
19599
19600    #[test]
19601    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
19602        let ctx = workflow_context(Vec::new());
19603        let mut call = Box::pin(keyed_activity_selection(&ctx));
19604        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19605
19606        assert!(matches!(
19607            call.as_mut().poll(&mut task_context),
19608            Poll::Pending
19609        ));
19610        let commands = ctx.take_commands().expect("selection commands");
19611        assert_eq!(commands.len(), 2);
19612        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
19613        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
19614        assert!(commands.iter().all(|command| {
19615            command["parallel_group_id"] == json!("select-calls:1:2")
19616                && command["parallel_group_mode"] == json!("select")
19617        }));
19618    }
19619
19620    #[test]
19621    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
19622        let ctx = workflow_context(Vec::new());
19623        let mut invalid = Box::pin(ctx.select_keyed(vec![(
19624            "",
19625            ParallelOperation::activity("invalid", json!([])),
19626        )]));
19627        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19628        assert!(matches!(
19629            invalid.as_mut().poll(&mut task_context),
19630            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
19631                reason: "selection_key_invalid",
19632                ..
19633            })))
19634        ));
19635
19636        for invalid_key in [json!(""), json!(-1)] {
19637            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
19638            event.payload["selection_member_key"] = invalid_key.clone();
19639            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
19640            assert!(matches!(
19641                WorkflowState::new_with_identity(
19642                    vec![event],
19643                    None,
19644                    None,
19645                    "rust-workers".to_string(),
19646                    DEFAULT_CODEC.to_string(),
19647                    None,
19648                ),
19649                Err(Error::NonDeterministicReplay(_))
19650            ));
19651        }
19652    }
19653
19654    #[test]
19655    fn selection_preserves_valid_named_and_numeric_keys() {
19656        let ctx = workflow_context(Vec::new());
19657        let mut selection = Box::pin(ctx.select_keyed(vec![
19658            (
19659                SelectionKey::Index(0),
19660                ParallelOperation::activity("numeric", json!([])),
19661            ),
19662            (
19663                SelectionKey::Name("named".to_string()),
19664                ParallelOperation::timer(Duration::from_secs(1)),
19665            ),
19666        ]));
19667        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19668
19669        assert!(matches!(
19670            selection.as_mut().poll(&mut task_context),
19671            Poll::Pending
19672        ));
19673        let commands = ctx.take_commands().expect("selection commands");
19674        assert_eq!(commands[0]["selection_member_key"], json!(0));
19675        assert_eq!(commands[1]["selection_member_key"], json!("named"));
19676    }
19677
19678    #[test]
19679    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
19680        let history = canonical_selection_history();
19681        assert_persisted_selection_replay(history.clone());
19682
19683        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19684            .join("tests/fixtures/durable_selection_runtime_history.json");
19685        let output =
19686            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
19687                .args([
19688                    "--exact",
19689                    "tests::selection_fresh_process_entrypoint",
19690                    "--nocapture",
19691                ])
19692                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
19693                .output()
19694                .expect("run fresh selection replay process");
19695
19696        assert!(
19697            output.status.success(),
19698            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
19699            String::from_utf8_lossy(&output.stdout),
19700            String::from_utf8_lossy(&output.stderr),
19701        );
19702    }
19703
19704    #[test]
19705    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
19706        let mut history = canonical_selection_history();
19707        history.retain(|event| event.event_type != "SelectionResolved");
19708        let ctx = workflow_context(history);
19709        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19710        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19711
19712        assert!(matches!(
19713            selection.as_mut().poll(&mut task_context),
19714            Poll::Pending
19715        ));
19716        assert!(ctx.take_commands().expect("commands").is_empty());
19717        assert!(
19718            ctx.matched_recorded_pending()
19719                .expect("selection pending state"),
19720            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
19721        );
19722    }
19723
19724    #[test]
19725    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
19726        for (terminal_event, predicate_satisfied, timeout_seconds) in [
19727            ("ConditionWaitSatisfied", true, None),
19728            ("ConditionWaitTimedOut", false, Some(0)),
19729        ] {
19730            let member = SelectionMemberMetadata {
19731                key: SelectionKey::Name("condition".to_string()),
19732                index: 0,
19733                base_sequence: 1,
19734                size: 1,
19735                kind: "condition".to_string(),
19736            };
19737            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
19738            let mut payload = json!({
19739                "sequence": 1,
19740                "condition_wait_id": "condition-1",
19741                "condition_wait_occurrence_id": "rust:condition-wait:0",
19742                "condition_key": "ready",
19743                "condition_definition_fingerprint": "sha256:ready-v1",
19744                "parallel_group_path": path,
19745            });
19746            payload
19747                .as_object_mut()
19748                .expect("condition history payload")
19749                .extend(
19750                    serde_json::to_value(&path[0])
19751                        .expect("condition selection metadata")
19752                        .as_object()
19753                        .expect("condition selection metadata object")
19754                        .clone(),
19755                );
19756            if let Some(timeout_seconds) = timeout_seconds {
19757                payload["timeout_seconds"] = json!(timeout_seconds);
19758            }
19759            let history = vec![
19760                history_event("ConditionWaitOpened", payload.clone()),
19761                history_event(terminal_event, payload),
19762            ];
19763            let ctx = workflow_context(history);
19764            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
19765            if timeout_seconds.is_some() {
19766                options = options.timeout(Duration::ZERO);
19767            }
19768            let mut selection = Box::pin(ctx.select_keyed(vec![(
19769                "condition",
19770                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
19771            )]));
19772            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19773
19774            assert!(matches!(
19775                selection.as_mut().poll(&mut task_context),
19776                Poll::Pending
19777            ));
19778            assert!(ctx.take_commands().expect("commands").is_empty());
19779            assert!(
19780                ctx.matched_recorded_pending()
19781                    .expect("condition selection pending state"),
19782                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
19783            );
19784        }
19785    }
19786
19787    #[test]
19788    fn selection_immediate_condition_members_open_a_durable_wait() {
19789        for predicate_satisfied in [true, false] {
19790            let ctx = workflow_context(Vec::new());
19791            let mut selection = Box::pin(ctx.select_keyed(vec![(
19792                "condition",
19793                ParallelOperation::condition(
19794                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
19795                    move || Ok(predicate_satisfied),
19796                ),
19797            )]));
19798            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19799
19800            assert!(matches!(
19801                selection.as_mut().poll(&mut task_context),
19802                Poll::Pending
19803            ));
19804            let commands = ctx.take_commands().expect("condition selection command");
19805            assert_eq!(commands.len(), 1);
19806            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
19807            assert_eq!(commands[0]["timeout_seconds"], json!(0));
19808            assert_eq!(
19809                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
19810                json!("select")
19811            );
19812        }
19813    }
19814
19815    #[test]
19816    fn selection_loser_cancellation_is_explicit_and_idempotent() {
19817        let history = vec![
19818            selection_activity_event("ActivityScheduled", 0, "slow", None),
19819            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19820            selection_winner_marker(),
19821        ];
19822        let ctx = workflow_context(history.clone());
19823        let mut call = Box::pin(keyed_activity_selection(&ctx));
19824        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19825        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19826            panic!("winner must replay");
19827        };
19828        let slow = selected
19829            .handle(&SelectionKey::Name("slow".to_string()))
19830            .expect("slow handle")
19831            .clone();
19832        let mut cancel = Box::pin(slow.cancel());
19833        assert!(matches!(
19834            cancel.as_mut().poll(&mut task_context),
19835            Poll::Ready(Ok(()))
19836        ));
19837        assert!(matches!(
19838            cancel.as_mut().poll(&mut task_context),
19839            Poll::Ready(Ok(()))
19840        ));
19841        let mut outcome = Box::pin(slow.await_result());
19842        assert!(matches!(
19843            outcome.as_mut().poll(&mut task_context),
19844            Poll::Pending
19845        ));
19846        let commands = ctx.take_commands().expect("cancel command");
19847        assert_eq!(commands.len(), 1);
19848        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
19849        assert_eq!(commands[0]["member_key"], json!("slow"));
19850
19851        let mut cancelled_history = history;
19852        cancelled_history.push(history_event(
19853            "SelectionOperationCancelled",
19854            json!({
19855                "selection_group_id": "select-calls:1:2",
19856                "member_key": "slow",
19857                "member_index": 0,
19858                "member_base_sequence": 1,
19859                "member_size": 1,
19860                "operation_kind": "activity",
19861                "operation_identity": "activity-slow",
19862                "cancelled_at": "2026-08-27T00:00:00Z",
19863            }),
19864        ));
19865        let replayed = workflow_context(cancelled_history);
19866        let mut call = Box::pin(keyed_activity_selection(&replayed));
19867        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
19868            panic!("winner must replay after cancellation");
19869        };
19870        let slow = selected
19871            .handle(&SelectionKey::Name("slow".to_string()))
19872            .expect("slow handle")
19873            .clone();
19874        let mut cancel = Box::pin(slow.cancel());
19875        assert!(matches!(
19876            cancel.as_mut().poll(&mut task_context),
19877            Poll::Ready(Ok(()))
19878        ));
19879        assert!(replayed.take_commands().expect("commands").is_empty());
19880    }
19881
19882    #[test]
19883    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
19884        let base_history = vec![
19885            selection_activity_event("ActivityScheduled", 0, "slow", None),
19886            selection_activity_event("ActivityScheduled", 1, "fast", None),
19887            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19888            selection_winner_marker(),
19889        ];
19890        for (field, corrupt) in [
19891            ("member_key", json!("fast")),
19892            ("member_index", json!(1)),
19893            ("member_base_sequence", json!(3)),
19894            ("member_size", json!(2)),
19895            ("operation_kind", json!("timer")),
19896            ("operation_identity", json!("forged")),
19897        ] {
19898            let mut cancellation = json!({
19899                "selection_group_id": "select-calls:1:2",
19900                "member_key": "slow",
19901                "member_index": 0,
19902                "member_base_sequence": 1,
19903                "member_size": 1,
19904                "operation_kind": "activity",
19905                "operation_identity": "activity-slow",
19906            });
19907            cancellation[field] = corrupt;
19908            let mut history = base_history.clone();
19909            history.push(history_event("SelectionOperationCancelled", cancellation));
19910            let ctx = workflow_context(history);
19911            let mut selection = Box::pin(keyed_activity_selection(&ctx));
19912            let mut task_context = TaskContext::from_waker(noop_waker_ref());
19913
19914            assert!(matches!(
19915                selection.as_mut().poll(&mut task_context),
19916                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19917            ));
19918        }
19919    }
19920
19921    #[test]
19922    fn selection_child_identity_prefers_the_durable_run_id() {
19923        let ctx = workflow_context(vec![history_event(
19924            "ChildWorkflowScheduled",
19925            json!({
19926                "sequence": 1,
19927                "child_workflow_type": "child",
19928                "child_workflow_instance_id": "child-instance",
19929                "child_workflow_run_id": "child-run",
19930            }),
19931        )]);
19932        let state = ctx.state.lock().expect("workflow state");
19933
19934        assert_eq!(
19935            selection_operation_identity(&state, "child", 1, 1),
19936            "child-run"
19937        );
19938    }
19939
19940    #[test]
19941    fn selection_activity_identity_requires_canonical_execution_id() {
19942        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
19943        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
19944        let mut fast_completed =
19945            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
19946        for event in [&mut fast_open, &mut fast_completed] {
19947            event
19948                .payload
19949                .as_object_mut()
19950                .expect("activity payload")
19951                .remove("activity_execution_id");
19952            event.payload["activity_id"] = json!("forged-activity-id");
19953        }
19954        let mut marker = selection_winner_marker();
19955        marker.payload["operation_identity"] = json!("forged-activity-id");
19956        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
19957        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19958        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19959
19960        assert!(matches!(
19961            selection.as_mut().poll(&mut task_context),
19962            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
19963        ));
19964    }
19965
19966    #[test]
19967    fn selection_completion_before_cancellation_remains_awaitable() {
19968        let history = vec![
19969            selection_activity_event("ActivityScheduled", 0, "slow", None),
19970            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
19971            selection_winner_marker(),
19972            selection_activity_event(
19973                "ActivityCompleted",
19974                0,
19975                "slow",
19976                Some(json!("completed-first")),
19977            ),
19978        ];
19979        let ctx = workflow_context(history);
19980        let mut selection = Box::pin(keyed_activity_selection(&ctx));
19981        let mut task_context = TaskContext::from_waker(noop_waker_ref());
19982        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
19983            panic!("winner must replay");
19984        };
19985        let slow = selected
19986            .handle(&SelectionKey::Name("slow".to_string()))
19987            .expect("slow handle")
19988            .clone();
19989        let mut cancel = Box::pin(slow.cancel());
19990        assert!(matches!(
19991            cancel.as_mut().poll(&mut task_context),
19992            Poll::Ready(Ok(()))
19993        ));
19994        let mut await_slow = Box::pin(slow.await_result());
19995        assert!(matches!(
19996            await_slow.as_mut().poll(&mut task_context),
19997            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
19998        ));
19999        let commands = ctx.take_commands().expect("commands");
20000        assert!(commands.is_empty());
20001    }
20002
20003    #[test]
20004    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
20005        let nested_member = SelectionMemberMetadata {
20006            key: SelectionKey::Name("nested".to_string()),
20007            index: 0,
20008            base_sequence: 1,
20009            size: 2,
20010            kind: "group".to_string(),
20011        };
20012        let deadline_member = SelectionMemberMetadata {
20013            key: SelectionKey::Name("deadline".to_string()),
20014            index: 1,
20015            base_sequence: 3,
20016            size: 1,
20017            kind: "timer".to_string(),
20018        };
20019        let nested_paths = [
20020            vec![
20021                selection_group_entry(1, 3, 0, "mixed", &nested_member),
20022                parallel_group_entry(1, 2, 0, "activity"),
20023            ],
20024            vec![
20025                selection_group_entry(1, 3, 1, "mixed", &nested_member),
20026                parallel_group_entry(1, 2, 1, "activity"),
20027            ],
20028        ];
20029        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
20030        let mut timer_fired = parallel_history_event(
20031            "TimerFired",
20032            3,
20033            "timer_id",
20034            "timer-3",
20035            deadline_path.clone(),
20036            None,
20037        );
20038        timer_fired.payload["delay_seconds"] = json!(0);
20039        timer_fired
20040            .raw
20041            .insert("id".to_string(), json!("timer-fired"));
20042        let mut timer_scheduled = parallel_history_event(
20043            "TimerScheduled",
20044            3,
20045            "timer_id",
20046            "timer-3",
20047            deadline_path,
20048            None,
20049        );
20050        timer_scheduled.payload["delay_seconds"] = json!(0);
20051        let history = vec![
20052            parallel_history_event(
20053                "ActivityScheduled",
20054                1,
20055                "activity_type",
20056                "nested-first",
20057                nested_paths[0].clone(),
20058                None,
20059            ),
20060            parallel_history_event(
20061                "ActivityScheduled",
20062                2,
20063                "activity_type",
20064                "nested-second",
20065                nested_paths[1].clone(),
20066                None,
20067            ),
20068            timer_scheduled,
20069            timer_fired,
20070            history_event(
20071                "SelectionResolved",
20072                json!({
20073                    "selection_group_id": "select-calls:1:3",
20074                    "selection_group_base_sequence": 1,
20075                    "selection_group_size": 3,
20076                    "member_key": "deadline",
20077                    "member_index": 1,
20078                    "member_base_sequence": 3,
20079                    "member_size": 1,
20080                    "operation_kind": "timer",
20081                    "operation_identity": "timer-3",
20082                    "outcome": "completed",
20083                    "resolution_event_id": "timer-fired",
20084                    "resolution_event_type": "TimerFired",
20085                }),
20086            ),
20087            parallel_history_event(
20088                "ActivityFailed",
20089                2,
20090                "activity_type",
20091                "nested-second",
20092                nested_paths[1].clone(),
20093                None,
20094            ),
20095        ];
20096        let ctx = workflow_context(history);
20097        let mut selection = Box::pin(ctx.select_keyed(vec![
20098            (
20099                "nested",
20100                ParallelOperation::group(vec![
20101                    ParallelOperation::activity("nested-first", json!([])),
20102                    ParallelOperation::activity("nested-second", json!([])),
20103                ]),
20104            ),
20105            ("deadline", ParallelOperation::timer(Duration::ZERO)),
20106        ]));
20107        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20108        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
20109            panic!("deadline winner must replay");
20110        };
20111        let nested = selected
20112            .handle(&SelectionKey::Name("nested".to_string()))
20113            .expect("nested handle")
20114            .clone();
20115        let mut cancel = Box::pin(nested.cancel());
20116        assert!(matches!(
20117            cancel.as_mut().poll(&mut task_context),
20118            Poll::Ready(Ok(()))
20119        ));
20120        let mut await_nested = Box::pin(nested.await_result());
20121
20122        assert!(matches!(
20123            await_nested.as_mut().poll(&mut task_context),
20124            Poll::Ready(Err(Error::ActivityFailed(_)))
20125        ));
20126        assert!(ctx.take_commands().expect("commands").is_empty());
20127    }
20128
20129    #[test]
20130    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
20131        let ctx = workflow_context(Vec::new());
20132        let mut call = Box::pin(ctx.select(vec![
20133            ParallelOperation::child_workflow(
20134                "child",
20135                ChildWorkflowOptions::new("children"),
20136                json!([]),
20137            ),
20138            ParallelOperation::timer(Duration::from_secs(30)),
20139            ParallelOperation::signal("approval"),
20140            ParallelOperation::condition(
20141                ConditionWaitOptions::new("ready", "sha256:ready"),
20142                || Ok(false),
20143            ),
20144            ParallelOperation::group(vec![
20145                ParallelOperation::activity("nested-one", json!([])),
20146                ParallelOperation::activity("nested-two", json!([])),
20147            ]),
20148        ]));
20149        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20150        assert!(matches!(
20151            call.as_mut().poll(&mut task_context),
20152            Poll::Pending
20153        ));
20154        let commands = ctx.take_commands().expect("selection commands");
20155        assert_eq!(
20156            commands
20157                .iter()
20158                .map(|command| command["type"].as_str().unwrap_or_default())
20159                .collect::<Vec<_>>(),
20160            [
20161                "start_child_workflow",
20162                "start_timer",
20163                "open_signal_wait",
20164                "open_condition_wait",
20165                "schedule_activity",
20166                "schedule_activity",
20167            ]
20168        );
20169        assert!(commands.iter().all(|command| {
20170            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
20171        }));
20172        assert_eq!(
20173            commands[4]["parallel_group_path"].as_array().map(Vec::len),
20174            Some(2)
20175        );
20176        assert_eq!(
20177            commands[4]["parallel_group_path"][0]["selection_member_kind"],
20178            json!("group")
20179        );
20180        assert_eq!(
20181            commands[5]["parallel_group_path"][0]["selection_member_kind"],
20182            json!("group")
20183        );
20184
20185        let one_leaf_ctx = workflow_context(Vec::new());
20186        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
20187            ParallelOperation::activity("nested-only", json!([])),
20188        ])]));
20189        assert!(matches!(
20190            one_leaf.as_mut().poll(&mut task_context),
20191            Poll::Pending
20192        ));
20193        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
20194        assert_eq!(one_leaf_commands.len(), 1);
20195        assert_eq!(
20196            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
20197            json!("group")
20198        );
20199        assert_eq!(
20200            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
20201            json!(1)
20202        );
20203    }
20204
20205    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
20206        let mut saga = ctx.saga();
20207        let outcome = async {
20208            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
20209            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
20210            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
20211            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
20212            ctx.activity("trip.charge", json!([])).await?;
20213            Ok(json!({"status": "booked"}))
20214        }
20215        .await;
20216        saga.finish(outcome).await
20217    }
20218
20219    fn saga_activity(
20220        event_type: &str,
20221        sequence: u64,
20222        activity_type: &str,
20223        result: Option<Value>,
20224    ) -> HistoryEvent {
20225        let mut payload = json!({
20226            "sequence": sequence,
20227            "activity_type": activity_type,
20228            "message": format!("{activity_type} failed"),
20229            "exception_type": "PlannedFailure",
20230            "non_retryable": true,
20231        });
20232        if let Some(result) = result {
20233            payload["result"] = fixture_envelope(result);
20234        }
20235        history_event(event_type, payload)
20236    }
20237
20238    #[test]
20239    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
20240        let completed_hotel_compensation = saga_activity(
20241            "ActivityCompleted",
20242            4,
20243            "trip.cancel-hotel",
20244            Some(Value::Null),
20245        );
20246        let history = vec![
20247            saga_activity(
20248                "ActivityCompleted",
20249                1,
20250                "trip.reserve-flight",
20251                Some(json!("flight-1")),
20252            ),
20253            saga_activity(
20254                "ActivityCompleted",
20255                2,
20256                "trip.reserve-hotel",
20257                Some(json!("hotel-1")),
20258            ),
20259            saga_activity("ActivityFailed", 3, "trip.charge", None),
20260            completed_hotel_compensation.clone(),
20261            completed_hotel_compensation,
20262        ];
20263
20264        for _restart in 0..2 {
20265            let ctx = workflow_context(history.clone());
20266            let mut future = Box::pin(trip_saga(ctx.clone()));
20267            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20268            assert!(matches!(
20269                future.as_mut().poll(&mut task_context),
20270                Poll::Pending
20271            ));
20272            let commands = ctx.take_commands().expect("compensation command");
20273            assert_eq!(commands.len(), 1);
20274            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
20275        }
20276    }
20277
20278    #[test]
20279    fn saga_compensation_failure_preserves_both_typed_failures() {
20280        let history = vec![
20281            saga_activity(
20282                "ActivityCompleted",
20283                1,
20284                "trip.reserve-flight",
20285                Some(json!("flight-1")),
20286            ),
20287            saga_activity(
20288                "ActivityCompleted",
20289                2,
20290                "trip.reserve-hotel",
20291                Some(json!("hotel-1")),
20292            ),
20293            saga_activity("ActivityFailed", 3, "trip.charge", None),
20294            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
20295        ];
20296        let ctx = workflow_context(history);
20297        let mut future = Box::pin(trip_saga(ctx));
20298        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20299        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
20300            future.as_mut().poll(&mut task_context)
20301        else {
20302            panic!("compensation failure must remain structured");
20303        };
20304        assert!(matches!(
20305            *failure.initiating_failure,
20306            Error::ActivityFailed(_)
20307        ));
20308        assert!(matches!(
20309            *failure.compensation_failure,
20310            Error::ActivityFailed(_)
20311        ));
20312        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
20313        assert_eq!(failure.compensation_registration_order, 2);
20314    }
20315
20316    #[test]
20317    fn saga_compensates_cooperative_cancellation() {
20318        let ctx = workflow_context(vec![saga_activity(
20319            "ActivityCompleted",
20320            1,
20321            "trip.reserve-flight",
20322            Some(json!("flight-1")),
20323        )]);
20324        ctx.state.lock().expect("state").cancel_requested = true;
20325        let run = {
20326            let ctx = ctx.clone();
20327            async move {
20328                let mut saga = ctx.saga();
20329                let outcome = async {
20330                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
20331                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
20332                    ctx.throw_if_cancellation_requested()?;
20333                    Ok(json!("unexpected"))
20334                }
20335                .await;
20336                saga.finish(outcome).await
20337            }
20338        };
20339        let mut future = Box::pin(run);
20340        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20341        assert!(matches!(
20342            future.as_mut().poll(&mut task_context),
20343            Poll::Pending
20344        ));
20345        let commands = ctx.take_commands().expect("cancellation compensation");
20346        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
20347    }
20348
20349    #[test]
20350    fn optional_task_observability_fields_round_trip_without_interpretation() {
20351        let context = json!({"schema": "unknown", "carrier": {"traceparent": "untrusted"}});
20352        let dispatch = json!({"task_id": "other-task"});
20353        let links = json!({"links": []});
20354        let mut value = json!({
20355            "task_id": "task", "query_task_id": "query", "workflow_type": "workflow",
20356            "activity_type": "activity", "query_name": "query", "payload_codec": "avro"
20357        });
20358        let workflow: WorkflowTask =
20359            serde_json::from_value(value.clone()).expect("legacy workflow task");
20360        let activity: ActivityTask =
20361            serde_json::from_value(value.clone()).expect("legacy activity task");
20362        let query: QueryTask = serde_json::from_value(value.clone()).expect("legacy query task");
20363        assert!(workflow.observability_context.is_none());
20364        assert!(activity.observability_context.is_none());
20365        assert!(query.observability_context.is_none());
20366        assert!(activity.workflow_id.is_none());
20367        assert!(activity.run_id.is_none());
20368        assert!(activity.activity_execution_id.is_none());
20369
20370        value["observability_context"] = context.clone();
20371        value["dispatch_observability_context"] = dispatch.clone();
20372        value["observability_links"] = links.clone();
20373        value["workflow_id"] = json!("workflow-id");
20374        value["run_id"] = json!("run-id");
20375        value["activity_execution_id"] = json!("activity-id");
20376        let workflow: WorkflowTask =
20377            serde_json::from_value(value.clone()).expect("workflow metadata");
20378        let activity: ActivityTask =
20379            serde_json::from_value(value.clone()).expect("activity metadata");
20380        let query: QueryTask = serde_json::from_value(value).expect("query metadata");
20381        for fields in [
20382            (
20383                workflow.observability_context,
20384                workflow.dispatch_observability_context,
20385                workflow.observability_links,
20386            ),
20387            (
20388                activity.observability_context,
20389                activity.dispatch_observability_context,
20390                activity.observability_links,
20391            ),
20392            (
20393                query.observability_context,
20394                query.dispatch_observability_context,
20395                query.observability_links,
20396            ),
20397        ] {
20398            assert_eq!(
20399                fields,
20400                (
20401                    Some(context.clone()),
20402                    Some(dispatch.clone()),
20403                    Some(links.clone())
20404                )
20405            );
20406        }
20407        assert_eq!(activity.workflow_id.as_deref(), Some("workflow-id"));
20408        assert_eq!(activity.run_id.as_deref(), Some("run-id"));
20409        assert_eq!(
20410            activity.activity_execution_id.as_deref(),
20411            Some("activity-id")
20412        );
20413    }
20414
20415    fn workflow_task(
20416        workflow_type: &str,
20417        history_events: Vec<HistoryEvent>,
20418        payload_codec: &str,
20419    ) -> WorkflowTask {
20420        WorkflowTask {
20421            task_id: format!("wft-{workflow_type}"),
20422            observability_context: None,
20423            dispatch_observability_context: None,
20424            observability_links: None,
20425            workflow_command_id: None,
20426            workflow_id: Some(format!("wf-{workflow_type}")),
20427            run_id: Some(format!("run-{workflow_type}")),
20428            workflow_type: workflow_type.to_string(),
20429            cancel_requested: false,
20430            payload_codec: payload_codec.to_string(),
20431            arguments: Some(
20432                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
20433            ),
20434            total_history_events: Some(history_events.len() as u64),
20435            history_size_bytes: None,
20436            continue_as_new_recommended: None,
20437            history_budget_pressure: None,
20438            history_events,
20439            next_history_page_token: None,
20440            workflow_task_attempt: 1,
20441            workflow_signal_id: None,
20442            signal_name: None,
20443            signal_arguments: None,
20444            workflow_update_id: None,
20445            update_name: None,
20446            lease_owner: Some("rust-worker".to_string()),
20447        }
20448    }
20449
20450    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
20451    struct SideEffectProbe {
20452        request_id: String,
20453        attempt: u32,
20454    }
20455
20456    #[test]
20457    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
20458        let calls = AtomicUsize::new(0);
20459        let ctx = workflow_context(Vec::new());
20460        let value = ctx
20461            .side_effect(|| {
20462                calls.fetch_add(1, Ordering::SeqCst);
20463                SideEffectProbe {
20464                    request_id: "request-42".to_string(),
20465                    attempt: 3,
20466                }
20467            })
20468            .expect("first side effect");
20469        assert_eq!(value.attempt, 3);
20470        assert_eq!(calls.load(Ordering::SeqCst), 1);
20471        let commands = ctx.take_commands().expect("commands");
20472        assert_eq!(commands.len(), 1);
20473        assert_eq!(commands[0]["type"], "record_side_effect");
20474        assert_eq!(
20475            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
20476            serde_json::to_value(&value).expect("value")
20477        );
20478
20479        let replay = workflow_context(vec![history_event(
20480            "SideEffectRecorded",
20481            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20482        )]);
20483        let replayed: SideEffectProbe = replay
20484            .side_effect(|| {
20485                calls.fetch_add(1, Ordering::SeqCst);
20486                panic!("committed side-effect callbacks must not run during replay")
20487            })
20488            .expect("replayed side effect");
20489        assert_eq!(replayed, value);
20490        assert_eq!(calls.load(Ordering::SeqCst), 1);
20491        assert!(replay.take_commands().expect("commands").is_empty());
20492        replay.ensure_history_consumed().expect("history consumed");
20493    }
20494
20495    #[test]
20496    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
20497        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
20498        let value = ctx
20499            .side_effect(|| SideEffectProbe {
20500                request_id: "avro-request".to_string(),
20501                attempt: 1,
20502            })
20503            .expect("Avro side effect");
20504        let uuid = ctx.uuid_v4().expect("deterministic UUID");
20505        let commands = ctx.take_commands().expect("commands");
20506        assert_eq!(commands.len(), 2);
20507        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
20508        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
20509        assert_eq!(
20510            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
20511            serde_json::to_value(&value).expect("value")
20512        );
20513
20514        let replay = workflow_context_with_codec(
20515            vec![
20516                history_event(
20517                    "SideEffectRecorded",
20518                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20519                ),
20520                history_event(
20521                    "SideEffectRecorded",
20522                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
20523                ),
20524            ],
20525            DEFAULT_CODEC,
20526        );
20527        let replayed: SideEffectProbe = replay
20528            .side_effect(|| panic!("Avro callback must not run"))
20529            .expect("replayed Avro value");
20530        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
20531        assert_eq!(replayed, value);
20532        assert_eq!(replayed_uuid, uuid);
20533        assert!(replay.take_commands().expect("commands").is_empty());
20534    }
20535
20536    #[test]
20537    fn typed_side_effect_replay_preserves_bytes_and_maps() {
20538        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
20539        let value = ctx
20540            .side_effect_avro_value(typed_fidelity_probe)
20541            .expect("typed side effect");
20542        let commands = ctx.take_commands().expect("side-effect command");
20543        assert_eq!(
20544            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
20545                .expect("recorded side effect"),
20546            value
20547        );
20548
20549        let replay = workflow_context_with_codec(
20550            vec![history_event(
20551                "SideEffectRecorded",
20552                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
20553            )],
20554            DEFAULT_CODEC,
20555        );
20556        assert_eq!(
20557            replay
20558                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
20559                .expect("replayed typed side effect"),
20560            value
20561        );
20562    }
20563
20564    #[test]
20565    fn ordered_side_effects_share_the_durable_command_stream() {
20566        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
20567        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
20568        let ctx = workflow_context(vec![
20569            history_event(
20570                "SideEffectRecorded",
20571                json!({"sequence": 1, "result": first}),
20572            ),
20573            history_event(
20574                "SideEffectRecorded",
20575                json!({"sequence": 2, "result": second}),
20576            ),
20577        ]);
20578        let first: String = ctx
20579            .side_effect(|| panic!("first callback must not run"))
20580            .expect("first replay");
20581        let second: i32 = ctx
20582            .side_effect(|| panic!("second callback must not run"))
20583            .expect("second replay");
20584        assert_eq!(first, "first");
20585        assert_eq!(second, 29);
20586        ctx.ensure_history_consumed().expect("ordered history");
20587
20588        let reordered = workflow_context(vec![history_event(
20589            "VersionMarkerRecorded",
20590            json!({
20591                "sequence": 1,
20592                "change_id": "before-side-effect",
20593                "version": 1,
20594                "min_supported": 1,
20595                "max_supported": 1,
20596            }),
20597        )]);
20598        let error = reordered
20599            .side_effect(|| "new".to_string())
20600            .expect_err("command reordering must fail");
20601        assert!(matches!(
20602            error,
20603            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20604                if reason == "recorded_command_mismatch"
20605        ));
20606    }
20607
20608    #[test]
20609    fn legacy_patch_preserves_pending_and_completed_activity_history() {
20610        for completed in [false, true] {
20611            let mut history = vec![history_event(
20612                "ActivityScheduled",
20613                json!({"sequence": 1, "activity_type": "old"}),
20614            )];
20615            if completed {
20616                history.push(history_event(
20617                    "ActivityCompleted",
20618                    json!({
20619                        "sequence": 1,
20620                        "activity_type": "old",
20621                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
20622                    }),
20623                ));
20624            }
20625            for _cold_replay in 0..2 {
20626                let ctx = workflow_context(history.clone());
20627                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
20628                assert!(!ctx.patched("added-step").expect("same frozen decision"));
20629                ctx.deprecate_patch("added-step")
20630                    .expect("retained boundary");
20631                let mut activity = Box::pin(ctx.activity("old", json!([])));
20632                let mut context = TaskContext::from_waker(noop_waker_ref());
20633                match activity.as_mut().poll(&mut context) {
20634                    Poll::Ready(result) => {
20635                        assert!(completed);
20636                        assert_eq!(result.expect("recorded result"), json!(41));
20637                        ctx.ensure_history_consumed().expect("old command retained");
20638                    }
20639                    Poll::Pending => assert!(!completed),
20640                }
20641                assert!(ctx.take_commands().expect("commands").is_empty());
20642            }
20643        }
20644    }
20645
20646    #[test]
20647    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
20648        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
20649        assert!(!ctx.patched("added-step").expect("legacy completed run"));
20650        ctx.deprecate_patch("added-step")
20651            .expect("same legacy decision");
20652        assert!(ctx.take_commands().expect("commands").is_empty());
20653        ctx.ensure_history_consumed().expect("completed history");
20654    }
20655
20656    #[test]
20657    fn legacy_patch_rejects_a_range_without_the_original_branch() {
20658        let ctx = workflow_context(vec![history_event(
20659            "ActivityScheduled",
20660            json!({"sequence": 1, "activity_type": "old"}),
20661        )]);
20662        let error = ctx
20663            .get_version("added-step", 0, 1)
20664            .expect_err("legacy is unsupported");
20665        assert!(matches!(
20666            error,
20667            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20668                if reason == "version_marker_incompatible_range"
20669        ));
20670        assert!(!ctx
20671            .patched("supported-step")
20672            .expect("failed check did not consume history"));
20673        assert!(ctx.take_commands().expect("commands").is_empty());
20674    }
20675
20676    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
20677        let mut event = history_event(
20678            "VersionMarkerRecorded",
20679            json!({
20680                "sequence": sequence,
20681                "change_id": "retained-patch",
20682                "version": version,
20683                "min_supported": -1,
20684                "max_supported": 1,
20685            }),
20686        );
20687        event.raw.insert("timestamp".into(), json!(time));
20688        event
20689    }
20690
20691    #[test]
20692    fn retained_patch_markers_preserve_each_original_boundary() {
20693        for completed in [false, true] {
20694            let mut history = vec![
20695                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20696                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
20697                history_event(
20698                    "ActivityScheduled",
20699                    json!({"sequence": 3, "activity_type": "old"}),
20700                ),
20701            ];
20702            if completed {
20703                history.push(history_event(
20704                    "ActivityCompleted",
20705                    json!({
20706                        "sequence": 3,
20707                        "activity_type": "old",
20708                        "result": fixture_envelope(json!(41)),
20709                    }),
20710                ));
20711            }
20712            for _cold_replay in 0..2 {
20713                let ctx = workflow_context(history.clone());
20714                assert!(ctx.patched("retained-patch").unwrap());
20715                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20716                assert!(ctx.patched("retained-patch").unwrap());
20717                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20718                ctx.deprecate_patch("retained-patch").unwrap();
20719                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
20720                let mut activity = Box::pin(ctx.activity("old", json!([])));
20721                let mut context = TaskContext::from_waker(noop_waker_ref());
20722                match activity.as_mut().poll(&mut context) {
20723                    Poll::Ready(result) => {
20724                        assert!(completed);
20725                        assert_eq!(result.unwrap(), json!(41));
20726                        ctx.ensure_history_consumed().unwrap();
20727                    }
20728                    Poll::Pending => assert!(!completed),
20729                }
20730                assert!(ctx.take_commands().unwrap().is_empty());
20731                let state = ctx.state.lock().unwrap();
20732                for (actual, original) in state.history_events.iter().zip(&history) {
20733                    assert_eq!(actual.payload, original.payload);
20734                    assert_eq!(actual.raw, original.raw);
20735                }
20736            }
20737        }
20738    }
20739
20740    #[test]
20741    fn retained_patch_aliases_do_not_skip_intervening_operations() {
20742        let ctx = workflow_context(vec![
20743            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20744            history_event(
20745                "SideEffectRecorded",
20746                json!({
20747                    "sequence": 2, "result": fixture_envelope(json!("between")),
20748                }),
20749            ),
20750            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
20751            history_event(
20752                "VersionMarkerRecorded",
20753                json!({
20754                    "sequence": 4, "change_id": "other-patch", "version": 1,
20755                    "min_supported": -1, "max_supported": 1,
20756                }),
20757            ),
20758        ]);
20759        assert!(ctx.patched("retained-patch").unwrap());
20760        assert!(ctx.patched("retained-patch").unwrap());
20761        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20762        assert_eq!(
20763            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
20764            "between"
20765        );
20766        ctx.deprecate_patch("retained-patch").unwrap();
20767        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20768        ctx.deprecate_patch("retained-patch").unwrap();
20769        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
20770        assert!(ctx.patched("other-patch").unwrap());
20771        ctx.ensure_history_consumed().unwrap();
20772        assert!(ctx.take_commands().unwrap().is_empty());
20773    }
20774
20775    #[test]
20776    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
20777        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
20778        alias.payload["max_supported"] = json!(3);
20779        let ctx = workflow_context(vec![
20780            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
20781            alias,
20782        ]);
20783        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
20784        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
20785        assert!(matches!(error,
20786            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20787                if reason == "version_marker_incompatible_range"));
20788        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
20789        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
20790        ctx.ensure_history_consumed().unwrap();
20791        assert!(ctx.take_commands().unwrap().is_empty());
20792    }
20793
20794    #[test]
20795    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
20796        let ctx = workflow_context(Vec::new());
20797        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
20798        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
20799        assert!(ctx.patched("new-search").expect("patch"));
20800        ctx.deprecate_patch("new-search").expect("deprecate patch");
20801        let commands = ctx.take_commands().expect("commands");
20802        assert_eq!(commands.len(), 2);
20803        assert_eq!(commands[0]["type"], "record_version_marker");
20804        assert_eq!(commands[0]["version"], 2);
20805        assert_eq!(commands[1]["change_id"], "new-search");
20806
20807        let replay = workflow_context(vec![history_event(
20808            "VersionMarkerRecorded",
20809            json!({
20810                "sequence": 1,
20811                "change_id": "checkout-v2",
20812                "version": 2,
20813                "min_supported": 1,
20814                "max_supported": 2,
20815            }),
20816        )]);
20817        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
20818        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
20819        assert!(replay.take_commands().expect("commands").is_empty());
20820        replay.ensure_history_consumed().expect("history consumed");
20821    }
20822
20823    #[test]
20824    fn version_markers_reject_incompatible_or_malformed_history() {
20825        let incompatible = workflow_context(vec![history_event(
20826            "VersionMarkerRecorded",
20827            json!({
20828                "sequence": 1,
20829                "change_id": "checkout-v2",
20830                "version": 1,
20831                "min_supported": 1,
20832                "max_supported": 2,
20833            }),
20834        )]);
20835        let error = incompatible
20836            .get_version("checkout-v2", 2, 3)
20837            .expect_err("old version is unsupported");
20838        assert!(matches!(
20839            error,
20840            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
20841                if reason == "version_marker_incompatible_range"
20842        ));
20843
20844        for (history, reason) in [
20845            (
20846                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
20847                "side_effect_result_missing",
20848            ),
20849            (
20850                vec![history_event(
20851                    "SideEffectRecorded",
20852                    json!({
20853                        "sequence": 1,
20854                        "result": {"codec": "avro", "blob": "not-base64"},
20855                    }),
20856                )],
20857                "side_effect_payload_incompatible",
20858            ),
20859            (
20860                vec![history_event(
20861                    "SideEffectRecorded",
20862                    json!({"sequence": 1, "result": {"unwrapped": true}}),
20863                )],
20864                "side_effect_payload_malformed",
20865            ),
20866            (
20867                vec![history_event(
20868                    "VersionMarkerRecorded",
20869                    json!({
20870                        "sequence": 1,
20871                        "change_id": "change",
20872                        "version": 1,
20873                        "min_supported": 2,
20874                        "max_supported": 1,
20875                    }),
20876                )],
20877                "version_marker_history_range_invalid",
20878            ),
20879        ] {
20880            let error = WorkflowState::new(
20881                history,
20882                "rust-workers".to_string(),
20883                DEFAULT_CODEC.to_string(),
20884                None,
20885            )
20886            .expect_err("malformed history must fail");
20887            assert!(matches!(
20888                error,
20889                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
20890                    if actual == reason
20891            ));
20892        }
20893    }
20894
20895    #[test]
20896    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
20897        let history = vec![history_event(
20898            "SearchAttributesUpserted",
20899            json!({
20900                "sequence": 1,
20901                "attributes": {"customer_tier": "gold"},
20902                "attribute_types": {"customer_tier": "keyword"},
20903                "merged": {"customer_tier": "gold"}
20904            }),
20905        )];
20906
20907        let matching = workflow_context(history.clone());
20908        matching
20909            .upsert_search_attributes(
20910                SearchAttributeUpdate::new()
20911                    .keyword("customer_tier", "gold")
20912                    .expect("keyword update"),
20913            )
20914            .expect("matching typed update must replay");
20915        matching
20916            .ensure_history_consumed()
20917            .expect("history consumed");
20918
20919        let changed_type = workflow_context(history.clone());
20920        let error = changed_type
20921            .upsert_search_attributes(
20922                SearchAttributeUpdate::new()
20923                    .string("customer_tier", "gold")
20924                    .expect("string update"),
20925            )
20926            .expect_err("same JSON value with a different declaration must be nondeterministic");
20927        let Error::NonDeterministicReplay(failure) = error else {
20928            panic!("typed identity drift must be a replay failure");
20929        };
20930        assert_eq!(failure.reason, "search_attribute_type_mismatch");
20931        assert_eq!(failure.sequence, Some(1));
20932
20933        let changed_value = workflow_context(history);
20934        let error = changed_value
20935            .upsert_search_attributes(
20936                SearchAttributeUpdate::new()
20937                    .keyword("customer_tier", "platinum")
20938                    .expect("keyword update"),
20939            )
20940            .expect_err("changed values must be nondeterministic");
20941        let Error::NonDeterministicReplay(failure) = error else {
20942            panic!("value drift must be a replay failure");
20943        };
20944        assert_eq!(failure.reason, "search_attribute_value_mismatch");
20945    }
20946
20947    #[test]
20948    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
20949        let history = vec![history_event(
20950            "SearchAttributesUpserted",
20951            json!({
20952                "sequence": 1,
20953                "attributes": {"customer_tier": "gold"},
20954                "merged": {"customer_tier": "gold"}
20955            }),
20956        )];
20957
20958        for update in [
20959            SearchAttributeUpdate::new()
20960                .keyword("customer_tier", "gold")
20961                .expect("keyword update"),
20962            SearchAttributeUpdate::new()
20963                .string("customer_tier", "gold")
20964                .expect("string update"),
20965        ] {
20966            let restarted = workflow_context(history.clone());
20967            restarted
20968                .upsert_search_attributes(update)
20969                .expect("legacy history constrains values but has unknown type identity");
20970            restarted
20971                .ensure_history_consumed()
20972                .expect("history consumed");
20973        }
20974    }
20975
20976    #[test]
20977    fn search_attribute_command_emits_canonical_types() {
20978        let ctx = workflow_context(Vec::new());
20979        ctx.upsert_search_attributes(
20980            SearchAttributeUpdate::new()
20981                .keyword("customer_tier", "gold")
20982                .expect("keyword update")
20983                .int("attempts", 3)
20984                .expect("int update")
20985                .delete("obsolete")
20986                .expect("delete update"),
20987        )
20988        .expect("valid search attributes");
20989
20990        assert_eq!(
20991            ctx.take_commands().expect("commands"),
20992            vec![json!({
20993                "type": "upsert_search_attributes",
20994                "attributes": {
20995                    "attempts": 3,
20996                    "customer_tier": "gold",
20997                    "obsolete": null
20998                },
20999                "attribute_types": {
21000                    "attempts": "int",
21001                    "customer_tier": "keyword"
21002                }
21003            })]
21004        );
21005    }
21006
21007    #[test]
21008    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
21009        let duplicate_side_effect = WorkflowState::new(
21010            vec![
21011                history_event(
21012                    "SideEffectRecorded",
21013                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
21014                ),
21015                history_event(
21016                    "SideEffectRecorded",
21017                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
21018                ),
21019            ],
21020            "rust-workers".to_string(),
21021            DEFAULT_CODEC.to_string(),
21022            None,
21023        )
21024        .expect_err("duplicate side effect");
21025        assert!(matches!(
21026            duplicate_side_effect,
21027            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21028                if reason == "duplicate_side_effect_record"
21029        ));
21030
21031        let marker = |sequence, version| {
21032            history_event(
21033                "VersionMarkerRecorded",
21034                json!({
21035                    "sequence": sequence,
21036                    "change_id": "same-change",
21037                    "version": version,
21038                    "min_supported": -1,
21039                    "max_supported": 1,
21040                }),
21041            )
21042        };
21043        let duplicate_marker = WorkflowState::new(
21044            vec![marker(1, 1), marker(3, -1)],
21045            "rust-workers".to_string(),
21046            DEFAULT_CODEC.to_string(),
21047            None,
21048        )
21049        .expect_err("conflicting marker");
21050        assert!(matches!(
21051            duplicate_marker,
21052            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21053                if reason == "version_marker_conflict"
21054        ));
21055    }
21056
21057    #[test]
21058    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
21059        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
21060        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
21061        invalid_alias.payload["max_supported"] = json!(0);
21062        for (history, expected_reason) in [
21063            (
21064                vec![marker.clone(), marker.clone()],
21065                "duplicate_version_marker_record",
21066            ),
21067            (
21068                vec![marker, invalid_alias],
21069                "version_marker_history_range_invalid",
21070            ),
21071        ] {
21072            let error =
21073                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
21074                    .expect_err("invalid historical alias");
21075            assert!(matches!(error,
21076                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
21077                    if reason == expected_reason));
21078        }
21079    }
21080
21081    #[test]
21082    fn retained_patch_aliases_require_the_original_call_boundary() {
21083        let ctx = workflow_context(vec![
21084            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
21085            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21086        ]);
21087        assert!(ctx.patched("retained-patch").unwrap());
21088        assert!(ctx.ensure_history_consumed().is_err());
21089        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21090        ctx.deprecate_patch("retained-patch").unwrap();
21091        ctx.ensure_history_consumed().unwrap();
21092        assert!(ctx.take_commands().unwrap().is_empty());
21093    }
21094
21095    #[test]
21096    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
21097        let ctx = workflow_context(vec![
21098            history_event(
21099                "SideEffectRecorded",
21100                json!({
21101                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
21102                }),
21103            ),
21104            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21105        ]);
21106        assert!(!ctx.patched("retained-patch").unwrap());
21107        assert_eq!(
21108            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
21109            "old-operation"
21110        );
21111        let error = ctx.patched("retained-patch").unwrap_err();
21112        assert!(matches!(error,
21113            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21114                if reason == "version_marker_conflict"));
21115        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21116        assert!(ctx.take_commands().unwrap().is_empty());
21117    }
21118
21119    #[test]
21120    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
21121        let mut state = WorkflowState::new(
21122            Vec::new(),
21123            "rust-workers".to_string(),
21124            DEFAULT_CODEC.to_string(),
21125            None,
21126        )
21127        .expect("workflow state");
21128        state.workflow_command_identity = "command-7".to_string();
21129        let context = WorkflowContext {
21130            state: Arc::new(Mutex::new(state)),
21131            cancellation_scope_id: "root".into(),
21132        };
21133        let item =
21134            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
21135
21136        context
21137            .append_workflow_stream("output", &[item], Some(10))
21138            .expect("append command");
21139        context
21140            .error_workflow_stream("output", "producer failed", None)
21141            .expect("error command");
21142        let commands = context.take_commands().expect("commands");
21143
21144        assert_eq!(commands[0]["type"], "record_side_effect");
21145        assert_eq!(
21146            commands[0]["workflow_stream"]["command_identity"],
21147            "command-7"
21148        );
21149        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
21150        assert_eq!(
21151            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
21152            "dw-stream:command-7:0:0"
21153        );
21154        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
21155
21156        let recorded = history_event(
21157            "SideEffectRecorded",
21158            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
21159        );
21160        let mut replay_state = WorkflowState::new(
21161            vec![recorded],
21162            "rust-workers".to_string(),
21163            DEFAULT_CODEC.to_string(),
21164            None,
21165        )
21166        .expect("replay state");
21167        replay_state.workflow_command_identity = "command-7".to_string();
21168        let replay_context = WorkflowContext {
21169            state: Arc::new(Mutex::new(replay_state)),
21170            cancellation_scope_id: "root".into(),
21171        };
21172        replay_context
21173            .append_workflow_stream(
21174                "output",
21175                &[WorkflowStreamAppendItem::from_reference(
21176                    "s3://bucket/item.avro",
21177                )],
21178                Some(10),
21179            )
21180            .expect("replayed append");
21181        assert!(replay_context
21182            .take_commands()
21183            .expect("replayed commands")
21184            .is_empty());
21185    }
21186
21187    #[test]
21188    fn workflow_stream_authoring_requires_server_durable_command_identity() {
21189        let context = workflow_context(Vec::new());
21190        let error = context
21191            .append_workflow_stream(
21192                "output",
21193                &[WorkflowStreamAppendItem::from_reference(
21194                    "s3://bucket/item.avro",
21195                )],
21196                None,
21197            )
21198            .expect_err("stream append without durable command identity must fail closed");
21199
21200        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
21201        assert!(context.take_commands().expect("commands").is_empty());
21202    }
21203
21204    #[test]
21205    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
21206        let client = Client::builder("http://localhost:8080").build().unwrap();
21207        let mut worker = Worker::new(client, "rust-workers");
21208        worker.register_workflow("streams.worker", |ctx, _| async move {
21209            ctx.append_workflow_stream(
21210                "output",
21211                &[WorkflowStreamAppendItem::new(json!("hello"))?],
21212                None,
21213            )?;
21214            ctx.close_workflow_stream("output", None)?;
21215            Ok(json!("done"))
21216        });
21217        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
21218            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
21219            task.workflow_command_id = command_id.clone();
21220            let expected_identity = command_id
21221                .as_deref()
21222                .filter(|id| !id.is_empty())
21223                .unwrap_or(&task.task_id)
21224                .to_string();
21225            let commands = worker
21226                .execute_workflow_task(task)
21227                .expect("ordinary worker stream output");
21228            assert_eq!(commands.len(), 3);
21229            assert_eq!(
21230                commands[0]["workflow_stream"]["command_identity"],
21231                expected_identity
21232            );
21233            assert_eq!(
21234                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
21235                format!("dw-stream:{expected_identity}:0:0")
21236            );
21237            assert_eq!(
21238                commands[1]["workflow_stream"]["command_identity"],
21239                expected_identity
21240            );
21241            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
21242            let history = commands[..2]
21243                .iter()
21244                .enumerate()
21245                .map(|(index, command)| {
21246                    history_event(
21247                        "SideEffectRecorded",
21248                        json!({"sequence":index + 1,"result":command["result"]}),
21249                    )
21250                })
21251                .collect();
21252            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
21253            replay.task_id = "replacement-task".to_string();
21254            let replayed = worker
21255                .execute_workflow_task(replay)
21256                .expect("replacement worker consumes recorded stream effects");
21257            assert_eq!(replayed.len(), 1);
21258            assert_eq!(replayed[0]["type"], "complete_workflow");
21259        }
21260        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
21261        missing.task_id.clear();
21262        assert!(matches!(
21263            worker.execute_workflow_task(missing),
21264            Err(Error::MissingWorkflowCommandIdentity)
21265        ));
21266    }
21267
21268    #[test]
21269    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
21270        fn worker(calls: Arc<AtomicUsize>) -> Worker {
21271            let client = Client::new("http://127.0.0.1:8080").expect("client");
21272            let mut worker = Worker::new(client, "rust-workers");
21273            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
21274                let calls = Arc::clone(&calls);
21275                async move {
21276                    let captured = ctx.side_effect(|| {
21277                        calls.fetch_add(1, Ordering::SeqCst);
21278                        "captured-once".to_string()
21279                    })?;
21280                    let version = ctx.get_version("cold-restart", 1, 2)?;
21281                    Ok(json!({"captured": captured, "version": version}))
21282                }
21283            });
21284            worker
21285        }
21286
21287        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
21288            WorkflowTask {
21289                task_id: "wft-side-effect-version".to_string(),
21290                observability_context: None,
21291                dispatch_observability_context: None,
21292                observability_links: None,
21293                workflow_command_id: None,
21294                workflow_id: Some("wf-side-effect-version".to_string()),
21295                run_id: Some("run-side-effect-version".to_string()),
21296                workflow_type: "rust.side-effect-version".to_string(),
21297                cancel_requested: false,
21298                payload_codec: DEFAULT_CODEC.to_string(),
21299                arguments: Some(
21300                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
21301                ),
21302                history_events,
21303                total_history_events: None,
21304                history_size_bytes: None,
21305                continue_as_new_recommended: None,
21306                history_budget_pressure: None,
21307                next_history_page_token: None,
21308                workflow_task_attempt: 1,
21309                workflow_signal_id: None,
21310                signal_name: None,
21311                signal_arguments: None,
21312                workflow_update_id: None,
21313                update_name: None,
21314                lease_owner: Some("rust-worker".to_string()),
21315            }
21316        }
21317
21318        let calls = Arc::new(AtomicUsize::new(0));
21319        let initial = worker(Arc::clone(&calls))
21320            .execute_workflow_task(task(Vec::new()))
21321            .expect("initial execution");
21322        assert_eq!(
21323            initial
21324                .iter()
21325                .map(|command| &command["type"])
21326                .collect::<Vec<_>>(),
21327            vec![
21328                "record_side_effect",
21329                "record_version_marker",
21330                "complete_workflow"
21331            ]
21332        );
21333        assert_eq!(calls.load(Ordering::SeqCst), 1);
21334
21335        let restarted = worker(Arc::clone(&calls));
21336        let replayed = restarted
21337            .execute_workflow_task(task(vec![
21338                history_event(
21339                    "SideEffectRecorded",
21340                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
21341                ),
21342                history_event(
21343                    "VersionMarkerRecorded",
21344                    json!({
21345                        "sequence": 2,
21346                        "change_id": "cold-restart",
21347                        "version": 2,
21348                        "min_supported": 1,
21349                        "max_supported": 2,
21350                    }),
21351                ),
21352            ]))
21353            .expect("cold replay");
21354        assert_eq!(replayed.len(), 1);
21355        assert_eq!(replayed[0]["type"], "complete_workflow");
21356        assert_eq!(calls.load(Ordering::SeqCst), 1);
21357    }
21358
21359    #[test]
21360    fn side_effect_replay_rejects_changed_rust_value_type() {
21361        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
21362        let ctx = workflow_context(vec![history_event(
21363            "SideEffectRecorded",
21364            json!({"sequence": 1, "result": result}),
21365        )]);
21366        let error = ctx
21367            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
21368            .expect_err("changed type must fail replay");
21369        assert!(matches!(
21370            error,
21371            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21372                if reason == "side_effect_type_mismatch"
21373        ));
21374    }
21375
21376    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
21377        vec![
21378            history_event(
21379                "ActivityScheduled",
21380                json!({
21381                    "sequence": 1,
21382                    "activity_type": "flaky",
21383                    "activity_execution_id": "act-1",
21384                    "activity": {
21385                        "id": "act-1",
21386                        "sequence": 1,
21387                        "type": "flaky",
21388                        "queue": "critical-activities",
21389                        "execution_mode": null,
21390                        "retry_policy": {
21391                            "snapshot_version": 1,
21392                            "max_attempts": 3,
21393                            "backoff_seconds": [2, 4],
21394                            "start_to_close_timeout": 30,
21395                            "schedule_to_start_timeout": 5,
21396                            "schedule_to_close_timeout": 90,
21397                            "heartbeat_timeout": 10,
21398                            "non_retryable_error_types": ["PermanentError"]
21399                        }
21400                    }
21401                }),
21402            ),
21403            history_event(
21404                "ActivityStarted",
21405                json!({
21406                    "sequence": 1,
21407                    "activity_type": "flaky",
21408                    "activity_execution_id": "act-1",
21409                    "activity_attempt_id": "attempt-1",
21410                    "attempt_number": 1
21411                }),
21412            ),
21413            history_event(
21414                "ActivityRetryScheduled",
21415                json!({
21416                    "sequence": 1,
21417                    "activity_type": "flaky",
21418                    "activity_execution_id": "act-1",
21419                    "activity_attempt_id": "attempt-1",
21420                    "attempt_number": 1,
21421                    "retry_after_attempt": 1,
21422                    "retry_backoff_seconds": 2,
21423                    "failure_category": "activity",
21424                    "exception_type": "TransientError"
21425                }),
21426            ),
21427            history_event(
21428                "ActivityStarted",
21429                json!({
21430                    "sequence": 1,
21431                    "activity_type": "flaky",
21432                    "activity_execution_id": "act-1",
21433                    "activity_attempt_id": "attempt-2",
21434                    "attempt_number": 2
21435                }),
21436            ),
21437            history_event(
21438                "ActivityCompleted",
21439                json!({
21440                    "sequence": 1,
21441                    "activity_type": "flaky",
21442                    "activity_execution_id": "act-1",
21443                    "activity_attempt_id": "attempt-2",
21444                    "attempt_number": 2,
21445                    "payload_codec": DEFAULT_CODEC,
21446                    "result": fixture_envelope(json!({"status":"recovered"}))
21447                }),
21448            ),
21449        ]
21450    }
21451
21452    fn retry_activity_options() -> ActivityOptions {
21453        ActivityOptions::new()
21454            .task_queue("critical-activities")
21455            .retry_policy(
21456                ActivityRetryPolicy::new(3)
21457                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
21458                    .non_retryable_error_type("PermanentError"),
21459            )
21460            .start_to_close_timeout(Duration::from_secs(30))
21461            .schedule_to_start_timeout(Duration::from_secs(5))
21462            .schedule_to_close_timeout(Duration::from_secs(90))
21463            .heartbeat_timeout(Duration::from_secs(10))
21464    }
21465
21466    #[test]
21467    fn fixed_avro_value_round_trips_json_values() {
21468        let value = json!({"greeting": "hello", "count": 3, "ok": true});
21469        let envelope = PayloadEnvelope::avro(&value).expect("encode");
21470        assert_eq!(envelope.codec, DEFAULT_CODEC);
21471        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
21472    }
21473
21474    #[tokio::test]
21475    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
21476        let client = Client::new("http://127.0.0.1:8080").expect("client");
21477        let mut worker = Worker::new(client, "rust-workers");
21478        worker.register_typed_workflow(
21479            "typed.contract.workflow",
21480            |_ctx, input: TypedContract| async move { Ok(input) },
21481        );
21482        worker.register_typed_activity(
21483            "typed.contract.activity",
21484            |_ctx, input: TypedContract| async move { Ok(input) },
21485        );
21486
21487        let expected = typed_contract();
21488        let arguments = AvroValue::Array(vec![
21489            AvroValue::from_serialize(&expected).expect("typed request")
21490        ]);
21491        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
21492        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
21493        workflow.arguments = Some(envelope.clone());
21494        let commands = worker
21495            .execute_workflow_task(workflow)
21496            .expect("typed workflow task");
21497        let workflow_result: TypedContract =
21498            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21499                .expect("workflow result envelope")
21500                .deserialize()
21501                .expect("workflow result type");
21502        assert_eq!(workflow_result, expected);
21503
21504        let activity = ActivityTask {
21505            task_id: "typed-contract-activity".to_string(),
21506            workflow_id: None,
21507            run_id: None,
21508            activity_execution_id: None,
21509            observability_context: None,
21510            dispatch_observability_context: None,
21511            observability_links: None,
21512            activity_attempt_id: Some("typed-contract-attempt".to_string()),
21513            attempt_id: None,
21514            activity_type: "typed.contract.activity".to_string(),
21515            payload_codec: DEFAULT_CODEC.to_string(),
21516            arguments: Some(envelope),
21517            attempt_number: 1,
21518            lease_owner: Some("rust-worker".to_string()),
21519        };
21520        let activity_result: TypedContract = worker
21521            .execute_activity_task(activity)
21522            .await
21523            .expect("typed activity task")
21524            .deserialize()
21525            .expect("activity result type");
21526        assert_eq!(activity_result, expected);
21527    }
21528
21529    #[test]
21530    fn typed_entry_mismatch_refuses_before_body_and_preserves_original_input() {
21531        let calls = Arc::new(AtomicUsize::new(0));
21532        let observed = Arc::clone(&calls);
21533        let client = Client::new("http://127.0.0.1:8080").expect("client");
21534        let mut worker = Worker::new(client.clone(), "rust-workers");
21535        worker.register_typed_workflow("entry.safe", move |_ctx, input: i64| {
21536            observed.fetch_add(1, Ordering::SeqCst);
21537            async move { Ok(input) }
21538        });
21539        let mut task = workflow_task("entry.safe", Vec::new(), DEFAULT_CODEC);
21540        task.arguments = Some(fixture_envelope(json!(["private-original-value"])));
21541        let original = task.clone();
21542        let error = worker
21543            .execute_workflow_task(task)
21544            .expect_err("incompatible entry must refuse the task, not fail the run");
21545        assert_eq!(calls.load(Ordering::SeqCst), 0);
21546        assert!(error
21547            .to_string()
21548            .contains("workflow_entry_arguments_mismatch:"));
21549        assert!(!error.to_string().contains("private-original-value"));
21550
21551        let mut compatible = Worker::new(client, "rust-workers");
21552        compatible
21553            .register_typed_workflow("entry.safe", |_ctx, input: String| async move { Ok(input) });
21554        let commands = compatible
21555            .execute_workflow_task(original)
21556            .expect("same recorded input");
21557        assert_eq!(commands[0]["type"], "complete_workflow");
21558        assert_eq!(
21559            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).unwrap(),
21560            json!("private-original-value")
21561        );
21562    }
21563
21564    #[test]
21565    fn typed_entry_replayed_mismatch_refuses_before_state_factory_and_body() {
21566        let factories = Arc::new(AtomicUsize::new(0));
21567        let observed = Arc::clone(&factories);
21568        let client = Client::new("http://127.0.0.1:8080").expect("client");
21569        let mut worker = Worker::new(client, "rust-workers");
21570        worker.register_typed_replayed_workflow(
21571            "entry.replayed",
21572            move || {
21573                observed.fetch_add(1, Ordering::SeqCst);
21574                ()
21575            },
21576            |_ctx, _input: i64, _state| async move {
21577                panic!("body must not start");
21578                #[allow(unreachable_code)]
21579                Ok(0_i64)
21580            },
21581        );
21582        let mut task = workflow_task("entry.replayed", Vec::new(), DEFAULT_CODEC);
21583        task.arguments = Some(fixture_envelope(json!(["private-replayed-value"])));
21584        let error = worker
21585            .execute_workflow_task(task)
21586            .expect_err("entry refusal");
21587        assert_eq!(factories.load(Ordering::SeqCst), 0);
21588        assert!(error
21589            .to_string()
21590            .contains("workflow_entry_arguments_mismatch:"));
21591        assert!(!error.to_string().contains("private-replayed-value"));
21592
21593        let replay = worker.workflows["entry.replayed"].replay.as_ref().unwrap();
21594        let Err(error) = replay(
21595            workflow_context(Vec::new()),
21596            AvroValue::Array(vec![AvroValue::String("private-replayed-value".into())]),
21597        ) else {
21598            panic!("query replay must refuse before creating application state");
21599        };
21600        assert_eq!(factories.load(Ordering::SeqCst), 0);
21601        assert!(!error.to_string().contains("private-replayed-value"));
21602    }
21603
21604    #[test]
21605    fn typed_entry_deserializes_once_before_entering_application_code() {
21606        static DECODES: AtomicUsize = AtomicUsize::new(0);
21607        struct Counted(i64);
21608        impl<'de> Deserialize<'de> for Counted {
21609            fn deserialize<D: Deserializer<'de>>(
21610                deserializer: D,
21611            ) -> std::result::Result<Self, D::Error> {
21612                DECODES.fetch_add(1, Ordering::SeqCst);
21613                i64::deserialize(deserializer).map(Self)
21614            }
21615        }
21616        DECODES.store(0, Ordering::SeqCst);
21617        let client = Client::new("http://127.0.0.1:8080").expect("client");
21618        let mut worker = Worker::new(client, "rust-workers");
21619        worker.register_typed_workflow(
21620            "entry.once",
21621            |_ctx, input: Counted| async move { Ok(input.0) },
21622        );
21623        let mut task = workflow_task("entry.once", Vec::new(), DEFAULT_CODEC);
21624        task.arguments = Some(fixture_envelope(json!([7])));
21625        let commands = worker.execute_workflow_task(task).expect("typed result");
21626        assert_eq!(commands[0]["type"], "complete_workflow");
21627        assert_eq!(DECODES.load(Ordering::SeqCst), 1);
21628    }
21629
21630    #[test]
21631    fn typed_entry_body_input_error_remains_a_business_failure() {
21632        let client = Client::new("http://127.0.0.1:8080").expect("client");
21633        let mut worker = Worker::new(client, "rust-workers");
21634        worker.register_typed_workflow("entry.body", |_ctx, _input: i64| async move {
21635            Err::<i64, _>(handler_type_error::<i64>(
21636                HandlerKind::Workflow,
21637                "entry.body",
21638                HandlerValueKind::Input,
21639                "deliberate body error",
21640            ))
21641        });
21642        let mut task = workflow_task("entry.body", Vec::new(), DEFAULT_CODEC);
21643        task.arguments = Some(fixture_envelope(json!([7])));
21644        let commands = worker
21645            .execute_workflow_task(task)
21646            .expect("business failure command");
21647        assert_eq!(commands[0]["type"], "fail_workflow");
21648        assert!(commands[0]["message"]
21649            .as_str()
21650            .unwrap()
21651            .contains("deliberate body error"));
21652    }
21653
21654    #[test]
21655    fn typed_entry_body_cannot_claim_the_adapter_refusal() {
21656        let client = Client::new("http://127.0.0.1:8080").expect("client");
21657        let mut worker = Worker::new(client, "rust-workers");
21658        worker.register_typed_workflow("entry.body.refusal", |_ctx, _input: i64| async move {
21659            Err::<i64, _>(handler_type_error::<i64>(
21660                HandlerKind::Workflow,
21661                "entry.body.refusal",
21662                HandlerValueKind::Input,
21663                "workflow_entry_arguments_mismatch: deliberate body error",
21664            ))
21665        });
21666        let mut task = workflow_task("entry.body.refusal", Vec::new(), DEFAULT_CODEC);
21667        task.arguments = Some(fixture_envelope(json!([7])));
21668        let commands = worker
21669            .execute_workflow_task(task)
21670            .expect("business failure");
21671        assert_eq!(commands[0]["type"], "fail_workflow");
21672    }
21673
21674    #[tokio::test]
21675    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
21676        let client = Client::new("http://127.0.0.1:8080").expect("client");
21677        let mut worker = Worker::new(client, "rust-workers");
21678        worker.register_typed_workflow(
21679            "typed.shape.workflow",
21680            |_ctx, input: TypedContract| async move { Ok(input) },
21681        );
21682        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
21683            Ok(f64::NAN)
21684        });
21685
21686        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
21687        workflow.arguments = Some(
21688            encode_typed_envelope(
21689                &AvroValue::Array(vec![
21690                    AvroValue::String("first".to_string()),
21691                    AvroValue::String("second".to_string()),
21692                ]),
21693                DEFAULT_CODEC,
21694            )
21695            .expect("malformed typed arguments"),
21696        );
21697        let error = worker
21698            .execute_workflow_task(workflow)
21699            .expect_err("entry shape mismatch refuses the task");
21700        let message = error.to_string();
21701        assert!(message.contains("workflow_entry_arguments_mismatch:"));
21702        assert!(message.contains("typed.shape.workflow"));
21703        assert!(message.contains(type_name::<TypedContract>()));
21704
21705        let activity = ActivityTask {
21706            task_id: "typed-unsupported-activity".to_string(),
21707            workflow_id: None,
21708            run_id: None,
21709            activity_execution_id: None,
21710            observability_context: None,
21711            dispatch_observability_context: None,
21712            observability_links: None,
21713            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
21714            attempt_id: None,
21715            activity_type: "typed.unsupported.activity".to_string(),
21716            payload_codec: DEFAULT_CODEC.to_string(),
21717            arguments: Some(
21718                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21719                    .expect("unit arguments"),
21720            ),
21721            attempt_number: 1,
21722            lease_owner: Some("rust-worker".to_string()),
21723        };
21724        let Error::HandlerType {
21725            handler_kind,
21726            handler_name,
21727            value_kind,
21728            rust_type,
21729            message,
21730        } = worker
21731            .execute_activity_task(activity)
21732            .await
21733            .expect_err("non-finite handler output must fail")
21734        else {
21735            panic!("expected contextual handler type failure");
21736        };
21737        assert_eq!(handler_kind, HandlerKind::Activity);
21738        assert_eq!(handler_name, "typed.unsupported.activity");
21739        assert_eq!(value_kind, HandlerValueKind::Result);
21740        assert_eq!(rust_type, type_name::<f64>());
21741        assert!(message.contains("non_finite_float"));
21742    }
21743
21744    #[tokio::test]
21745    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
21746        #[derive(Clone, Default)]
21747        struct State {
21748            observed: Option<TypedContract>,
21749        }
21750
21751        let client = Client::new("http://127.0.0.1:8080").expect("client");
21752        let mut worker = Worker::new(client, "rust-workers");
21753        worker.register_typed_replayed_workflow(
21754            "typed.contract.replayed",
21755            State::default,
21756            |ctx, input: TypedContract, state| async move {
21757                let result: TypedContract =
21758                    ctx.activity_typed("typed.contract.activity", input).await?;
21759                state.update(|current| current.observed = Some(result.clone()))?;
21760                Ok(result)
21761            },
21762        );
21763        worker.register_replayed_query::<State, _, _>(
21764            "typed.contract.replayed",
21765            "observed",
21766            |_ctx, state, _args| async move {
21767                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
21768            },
21769        );
21770
21771        let expected = typed_contract();
21772        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
21773        let workflow_arguments =
21774            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
21775                .expect("workflow arguments");
21776        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
21777        let task = QueryTask {
21778            query_task_id: "typed-replay-query".to_string(),
21779            observability_context: None,
21780            dispatch_observability_context: None,
21781            observability_links: None,
21782            query_task_attempt: 1,
21783            lease_owner: Some("rust-worker".to_string()),
21784            workflow_id: Some("typed-replay".to_string()),
21785            run_id: Some("typed-replay-run".to_string()),
21786            workflow_type: "typed.contract.replayed".to_string(),
21787            query_name: "observed".to_string(),
21788            payload_codec: DEFAULT_CODEC.to_string(),
21789            workflow_arguments: Some(workflow_arguments),
21790            query_arguments: Some(
21791                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
21792                    .expect("query arguments"),
21793            ),
21794            history_events: vec![
21795                history_event(
21796                    "ActivityScheduled",
21797                    json!({
21798                        "sequence": 1,
21799                        "activity_type": "typed.contract.activity"
21800                    }),
21801                ),
21802                history_event(
21803                    "ActivityCompleted",
21804                    json!({
21805                        "sequence": 1,
21806                        "activity_type": "typed.contract.activity",
21807                        "payload_codec": DEFAULT_CODEC,
21808                        "result": result
21809                    }),
21810                ),
21811            ],
21812            history_export: None,
21813            run_status: Some("completed".to_string()),
21814        };
21815
21816        assert_eq!(
21817            worker
21818                .execute_query_task(task)
21819                .await
21820                .expect("typed replay query")
21821                .deserialize::<i64>()
21822                .expect("query result"),
21823            expected.signed
21824        );
21825    }
21826
21827    #[tokio::test]
21828    async fn update_context_preserves_workflow_input_and_committed_signals() {
21829        let client = Client::new("http://127.0.0.1:8080").expect("client");
21830        let mut worker = Worker::new(client, "rust-workers");
21831        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
21832        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
21833        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
21834        let expected_input = workflow_input.clone();
21835        let expected_signals = signal_arguments.clone();
21836        let handler = move |context: QueryContext, arguments: AvroValue| {
21837            let expected_input = expected_input.clone();
21838            let expected_signals = expected_signals.clone();
21839            async move {
21840                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
21841                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
21842                assert_eq!(context.workflow_input_avro_value(), &expected_input);
21843                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
21844                assert_eq!(
21845                    context.signals_avro_value("changed"),
21846                    vec![expected_signals.clone()]
21847                );
21848                assert_eq!(
21849                    context.signals("changed"),
21850                    vec![expected_signals
21851                        .into_iter()
21852                        .map(AvroValue::into_json)
21853                        .collect::<Result<Vec<_>>>()?]
21854                );
21855                assert_eq!(
21856                    context.signal_events()[0].id.as_deref(),
21857                    Some("signal-original")
21858                );
21859                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
21860                Ok(arguments)
21861            }
21862        };
21863        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
21864        worker.register_update_avro_value("snapshot", "inspect", handler);
21865        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
21866        let update_envelope =
21867            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
21868        let mut task = workflow_task(
21869            "snapshot",
21870            vec![
21871                history_event(
21872                    "SignalReceived",
21873                    json!({
21874                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
21875                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
21876                    }),
21877                ),
21878                history_event(
21879                    "UpdateAccepted",
21880                    json!({
21881                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
21882                    }),
21883                ),
21884            ],
21885            DEFAULT_CODEC,
21886        );
21887        task.arguments =
21888            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
21889        task.workflow_update_id = Some("update-original".into());
21890        task.update_name = Some("inspect".into());
21891        let query = QueryTask {
21892            query_task_id: "query-snapshot".into(),
21893            observability_context: None,
21894            dispatch_observability_context: None,
21895            observability_links: None,
21896            query_task_attempt: 1,
21897            lease_owner: None,
21898            workflow_id: task.workflow_id.clone(),
21899            run_id: task.run_id.clone(),
21900            workflow_type: task.workflow_type.clone(),
21901            query_name: "inspect".into(),
21902            payload_codec: DEFAULT_CODEC.into(),
21903            workflow_arguments: task.arguments.clone(),
21904            query_arguments: Some(update_envelope),
21905            history_events: task.history_events.clone(),
21906            history_export: None,
21907            run_status: Some("running".into()),
21908        };
21909        assert_eq!(
21910            worker
21911                .execute_query_task(query)
21912                .await
21913                .expect("query snapshot"),
21914            update_arguments
21915        );
21916        for _ in 0..2 {
21917            let commands = worker
21918                .execute_workflow_task(task.clone())
21919                .expect("cold update snapshot");
21920            assert_eq!(commands[0]["type"], "complete_update");
21921            assert_eq!(commands[0]["update_id"], "update-original");
21922            assert_eq!(
21923                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21924                    .expect("update result"),
21925                update_arguments
21926            );
21927        }
21928    }
21929
21930    #[test]
21931    fn committed_signal_snapshot_counts_identities_once() {
21932        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
21933        let received = history_event(
21934            "SignalReceived",
21935            json!({
21936                "signal_id": "signal-first", "workflow_command_id": "command-first",
21937                "signal_name": "changed", "arguments": arguments.clone(),
21938            }),
21939        );
21940        let applied = history_event(
21941            "SignalApplied",
21942            json!({
21943                "signal_id": "signal-first", "workflow_command_id": "command-first",
21944                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
21945            }),
21946        );
21947        let distinct = history_event(
21948            "SignalReceived",
21949            json!({
21950                "signal_id": "signal-second", "workflow_command_id": "command-second",
21951                "signal_name": "changed", "arguments": arguments,
21952            }),
21953        );
21954        let history = vec![received.clone(), applied.clone(), distinct];
21955        let signals =
21956            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
21957        assert_eq!(signals.len(), 2);
21958        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21959        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
21960        assert_eq!(signals[0].workflow_sequence, Some(1));
21961        assert_eq!(signals[0].arguments, signals[1].arguments);
21962        let mut command_only = received.clone();
21963        command_only
21964            .payload
21965            .as_object_mut()
21966            .expect("payload")
21967            .remove("signal_id");
21968        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
21969            .expect("command identity");
21970        assert_eq!(signals.len(), 1);
21971        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
21972        let mut conflicting = applied;
21973        conflicting.payload["value"] =
21974            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
21975        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
21976    }
21977
21978    #[test]
21979    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
21980        for arguments in [
21981            vec![],
21982            vec![AvroValue::Array(vec![
21983                AvroValue::Long(1),
21984                AvroValue::Long(2),
21985            ])],
21986            vec![AvroValue::Bytes(vec![0, 255])],
21987            vec![AvroValue::Null],
21988            vec![AvroValue::Boolean(false)],
21989            vec![
21990                AvroValue::Long(1),
21991                AvroValue::Array(vec![AvroValue::Long(2)]),
21992            ],
21993        ] {
21994            let applied = match arguments.as_slice() {
21995                [] => AvroValue::Boolean(true),
21996                [value] => value.clone(),
21997                values => AvroValue::Array(values.to_vec()),
21998            };
21999            for applied in [applied, AvroValue::Array(arguments.clone())] {
22000                let events = vec![
22001                    history_event(
22002                        "SignalReceived",
22003                        json!({
22004                            "signal_id": "original", "signal_name": "changed",
22005                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
22006                        }),
22007                    ),
22008                    history_event(
22009                        "SignalApplied",
22010                        json!({
22011                            "signal_id": "original", "signal_name": "changed",
22012                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
22013                        }),
22014                    ),
22015                ];
22016                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
22017                    .expect("canonical signal snapshot");
22018                assert_eq!(signals.len(), 1);
22019                assert_eq!(signals[0].avro_arguments, arguments);
22020            }
22021        }
22022    }
22023
22024    #[tokio::test]
22025    async fn update_context_rejects_malformed_snapshot_before_handler() {
22026        let client = Client::new("http://127.0.0.1:8080").expect("client");
22027        let mut worker = Worker::new(client, "rust-workers");
22028        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
22029        let calls = Arc::new(AtomicUsize::new(0));
22030        let observed = Arc::clone(&calls);
22031        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
22032            observed.fetch_add(1, Ordering::SeqCst);
22033            async { Ok(Value::Null) }
22034        });
22035        let mut task = workflow_task(
22036            "snapshot",
22037            vec![history_event(
22038                "UpdateAccepted",
22039                json!({
22040                    "update_id": "update-original", "update_name": "inspect",
22041                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
22042                }),
22043            )],
22044            DEFAULT_CODEC,
22045        );
22046        task.workflow_update_id = Some("update-original".into());
22047        task.update_name = Some("inspect".into());
22048        let mut bad_input = task.clone();
22049        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
22050        assert!(worker.execute_workflow_task(bad_input).is_err());
22051        task.history_events.insert(0, history_event("SignalReceived", json!({
22052            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
22053        })));
22054        assert!(worker.execute_workflow_task(task).is_err());
22055        assert_eq!(calls.load(Ordering::SeqCst), 0);
22056    }
22057
22058    #[tokio::test]
22059    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
22060        let client = Client::new("http://127.0.0.1:8080").expect("client");
22061        let mut worker = Worker::new(client, "rust-workers");
22062        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
22063        worker
22064            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
22065        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
22066            Ok(input)
22067        });
22068        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
22069            Ok(input)
22070        });
22071        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
22072            Ok(AvroValue::Array(
22073                ctx.wait_signal_avro_value("changed").await?,
22074            ))
22075        });
22076
22077        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
22078        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
22079
22080        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
22081        workflow.arguments = Some(envelope.clone());
22082        let commands = worker
22083            .execute_workflow_task(workflow)
22084            .expect("typed workflow task");
22085        assert_eq!(commands[0]["type"], "complete_workflow");
22086        assert_eq!(
22087            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22088                .expect("typed workflow result"),
22089            arguments
22090        );
22091
22092        let activity = ActivityTask {
22093            task_id: "activity-typed".to_string(),
22094            workflow_id: None,
22095            run_id: None,
22096            activity_execution_id: None,
22097            observability_context: None,
22098            dispatch_observability_context: None,
22099            observability_links: None,
22100            activity_attempt_id: Some("attempt-typed".to_string()),
22101            attempt_id: None,
22102            activity_type: "typed.activity".to_string(),
22103            payload_codec: DEFAULT_CODEC.to_string(),
22104            arguments: Some(envelope.clone()),
22105            attempt_number: 1,
22106            lease_owner: Some("rust-worker".to_string()),
22107        };
22108        assert_eq!(
22109            worker
22110                .execute_activity_task(activity)
22111                .await
22112                .expect("typed activity result"),
22113            arguments
22114        );
22115
22116        let query = QueryTask {
22117            query_task_id: "query-typed".to_string(),
22118            observability_context: None,
22119            dispatch_observability_context: None,
22120            observability_links: None,
22121            query_task_attempt: 1,
22122            lease_owner: Some("rust-worker".to_string()),
22123            workflow_id: Some("typed-1".to_string()),
22124            run_id: Some("run-typed".to_string()),
22125            workflow_type: "typed.echo".to_string(),
22126            query_name: "inspect".to_string(),
22127            payload_codec: DEFAULT_CODEC.to_string(),
22128            workflow_arguments: Some(
22129                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
22130                    .expect("workflow input"),
22131            ),
22132            query_arguments: Some(envelope.clone()),
22133            history_events: Vec::new(),
22134            history_export: None,
22135            run_status: Some("running".to_string()),
22136        };
22137        assert_eq!(
22138            worker
22139                .execute_query_task(query)
22140                .await
22141                .expect("typed query result"),
22142            arguments
22143        );
22144
22145        let mut update = workflow_task(
22146            "typed.echo",
22147            vec![history_event(
22148                "UpdateAccepted",
22149                json!({
22150                    "update_id": "update-typed",
22151                    "update_name": "replace",
22152                    "arguments": envelope.clone(),
22153                }),
22154            )],
22155            DEFAULT_CODEC,
22156        );
22157        update.workflow_update_id = Some("update-typed".to_string());
22158        update.update_name = Some("replace".to_string());
22159        let commands = worker
22160            .execute_workflow_task(update)
22161            .expect("typed update task");
22162        assert_eq!(commands[0]["type"], "complete_update");
22163        assert_eq!(
22164            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22165                .expect("typed update result"),
22166            arguments
22167        );
22168
22169        let mut signal = workflow_task(
22170            "typed.signal",
22171            vec![history_event(
22172                "SignalReceived",
22173                json!({
22174                    "signal_id": "signal-typed",
22175                    "signal_name": "changed",
22176                    "arguments": envelope.clone(),
22177                }),
22178            )],
22179            DEFAULT_CODEC,
22180        );
22181        signal.workflow_signal_id = Some("signal-typed".to_string());
22182        signal.signal_name = Some("changed".to_string());
22183        signal.signal_arguments = Some(envelope);
22184        let commands = worker
22185            .execute_workflow_task(signal)
22186            .expect("typed signal resume");
22187        assert_eq!(
22188            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22189                .expect("typed signal result"),
22190            arguments
22191        );
22192    }
22193
22194    #[tokio::test]
22195    async fn typed_helpers_never_parse_json_inspection_projection() {
22196        let collision_values = projection_collision_probe();
22197        let expected = AvroValue::Array(collision_values.clone());
22198        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
22199
22200        let activity_context = workflow_context_with_codec(
22201            vec![history_event(
22202                "ActivityCompleted",
22203                json!({
22204                    "sequence": 1,
22205                    "activity_type": "collision.activity",
22206                    "payload_codec": DEFAULT_CODEC,
22207                    "result": envelope.clone(),
22208                }),
22209            )],
22210            DEFAULT_CODEC,
22211        );
22212        assert_eq!(
22213            activity_context
22214                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
22215                .await
22216                .expect("typed activity collision result"),
22217            expected
22218        );
22219
22220        let signal_context = workflow_context_with_codec(
22221            vec![
22222                history_event(
22223                    "SignalWaitOpened",
22224                    json!({"sequence": 1, "signal_name": "collision"}),
22225                ),
22226                history_event(
22227                    "SignalApplied",
22228                    json!({
22229                        "sequence": 1,
22230                        "signal_name": "collision",
22231                        "payload_codec": DEFAULT_CODEC,
22232                        "value": envelope.clone(),
22233                    }),
22234                ),
22235            ],
22236            DEFAULT_CODEC,
22237        );
22238        assert_eq!(
22239            signal_context
22240                .wait_signal_avro_value("collision")
22241                .await
22242                .expect("typed signal collision arguments"),
22243            collision_values
22244        );
22245
22246        let child_context = workflow_context_with_codec(
22247            vec![
22248                history_event(
22249                    "ChildWorkflowScheduled",
22250                    json!({
22251                        "sequence": 1,
22252                        "child_workflow_instance_id": "collision-child",
22253                        "child_workflow_run_id": "collision-run",
22254                        "child_workflow_type": "collision.child",
22255                    }),
22256                ),
22257                history_event(
22258                    "ChildRunCompleted",
22259                    json!({
22260                        "sequence": 1,
22261                        "child_workflow_instance_id": "collision-child",
22262                        "child_workflow_run_id": "collision-run",
22263                        "child_workflow_type": "collision.child",
22264                        "payload_codec": DEFAULT_CODEC,
22265                        "result": envelope,
22266                    }),
22267                ),
22268            ],
22269            DEFAULT_CODEC,
22270        );
22271        let child = child_context
22272            .start_child_workflow_avro_value(
22273                "collision.child",
22274                ChildWorkflowOptions::new("collision-workers"),
22275                AvroValue::Array(Vec::new()),
22276            )
22277            .await
22278            .expect("typed child collision result");
22279        assert_eq!(child.result, expected);
22280    }
22281
22282    #[tokio::test]
22283    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
22284        let client = Client::new("http://127.0.0.1:8080").expect("client");
22285        let mut worker = Worker::new(client, "rust-workers");
22286        worker.register_replayed_workflow_avro_value(
22287            "typed.replayed",
22288            || (),
22289            |_ctx, input, _state| async move { Ok(input) },
22290        );
22291        worker.register_replayed_query_avro_value::<(), _, _>(
22292            "typed.replayed",
22293            "inspect",
22294            |ctx, _state, args| async move {
22295                let mut signals = ctx.signals_avro_value("collision");
22296                let signal = signals
22297                    .pop()
22298                    .map(AvroValue::Array)
22299                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
22300                Ok(AvroValue::Array(vec![
22301                    ctx.workflow_input_avro_value().clone(),
22302                    signal,
22303                    args,
22304                ]))
22305            },
22306        );
22307        let arguments = AvroValue::Array(projection_collision_probe());
22308        let signal_arguments =
22309            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
22310        let task = QueryTask {
22311            query_task_id: "query-typed-replay".to_string(),
22312            observability_context: None,
22313            dispatch_observability_context: None,
22314            observability_links: None,
22315            query_task_attempt: 1,
22316            lease_owner: Some("rust-worker".to_string()),
22317            workflow_id: Some("typed-replay".to_string()),
22318            run_id: Some("run-typed-replay".to_string()),
22319            workflow_type: "typed.replayed".to_string(),
22320            query_name: "inspect".to_string(),
22321            payload_codec: DEFAULT_CODEC.to_string(),
22322            workflow_arguments: Some(
22323                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
22324            ),
22325            query_arguments: Some(
22326                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
22327            ),
22328            history_events: vec![history_event(
22329                "SignalReceived",
22330                json!({
22331                    "signal_id": "collision-signal",
22332                    "signal_name": "collision",
22333                    "workflow_sequence": 1,
22334                    "payload_codec": DEFAULT_CODEC,
22335                    "arguments": signal_arguments,
22336                }),
22337            )],
22338            history_export: None,
22339            run_status: Some("completed".to_string()),
22340        };
22341
22342        assert_eq!(
22343            worker
22344                .execute_query_task(task)
22345                .await
22346                .expect("typed replay query"),
22347            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
22348        );
22349    }
22350
22351    #[test]
22352    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
22353        let value = BTreeMap::from([(1_i32, "integer key")]);
22354        let error = PayloadEnvelope::avro(&value)
22355            .expect_err("integer map keys must fail")
22356            .to_string();
22357
22358        assert!(error.contains("invalid_map_key"));
22359    }
22360
22361    #[test]
22362    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
22363        let envelope = PayloadEnvelope {
22364            codec: "json".to_string(),
22365            blob: r#"{"greeting":"hello"}"#.to_string(),
22366        };
22367
22368        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
22369        let diagnostic = error.to_string();
22370        assert!(diagnostic.contains("unsupported_payload_codec"));
22371        assert!(diagnostic.contains("codec=\"avro\""));
22372        assert!(diagnostic.contains("HTTP document transport"));
22373    }
22374
22375    #[test]
22376    fn untagged_json_payload_value_fails_closed() {
22377        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
22378            .expect_err("untagged JSON payload values must fail");
22379        let diagnostic = error.to_string();
22380        assert!(diagnostic.contains("unsupported_payload_codec"));
22381        assert!(diagnostic.contains("untagged durable payload"));
22382        assert!(diagnostic.contains("HTTP document transport"));
22383    }
22384
22385    #[test]
22386    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
22387        let envelope = PayloadEnvelope {
22388            codec: DEFAULT_CODEC.to_string(),
22389            blob: BASE64.encode([0x01]),
22390        };
22391
22392        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
22393        assert!(error.to_string().contains("invalid_payload_framing"));
22394    }
22395
22396    #[tokio::test]
22397    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
22398        let server = MockWorkerServer::start();
22399        let client = Client::builder(server.base_url())
22400            .timeout(Duration::from_secs(2))
22401            .build()
22402            .expect("client");
22403        let invalid_commands = [
22404            json!({
22405                "type": "complete_workflow",
22406                "result": {"codec": "json", "blob": null}
22407            }),
22408            json!({
22409                "type": "schedule_activity",
22410                "arguments": {"codec": "yaml", "blob": "ignored"}
22411            }),
22412            json!({
22413                "type": "start_child_workflow",
22414                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
22415            }),
22416            json!({"type": "continue_as_new", "arguments": []}),
22417            json!({"type": "complete_update"}),
22418            json!({"type": "record_side_effect", "result": null}),
22419            json!({
22420                "type": "start_service_operation",
22421                "payload_codec": DEFAULT_CODEC,
22422                "request_payload": "raw-avro-bytes"
22423            }),
22424        ];
22425
22426        for command in invalid_commands {
22427            let error = client
22428                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
22429                .await
22430                .expect_err("invalid durable payload must fail locally");
22431            let diagnostic = error.to_string();
22432            assert!(
22433                diagnostic.contains("unsupported_payload_codec")
22434                    || diagnostic.contains("invalid_payload_envelope")
22435                    || diagnostic.contains("untagged durable payload"),
22436                "unexpected validation diagnostic: {diagnostic}"
22437            );
22438        }
22439
22440        assert_eq!(
22441            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
22442            0,
22443            "invalid command payloads must not reach HTTP transport"
22444        );
22445    }
22446
22447    #[test]
22448    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
22449        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
22450        let commands = [
22451            json!({"type": "complete_workflow", "result": envelope.clone()}),
22452            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
22453            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
22454            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
22455            json!({"type": "complete_update", "result": envelope.clone()}),
22456            json!({"type": "record_side_effect", "result": envelope.clone()}),
22457            json!({
22458                "type": "start_service_operation",
22459                "payload_codec": DEFAULT_CODEC,
22460                "request_payload": envelope.clone()
22461            }),
22462            json!({
22463                "type": "complete_workflow",
22464                "result": envelope,
22465                "metadata": {
22466                    "codec": "json",
22467                    "payload_codec": "customer-codec",
22468                    "result": {"codec": "yaml", "blob": null}
22469                }
22470            }),
22471        ];
22472
22473        validate_workflow_task_commands(&commands)
22474            .expect("customer metadata must not become a protocol codec declaration");
22475    }
22476
22477    #[test]
22478    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
22479        assert_eq!(
22480            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
22481            AvroValue::Array(Vec::new())
22482        );
22483        assert_eq!(
22484            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
22485            AvroValue::Array(Vec::new())
22486        );
22487
22488        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22489        signal.signal_name = Some("empty-signal".to_string());
22490        signal.signal_arguments = None;
22491        let decoded = decode_resume_signal(&signal)
22492            .expect("valid Avro signal")
22493            .expect("named signal resumes the workflow");
22494        assert!(decoded.arguments.is_empty());
22495    }
22496
22497    #[tokio::test]
22498    async fn malformed_task_level_codecs_become_pre_handler_failures() {
22499        let client = Client::new("http://127.0.0.1:8080").expect("client");
22500        let mut worker = Worker::new(client, "rust-workers");
22501        let handler_calls = Arc::new(AtomicUsize::new(0));
22502
22503        let calls = Arc::clone(&handler_calls);
22504        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22505            calls.fetch_add(1, Ordering::SeqCst);
22506            async move { Ok(Value::Null) }
22507        });
22508        let calls = Arc::clone(&handler_calls);
22509        worker.register_activity("codec.activity", move |_ctx, _args| {
22510            calls.fetch_add(1, Ordering::SeqCst);
22511            async move { Ok(Value::Null) }
22512        });
22513        let calls = Arc::clone(&handler_calls);
22514        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22515            calls.fetch_add(1, Ordering::SeqCst);
22516            async move { Ok(Value::Null) }
22517        });
22518
22519        let mut failures = Vec::new();
22520        for codec_case in [
22521            InvalidTaskPayloadCodec::Missing,
22522            InvalidTaskPayloadCodec::Null,
22523            InvalidTaskPayloadCodec::NonString,
22524        ] {
22525            let mut workflow = json!({
22526                "task_id": format!("workflow-{}", codec_case.label()),
22527                "workflow_type": "codec.workflow"
22528            });
22529            codec_case.apply(&mut workflow);
22530            match serde_json::from_value::<WorkflowTask>(workflow) {
22531                Ok(task) => match worker.execute_workflow_task(task) {
22532                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
22533                    outcome => failures.push(format!(
22534                        "workflow {} codec returned {outcome:?}",
22535                        codec_case.label()
22536                    )),
22537                },
22538                Err(error) => failures.push(format!(
22539                    "workflow {} codec failed transport deserialization: {error}",
22540                    codec_case.label()
22541                )),
22542            }
22543
22544            let mut activity = json!({
22545                "task_id": format!("activity-{}", codec_case.label()),
22546                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
22547                "activity_type": "codec.activity",
22548                "attempt_number": 1
22549            });
22550            codec_case.apply(&mut activity);
22551            match serde_json::from_value::<ActivityTask>(activity) {
22552                Ok(task) => match worker.execute_activity_task(task).await {
22553                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
22554                    outcome => failures.push(format!(
22555                        "activity {} codec returned {outcome:?}",
22556                        codec_case.label()
22557                    )),
22558                },
22559                Err(error) => failures.push(format!(
22560                    "activity {} codec failed transport deserialization: {error}",
22561                    codec_case.label()
22562                )),
22563            }
22564
22565            let mut query = json!({
22566                "query_task_id": format!("query-{}", codec_case.label()),
22567                "workflow_type": "codec.workflow",
22568                "query_name": "known"
22569            });
22570            codec_case.apply(&mut query);
22571            match serde_json::from_value::<QueryTask>(query) {
22572                Ok(task) => match worker.execute_query_task(task).await {
22573                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
22574                    outcome => failures.push(format!(
22575                        "query {} codec returned {outcome:?}",
22576                        codec_case.label()
22577                    )),
22578                },
22579                Err(error) => failures.push(format!(
22580                    "query {} codec failed transport deserialization: {error}",
22581                    codec_case.label()
22582                )),
22583            }
22584        }
22585
22586        assert!(failures.is_empty(), "{}", failures.join("\n"));
22587        assert_eq!(
22588            handler_calls.load(Ordering::SeqCst),
22589            0,
22590            "invalid task codecs must not invoke a handler"
22591        );
22592    }
22593
22594    #[tokio::test]
22595    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
22596        for codec_case in [
22597            InvalidTaskPayloadCodec::Missing,
22598            InvalidTaskPayloadCodec::Null,
22599            InvalidTaskPayloadCodec::NonString,
22600        ] {
22601            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
22602            let client = Client::builder(server.base_url())
22603                .timeout(Duration::from_secs(2))
22604                .build()
22605                .expect("client");
22606            let mut worker = Worker::new(client, "rust-workers")
22607                .worker_id("codec-worker")
22608                .poll_timeout(Duration::from_millis(10));
22609            let handler_calls = Arc::new(AtomicUsize::new(0));
22610
22611            let calls = Arc::clone(&handler_calls);
22612            worker.register_workflow("codec.workflow", move |_ctx, _args| {
22613                calls.fetch_add(1, Ordering::SeqCst);
22614                async move { Ok(Value::Null) }
22615            });
22616            let calls = Arc::clone(&handler_calls);
22617            worker.register_activity("codec.activity", move |_ctx, _args| {
22618                calls.fetch_add(1, Ordering::SeqCst);
22619                async move { Ok(Value::Null) }
22620            });
22621            let calls = Arc::clone(&handler_calls);
22622            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22623                calls.fetch_add(1, Ordering::SeqCst);
22624                async move { Ok(Value::Null) }
22625            });
22626
22627            assert_eq!(
22628                worker.run_once().await.expect("invalid tasks are settled"),
22629                3,
22630                "all {} codec tasks must be handled",
22631                codec_case.label()
22632            );
22633            assert_eq!(
22634                handler_calls.load(Ordering::SeqCst),
22635                0,
22636                "{} task codecs must fail before every handler",
22637                codec_case.label()
22638            );
22639
22640            for path in [
22641                "/api/worker/workflow-tasks/codec-workflow/fail",
22642                "/api/worker/activity-tasks/codec-activity/fail",
22643                "/api/worker/query-tasks/codec-query/fail",
22644            ] {
22645                let body = server.request_body(path);
22646                assert!(
22647                    body["failure"]["message"]
22648                        .as_str()
22649                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
22650                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
22651                    codec_case.label()
22652                );
22653            }
22654            assert_eq!(
22655                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
22656                    ["reason"],
22657                "query_payload_decode_failed"
22658            );
22659            for path in [
22660                "/api/worker/workflow-tasks/codec-workflow/complete",
22661                "/api/worker/activity-tasks/codec-activity/complete",
22662                "/api/worker/query-tasks/codec-query/complete",
22663            ] {
22664                assert_eq!(
22665                    server.request_count(path),
22666                    0,
22667                    "invalid {} codec task reached {path}",
22668                    codec_case.label()
22669                );
22670            }
22671        }
22672    }
22673
22674    #[tokio::test]
22675    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
22676        let client = Client::new("http://127.0.0.1:8080").expect("client");
22677        let mut worker = Worker::new(client, "rust-workers");
22678        let handler_calls = Arc::new(AtomicUsize::new(0));
22679
22680        let calls = Arc::clone(&handler_calls);
22681        worker.register_workflow("codec.workflow", move |_ctx, _args| {
22682            calls.fetch_add(1, Ordering::SeqCst);
22683            async move { Ok(Value::Null) }
22684        });
22685        let calls = Arc::clone(&handler_calls);
22686        worker.register_activity("codec.activity", move |_ctx, _args| {
22687            calls.fetch_add(1, Ordering::SeqCst);
22688            async move { Ok(Value::Null) }
22689        });
22690        let calls = Arc::clone(&handler_calls);
22691        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
22692            calls.fetch_add(1, Ordering::SeqCst);
22693            async move { Ok(Value::Null) }
22694        });
22695        let calls = Arc::clone(&handler_calls);
22696        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
22697            calls.fetch_add(1, Ordering::SeqCst);
22698            async move { Ok(Value::Null) }
22699        });
22700
22701        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22702        workflow.payload_codec = "json".to_string();
22703        workflow.arguments = None;
22704        let error = worker
22705            .execute_workflow_task(workflow)
22706            .expect_err("task codec must be checked before workflow invocation");
22707        assert!(error.to_string().contains("unsupported_payload_codec"));
22708
22709        let activity = ActivityTask {
22710            task_id: "activity-invalid-codec".to_string(),
22711            workflow_id: None,
22712            run_id: None,
22713            activity_execution_id: None,
22714            observability_context: None,
22715            dispatch_observability_context: None,
22716            observability_links: None,
22717            activity_attempt_id: None,
22718            attempt_id: None,
22719            activity_type: "codec.activity".to_string(),
22720            payload_codec: "unknown".to_string(),
22721            arguments: None,
22722            attempt_number: 1,
22723            lease_owner: None,
22724        };
22725        let error = worker
22726            .execute_activity_task(activity)
22727            .await
22728            .expect_err("task codec must be checked before activity invocation");
22729        assert!(error.to_string().contains("unsupported_payload_codec"));
22730
22731        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22732        update.workflow_update_id = Some("update-invalid-codec".to_string());
22733        update.update_name = Some("known".to_string());
22734        update.history_events.push(history_event(
22735            "UpdateAccepted",
22736            json!({
22737                "update_id": "update-invalid-codec",
22738                "update_name": "known",
22739                "arguments": {"codec": "json", "blob": null}
22740            }),
22741        ));
22742        let error = worker
22743            .execute_workflow_task(update)
22744            .expect_err("nested update codec must be checked before handler lookup");
22745        assert!(error.to_string().contains("unsupported_payload_codec"));
22746
22747        let query: QueryTask = serde_json::from_value(json!({
22748            "query_task_id": "query-invalid-codec",
22749            "workflow_type": "codec.workflow",
22750            "query_name": "known",
22751            "payload_codec": DEFAULT_CODEC,
22752            "workflow_arguments": null,
22753            "query_arguments": null,
22754            "history_export": {
22755                "payloads": {"codec": DEFAULT_CODEC},
22756                "signals": [{
22757                    "name": "empty",
22758                    "payload_codec": "json",
22759                    "arguments": null
22760                }]
22761            }
22762        }))
22763        .expect("query task");
22764        let failure = worker
22765            .execute_query_task(query)
22766            .await
22767            .expect_err("exported signal codec must be checked before query invocation");
22768        assert_eq!(failure.reason, "query_payload_decode_failed");
22769        assert!(failure.message.contains("unsupported_payload_codec"));
22770
22771        let exported_history: QueryTask = serde_json::from_value(json!({
22772            "query_task_id": "query-invalid-history-codec",
22773            "workflow_type": "codec.workflow",
22774            "query_name": "known",
22775            "payload_codec": DEFAULT_CODEC,
22776            "history_export": {
22777                "payloads": {"codec": DEFAULT_CODEC},
22778                "history_events": [{
22779                    "type": "ActivityCompleted",
22780                    "payload": {"payload_codec": "unknown", "result": null}
22781                }]
22782            }
22783        }))
22784        .expect("query task");
22785        let failure = worker
22786            .execute_query_task(exported_history)
22787            .await
22788            .expect_err("exported history codec must be checked before query invocation");
22789        assert_eq!(failure.reason, "query_payload_decode_failed");
22790        assert!(failure.message.contains("unsupported_payload_codec"));
22791        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
22792
22793        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
22794        unknown_workflow.arguments = None;
22795        unknown_workflow.history_events.push(history_event(
22796            "SignalReceived",
22797            json!({
22798                "signal_name": "empty",
22799                "payload_codec": "json",
22800                "arguments": null
22801            }),
22802        ));
22803        let error = worker
22804            .execute_workflow_task(unknown_workflow)
22805            .expect_err("history codec must precede unknown workflow outcome");
22806        assert!(error.to_string().contains("unsupported_payload_codec"));
22807
22808        let unknown_activity = ActivityTask {
22809            task_id: "activity-unknown".to_string(),
22810            workflow_id: None,
22811            run_id: None,
22812            activity_execution_id: None,
22813            observability_context: None,
22814            dispatch_observability_context: None,
22815            observability_links: None,
22816            activity_attempt_id: None,
22817            attempt_id: None,
22818            activity_type: "missing".to_string(),
22819            payload_codec: "json".to_string(),
22820            arguments: None,
22821            attempt_number: 1,
22822            lease_owner: None,
22823        };
22824        let error = worker
22825            .execute_activity_task(unknown_activity)
22826            .await
22827            .expect_err("codec must precede unknown activity outcome");
22828        assert!(error.to_string().contains("unsupported_payload_codec"));
22829
22830        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
22831        unknown_update.payload_codec = "json".to_string();
22832        unknown_update.arguments = None;
22833        unknown_update.workflow_update_id = Some("update-unknown".to_string());
22834        unknown_update.update_name = Some("missing".to_string());
22835        let error = worker
22836            .execute_workflow_task(unknown_update)
22837            .expect_err("codec must precede fail_update shortcut");
22838        assert!(error.to_string().contains("unsupported_payload_codec"));
22839
22840        let unknown_query: QueryTask = serde_json::from_value(json!({
22841            "query_task_id": "query-unknown",
22842            "workflow_type": "missing",
22843            "query_name": "missing",
22844            "payload_codec": "json",
22845            "workflow_arguments": null,
22846            "query_arguments": null
22847        }))
22848        .expect("query task");
22849        let failure = worker
22850            .execute_query_task(unknown_query)
22851            .await
22852            .expect_err("codec must precede unknown query outcome");
22853        assert_eq!(failure.reason, "query_payload_decode_failed");
22854        assert!(failure.message.contains("unsupported_payload_codec"));
22855    }
22856
22857    #[tokio::test]
22858    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
22859        let client = Client::new("http://127.0.0.1:8080").expect("client");
22860        let worker = Worker::new(client, "rust-workers");
22861
22862        for event_type in ["SignalReceived", "SignalApplied"] {
22863            for (payload_field, codec) in [
22864                ("value", "json"),
22865                ("input", "unknown"),
22866                ("arguments", "json"),
22867            ] {
22868                let payload = json!({
22869                    "signal_name": "empty",
22870                    payload_field: {"codec": codec, "blob": null}
22871                });
22872                let workflow = workflow_task(
22873                    "missing",
22874                    vec![history_event(event_type, payload.clone())],
22875                    DEFAULT_CODEC,
22876                );
22877                let error = worker
22878                    .execute_workflow_task(workflow)
22879                    .expect_err("signal payload codec must precede unknown workflow outcome");
22880                assert!(
22881                    error.to_string().contains("unsupported_payload_codec"),
22882                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
22883                );
22884
22885                let query: QueryTask = serde_json::from_value(json!({
22886                    "query_task_id": format!("query-{event_type}-{payload_field}"),
22887                    "workflow_type": "missing",
22888                    "query_name": "missing",
22889                    "payload_codec": DEFAULT_CODEC,
22890                    "workflow_arguments": null,
22891                    "query_arguments": null,
22892                    "history_events": [{
22893                        "event_type": event_type,
22894                        "payload": payload
22895                    }]
22896                }))
22897                .expect("query task");
22898                let failure = worker
22899                    .execute_query_task(query)
22900                    .await
22901                    .expect_err("signal payload codec must precede unknown query outcome");
22902                assert_eq!(
22903                    failure.reason, "query_payload_decode_failed",
22904                    "{event_type}.{payload_field} returned an unrelated query outcome"
22905                );
22906                assert!(
22907                    failure.message.contains("unsupported_payload_codec"),
22908                    "{event_type}.{payload_field} returned an unrelated query error: {}",
22909                    failure.message
22910                );
22911            }
22912        }
22913    }
22914
22915    #[test]
22916    fn workflow_context_schedules_activity_until_completion_is_in_history() {
22917        let ctx = WorkflowContext {
22918            cancellation_scope_id: "root".into(),
22919            state: Arc::new(Mutex::new(
22920                WorkflowState::new_with_identity(
22921                    Vec::new(),
22922                    Some("wf-parent".to_string()),
22923                    Some("run-parent".to_string()),
22924                    "rust-workers".to_string(),
22925                    DEFAULT_CODEC.to_string(),
22926                    None,
22927                )
22928                .expect("workflow state"),
22929            )),
22930        };
22931
22932        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
22933        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22934        assert!(matches!(
22935            call.as_mut().poll(&mut task_context),
22936            Poll::Pending
22937        ));
22938
22939        let commands = ctx.take_commands().expect("commands");
22940        assert_eq!(commands[0]["type"], "schedule_activity");
22941        assert_eq!(commands[0]["activity_type"], "hello.activity");
22942    }
22943
22944    #[test]
22945    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
22946        let ctx = workflow_context(Vec::new());
22947        let options = ActivityOptions::new()
22948            .task_queue("payments")
22949            .retry_policy(
22950                ActivityRetryPolicy::new(4)
22951                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
22952                    .non_retryable_error_type("ValidationError"),
22953            )
22954            .start_to_close_timeout(Duration::from_secs(120))
22955            .schedule_to_start_timeout(Duration::from_secs(10))
22956            .schedule_to_close_timeout(Duration::from_secs(300))
22957            .heartbeat_timeout(Duration::from_secs(15));
22958        let mut call = Box::pin(ctx.activity_with_options(
22959            "charge-card",
22960            options,
22961            json!([{"order_id": "o-1"}]),
22962        ));
22963        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22964
22965        assert!(matches!(
22966            call.as_mut().poll(&mut task_context),
22967            Poll::Pending
22968        ));
22969        assert!(matches!(
22970            call.as_mut().poll(&mut task_context),
22971            Poll::Pending
22972        ));
22973
22974        let commands = ctx.take_commands().expect("activity command");
22975        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
22976        assert_eq!(commands[0]["queue"], "payments");
22977        assert_eq!(
22978            commands[0]["retry_policy"],
22979            json!({
22980                "max_attempts": 4,
22981                "backoff_seconds": [1, 3, 9],
22982                "non_retryable_error_types": ["ValidationError"],
22983            })
22984        );
22985        assert_eq!(commands[0]["start_to_close_timeout"], 120);
22986        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
22987        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
22988        assert_eq!(commands[0]["heartbeat_timeout"], 15);
22989    }
22990
22991    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
22992        vec![
22993            history_event(
22994                "ActivityScheduled",
22995                json!({"sequence":1,"activity_type":"render",
22996                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
22997            ),
22998            history_event(
22999                "ActivityCompleted",
23000                json!({"sequence":1,"activity_type":"render",
23001                "payload_codec":DEFAULT_CODEC,
23002                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
23003            ),
23004        ]
23005    }
23006
23007    #[test]
23008    fn worker_session_activity_routes_to_session_queue_once() {
23009        let ctx = workflow_context(Vec::new());
23010        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23011        let mut call = Box::pin(
23012            ctx.activity("render", json!([]))
23013                .in_worker_session(session.clone()),
23014        );
23015        let mut cx = TaskContext::from_waker(noop_waker_ref());
23016        assert!(call.as_mut().poll(&mut cx).is_pending());
23017        assert!(call.as_mut().poll(&mut cx).is_pending());
23018        let commands = ctx.take_commands().unwrap();
23019        assert_eq!(commands.len(), 1);
23020        assert_eq!(commands[0]["queue"], "gpu-workers");
23021        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
23022    }
23023
23024    #[tokio::test]
23025    async fn worker_session_cold_replay_uses_recorded_avro_result() {
23026        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23027        for _replacement in 0..2 {
23028            let ctx = workflow_context(completed_worker_session_history(&session));
23029            let result: i64 = ctx
23030                .activity("render", json!([]))
23031                .in_worker_session(session.clone())
23032                .typed()
23033                .await
23034                .unwrap();
23035            assert_eq!(result, 42);
23036            assert!(ctx.take_commands().unwrap().is_empty());
23037        }
23038    }
23039
23040    #[test]
23041    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
23042        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23043        for changed in [
23044            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
23045            Some(original.clone().ttl_seconds(60)),
23046            Some(original.clone().requirements(["gpu:l4"])),
23047            None,
23048        ] {
23049            let ctx = workflow_context(completed_worker_session_history(&original));
23050            let mut call = ctx.activity_with_options(
23051                "render",
23052                ActivityOptions::new().task_queue("gpu-workers"),
23053                json!([]),
23054            );
23055            if let Some(changed) = changed {
23056                call = call.in_worker_session(changed);
23057            }
23058            let mut call = Box::pin(call);
23059            let mut cx = TaskContext::from_waker(noop_waker_ref());
23060            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23061                call.as_mut().poll(&mut cx)
23062            else {
23063                panic!("changed session must fail replay");
23064            };
23065            assert_eq!(failure.reason, "activity_worker_session_mismatch");
23066            assert!(ctx.take_commands().unwrap().is_empty());
23067        }
23068    }
23069
23070    #[test]
23071    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
23072        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23073        let ctx = workflow_context(Vec::new());
23074        let mut local = Box::pin(
23075            ctx.local_activity("render", json!([]))
23076                .in_worker_session(session.clone()),
23077        );
23078        let mut cx = TaskContext::from_waker(noop_waker_ref());
23079        assert!(matches!(
23080            local.as_mut().poll(&mut cx),
23081            Poll::Ready(Err(Error::WorkerLoop(_)))
23082        ));
23083        assert!(ctx.take_commands().unwrap().is_empty());
23084        let mut remote = Box::pin(
23085            ctx.activity_with_options(
23086                "render",
23087                ActivityOptions::new().task_queue("other"),
23088                json!([]),
23089            )
23090            .in_worker_session(session),
23091        );
23092        assert!(matches!(
23093            remote.as_mut().poll(&mut cx),
23094            Poll::Ready(Err(Error::WorkerLoop(_)))
23095        ));
23096        assert!(ctx.take_commands().unwrap().is_empty());
23097    }
23098
23099    #[test]
23100    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
23101        let ctx = workflow_context(Vec::new());
23102        let options = ActivityOptions::new().retry_policy(
23103            ActivityRetryPolicy::new(3)
23104                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
23105        );
23106        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23107        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23108
23109        assert!(matches!(
23110            call.as_mut().poll(&mut task_context),
23111            Poll::Pending
23112        ));
23113        assert_eq!(
23114            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
23115            json!([1, 2])
23116        );
23117    }
23118
23119    #[test]
23120    fn activity_options_preserve_unused_explicit_backoff_entries() {
23121        for max_attempts in [1, 2, 10] {
23122            let ctx = workflow_context(Vec::new());
23123            let options =
23124                ActivityOptions::new()
23125                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
23126                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
23127                    ));
23128            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23129            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23130            assert!(matches!(
23131                call.as_mut().poll(&mut task_context),
23132                Poll::Pending
23133            ));
23134            let commands = ctx.take_commands().expect("command");
23135            assert_eq!(commands.len(), 1);
23136            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
23137            assert_eq!(
23138                commands[0]["retry_policy"]["backoff_seconds"],
23139                json!([1, 2, 5, 10, 15, 30, 60, 120])
23140            );
23141        }
23142        let default_options = ActivityOptions::new().validate().expect("default options");
23143        let default_policy = current_activity_retry_snapshot(&default_options);
23144        assert_eq!(
23145            default_policy.max_attempts,
23146            RecordedSnapshotValue::Known(Some(1))
23147        );
23148        assert_eq!(
23149            default_policy.backoff_seconds,
23150            RecordedSnapshotValue::Known(Vec::new())
23151        );
23152    }
23153
23154    #[test]
23155    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
23156        let fixture: Value = serde_json::from_str(include_str!(
23157            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
23158        ))
23159        .expect("published PHP fixture");
23160        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
23161            .expect("unchanged published history");
23162        let matching = ActivityOptions::new().task_queue("default").retry_policy(
23163            ActivityRetryPolicy::new(1)
23164                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
23165        );
23166        let mut changed_tail = matching.clone();
23167        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
23168            [1, 2, 5, 10, 15, 30, 60, 121]
23169                .map(Duration::from_secs)
23170                .to_vec(),
23171        ));
23172        let mut changed_first = matching.clone();
23173        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
23174            [2, 2, 5, 10, 15, 30, 60, 120]
23175                .map(Duration::from_secs)
23176                .to_vec(),
23177        ));
23178        let mut changed_attempts = matching.clone();
23179        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
23180        let mut changed_types = matching.clone();
23181        changed_types
23182            .retry_policy
23183            .as_mut()
23184            .unwrap()
23185            .non_retryable_error_types = vec!["ChangedError".into()];
23186        let mut changed_start = matching.clone();
23187        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
23188        let mut changed_schedule_start = matching.clone();
23189        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
23190        let mut changed_schedule_close = matching.clone();
23191        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
23192        let mut changed_heartbeat = matching;
23193        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
23194        let unchanged_defaults = ActivityOptions::new().task_queue("default");
23195        for options in [
23196            changed_tail,
23197            changed_first,
23198            changed_attempts,
23199            changed_types,
23200            changed_start,
23201            changed_schedule_start,
23202            changed_schedule_close,
23203            changed_heartbeat,
23204            unchanged_defaults,
23205        ] {
23206            let ctx = workflow_context(history.clone());
23207            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
23208            assert!(!ctx.patched("frozen-zero").unwrap());
23209            ctx.deprecate_patch("frozen-zero").unwrap();
23210            let mut call =
23211                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
23212            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23213            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23214                call.as_mut().poll(&mut task_context)
23215            else {
23216                panic!("changed explicit policy must fail replay")
23217            };
23218            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
23219            assert_eq!(failure.sequence, Some(2));
23220            assert!(ctx.take_commands().unwrap().is_empty());
23221        }
23222    }
23223
23224    #[test]
23225    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
23226        let cases = [
23227            (
23228                ActivityOptions::new().task_queue("  "),
23229                ActivityOptionsErrorKind::EmptyTaskQueue,
23230            ),
23231            (
23232                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
23233                ActivityOptionsErrorKind::EmptyRetryPolicy,
23234            ),
23235            (
23236                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
23237                ActivityOptionsErrorKind::InvalidMaxAttempts,
23238            ),
23239            (
23240                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
23241                    max_attempts: None,
23242                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
23243                    non_retryable_error_types: Vec::new(),
23244                }),
23245                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
23246            ),
23247            (
23248                ActivityOptions::new().retry_policy(
23249                    ActivityRetryPolicy::new(2).exponential_backoff(
23250                        Duration::from_secs(1),
23251                        0,
23252                        None,
23253                    ),
23254                ),
23255                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
23256            ),
23257            (
23258                ActivityOptions::new()
23259                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
23260                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
23261            ),
23262            (
23263                ActivityOptions::new().retry_policy(
23264                    ActivityRetryPolicy::new(10_002).exponential_backoff(
23265                        Duration::from_secs(1),
23266                        1,
23267                        None,
23268                    ),
23269                ),
23270                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
23271            ),
23272            (
23273                ActivityOptions::new().retry_policy(
23274                    ActivityRetryPolicy::new(2)
23275                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
23276                ),
23277                ActivityOptionsErrorKind::BackoffOverflow,
23278            ),
23279        ];
23280
23281        for (options, expected_kind) in cases {
23282            let ctx = workflow_context(Vec::new());
23283            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
23284            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23285            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
23286                call.as_mut().poll(&mut task_context)
23287            else {
23288                panic!("expected typed activity validation error");
23289            };
23290            assert_eq!(error.kind, expected_kind);
23291            assert!(ctx.take_commands().expect("commands").is_empty());
23292        }
23293    }
23294
23295    #[test]
23296    fn activity_options_validate_positive_and_ordered_timeouts() {
23297        let zero_timeout_cases = [
23298            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
23299            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
23300            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
23301            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
23302        ];
23303        for options in zero_timeout_cases {
23304            assert_eq!(
23305                options.validate().expect_err("zero timeout").kind,
23306                ActivityOptionsErrorKind::TimeoutNotPositive
23307            );
23308        }
23309
23310        let ordering_cases = [
23311            ActivityOptions::new()
23312                .heartbeat_timeout(Duration::from_secs(11))
23313                .start_to_close_timeout(Duration::from_secs(10)),
23314            ActivityOptions::new()
23315                .start_to_close_timeout(Duration::from_secs(31))
23316                .schedule_to_close_timeout(Duration::from_secs(30)),
23317            ActivityOptions::new()
23318                .schedule_to_start_timeout(Duration::from_secs(31))
23319                .schedule_to_close_timeout(Duration::from_secs(30)),
23320        ];
23321        for options in ordering_cases {
23322            assert_eq!(
23323                options.validate().expect_err("timeout order").kind,
23324                ActivityOptionsErrorKind::TimeoutOrder
23325            );
23326        }
23327
23328        assert_eq!(
23329            ActivityOptions::new()
23330                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
23331                .validate()
23332                .expect_err("protocol integer overflow")
23333                .kind,
23334            ActivityOptionsErrorKind::TimeoutOverflow
23335        );
23336    }
23337
23338    #[test]
23339    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
23340        let ctx = workflow_context(completed_retry_activity_history());
23341        let mut call =
23342            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23343        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23344
23345        assert!(matches!(
23346            call.as_mut().poll(&mut task_context),
23347            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23348        ));
23349        assert!(ctx.take_commands().expect("commands").is_empty());
23350        ctx.ensure_history_consumed().expect("history consumed");
23351    }
23352
23353    #[test]
23354    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
23355        let mut options = retry_activity_options();
23356        options
23357            .retry_policy
23358            .as_mut()
23359            .expect("retry policy")
23360            .non_retryable_error_types
23361            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
23362
23363        let new_ctx = workflow_context(Vec::new());
23364        let mut new_call =
23365            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
23366        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23367        assert!(matches!(
23368            new_call.as_mut().poll(&mut task_context),
23369            Poll::Pending
23370        ));
23371        let commands = new_ctx.take_commands().expect("commands");
23372        assert_eq!(commands.len(), 1);
23373        assert_eq!(
23374            commands[0]["retry_policy"]["non_retryable_error_types"],
23375            json!(["PermanentError"])
23376        );
23377
23378        let replay_ctx = workflow_context(completed_retry_activity_history());
23379        let mut replay_call =
23380            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
23381        assert!(matches!(
23382            replay_call.as_mut().poll(&mut task_context),
23383            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23384        ));
23385        assert!(replay_ctx.take_commands().expect("commands").is_empty());
23386        replay_ctx
23387            .ensure_history_consumed()
23388            .expect("history consumed");
23389    }
23390
23391    #[test]
23392    fn replayed_intermediate_retry_remains_pending_across_restarts() {
23393        let history = completed_retry_activity_history()
23394            .into_iter()
23395            .take(3)
23396            .collect::<Vec<_>>();
23397
23398        for _restart in 0..2 {
23399            let ctx = workflow_context(history.clone());
23400            let mut call =
23401                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23402            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23403            assert!(matches!(
23404                call.as_mut().poll(&mut task_context),
23405                Poll::Pending
23406            ));
23407            assert!(ctx.take_commands().expect("commands").is_empty());
23408        }
23409    }
23410
23411    #[test]
23412    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
23413        let mut changed_queue = retry_activity_options();
23414        changed_queue.task_queue = Some("different-queue".to_string());
23415
23416        let mut changed_max_attempts = retry_activity_options();
23417        let retry_policy = changed_max_attempts
23418            .retry_policy
23419            .as_mut()
23420            .expect("retry policy");
23421        retry_policy.max_attempts = Some(4);
23422
23423        let mut changed_backoff = retry_activity_options();
23424        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
23425        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
23426            Duration::from_secs(3),
23427            Duration::from_secs(4),
23428        ]));
23429
23430        let mut changed_non_retryable_types = retry_activity_options();
23431        let retry_policy = changed_non_retryable_types
23432            .retry_policy
23433            .as_mut()
23434            .expect("retry policy");
23435        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
23436
23437        let mut changed_start_to_close = retry_activity_options();
23438        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
23439        let mut changed_schedule_to_start = retry_activity_options();
23440        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
23441        let mut changed_schedule_to_close = retry_activity_options();
23442        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
23443        let mut changed_heartbeat = retry_activity_options();
23444        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
23445
23446        let cases = [
23447            (changed_queue, "activity_task_queue_mismatch"),
23448            (changed_max_attempts, "activity_retry_policy_mismatch"),
23449            (changed_backoff, "activity_retry_policy_mismatch"),
23450            (
23451                changed_non_retryable_types,
23452                "activity_retry_policy_mismatch",
23453            ),
23454            (changed_start_to_close, "activity_retry_policy_mismatch"),
23455            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
23456            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
23457            (changed_heartbeat, "activity_retry_policy_mismatch"),
23458        ];
23459
23460        for (options, expected_reason) in cases {
23461            let ctx = workflow_context(completed_retry_activity_history());
23462            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
23463            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23464            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23465                call.as_mut().poll(&mut task_context)
23466            else {
23467                panic!("changed activity options must fail replay");
23468            };
23469            assert_eq!(failure.reason, expected_reason);
23470            assert_eq!(failure.sequence, Some(1));
23471            assert!(ctx.take_commands().expect("commands").is_empty());
23472        }
23473    }
23474
23475    #[test]
23476    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
23477        let cases = [
23478            (
23479                "execution_mode",
23480                json!("local"),
23481                "activity_execution_mode_mismatch",
23482            ),
23483            (
23484                "snapshot_version",
23485                json!(2),
23486                "activity_retry_policy_mismatch",
23487            ),
23488        ];
23489
23490        for (field, value, expected_reason) in cases {
23491            let mut history = completed_retry_activity_history();
23492            let activity = history[0].payload["activity"]
23493                .as_object_mut()
23494                .expect("activity snapshot");
23495            if field == "execution_mode" {
23496                activity.insert(field.to_string(), value);
23497            } else {
23498                activity["retry_policy"]
23499                    .as_object_mut()
23500                    .expect("retry snapshot")
23501                    .insert(field.to_string(), value);
23502            }
23503
23504            let ctx = workflow_context(history);
23505            let mut call =
23506                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23507            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23508            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23509                call.as_mut().poll(&mut task_context)
23510            else {
23511                panic!("changed {field} must fail replay");
23512            };
23513            assert_eq!(failure.reason, expected_reason);
23514            assert_eq!(failure.sequence, Some(1));
23515            assert!(ctx.take_commands().expect("commands").is_empty());
23516        }
23517    }
23518
23519    #[test]
23520    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
23521        for (nested, field, value, terminal_only) in [
23522            (false, "execution_mode", json!("local"), false),
23523            (false, "local_activity", json!(true), false),
23524            (true, "local_activity", json!(true), false),
23525            (false, "local_activity", json!(true), true),
23526        ] {
23527            let mut history = completed_retry_activity_history();
23528            history[0]
23529                .payload
23530                .as_object_mut()
23531                .unwrap()
23532                .remove("activity");
23533            let event = if terminal_only {
23534                history.last_mut().unwrap()
23535            } else {
23536                &mut history[0]
23537            };
23538            if nested {
23539                event.payload["activity"] = json!({(field): value});
23540            } else {
23541                event.payload[field] = value;
23542            }
23543            let ctx = workflow_context(history);
23544            let mut call =
23545                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23546            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23547            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23548                call.as_mut().poll(&mut task_context)
23549            else {
23550                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
23551            };
23552            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
23553            assert_eq!(failure.sequence, Some(1));
23554            assert!(ctx.take_commands().expect("commands").is_empty());
23555        }
23556    }
23557
23558    #[test]
23559    fn activity_history_rejects_conflicting_local_execution_markers() {
23560        let mut history = completed_retry_activity_history();
23561        history.last_mut().unwrap().payload["local_activity"] = json!(true);
23562        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
23563            .expect_err("remote schedule cannot become a local completion");
23564        assert!(
23565            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
23566            if reason == "activity_execution_mode_conflict")
23567        );
23568    }
23569
23570    #[test]
23571    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
23572        let mut history = completed_retry_activity_history();
23573        let activity = history[0].payload["activity"]
23574            .as_object_mut()
23575            .expect("activity snapshot");
23576        activity.remove("execution_mode");
23577        activity.remove("retry_policy");
23578
23579        let mut current = retry_activity_options();
23580        current.start_to_close_timeout = Some(Duration::from_secs(45));
23581        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
23582        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
23583        current.heartbeat_timeout = Some(Duration::from_secs(12));
23584
23585        let ctx = workflow_context(history);
23586        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
23587        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23588        assert!(matches!(
23589            call.as_mut().poll(&mut task_context),
23590            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
23591        ));
23592        assert!(ctx.take_commands().expect("commands").is_empty());
23593        ctx.ensure_history_consumed().expect("history consumed");
23594    }
23595
23596    #[test]
23597    fn terminal_activity_failed_after_start_returns_typed_failure() {
23598        let history = vec![
23599            history_event(
23600                "ActivityScheduled",
23601                json!({
23602                    "sequence": 1,
23603                    "activity_type": "flaky",
23604                    "activity_execution_id": "act-terminal",
23605                    "activity": {
23606                        "id": "act-terminal",
23607                        "sequence": 1,
23608                        "type": "flaky",
23609                        "queue": "critical-activities",
23610                        "retry_policy": {
23611                            "snapshot_version": 1,
23612                            "max_attempts": 3,
23613                            "backoff_seconds": [2, 4],
23614                            "non_retryable_error_types": ["PermanentError"]
23615                        }
23616                    }
23617                }),
23618            ),
23619            history_event(
23620                "ActivityStarted",
23621                json!({
23622                    "sequence": 1,
23623                    "activity_type": "flaky",
23624                    "activity_execution_id": "act-terminal",
23625                    "activity_attempt_id": "attempt-1",
23626                    "attempt_number": 1
23627                }),
23628            ),
23629            history_event(
23630                "ActivityFailed",
23631                json!({
23632                    "sequence": 1,
23633                    "activity_type": "flaky",
23634                    "activity_execution_id": "act-terminal",
23635                    "activity_attempt_id": "attempt-1",
23636                    "attempt_number": 1,
23637                    "failure_id": "failure-terminal",
23638                    "failure_category": "activity",
23639                    "exception_type": "PermanentError",
23640                    "message": "cannot retry",
23641                    "non_retryable": true
23642                }),
23643            ),
23644        ];
23645        let ctx = workflow_context(history);
23646        let mut call =
23647            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
23648        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23649
23650        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23651            call.as_mut().poll(&mut task_context)
23652        else {
23653            panic!("terminal ActivityFailed must settle the activity future");
23654        };
23655        assert_eq!(failure.kind, ActivityFailureKind::Failed);
23656        assert_eq!(
23657            failure.activity_execution_id.as_deref(),
23658            Some("act-terminal")
23659        );
23660        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
23661        assert!(failure.non_retryable);
23662        assert!(ctx.take_commands().expect("commands").is_empty());
23663        ctx.ensure_history_consumed().expect("history consumed");
23664    }
23665
23666    #[test]
23667    fn activity_terminal_events_return_machine_readable_failures() {
23668        let cases = [
23669            (
23670                "ActivityFailed",
23671                json!({
23672                    "sequence": 1,
23673                    "activity_type": "charge-card",
23674                    "activity_execution_id": "act-1",
23675                    "activity_attempt_id": "attempt-2",
23676                    "attempt_number": 2,
23677                    "failure_id": "failure-1",
23678                    "failure_category": "activity",
23679                    "exception_type": "PaymentDeclined",
23680                    "exception_class": "payments.PaymentDeclined",
23681                    "message": "card declined",
23682                    "non_retryable": true
23683                }),
23684                ActivityFailureKind::Failed,
23685                "activity",
23686            ),
23687            (
23688                "ActivityCancelled",
23689                json!({
23690                    "sequence": 1,
23691                    "activity_type": "charge-card",
23692                    "activity_execution_id": "act-1",
23693                    "activity_attempt_id": "attempt-1"
23694                }),
23695                ActivityFailureKind::Cancelled,
23696                "cancelled",
23697            ),
23698        ];
23699
23700        for (event_type, payload, expected_kind, expected_reason) in cases {
23701            let ctx = workflow_context(vec![history_event(event_type, payload)]);
23702            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
23703            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23704            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23705                call.as_mut().poll(&mut task_context)
23706            else {
23707                panic!("expected terminal activity failure");
23708            };
23709            assert_eq!(failure.kind, expected_kind);
23710            assert_eq!(failure.reason, expected_reason);
23711            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
23712            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
23713        }
23714    }
23715
23716    #[test]
23717    fn every_activity_timeout_class_is_typed() {
23718        for timeout_kind in [
23719            "start_to_close",
23720            "schedule_to_start",
23721            "schedule_to_close",
23722            "heartbeat",
23723        ] {
23724            let ctx = workflow_context(vec![history_event(
23725                "ActivityTimedOut",
23726                json!({
23727                    "sequence": 1,
23728                    "activity_type": "slow",
23729                    "activity_execution_id": "act-timeout",
23730                    "activity_attempt_id": "attempt-timeout",
23731                    "failure_category": "timeout",
23732                    "timeout_kind": timeout_kind,
23733                    "message": "deadline expired"
23734                }),
23735            )]);
23736            let mut call = Box::pin(ctx.activity("slow", json!([])));
23737            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23738            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
23739                call.as_mut().poll(&mut task_context)
23740            else {
23741                panic!("expected timeout failure");
23742            };
23743            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
23744            assert_eq!(failure.reason, timeout_kind);
23745            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
23746            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
23747        }
23748    }
23749
23750    #[test]
23751    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
23752        let ctx = workflow_context(Vec::new());
23753        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
23754        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23755
23756        assert!(matches!(
23757            sleep.as_mut().poll(&mut task_context),
23758            Poll::Pending
23759        ));
23760        assert!(matches!(
23761            sleep.as_mut().poll(&mut task_context),
23762            Poll::Pending
23763        ));
23764
23765        let commands = ctx.take_commands().expect("timer command");
23766        assert_eq!(
23767            commands,
23768            vec![json!({
23769                "type": "start_timer",
23770                "delay_seconds": 2,
23771            })]
23772        );
23773    }
23774
23775    #[test]
23776    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
23777        let history = vec![
23778            history_event(
23779                "TimerScheduled",
23780                json!({
23781                    "sequence": 1,
23782                    "timer_id": "timer-1",
23783                    "delay_seconds": 5,
23784                    "fire_at": "2026-07-11T12:00:05Z",
23785                }),
23786            ),
23787            history_event(
23788                "TimerFired",
23789                json!({
23790                    "sequence": 1,
23791                    "timer_id": "timer-1",
23792                    "delay_seconds": 5,
23793                    "fire_at": "2026-07-11T12:00:05Z",
23794                    "fired_at": "2026-07-11T12:00:05Z",
23795                }),
23796            ),
23797        ];
23798
23799        for _restart in 0..2 {
23800            let ctx = workflow_context(history.clone());
23801            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
23802            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23803            assert!(matches!(
23804                sleep.as_mut().poll(&mut task_context),
23805                Poll::Ready(Ok(()))
23806            ));
23807            assert!(ctx.take_commands().expect("commands").is_empty());
23808            ctx.ensure_history_consumed().expect("history consumed");
23809        }
23810    }
23811
23812    #[test]
23813    fn workflow_sleep_rejects_changed_delay_during_replay() {
23814        let ctx = workflow_context(vec![
23815            history_event(
23816                "TimerScheduled",
23817                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23818            ),
23819            history_event(
23820                "TimerFired",
23821                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
23822            ),
23823        ]);
23824        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
23825        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23826
23827        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
23828            sleep.as_mut().poll(&mut task_context)
23829        else {
23830            panic!("changed timer delay must be rejected");
23831        };
23832        assert_eq!(failure.reason, "timer_delay_mismatch");
23833        assert_eq!(failure.sequence, Some(1));
23834    }
23835
23836    #[test]
23837    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
23838        let ctx = workflow_context(Vec::new());
23839        let mut wait = Box::pin(
23840            ctx.wait_condition(
23841                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
23842                    .timeout(Duration::from_millis(60_001)),
23843                || Ok(false),
23844            ),
23845        );
23846        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23847
23848        assert!(matches!(
23849            wait.as_mut().poll(&mut task_context),
23850            Poll::Pending
23851        ));
23852        assert!(matches!(
23853            wait.as_mut().poll(&mut task_context),
23854            Poll::Pending
23855        ));
23856        assert_eq!(
23857            ctx.take_commands().expect("condition command"),
23858            vec![json!({
23859                "type": "open_condition_wait",
23860                "condition_wait_occurrence_id": "rust:condition-wait:0",
23861                "condition_key": "approval.ready",
23862                "condition_definition_fingerprint": "sha256:approval-v1",
23863                "timeout_seconds": 61,
23864            })]
23865        );
23866    }
23867
23868    #[test]
23869    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
23870        let ctx = workflow_context(Vec::new());
23871        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
23872        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23873        assert!(matches!(
23874            satisfied.as_mut().poll(&mut task_context),
23875            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23876        ));
23877
23878        let mut timed_out = Box::pin(wait_condition!(
23879            ctx,
23880            "no-wait",
23881            timeout: Duration::ZERO,
23882            || Ok(false),
23883        ));
23884        assert!(matches!(
23885            timed_out.as_mut().poll(&mut task_context),
23886            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
23887        ));
23888        assert!(ctx.take_commands().expect("commands").is_empty());
23889    }
23890
23891    #[test]
23892    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
23893        let signal_history = vec![
23894            history_event(
23895                "ConditionWaitOpened",
23896                json!({
23897                    "sequence": 4,
23898                    "condition_wait_id": "condition:4",
23899                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23900                    "condition_key": "approval",
23901                    "condition_definition_fingerprint": "sha256:approval-v1",
23902                    "timeout_seconds": 30,
23903                }),
23904            ),
23905            history_event(
23906                "SignalReceived",
23907                json!({
23908                    "workflow_sequence": 4,
23909                    "signal_name": "approve",
23910                    "arguments": fixture_envelope(json!(["Ada"])),
23911                }),
23912            ),
23913        ];
23914        for _worker_before_or_after_restart in 0..2 {
23915            let ctx = workflow_context(signal_history.clone());
23916            let predicate_ctx = ctx.clone();
23917            let mut wait = Box::pin(
23918                ctx.wait_condition(
23919                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
23920                        .timeout(Duration::from_secs(30)),
23921                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
23922                ),
23923            );
23924            let mut task_context = TaskContext::from_waker(noop_waker_ref());
23925            assert!(matches!(
23926                wait.as_mut().poll(&mut task_context),
23927                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23928            ));
23929            assert!(ctx.take_commands().expect("commands").is_empty());
23930            ctx.ensure_history_consumed().expect("condition consumed");
23931        }
23932
23933        let update_history = vec![
23934            history_event(
23935                "ConditionWaitOpened",
23936                json!({
23937                    "sequence": 7,
23938                    "condition_wait_id": "condition:7",
23939                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23940                    "condition_key": "update-approval",
23941                    "condition_definition_fingerprint": "sha256:update-approval-v1",
23942                }),
23943            ),
23944            history_event(
23945                "UpdateApplied",
23946                json!({
23947                    "sequence": 7,
23948                    "update_id": "update-1",
23949                    "update_name": "approve",
23950                    "arguments": fixture_envelope(json!([true])),
23951                }),
23952            ),
23953        ];
23954        let ctx = workflow_context(update_history);
23955        let predicate_ctx = ctx.clone();
23956        let mut wait = Box::pin(ctx.wait_condition(
23957            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
23958            move || {
23959                Ok(predicate_ctx
23960                    .updates("approve")?
23961                    .first()
23962                    .and_then(|arguments| arguments.first())
23963                    .and_then(Value::as_bool)
23964                    == Some(true))
23965            },
23966        ));
23967        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23968        assert!(matches!(
23969            wait.as_mut().poll(&mut task_context),
23970            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
23971        ));
23972        assert!(ctx.take_commands().expect("commands").is_empty());
23973        ctx.ensure_history_consumed().expect("condition consumed");
23974    }
23975
23976    #[test]
23977    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
23978        let open_history = vec![
23979            history_event(
23980                "ConditionWaitOpened",
23981                json!({
23982                    "sequence": 3,
23983                    "condition_wait_id": "condition:3",
23984                    "condition_wait_occurrence_id": "rust:condition-wait:0",
23985                    "condition_key": "two-votes",
23986                    "condition_definition_fingerprint": "sha256:two-votes-v1",
23987                    "timeout_seconds": 120,
23988                }),
23989            ),
23990            history_event(
23991                "SignalReceived",
23992                json!({
23993                    "workflow_sequence": 3,
23994                    "signal_name": "vote",
23995                    "arguments": fixture_envelope(json!(["first"])),
23996                }),
23997            ),
23998        ];
23999        for _worker_before_or_after_restart in 0..2 {
24000            let ctx = workflow_context(open_history.clone());
24001            let predicate_ctx = ctx.clone();
24002            let mut wait = Box::pin(
24003                ctx.wait_condition(
24004                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24005                        .timeout(Duration::from_secs(120)),
24006                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
24007                ),
24008            );
24009            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24010            assert!(matches!(
24011                wait.as_mut().poll(&mut task_context),
24012                Poll::Pending
24013            ));
24014            assert_eq!(
24015                ctx.take_commands().expect("reopened condition"),
24016                vec![json!({
24017                    "type": "open_condition_wait",
24018                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24019                    "condition_key": "two-votes",
24020                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24021                    "timeout_seconds": 120,
24022                })]
24023            );
24024        }
24025
24026        let satisfied_ctx = workflow_context(vec![
24027            history_event(
24028                "ConditionWaitOpened",
24029                json!({
24030                    "sequence": 5,
24031                    "condition_wait_id": "condition:5",
24032                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24033                    "condition_key": "approval",
24034                    "condition_definition_fingerprint": "sha256:approval-v1",
24035                }),
24036            ),
24037            history_event(
24038                "ConditionWaitSatisfied",
24039                json!({
24040                    "sequence": 5,
24041                    "condition_wait_id": "condition:5",
24042                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24043                    "condition_key": "approval",
24044                    "condition_definition_fingerprint": "sha256:approval-v1",
24045                }),
24046            ),
24047        ]);
24048        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
24049            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
24050            || Ok(false),
24051        ));
24052        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24053        assert!(matches!(
24054            satisfied.as_mut().poll(&mut task_context),
24055            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24056        ));
24057
24058        let timed_out_ctx = workflow_context(vec![
24059            history_event(
24060                "ConditionWaitOpened",
24061                json!({
24062                    "sequence": 8,
24063                    "condition_wait_id": "condition:8",
24064                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24065                    "condition_key": "approval-timeout",
24066                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
24067                    "timeout_seconds": 5,
24068                }),
24069            ),
24070            history_event(
24071                "TimerScheduled",
24072                json!({
24073                    "sequence": 9,
24074                    "timer_id": "condition-timer:9",
24075                    "timer_kind": "condition_timeout",
24076                    "condition_wait_id": "condition:8",
24077                    "delay_seconds": 5,
24078                }),
24079            ),
24080            history_event(
24081                "TimerFired",
24082                json!({
24083                    "sequence": 9,
24084                    "timer_id": "condition-timer:9",
24085                    "timer_kind": "condition_timeout",
24086                    "condition_wait_id": "condition:8",
24087                    "delay_seconds": 5,
24088                }),
24089            ),
24090        ]);
24091        let mut timed_out = Box::pin(
24092            timed_out_ctx.wait_condition(
24093                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
24094                    .timeout(Duration::from_secs(5)),
24095                || Ok(true),
24096            ),
24097        );
24098        assert!(matches!(
24099            timed_out.as_mut().poll(&mut task_context),
24100            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
24101        ));
24102    }
24103
24104    #[test]
24105    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
24106        let ctx = workflow_context(reopened_selection_condition_history());
24107        {
24108            let state = ctx.state.lock().unwrap();
24109            assert!(matches!(
24110                selection_member_recorded_command(&state, 2),
24111                Some(RecordedCommand::ConditionWait {
24112                    sequence: 3,
24113                    result: None,
24114                    ..
24115                })
24116            ));
24117        }
24118        let mut selected = Box::pin(ctx.select_keyed(vec![
24119            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
24120            (
24121                "votes",
24122                ParallelOperation::condition(
24123                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
24124                    || Ok(true),
24125                ),
24126            ),
24127        ]));
24128        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24129        assert!(selected.as_mut().poll(&mut task_context).is_pending());
24130        assert!(
24131            ctx.take_commands().unwrap().is_empty(),
24132            "true predicate must not reopen the recorded wait"
24133        );
24134        ctx.ensure_history_consumed()
24135            .expect("physical reopens are consumed while canonical selection is pending");
24136    }
24137
24138    #[test]
24139    fn reopened_selection_condition_replays_its_latest_physical_winner() {
24140        for (terminal_type, acknowledge_timeout) in [
24141            ("ConditionWaitSatisfied", false),
24142            ("ConditionWaitTimedOut", false),
24143            ("TimerFired", false),
24144            ("TimerFired", true),
24145        ] {
24146            let mut history = reopened_selection_condition_history();
24147            let original_identity = history[1].payload["condition_wait_id"].clone();
24148            let uses_timer = terminal_type == "TimerFired";
24149            let mut resolution_payload = history[3].payload.clone();
24150            if uses_timer {
24151                for event in &mut history[1..] {
24152                    event.payload["timeout_seconds"] = json!(3);
24153                }
24154                resolution_payload = history[3].payload.clone();
24155                resolution_payload["timer_kind"] = json!("condition_timeout");
24156                resolution_payload["timer_id"] = json!("condition-timeout-3");
24157                resolution_payload["delay_seconds"] = json!(3);
24158                history.push(history_event("TimerScheduled", resolution_payload.clone()));
24159            }
24160            let mut resolution = history_event(terminal_type, resolution_payload.clone());
24161            resolution
24162                .raw
24163                .insert("id".into(), json!("latest-condition-resolution"));
24164            history.push(resolution);
24165            history.push(history_event(
24166                "SelectionResolved",
24167                json!({
24168                    "selection_group_id": "select-calls:1:2",
24169                    "selection_group_base_sequence": 1,
24170                    "selection_group_size": 2,
24171                    "member_key": "votes",
24172                    "member_index": 1,
24173                    "member_base_sequence": 2,
24174                    "member_size": 1,
24175                    "operation_kind": "condition",
24176                    "operation_identity": original_identity,
24177                    "outcome": "completed",
24178                    "resolution_event_id": "latest-condition-resolution",
24179                    "resolution_event_type": terminal_type,
24180                }),
24181            ));
24182            if acknowledge_timeout {
24183                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
24184            }
24185            let ctx = workflow_context(history);
24186            let mut selected = Box::pin(ctx.select_keyed(vec![
24187                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
24188                (
24189                    "votes",
24190                    ParallelOperation::condition(
24191                        if uses_timer {
24192                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24193                                .timeout(Duration::from_secs(3))
24194                        } else {
24195                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24196                        },
24197                        || Ok(true),
24198                    ),
24199                ),
24200            ]));
24201            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24202            match selected.as_mut().poll(&mut task_context) {
24203                Poll::Ready(Ok(result)) => {
24204                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
24205                    let expected = if terminal_type == "ConditionWaitSatisfied" {
24206                        ConditionWaitResult::Satisfied
24207                    } else {
24208                        ConditionWaitResult::TimedOut
24209                    };
24210                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
24211                }
24212                other => panic!("latest physical winner must replay: {other:?}"),
24213            }
24214            assert!(ctx.take_commands().unwrap().is_empty());
24215            ctx.ensure_history_consumed()
24216                .expect("winner history consumed");
24217        }
24218    }
24219
24220    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
24221        let fixture: Value = serde_json::from_str(include_str!(
24222            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
24223        ))
24224        .expect("grouped condition fixture");
24225        fixture["history"]
24226            .as_array()
24227            .unwrap()
24228            .iter()
24229            .map(|event| {
24230                let mut payload = event["payload"].clone();
24231                let index = payload["parallel_group_index"].as_u64().unwrap();
24232                payload["parallel_group_id"] = json!("select-calls:1:2");
24233                payload["parallel_group_mode"] = json!("select");
24234                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
24235                payload["selection_member_index"] = json!(index);
24236                payload["selection_member_base_sequence"] = json!(index + 1);
24237                payload["selection_member_size"] = json!(1);
24238                payload["selection_member_kind"] =
24239                    json!(if index == 0 { "timer" } else { "condition" });
24240                history_event(event["event_type"].as_str().unwrap(), payload)
24241            })
24242            .collect()
24243    }
24244
24245    #[test]
24246    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
24247        let fixture: Value = serde_json::from_str(include_str!(
24248            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
24249        ))
24250        .expect("grouped condition fixture");
24251        let original = fixture["history"].as_array().expect("fixture history");
24252        let decode = |events: &[Value]| {
24253            let history = events
24254                .iter()
24255                .map(|event| {
24256                    history_event(
24257                        event["event_type"].as_str().unwrap(),
24258                        event["payload"].clone(),
24259                    )
24260                })
24261                .collect::<Vec<_>>();
24262            recorded_commands(
24263                &history,
24264                DEFAULT_CODEC,
24265                WorkflowIdentity {
24266                    workflow_id: None,
24267                    run_id: None,
24268                },
24269            )
24270        };
24271        assert!(decode(original).is_ok());
24272        for field in [
24273            "condition_wait_occurrence_id",
24274            "condition_key",
24275            "condition_definition_fingerprint",
24276            "timeout_seconds",
24277            "parallel_group_id",
24278            "parallel_group_size",
24279            "parallel_group_index",
24280        ] {
24281            let mut changed = original.clone();
24282            changed[3]["payload"][field] = match field {
24283                "timeout_seconds" | "parallel_group_size" => json!(30),
24284                "parallel_group_index" => json!(0),
24285                _ => json!("changed"),
24286            };
24287            assert!(
24288                decode(&changed).is_err(),
24289                "reopen must reject changed {field}"
24290            );
24291        }
24292        let mut unsettled = original.clone();
24293        unsettled.remove(2);
24294        assert!(
24295            decode(&unsettled).is_err(),
24296            "physical predecessor must be resolved"
24297        );
24298        let mut timed_out = original.clone();
24299        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
24300        assert!(decode(&timed_out).is_err(), "timeout is terminal");
24301        let mut late_resolution = original.clone();
24302        late_resolution.swap(2, 3);
24303        assert!(
24304            decode(&late_resolution).is_err(),
24305            "later history cannot authorize a reopen"
24306        );
24307    }
24308
24309    #[test]
24310    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
24311        let history = vec![
24312            history_event(
24313                "ConditionWaitOpened",
24314                json!({
24315                    "sequence": 3,
24316                    "condition_wait_id": "condition:3",
24317                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24318                    "condition_key": "two-votes",
24319                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24320                }),
24321            ),
24322            history_event(
24323                "SignalReceived",
24324                json!({
24325                    "workflow_sequence": 3,
24326                    "signal_name": "vote",
24327                    "arguments": fixture_envelope(json!(["first"])),
24328                }),
24329            ),
24330            history_event(
24331                "ConditionWaitSatisfied",
24332                json!({
24333                    "sequence": 3,
24334                    "condition_wait_id": "condition:3",
24335                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24336                    "condition_key": "two-votes",
24337                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24338                }),
24339            ),
24340            history_event(
24341                "ConditionWaitOpened",
24342                json!({
24343                    "sequence": 5,
24344                    "condition_wait_id": "condition:5",
24345                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24346                    "condition_key": "two-votes",
24347                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24348                }),
24349            ),
24350            history_event(
24351                "SignalReceived",
24352                json!({
24353                    "workflow_sequence": 5,
24354                    "signal_name": "vote",
24355                    "arguments": fixture_envelope(json!(["second"])),
24356                }),
24357            ),
24358            history_event(
24359                "ConditionWaitSatisfied",
24360                json!({
24361                    "sequence": 5,
24362                    "condition_wait_id": "condition:5",
24363                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24364                    "condition_key": "two-votes",
24365                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24366                }),
24367            ),
24368        ];
24369        for _cold_worker_or_restart in 0..2 {
24370            let ctx = workflow_context(history.clone());
24371            let predicate_ctx = ctx.clone();
24372            let mut wait = Box::pin(ctx.wait_condition(
24373                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
24374                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
24375            ));
24376            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24377
24378            assert!(matches!(
24379                wait.as_mut().poll(&mut task_context),
24380                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24381            ));
24382            assert!(ctx.take_commands().expect("commands").is_empty());
24383            ctx.ensure_history_consumed()
24384                .expect("every physical wait-open is consumed");
24385        }
24386    }
24387
24388    #[test]
24389    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
24390        let history = vec![
24391            history_event(
24392                "ConditionWaitOpened",
24393                json!({
24394                    "sequence": 3,
24395                    "condition_wait_id": "condition:3",
24396                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24397                    "condition_key": "approved",
24398                    "condition_definition_fingerprint": "sha256:approved-v1",
24399                }),
24400            ),
24401            history_event(
24402                "UpdateApplied",
24403                json!({
24404                    "sequence": 3,
24405                    "update_id": "update-1",
24406                    "update_name": "approve",
24407                    "arguments": fixture_envelope(json!([false])),
24408                }),
24409            ),
24410            history_event(
24411                "ConditionWaitOpened",
24412                json!({
24413                    "sequence": 5,
24414                    "condition_wait_id": "condition:5",
24415                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24416                    "condition_key": "approved",
24417                    "condition_definition_fingerprint": "sha256:approved-v1",
24418                }),
24419            ),
24420            history_event(
24421                "UpdateApplied",
24422                json!({
24423                    "sequence": 5,
24424                    "update_id": "update-2",
24425                    "update_name": "approve",
24426                    "arguments": fixture_envelope(json!([true])),
24427                }),
24428            ),
24429        ];
24430
24431        for _cold_worker_or_restart in 0..2 {
24432            let ctx = workflow_context(history.clone());
24433            let predicate_ctx = ctx.clone();
24434            let mut wait = Box::pin(ctx.wait_condition(
24435                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
24436                move || {
24437                    Ok(predicate_ctx
24438                        .updates("approve")?
24439                        .last()
24440                        .and_then(|arguments| arguments.first())
24441                        .and_then(Value::as_bool)
24442                        == Some(true))
24443                },
24444            ));
24445            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24446
24447            assert!(matches!(
24448                wait.as_mut().poll(&mut task_context),
24449                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24450            ));
24451            assert!(ctx.take_commands().expect("commands").is_empty());
24452            ctx.ensure_history_consumed()
24453                .expect("every update-driven reopen is consumed");
24454        }
24455    }
24456
24457    #[test]
24458    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
24459        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
24460            ("shared", "sha256:first", "shared", "sha256:second"),
24461            ("first", "sha256:shared", "second", "sha256:shared"),
24462            ("shared", "sha256:shared", "shared", "sha256:shared"),
24463            ("first", "sha256:first", "second", "sha256:second"),
24464        ] {
24465            let history = vec![
24466                history_event(
24467                    "ConditionWaitOpened",
24468                    json!({
24469                        "sequence": 3,
24470                        "condition_wait_id": "condition:3",
24471                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24472                        "condition_key": first_key,
24473                        "condition_definition_fingerprint": first_fingerprint,
24474                    }),
24475                ),
24476                history_event(
24477                    "ConditionWaitSatisfied",
24478                    json!({
24479                        "sequence": 3,
24480                        "condition_wait_id": "condition:3",
24481                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24482                        "condition_key": first_key,
24483                        "condition_definition_fingerprint": first_fingerprint,
24484                    }),
24485                ),
24486                history_event(
24487                    "ConditionWaitOpened",
24488                    json!({
24489                        "sequence": 4,
24490                        "condition_wait_id": "condition:4",
24491                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24492                        "condition_key": second_key,
24493                        "condition_definition_fingerprint": second_fingerprint,
24494                    }),
24495                ),
24496                history_event(
24497                    "ConditionWaitSatisfied",
24498                    json!({
24499                        "sequence": 4,
24500                        "condition_wait_id": "condition:4",
24501                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24502                        "condition_key": second_key,
24503                        "condition_definition_fingerprint": second_fingerprint,
24504                    }),
24505                ),
24506            ];
24507            for _cold_worker_or_restart in 0..2 {
24508                let ctx = workflow_context(history.clone());
24509                let mut task_context = TaskContext::from_waker(noop_waker_ref());
24510                let mut first = Box::pin(ctx.wait_condition(
24511                    ConditionWaitOptions::new(first_key, first_fingerprint),
24512                    || Ok(false),
24513                ));
24514                assert!(matches!(
24515                    first.as_mut().poll(&mut task_context),
24516                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24517                ));
24518
24519                let mut second = Box::pin(ctx.wait_condition(
24520                    ConditionWaitOptions::new(second_key, second_fingerprint),
24521                    || Ok(false),
24522                ));
24523                assert!(matches!(
24524                    second.as_mut().poll(&mut task_context),
24525                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24526                ));
24527                assert!(ctx.take_commands().expect("commands").is_empty());
24528                ctx.ensure_history_consumed()
24529                    .expect("each authored wait consumes one occurrence");
24530            }
24531        }
24532    }
24533
24534    #[test]
24535    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
24536        fn worker() -> Worker {
24537            let client = Client::new("http://127.0.0.1:8080").expect("client");
24538            let mut worker = Worker::new(client, "rust-workers");
24539            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
24540                let mut outcomes = Vec::new();
24541                for _ in 0..2 {
24542                    outcomes.push(
24543                        ctx.wait_condition(
24544                            ConditionWaitOptions::new("shared", "sha256:shared"),
24545                            || Ok(false),
24546                        )
24547                        .await?,
24548                    );
24549                }
24550                Ok(json!(outcomes))
24551            });
24552            worker
24553        }
24554
24555        let task = workflow_task(
24556            "rust.condition-loop",
24557            vec![
24558                history_event(
24559                    "ConditionWaitOpened",
24560                    json!({
24561                        "sequence": 1,
24562                        "condition_wait_id": "condition:1",
24563                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24564                        "condition_key": "shared",
24565                        "condition_definition_fingerprint": "sha256:shared",
24566                    }),
24567                ),
24568                history_event(
24569                    "ConditionWaitSatisfied",
24570                    json!({
24571                        "sequence": 1,
24572                        "condition_wait_id": "condition:1",
24573                        "condition_wait_occurrence_id": "rust:condition-wait:0",
24574                        "condition_key": "shared",
24575                        "condition_definition_fingerprint": "sha256:shared",
24576                    }),
24577                ),
24578                history_event(
24579                    "ConditionWaitOpened",
24580                    json!({
24581                        "sequence": 2,
24582                        "condition_wait_id": "condition:2",
24583                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24584                        "condition_key": "shared",
24585                        "condition_definition_fingerprint": "sha256:shared",
24586                    }),
24587                ),
24588                history_event(
24589                    "ConditionWaitSatisfied",
24590                    json!({
24591                        "sequence": 2,
24592                        "condition_wait_id": "condition:2",
24593                        "condition_wait_occurrence_id": "rust:condition-wait:1",
24594                        "condition_key": "shared",
24595                        "condition_definition_fingerprint": "sha256:shared",
24596                    }),
24597                ),
24598            ],
24599            DEFAULT_CODEC,
24600        );
24601
24602        for _cold_worker_or_restart in 0..2 {
24603            let commands = worker()
24604                .execute_workflow_task(task.clone())
24605                .expect("adjacent loop waits replay deterministically");
24606            assert_eq!(commands.len(), 1);
24607            assert_eq!(commands[0]["type"], "complete_workflow");
24608            assert_eq!(
24609                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
24610                json!(["satisfied", "satisfied"])
24611            );
24612        }
24613    }
24614
24615    #[test]
24616    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
24617        let history = vec![history_event(
24618            "ConditionWaitOpened",
24619            json!({
24620                "sequence": 12,
24621                "condition_wait_id": "condition:12",
24622                "condition_wait_occurrence_id": "rust:condition-wait:0",
24623                "condition_key": "approval",
24624                "condition_definition_fingerprint": "sha256:approval-v1",
24625                "timeout_seconds": 30,
24626            }),
24627        )];
24628        for (options, expected_reason) in [
24629            (
24630                ConditionWaitOptions::new("changed", "sha256:approval-v1")
24631                    .timeout(Duration::from_secs(30)),
24632                "condition_wait_key_mismatch",
24633            ),
24634            (
24635                ConditionWaitOptions::new("approval", "sha256:approval-v2")
24636                    .timeout(Duration::from_secs(30)),
24637                "condition_wait_predicate_mismatch",
24638            ),
24639            (
24640                ConditionWaitOptions::new("approval", "sha256:approval-v1")
24641                    .timeout(Duration::from_secs(29)),
24642                "condition_wait_timeout_mismatch",
24643            ),
24644        ] {
24645            let ctx = workflow_context(history.clone());
24646            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
24647            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24648            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24649                wait.as_mut().poll(&mut task_context)
24650            else {
24651                panic!("changed condition definition must fail replay");
24652            };
24653            assert_eq!(failure.reason, expected_reason);
24654            assert_eq!(failure.sequence, Some(12));
24655        }
24656    }
24657
24658    #[test]
24659    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
24660        let error = WorkflowState::new(
24661            vec![history_event(
24662                "ConditionWaitOpened",
24663                json!({
24664                    "sequence": 12,
24665                    "condition_wait_id": "condition:12",
24666                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24667                    "condition_key": "approval",
24668                }),
24669            )],
24670            "rust-workers".to_string(),
24671            DEFAULT_CODEC.to_string(),
24672            None,
24673        )
24674        .expect_err("condition history without a predicate fingerprint must fail");
24675
24676        assert!(matches!(
24677            error,
24678            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24679                if reason == "condition_wait_predicate_fingerprint_missing"
24680        ));
24681    }
24682
24683    #[test]
24684    fn condition_wait_history_requires_authored_occurrence_identity() {
24685        let error = WorkflowState::new(
24686            vec![history_event(
24687                "ConditionWaitOpened",
24688                json!({
24689                    "sequence": 12,
24690                    "condition_wait_id": "condition:12",
24691                    "condition_key": "approval",
24692                    "condition_definition_fingerprint": "sha256:approval-v1",
24693                }),
24694            )],
24695            "rust-workers".to_string(),
24696            DEFAULT_CODEC.to_string(),
24697            None,
24698        )
24699        .expect_err("condition history without occurrence identity must fail");
24700
24701        assert!(matches!(
24702            error,
24703            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24704                if reason == "condition_wait_occurrence_id_missing"
24705        ));
24706    }
24707
24708    #[test]
24709    fn typed_search_attribute_updates_validate_emit_and_replay() {
24710        let update = SearchAttributeUpdate::new()
24711            .keyword("OrderStatus", " waiting ")
24712            .expect("keyword")
24713            .int("Attempt", 3)
24714            .expect("int")
24715            .bool("Escalated", false)
24716            .expect("bool")
24717            .keyword_list("Regions", ["us-east", "eu-west"])
24718            .expect("list")
24719            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
24720            .expect("datetime")
24721            .delete("LegacyStatus")
24722            .expect("delete");
24723        let ctx = workflow_context(Vec::new());
24724        ctx.upsert_search_attributes(update.clone())
24725            .expect("typed update");
24726        assert_eq!(
24727            ctx.take_commands().expect("search-attribute command"),
24728            vec![json!({
24729                "type": "upsert_search_attributes",
24730                "attributes": {
24731                    "Attempt": 3,
24732                    "Escalated": false,
24733                    "LegacyStatus": null,
24734                    "OrderStatus": "waiting",
24735                    "Regions": ["us-east", "eu-west"],
24736                    "UpdatedAt": "2026-08-22T04:00:00Z",
24737                },
24738                "attribute_types": {
24739                    "Attempt": "int",
24740                    "Escalated": "bool",
24741                    "OrderStatus": "keyword",
24742                    "Regions": "keyword_list",
24743                    "UpdatedAt": "datetime",
24744                },
24745            })]
24746        );
24747
24748        let replay = workflow_context(vec![history_event(
24749            "SearchAttributesUpserted",
24750            json!({
24751                "sequence": 6,
24752                "attributes": {
24753                    "Attempt": 3,
24754                    "Escalated": false,
24755                    "LegacyStatus": null,
24756                    "OrderStatus": "waiting",
24757                    "Regions": ["us-east", "eu-west"],
24758                    "UpdatedAt": "2026-08-22T04:00:00Z",
24759                },
24760                "attribute_types": {
24761                    "Attempt": "int",
24762                    "Escalated": "bool",
24763                    "OrderStatus": "keyword",
24764                    "Regions": "keyword_list",
24765                    "UpdatedAt": "datetime",
24766                },
24767                "merged": {},
24768            }),
24769        )]);
24770        replay
24771            .upsert_search_attributes(update)
24772            .expect("matching update replays");
24773        assert!(replay.take_commands().expect("commands").is_empty());
24774        replay.ensure_history_consumed().expect("history consumed");
24775
24776        let type_drift = workflow_context(vec![history_event(
24777            "SearchAttributesUpserted",
24778            json!({
24779                "sequence": 7,
24780                "attributes": {"OrderStatus": "waiting"},
24781                "attribute_types": {"OrderStatus": "keyword"},
24782                "merged": {"OrderStatus": "waiting"},
24783            }),
24784        )]);
24785        let error = type_drift
24786            .upsert_search_attributes(
24787                SearchAttributeUpdate::new()
24788                    .string("OrderStatus", "waiting")
24789                    .expect("string update"),
24790            )
24791            .expect_err("same JSON value with a changed type must fail replay");
24792        assert!(matches!(
24793            error,
24794            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24795                if reason == "search_attribute_type_mismatch"
24796        ));
24797
24798        let malformed_types = WorkflowState::new(
24799            vec![history_event(
24800                "SearchAttributesUpserted",
24801                json!({
24802                    "sequence": 8,
24803                    "attributes": {"OrderStatus": "waiting"},
24804                    "attribute_types": {"OrderStatus": "unsupported"},
24805                    "merged": {"OrderStatus": "waiting"},
24806                }),
24807            )],
24808            "rust-workers".to_string(),
24809            DEFAULT_CODEC.to_string(),
24810            None,
24811        )
24812        .expect_err("unsupported search-attribute type metadata must fail");
24813        assert!(matches!(
24814            malformed_types,
24815            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24816                if reason == "search_attribute_types_malformed"
24817        ));
24818
24819        assert!(matches!(
24820            SearchAttributeUpdate::new().keyword("bad key", "value"),
24821            Err(SearchAttributeUpdateError::InvalidKey(_))
24822        ));
24823        assert!(matches!(
24824            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
24825            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
24826        ));
24827        assert!(matches!(
24828            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
24829            Err(SearchAttributeUpdateError::ValueTooLong { .. })
24830        ));
24831        assert!(matches!(
24832            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
24833            Err(SearchAttributeUpdateError::InvalidDateTime(_))
24834        ));
24835        assert!(matches!(
24836            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
24837            Err(Error::InvalidSearchAttributeUpdate(
24838                SearchAttributeUpdateError::Empty
24839            ))
24840        ));
24841    }
24842
24843    #[test]
24844    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
24845        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
24846        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
24847
24848        assert!(SearchAttributeUpdate::new()
24849            .string("AsciiDescription", ascii)
24850            .is_ok());
24851        assert!(SearchAttributeUpdate::new()
24852            .string("Utf8Description", utf8)
24853            .is_ok());
24854        assert!(matches!(
24855            SearchAttributeUpdate::new().string(
24856                "TooLongDescription",
24857                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
24858            ),
24859            Err(SearchAttributeUpdateError::ValueTooLong {
24860                kind: "string",
24861                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
24862                ..
24863            })
24864        ));
24865    }
24866
24867    #[test]
24868    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
24869        let lone_fire = WorkflowState::new(
24870            vec![history_event(
24871                "TimerFired",
24872                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24873            )],
24874            "rust-workers".to_string(),
24875            DEFAULT_CODEC.to_string(),
24876            None,
24877        )
24878        .expect_err("TimerFired requires TimerScheduled");
24879        assert!(matches!(
24880            lone_fire,
24881            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24882                if reason == "timer_schedule_missing_or_duplicate"
24883        ));
24884
24885        let wrong_identity = WorkflowState::new(
24886            vec![
24887                history_event(
24888                    "TimerScheduled",
24889                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24890                ),
24891                history_event(
24892                    "TimerFired",
24893                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
24894                ),
24895            ],
24896            "rust-workers".to_string(),
24897            DEFAULT_CODEC.to_string(),
24898            None,
24899        )
24900        .expect_err("fire must match scheduled timer identity");
24901        assert!(matches!(
24902            wrong_identity,
24903            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24904                if reason == "timer_identity_mismatch"
24905        ));
24906
24907        let duplicate_fire = WorkflowState::new(
24908            vec![
24909                history_event(
24910                    "TimerScheduled",
24911                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24912                ),
24913                history_event(
24914                    "TimerFired",
24915                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24916                ),
24917                history_event(
24918                    "TimerFired",
24919                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24920                ),
24921            ],
24922            "rust-workers".to_string(),
24923            DEFAULT_CODEC.to_string(),
24924            None,
24925        )
24926        .expect_err("a durable timer cannot fire twice");
24927        assert!(matches!(
24928            duplicate_fire,
24929            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24930                if reason == "duplicate_timer_fire"
24931        ));
24932
24933        let wrong_fired_delay = WorkflowState::new(
24934            vec![
24935                history_event(
24936                    "TimerScheduled",
24937                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24938                ),
24939                history_event(
24940                    "TimerFired",
24941                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
24942                ),
24943            ],
24944            "rust-workers".to_string(),
24945            DEFAULT_CODEC.to_string(),
24946            None,
24947        )
24948        .expect_err("timer schedule and fire delays must agree");
24949        assert!(matches!(
24950            wrong_fired_delay,
24951            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
24952                if reason == "timer_history_delay_mismatch"
24953        ));
24954    }
24955
24956    #[test]
24957    fn replay_rejects_activity_moved_before_recorded_timer() {
24958        let ctx = workflow_context(vec![
24959            history_event(
24960                "TimerScheduled",
24961                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24962            ),
24963            history_event(
24964                "TimerFired",
24965                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24966            ),
24967            history_event(
24968                "ActivityCompleted",
24969                json!({
24970                    "sequence": 2,
24971                    "activity_type": "after-timer",
24972                    "payload_codec": DEFAULT_CODEC,
24973                    "result": fixture_envelope(json!("done")),
24974                }),
24975            ),
24976        ]);
24977        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
24978        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24979
24980        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24981            activity.as_mut().poll(&mut task_context)
24982        else {
24983            panic!("reordered durable command must be rejected");
24984        };
24985        assert_eq!(failure.reason, "recorded_command_mismatch");
24986        assert_eq!(failure.sequence, Some(1));
24987        assert_eq!(failure.expected.as_deref(), Some("timer"));
24988        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
24989    }
24990
24991    #[test]
24992    fn workflow_context_emits_a_typed_named_signal_wait() {
24993        let ctx = workflow_context(Vec::new());
24994        let mut signal = Box::pin(ctx.wait_signal("finish"));
24995        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24996
24997        assert!(matches!(
24998            signal.as_mut().poll(&mut task_context),
24999            Poll::Pending
25000        ));
25001        assert_eq!(
25002            ctx.take_commands().expect("signal-wait command"),
25003            vec![json!({
25004                "type": "open_signal_wait",
25005                "signal_name": "finish",
25006            })]
25007        );
25008    }
25009
25010    #[test]
25011    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
25012        let ctx = workflow_context(Vec::new());
25013        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
25014        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25015
25016        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
25017        else {
25018            panic!("runtime-reserved signal should be rejected");
25019        };
25020        assert!(message.contains("reserved by the workflow runtime"));
25021        assert!(ctx.take_commands().expect("commands").is_empty());
25022    }
25023
25024    #[tokio::test]
25025    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
25026        let client = Client::builder("http://127.0.0.1:9")
25027            .build()
25028            .expect("client");
25029        let error = client
25030            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
25031            .await
25032            .expect_err("runtime-reserved signal should be rejected before transport");
25033
25034        assert!(
25035            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
25036        );
25037    }
25038
25039    #[test]
25040    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
25041        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25042            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25043                value.to_string(),
25044            )]))
25045            .expect("message payload");
25046            json!({
25047                "schema": MESSAGE_STREAM_SCHEMA,
25048                "stream_name": "orders",
25049                "message_id": message_id,
25050                "position": position,
25051                "payload_envelope": payload,
25052            })
25053        }
25054
25055        fn opened(sequence: u64) -> HistoryEvent {
25056            history_event(
25057                "SignalWaitOpened",
25058                json!({
25059                    "sequence": sequence,
25060                    "signal_name": MESSAGE_STREAM_SIGNAL,
25061                }),
25062            )
25063        }
25064
25065        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25066            history_event(
25067                "SignalApplied",
25068                json!({
25069                    "sequence": sequence,
25070                    "signal_name": MESSAGE_STREAM_SIGNAL,
25071                    "value": fixture_envelope(json!([delivery])),
25072                }),
25073            )
25074        }
25075
25076        fn received(delivery: Value) -> HistoryEvent {
25077            history_event(
25078                "SignalReceived",
25079                json!({
25080                    "signal_name": MESSAGE_STREAM_SIGNAL,
25081                    "arguments": fixture_envelope(json!([delivery])),
25082                    "payload_codec": DEFAULT_CODEC,
25083                }),
25084            )
25085        }
25086
25087        let client = Client::new("http://127.0.0.1:8080").expect("client");
25088        let mut worker = Worker::new(client, "rust-workers");
25089        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
25090            let messages = ctx.message_stream("orders")?.receive(2).await?;
25091            Ok(json!(messages
25092                .into_iter()
25093                .map(|message| message.message_id)
25094                .collect::<Vec<_>>()))
25095        });
25096
25097        let first = delivery("message-1", 1, "one");
25098        let second = delivery("message-2", 2, "two");
25099        let batch = worker
25100            .execute_workflow_task_decision(workflow_task(
25101                "rust.message-stream-batch",
25102                vec![
25103                    opened(1),
25104                    received(first.clone()),
25105                    applied(1, first.clone()),
25106                    received(first.clone()),
25107                    received(second),
25108                ],
25109                DEFAULT_CODEC,
25110            ))
25111            .expect("worker task consumes the available batch");
25112
25113        assert_eq!(batch.commands.len(), 1);
25114        assert_eq!(batch.commands[0]["type"], "complete_workflow");
25115        assert_eq!(
25116            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
25117                .expect("workflow result"),
25118            json!(["message-1", "message-2"])
25119        );
25120        assert_eq!(
25121            batch.message_stream_cursors,
25122            vec![json!({"stream_name": "orders", "through_position": 2})]
25123        );
25124        assert!(batch.message_stream_waits.is_empty());
25125
25126        let partial = worker
25127            .execute_workflow_task_decision(workflow_task(
25128                "rust.message-stream-batch",
25129                vec![opened(1), received(first.clone()), applied(1, first)],
25130                DEFAULT_CODEC,
25131            ))
25132            .expect("worker task returns without waiting for a missing second item");
25133        assert_eq!(partial.commands.len(), 1);
25134        assert_eq!(partial.commands[0]["type"], "complete_workflow");
25135        assert_eq!(
25136            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
25137                .expect("workflow result"),
25138            json!(["message-1"])
25139        );
25140        assert_eq!(
25141            partial.message_stream_cursors,
25142            vec![json!({"stream_name": "orders", "through_position": 1})]
25143        );
25144        assert!(partial.message_stream_waits.is_empty());
25145    }
25146
25147    #[test]
25148    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
25149        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25150            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25151                value.to_string(),
25152            )]))
25153            .expect("message payload");
25154            json!({
25155                "schema": MESSAGE_STREAM_SCHEMA,
25156                "stream_name": "orders",
25157                "message_id": message_id,
25158                "position": position,
25159                "payload_envelope": payload,
25160            })
25161        }
25162
25163        fn opened(sequence: u64) -> HistoryEvent {
25164            history_event(
25165                "SignalWaitOpened",
25166                json!({
25167                    "sequence": sequence,
25168                    "signal_name": MESSAGE_STREAM_SIGNAL,
25169                }),
25170            )
25171        }
25172
25173        fn received(delivery: Value) -> HistoryEvent {
25174            history_event(
25175                "SignalReceived",
25176                json!({
25177                    "signal_name": MESSAGE_STREAM_SIGNAL,
25178                    "arguments": fixture_envelope(json!([delivery])),
25179                    "payload_codec": DEFAULT_CODEC,
25180                }),
25181            )
25182        }
25183
25184        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25185            history_event(
25186                "SignalApplied",
25187                json!({
25188                    "sequence": sequence,
25189                    "signal_name": MESSAGE_STREAM_SIGNAL,
25190                    "value": fixture_envelope(json!([delivery])),
25191                }),
25192            )
25193        }
25194
25195        let client = Client::new("http://127.0.0.1:8080").expect("client");
25196        let mut worker = Worker::new(client, "rust-workers");
25197        worker.register_workflow(
25198            "rust.message-stream-partial-batches",
25199            |ctx, _input| async move {
25200                let stream = ctx.message_stream("orders")?;
25201                let first = stream.receive(10).await?;
25202                let second = stream.receive(10).await?;
25203                Ok(json!([
25204                    first
25205                        .into_iter()
25206                        .map(|message| message.message_id)
25207                        .collect::<Vec<_>>(),
25208                    second
25209                        .into_iter()
25210                        .map(|message| message.message_id)
25211                        .collect::<Vec<_>>(),
25212                ]))
25213            },
25214        );
25215
25216        let first = delivery("message-1", 1, "one");
25217        let second = delivery("message-2", 2, "two");
25218        let decision = worker
25219            .execute_workflow_task_decision(workflow_task(
25220                "rust.message-stream-partial-batches",
25221                vec![
25222                    opened(1),
25223                    received(first.clone()),
25224                    applied(1, first),
25225                    opened(2),
25226                    received(second.clone()),
25227                    applied(2, second),
25228                ],
25229                DEFAULT_CODEC,
25230            ))
25231            .expect("cold replay preserves both authored receive boundaries");
25232
25233        assert_eq!(decision.commands.len(), 1);
25234        assert_eq!(decision.commands[0]["type"], "complete_workflow");
25235        assert_eq!(
25236            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
25237                .expect("workflow result"),
25238            json!([["message-1"], ["message-2"]])
25239        );
25240        assert_eq!(
25241            decision.message_stream_cursors,
25242            vec![json!({"stream_name": "orders", "through_position": 2})]
25243        );
25244        assert!(decision.message_stream_waits.is_empty());
25245    }
25246
25247    #[test]
25248    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
25249        let ctx = workflow_context(Vec::new());
25250        let stream = ctx.message_stream("orders").expect("message stream");
25251        let mut receive = Box::pin(stream.receive(10));
25252        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25253
25254        assert!(matches!(
25255            receive.as_mut().poll(&mut task_context),
25256            Poll::Pending
25257        ));
25258        assert_eq!(
25259            ctx.take_commands().expect("message-stream wait command"),
25260            vec![json!({
25261                "type": "open_signal_wait",
25262                "signal_name": MESSAGE_STREAM_SIGNAL,
25263            })]
25264        );
25265        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
25266        assert!(cursors.is_empty());
25267        assert_eq!(
25268            waits,
25269            vec![json!({"stream_name": "orders", "after_position": 0})]
25270        );
25271    }
25272
25273    #[test]
25274    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
25275        let ctx = workflow_context(vec![history_event(
25276            "SignalReceived",
25277            json!({
25278                "signal_name": MESSAGE_STREAM_SIGNAL,
25279                "arguments": fixture_envelope(json!([{
25280                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
25281                    "stream_name": "orders",
25282                    "through_position": 2,
25283                }])),
25284                "payload_codec": DEFAULT_CODEC,
25285            }),
25286        )]);
25287        let stream = ctx.message_stream("orders").expect("message stream");
25288        let mut receive = Box::pin(stream.receive(10));
25289        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25290
25291        assert!(matches!(
25292            receive.as_mut().poll(&mut task_context),
25293            Poll::Pending
25294        ));
25295        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
25296        assert_eq!(
25297            cursors,
25298            vec![json!({"stream_name": "orders", "through_position": 2})]
25299        );
25300        assert_eq!(
25301            waits,
25302            vec![json!({"stream_name": "orders", "after_position": 2})]
25303        );
25304    }
25305
25306    #[test]
25307    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
25308        let mut empty_map = BTreeMap::new();
25309        let mut nested = BTreeMap::new();
25310        nested.insert(
25311            "value".to_string(),
25312            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
25313        );
25314        let values = vec![
25315            AvroValue::Bytes(vec![0, 255]),
25316            AvroValue::Long(1),
25317            AvroValue::Double(1.0),
25318            AvroValue::Array(Vec::new()),
25319            AvroValue::Map(std::mem::take(&mut empty_map)),
25320            AvroValue::Map(nested),
25321        ];
25322        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
25323        let transport = vec![json!({
25324            "schema": MESSAGE_STREAM_SCHEMA,
25325            "stream_name": "orders",
25326            "message_id": "message-1",
25327            "position": 1,
25328            "payload_envelope": payload,
25329        })];
25330
25331        for _ in 0..2 {
25332            let Some(MessageStreamDelivery::Message(message)) =
25333                decode_message_stream_delivery(transport.clone()).expect("delivery")
25334            else {
25335                panic!("message delivery expected");
25336            };
25337            assert_eq!(message.arguments, values);
25338            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
25339            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
25340        }
25341    }
25342
25343    #[test]
25344    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
25345        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
25346            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
25347                value.to_string(),
25348            )]))
25349            .expect("message payload");
25350            json!({
25351                "schema": MESSAGE_STREAM_SCHEMA,
25352                "stream_name": "orders",
25353                "message_id": message_id,
25354                "position": position,
25355                "payload_envelope": payload,
25356            })
25357        }
25358
25359        fn opened(sequence: u64) -> HistoryEvent {
25360            history_event(
25361                "SignalWaitOpened",
25362                json!({
25363                    "sequence": sequence,
25364                    "signal_name": MESSAGE_STREAM_SIGNAL,
25365                }),
25366            )
25367        }
25368
25369        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
25370            history_event(
25371                "SignalApplied",
25372                json!({
25373                    "sequence": sequence,
25374                    "signal_name": MESSAGE_STREAM_SIGNAL,
25375                    "value": fixture_envelope(json!([delivery])),
25376                }),
25377            )
25378        }
25379
25380        fn worker() -> Worker {
25381            let client = Client::new("http://127.0.0.1:8080").expect("client");
25382            let mut worker = Worker::new(client, "rust-workers");
25383            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
25384                let stream = ctx.message_stream("orders")?;
25385                let first = stream.receive_one().await?;
25386                let second = stream.receive_one().await?;
25387                Ok(json!([first.message_id, second.message_id]))
25388            });
25389            worker
25390        }
25391
25392        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
25393            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
25394            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
25395            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
25396            task
25397        }
25398
25399        let waiting = worker()
25400            .execute_workflow_task_decision(workflow_task(
25401                "rust.message-stream",
25402                Vec::new(),
25403                DEFAULT_CODEC,
25404            ))
25405            .expect("first worker opens the stream wait");
25406        assert_eq!(
25407            waiting.commands,
25408            vec![json!({
25409                "type": "open_signal_wait",
25410                "signal_name": MESSAGE_STREAM_SIGNAL,
25411            })]
25412        );
25413        assert!(waiting.message_stream_cursors.is_empty());
25414        assert_eq!(
25415            waiting.message_stream_waits,
25416            vec![json!({"stream_name": "orders", "after_position": 0})]
25417        );
25418
25419        let first_delivery = delivery("message-1", 1, "one");
25420        let first_arrival = worker()
25421            .execute_workflow_task_decision(task_with_resume(
25422                vec![opened(1)],
25423                first_delivery.clone(),
25424            ))
25425            .expect("replacement worker consumes the first arrival");
25426        assert_eq!(
25427            first_arrival.commands,
25428            vec![json!({
25429                "type": "open_signal_wait",
25430                "signal_name": MESSAGE_STREAM_SIGNAL,
25431            })]
25432        );
25433        assert_eq!(
25434            first_arrival.message_stream_cursors,
25435            vec![json!({"stream_name": "orders", "through_position": 1})]
25436        );
25437        assert_eq!(
25438            first_arrival.message_stream_waits,
25439            vec![json!({"stream_name": "orders", "after_position": 1})]
25440        );
25441
25442        let second_delivery = delivery("message-2", 2, "two");
25443        let first_applied = applied(1, first_delivery);
25444        let completed = worker()
25445            .execute_workflow_task_decision(task_with_resume(
25446                vec![opened(1), first_applied.clone(), opened(2)],
25447                second_delivery.clone(),
25448            ))
25449            .expect("next replacement worker consumes the second arrival");
25450        assert_eq!(completed.commands.len(), 1);
25451        assert_eq!(completed.commands[0]["type"], "complete_workflow");
25452        assert_eq!(
25453            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
25454                .expect("workflow result"),
25455            json!(["message-1", "message-2"])
25456        );
25457        assert_eq!(
25458            completed.message_stream_cursors,
25459            vec![json!({"stream_name": "orders", "through_position": 2})]
25460        );
25461        assert!(completed.message_stream_waits.is_empty());
25462
25463        let replay_history = vec![
25464            opened(1),
25465            first_applied,
25466            opened(2),
25467            applied(2, second_delivery),
25468        ];
25469        for _cold_worker_or_restart in 0..2 {
25470            let replayed = worker()
25471                .execute_workflow_task_decision(workflow_task(
25472                    "rust.message-stream",
25473                    replay_history.clone(),
25474                    DEFAULT_CODEC,
25475                ))
25476                .expect("cold worker replays each logical message exactly once");
25477            assert_eq!(replayed.commands.len(), 1);
25478            assert_eq!(
25479                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
25480                    .expect("replayed workflow result"),
25481                json!(["message-1", "message-2"])
25482            );
25483            assert_eq!(
25484                replayed.message_stream_cursors,
25485                vec![json!({"stream_name": "orders", "through_position": 2})]
25486            );
25487            assert!(replayed.message_stream_waits.is_empty());
25488        }
25489    }
25490
25491    #[test]
25492    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
25493        assert!(!worker_protocol_supports_message_streams("1.14"));
25494        assert!(worker_protocol_supports_message_streams("1.15"));
25495        assert!(worker_protocol_supports_message_streams("1.16"));
25496        assert!(worker_protocol_supports_message_streams(
25497            WORKER_PROTOCOL_VERSION
25498        ));
25499        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
25500    }
25501
25502    #[test]
25503    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
25504        let ctx = workflow_context(vec![
25505            history_event(
25506                "ConditionWaitOpened",
25507                json!({
25508                    "sequence": 1,
25509                    "condition_wait_id": "condition:1",
25510                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25511                    "condition_key": "signal:finish",
25512                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
25513                }),
25514            ),
25515            history_event(
25516                "ConditionWaitSatisfied",
25517                json!({
25518                    "sequence": 1,
25519                    "condition_wait_id": "condition:1",
25520                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25521                    "condition_key": "signal:finish",
25522                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
25523                }),
25524            ),
25525            history_event(
25526                "SignalReceived",
25527                json!({"signal_name": "finish", "arguments": []}),
25528            ),
25529        ]);
25530        let mut signal = Box::pin(ctx.wait_signal("finish"));
25531        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25532
25533        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25534            signal.as_mut().poll(&mut task_context)
25535        else {
25536            panic!("condition history must not resolve as a typed signal wait");
25537        };
25538        assert_eq!(failure.reason, "recorded_command_mismatch");
25539        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
25540    }
25541
25542    #[test]
25543    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
25544        let signal_then_timer = vec![
25545            history_event(
25546                "SignalWaitOpened",
25547                json!({"sequence": 1, "signal_name": "go"}),
25548            ),
25549            history_event(
25550                "SignalApplied",
25551                json!({
25552                    "sequence": 1,
25553                    "signal_name": "go",
25554                    "value": fixture_envelope(json!(["now"])),
25555                }),
25556            ),
25557            history_event(
25558                "TimerScheduled",
25559                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
25560            ),
25561            history_event(
25562                "TimerFired",
25563                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
25564            ),
25565        ];
25566
25567        let ctx = workflow_context(signal_then_timer.clone());
25568        let mut signal = Box::pin(ctx.wait_signal("go"));
25569        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25570        assert!(matches!(
25571            signal.as_mut().poll(&mut task_context),
25572            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
25573        ));
25574        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
25575        assert!(matches!(
25576            timer.as_mut().poll(&mut task_context),
25577            Poll::Ready(Ok(()))
25578        ));
25579        ctx.ensure_history_consumed()
25580            .expect("signal and timer history consumed in order");
25581
25582        let reordered = workflow_context(signal_then_timer);
25583        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
25584        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25585            timer_first.as_mut().poll(&mut task_context)
25586        else {
25587            panic!("timer cannot consume signal-wait-first history");
25588        };
25589        assert_eq!(failure.reason, "recorded_command_mismatch");
25590        assert_eq!(failure.sequence, Some(1));
25591        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
25592
25593        let timer_then_signal = vec![
25594            history_event(
25595                "TimerScheduled",
25596                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25597            ),
25598            history_event(
25599                "TimerFired",
25600                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25601            ),
25602            history_event(
25603                "SignalWaitOpened",
25604                json!({"sequence": 2, "signal_name": "go"}),
25605            ),
25606            history_event(
25607                "SignalApplied",
25608                json!({
25609                    "sequence": 2,
25610                    "signal_name": "go",
25611                    "value": fixture_envelope(json!([])),
25612                }),
25613            ),
25614        ];
25615        let reordered = workflow_context(timer_then_signal);
25616        let mut signal_first = Box::pin(reordered.wait_signal("go"));
25617        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25618            signal_first.as_mut().poll(&mut task_context)
25619        else {
25620            panic!("signal wait cannot consume timer-first history");
25621        };
25622        assert_eq!(failure.reason, "recorded_command_mismatch");
25623        assert_eq!(failure.sequence, Some(1));
25624        assert_eq!(failure.expected.as_deref(), Some("timer"));
25625    }
25626
25627    #[test]
25628    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
25629        let duplicate_timer = WorkflowState::new(
25630            vec![
25631                history_event(
25632                    "TimerScheduled",
25633                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25634                ),
25635                history_event(
25636                    "TimerScheduled",
25637                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
25638                ),
25639            ],
25640            "rust-workers".to_string(),
25641            DEFAULT_CODEC.to_string(),
25642            None,
25643        )
25644        .expect_err("one workflow sequence cannot schedule two timers");
25645        assert!(matches!(
25646            duplicate_timer,
25647            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25648                if reason == "timer_schedule_missing_or_duplicate"
25649        ));
25650
25651        let colliding_kinds = WorkflowState::new(
25652            vec![
25653                history_event(
25654                    "TimerScheduled",
25655                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
25656                ),
25657                history_event(
25658                    "ActivityCompleted",
25659                    json!({"sequence": 1, "activity_type": "same-sequence"}),
25660                ),
25661            ],
25662            "rust-workers".to_string(),
25663            DEFAULT_CODEC.to_string(),
25664            None,
25665        )
25666        .expect_err("one workflow sequence cannot identify two command kinds");
25667        assert!(matches!(
25668            colliding_kinds,
25669            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25670                if reason == "durable_command_sequence_collision"
25671        ));
25672
25673        let duplicate_signal_wait = WorkflowState::new(
25674            vec![
25675                history_event(
25676                    "SignalWaitOpened",
25677                    json!({"sequence": 1, "signal_name": "go"}),
25678                ),
25679                history_event(
25680                    "SignalWaitOpened",
25681                    json!({"sequence": 1, "signal_name": "go"}),
25682                ),
25683            ],
25684            "rust-workers".to_string(),
25685            DEFAULT_CODEC.to_string(),
25686            None,
25687        )
25688        .expect_err("one workflow sequence cannot open two signal waits");
25689        assert!(matches!(
25690            duplicate_signal_wait,
25691            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25692                if reason == "signal_wait_open_missing_or_duplicate"
25693        ));
25694    }
25695
25696    #[test]
25697    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
25698        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
25699            .expect("side-effect result");
25700        let ctx = workflow_context(vec![history_event(
25701            "SideEffectRecorded",
25702            json!({"sequence": 99, "result": result}),
25703        )]);
25704
25705        let replayed: Value = ctx
25706            .side_effect(|| panic!("recorded side effect must not run"))
25707            .expect("positive global workflow sequence is valid");
25708        assert_eq!(replayed, json!({"captured": true}));
25709        ctx.ensure_history_consumed().expect("history consumed");
25710    }
25711
25712    #[test]
25713    fn workflow_history_rejects_zero_and_descending_command_sequences() {
25714        let result =
25715            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
25716        let zero = WorkflowState::new(
25717            vec![history_event(
25718                "SideEffectRecorded",
25719                json!({"sequence": 0, "result": result.clone()}),
25720            )],
25721            "rust-workers".to_string(),
25722            DEFAULT_CODEC.to_string(),
25723            None,
25724        )
25725        .expect_err("durable command sequences must be positive");
25726        assert!(matches!(
25727            zero,
25728            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
25729                if reason == "durable_command_sequence_invalid"
25730        ));
25731
25732        let descending = WorkflowState::new(
25733            vec![
25734                history_event(
25735                    "SideEffectRecorded",
25736                    json!({"sequence": 3, "result": result}),
25737                ),
25738                history_event(
25739                    "VersionMarkerRecorded",
25740                    json!({
25741                        "sequence": 2,
25742                        "change_id": "descending-marker",
25743                        "version": 1,
25744                        "min_supported": 1,
25745                        "max_supported": 1,
25746                    }),
25747                ),
25748            ],
25749            "rust-workers".to_string(),
25750            DEFAULT_CODEC.to_string(),
25751            None,
25752        )
25753        .expect_err("new durable commands must remain strictly ordered");
25754        let Error::NonDeterministicReplay(failure) = descending else {
25755            panic!("expected typed replay failure");
25756        };
25757        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
25758        assert_eq!(failure.sequence, Some(2));
25759        assert_eq!(
25760            failure.expected.as_deref(),
25761            Some("workflow sequence greater than 3")
25762        );
25763        assert_eq!(failure.actual.as_deref(), Some("2"));
25764    }
25765
25766    #[test]
25767    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
25768        fn worker() -> Worker {
25769            let client = Client::new("http://127.0.0.1:8080").expect("client");
25770            let mut worker = Worker::new(client, "rust-workers");
25771            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
25772                ctx.wait_signal("finish").await?;
25773                let marker: String =
25774                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
25775                assert_eq!(marker, "after-finish");
25776                Ok(json!("finished"))
25777            });
25778            worker
25779        }
25780
25781        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
25782            .expect("side-effect result");
25783        let task = workflow_task(
25784            "rust.finish-after-gaps",
25785            vec![
25786                history_event(
25787                    "SignalWaitOpened",
25788                    json!({"sequence": 1, "signal_name": "finish"}),
25789                ),
25790                history_event(
25791                    "SignalReceived",
25792                    json!({
25793                        "signal_id": "increment-3",
25794                        "signal_name": "increment",
25795                        "workflow_sequence": 2,
25796                        "payload_codec": DEFAULT_CODEC,
25797                        "arguments": fixture_envelope(json!([3])),
25798                    }),
25799                ),
25800                history_event(
25801                    "SignalReceived",
25802                    json!({
25803                        "signal_id": "increment-5",
25804                        "signal_name": "increment",
25805                        "workflow_sequence": 3,
25806                        "payload_codec": DEFAULT_CODEC,
25807                        "arguments": fixture_envelope(json!([5])),
25808                    }),
25809                ),
25810                history_event(
25811                    "SignalReceived",
25812                    json!({
25813                        "signal_id": "finish",
25814                        "signal_name": "finish",
25815                        "workflow_sequence": 4,
25816                        "payload_codec": DEFAULT_CODEC,
25817                        "arguments": fixture_envelope(json!([])),
25818                    }),
25819                ),
25820                history_event(
25821                    "SignalApplied",
25822                    json!({
25823                        "sequence": 1,
25824                        "signal_id": "finish",
25825                        "signal_name": "finish",
25826                        "payload_codec": DEFAULT_CODEC,
25827                        "value": fixture_envelope(json!([])),
25828                    }),
25829                ),
25830                history_event(
25831                    "SideEffectRecorded",
25832                    json!({"sequence": 5, "result": marker}),
25833                ),
25834            ],
25835            DEFAULT_CODEC,
25836        );
25837
25838        for _original_or_cold_worker in 0..2 {
25839            let commands = worker()
25840                .execute_workflow_task(task.clone())
25841                .expect("signal gaps preserve deterministic replay");
25842            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
25843            assert_eq!(commands[0]["type"], "complete_workflow");
25844            assert_eq!(
25845                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
25846                json!("finished")
25847            );
25848        }
25849    }
25850
25851    #[test]
25852    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
25853        let ctx = workflow_context(Vec::new());
25854        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
25855        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25856        assert!(matches!(
25857            sleep.as_mut().poll(&mut task_context),
25858            Poll::Ready(Err(Error::TimerDurationOverflow))
25859        ));
25860        assert!(ctx.take_commands().expect("commands").is_empty());
25861    }
25862
25863    #[test]
25864    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
25865        let entries = AvroValue::Map(BTreeMap::from([
25866            ("text".to_string(), AvroValue::String("same".to_string())),
25867            (
25868                "nested".to_string(),
25869                AvroValue::Map(BTreeMap::from([
25870                    ("beta".to_string(), AvroValue::Long(2)),
25871                    ("alpha".to_string(), AvroValue::Long(1)),
25872                ])),
25873            ),
25874            ("long".to_string(), AvroValue::Long(7)),
25875            ("double".to_string(), AvroValue::Double(7.0)),
25876            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
25877        ]));
25878        let ctx = workflow_context(Vec::new());
25879        ctx.upsert_memo(entries.clone()).expect("valid memo update");
25880        let commands = ctx.take_commands().expect("commands");
25881
25882        assert_eq!(commands.len(), 1);
25883        assert_eq!(commands[0]["type"], "upsert_memo");
25884        let server_entries = json!({
25885            "codec": "avro",
25886            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
25887        });
25888        assert_eq!(
25889            commands[0]["entries"]
25890                .as_object()
25891                .expect("entries envelope")
25892                .keys()
25893                .collect::<Vec<_>>(),
25894            vec!["blob", "codec"]
25895        );
25896        assert_eq!(commands[0]["entries"], server_entries);
25897        let wire_entries =
25898            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
25899        assert_eq!(wire_entries, entries);
25900
25901        let history = vec![history_event(
25902            "MemoUpserted",
25903            json!({
25904                "sequence": 1,
25905                "entries": server_entries.clone(),
25906                "merged": server_entries,
25907            }),
25908        )];
25909        let replay = workflow_context(history.clone());
25910        replay
25911            .upsert_memo(entries.clone())
25912            .expect("matching replay identity");
25913        assert!(replay.take_commands().expect("replay commands").is_empty());
25914
25915        let changed_types = AvroValue::Map(BTreeMap::from([
25916            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
25917            (
25918                "nested".to_string(),
25919                AvroValue::Map(BTreeMap::from([
25920                    ("alpha".to_string(), AvroValue::Long(1)),
25921                    ("beta".to_string(), AvroValue::Long(2)),
25922                ])),
25923            ),
25924            ("long".to_string(), AvroValue::Double(7.0)),
25925            ("double".to_string(), AvroValue::Long(7)),
25926            ("binary".to_string(), AvroValue::String("same".to_string())),
25927        ]));
25928        let error = workflow_context(history)
25929            .upsert_memo(changed_types)
25930            .expect_err("memo replay identity must preserve Avro value types");
25931        assert!(matches!(
25932            error,
25933            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25934        ));
25935    }
25936
25937    #[test]
25938    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
25939        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
25940            .expect("memo envelope");
25941        let replay = workflow_context(vec![history_event(
25942            "MemoUpserted",
25943            json!({
25944                "sequence": 1,
25945                "entries": original.clone(),
25946                "merged": original
25947            }),
25948        )]);
25949        let error = replay
25950            .upsert_memo(json!({"stage": "changed"}))
25951            .expect_err("changed memo update must fail replay");
25952        assert!(matches!(
25953            error,
25954            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25955        ));
25956
25957        let invalid = workflow_context(Vec::new())
25958            .upsert_memo(
25959                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
25960            )
25961            .expect_err("oversized key");
25962        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
25963    }
25964
25965    #[test]
25966    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
25967        let negative_zero = AvroValue::Map(BTreeMap::from([(
25968            "reading".to_string(),
25969            AvroValue::Double(-0.0),
25970        )]));
25971        let negative_zero_envelope =
25972            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
25973        let history = vec![history_event(
25974            "MemoUpserted",
25975            json!({
25976                "sequence": 1,
25977                "entries": negative_zero_envelope.clone(),
25978                "merged": negative_zero_envelope,
25979            }),
25980        )];
25981
25982        workflow_context(history.clone())
25983            .upsert_memo(negative_zero)
25984            .expect("matching negative-zero history identity");
25985
25986        let error = workflow_context(history)
25987            .upsert_memo(AvroValue::Map(BTreeMap::from([(
25988                "reading".to_string(),
25989                AvroValue::Double(0.0),
25990            )])))
25991            .expect_err("positive zero must not consume negative-zero memo history");
25992        assert!(matches!(
25993            error,
25994            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
25995        ));
25996    }
25997
25998    #[test]
25999    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
26000        let supported = json!({
26001            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
26002            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
26003        });
26004        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
26005        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
26006            "workflow_memo_updates": {"supported": false},
26007            "supported_workflow_task_commands": ["upsert_memo"]
26008        }))));
26009        assert!(commands_use_workflow_memo_updates(&[json!({
26010            "type": "upsert_memo",
26011            "entries": {"stage": "processing"}
26012        })]));
26013    }
26014
26015    #[test]
26016    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
26017        let client = Client::new("http://127.0.0.1:8080").expect("client");
26018        let mut worker = Worker::new(client, "rust-workers");
26019        worker.register_workflow("rust.timer", |ctx, _input| async move {
26020            ctx.sleep(Duration::from_secs(5)).await?;
26021            ctx.activity("after-timer", json!([])).await
26022        });
26023
26024        let task = |history_events| WorkflowTask {
26025            task_id: "wft-rust-timer-1".to_string(),
26026            observability_context: None,
26027            dispatch_observability_context: None,
26028            observability_links: None,
26029            workflow_command_id: None,
26030            workflow_id: Some("wf-rust-timer".to_string()),
26031            run_id: Some("run-rust-timer".to_string()),
26032            workflow_type: "rust.timer".to_string(),
26033            cancel_requested: false,
26034            payload_codec: DEFAULT_CODEC.to_string(),
26035            arguments: Some(
26036                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26037            ),
26038            history_events,
26039            total_history_events: None,
26040            history_size_bytes: None,
26041            continue_as_new_recommended: None,
26042            history_budget_pressure: None,
26043            next_history_page_token: None,
26044            workflow_task_attempt: 1,
26045            workflow_signal_id: None,
26046            signal_name: None,
26047            signal_arguments: None,
26048            workflow_update_id: None,
26049            update_name: None,
26050            lease_owner: Some("rust-worker".to_string()),
26051        };
26052
26053        let initial = worker
26054            .execute_workflow_task(task(Vec::new()))
26055            .expect("initial timer task");
26056        assert_eq!(
26057            initial,
26058            vec![json!({"type": "start_timer", "delay_seconds": 5})]
26059        );
26060
26061        let activity_result =
26062            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
26063        let replayed = worker
26064            .execute_workflow_task(task(vec![
26065                history_event(
26066                    "TimerScheduled",
26067                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26068                ),
26069                history_event(
26070                    "TimerFired",
26071                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26072                ),
26073                history_event(
26074                    "ActivityCompleted",
26075                    json!({
26076                        "sequence": 2,
26077                        "activity_type": "after-timer",
26078                        "payload_codec": DEFAULT_CODEC,
26079                        "result": activity_result,
26080                    }),
26081                ),
26082            ]))
26083            .expect("replayed workflow task");
26084        assert_eq!(replayed.len(), 1);
26085        assert_eq!(replayed[0]["type"], "complete_workflow");
26086        assert_eq!(
26087            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
26088            json!("done")
26089        );
26090    }
26091
26092    #[test]
26093    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
26094        let client = Client::new("http://127.0.0.1:8080").expect("client");
26095        let mut worker = Worker::new(client, "rust-workers");
26096        worker.register_workflow("rust.continue", |ctx, _input| async move {
26097            ctx.continue_as_new_with_options(
26098                ContinueAsNewOptions::new()
26099                    .workflow_type("rust.next")
26100                    .task_queue("next-workers"),
26101                json!([2, {"cursor": "next"}]),
26102            )
26103        });
26104
26105        let commands = worker
26106            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
26107            .expect("continue-as-new command");
26108
26109        assert_eq!(commands.len(), 1);
26110        assert_eq!(commands[0]["type"], "continue_as_new");
26111        assert_eq!(commands[0]["workflow_type"], "rust.next");
26112        assert_eq!(commands[0]["queue"], "next-workers");
26113        assert_eq!(
26114            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
26115                .expect("continue-as-new arguments"),
26116            json!([2, {"cursor": "next"}])
26117        );
26118    }
26119
26120    #[test]
26121    fn continue_as_new_preserves_typed_arguments() {
26122        let client = Client::new("http://127.0.0.1:8080").expect("client");
26123        let mut worker = Worker::new(client, "rust-workers");
26124        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
26125            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
26126            unreachable!("continue-as-new returns a control-flow error")
26127        });
26128
26129        let commands = worker
26130            .execute_workflow_task(workflow_task(
26131                "rust.typed-continue",
26132                Vec::new(),
26133                DEFAULT_CODEC,
26134            ))
26135            .expect("typed continue-as-new command");
26136
26137        assert_eq!(commands[0]["type"], "continue_as_new");
26138        assert_eq!(
26139            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
26140                .expect("typed continue arguments"),
26141            AvroValue::Array(vec![typed_fidelity_probe()])
26142        );
26143    }
26144
26145    #[test]
26146    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
26147        let client = Client::new("http://127.0.0.1:8080").expect("client");
26148        let mut worker = Worker::new(client, "rust-workers");
26149        worker.register_workflow("rust.continue", |ctx, _input| async move {
26150            ctx.continue_as_new(json!([2]))
26151        });
26152        let task = workflow_task(
26153            "rust.continue",
26154            vec![history_event(
26155                "WorkflowContinuedAsNew",
26156                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
26157            )],
26158            DEFAULT_CODEC,
26159        );
26160
26161        for _worker_restart_or_redelivery in 0..2 {
26162            let commands = worker
26163                .execute_workflow_task(task.clone())
26164                .expect("recorded transition replays");
26165            assert!(
26166                commands.is_empty(),
26167                "replay must not emit another successor"
26168            );
26169        }
26170    }
26171
26172    #[test]
26173    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
26174        let ctx = workflow_context(Vec::new());
26175        let error = ctx
26176            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
26177            .expect_err("blank queue must be rejected");
26178
26179        let Error::InvalidContinueAsNewOptions(error) = error else {
26180            panic!("expected typed continue-as-new validation error");
26181        };
26182        assert_eq!(error.field, "task_queue");
26183        assert!(ctx.take_commands().expect("commands").is_empty());
26184    }
26185
26186    #[test]
26187    fn workflow_context_exposes_server_history_budget() {
26188        let client = Client::new("http://127.0.0.1:8080").expect("client");
26189        let mut worker = Worker::new(client, "rust-workers");
26190        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
26191            let budget = ctx.history_budget()?;
26192            Ok(json!({
26193                "events": budget.event_count,
26194                "bytes": budget.size_bytes,
26195                "recommended": budget.continue_as_new_recommended,
26196                "pressure": budget.pressure,
26197            }))
26198        });
26199        let task: WorkflowTask = serde_json::from_value(json!({
26200            "task_id": "task-history-budget",
26201            "workflow_type": "rust.history-budget",
26202            "payload_codec": DEFAULT_CODEC,
26203            "history_events": [],
26204            "total_history_events": 480,
26205            "history_size_bytes": 1_048_576,
26206            "continue_as_new_recommended": true,
26207            "history_budget_pressure": "continue_as_new_recommended",
26208        }))
26209        .expect("published workflow task");
26210
26211        let commands = worker
26212            .execute_workflow_task(task)
26213            .expect("history-budget workflow");
26214        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
26215        assert_eq!(result["events"], 480);
26216        assert_eq!(result["bytes"], 1_048_576);
26217        assert_eq!(result["recommended"], true);
26218        assert_eq!(result["pressure"], "continue_as_new_recommended");
26219    }
26220
26221    #[test]
26222    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
26223        let client = Client::new("http://127.0.0.1:8080").expect("client");
26224        let mut worker = Worker::new(client, "rust-workers");
26225        worker.register_workflow("rust.failing", |_ctx, _input| async move {
26226            Err(Error::Codec("rust_conformance_failure".to_string()))
26227        });
26228        let task = WorkflowTask {
26229            task_id: "wft-rust-failing-1".to_string(),
26230            observability_context: None,
26231            dispatch_observability_context: None,
26232            observability_links: None,
26233            workflow_command_id: None,
26234            workflow_id: Some("wf-rust-failing".to_string()),
26235            run_id: Some("run-rust-failing".to_string()),
26236            workflow_type: "rust.failing".to_string(),
26237            cancel_requested: false,
26238            payload_codec: DEFAULT_CODEC.to_string(),
26239            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26240            history_events: Vec::new(),
26241            total_history_events: Some(0),
26242            history_size_bytes: None,
26243            continue_as_new_recommended: None,
26244            history_budget_pressure: None,
26245            next_history_page_token: None,
26246            workflow_task_attempt: 1,
26247            workflow_signal_id: None,
26248            signal_name: None,
26249            signal_arguments: None,
26250            workflow_update_id: None,
26251            update_name: None,
26252            lease_owner: Some("rust-worker".to_string()),
26253        };
26254
26255        let commands = worker
26256            .execute_workflow_task(task)
26257            .expect("handler failure becomes a workflow command");
26258
26259        assert_eq!(commands.len(), 1);
26260        assert_eq!(commands[0]["type"], "fail_workflow");
26261        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
26262        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
26263        assert_eq!(commands[0]["non_retryable"], false);
26264        assert_eq!(
26265            commands[0]["message"],
26266            "codec error: rust_conformance_failure"
26267        );
26268        assert_eq!(
26269            commands[0]["exception"]["message"],
26270            "codec error: rust_conformance_failure"
26271        );
26272    }
26273
26274    #[test]
26275    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
26276        let client = Client::new("http://127.0.0.1:8080").expect("client");
26277        let mut worker = Worker::new(client, "rust-workers");
26278        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
26279            let _: String = ctx.side_effect(|| "captured".to_string())?;
26280            Err(Error::WorkerLoop("application failure".to_string()))
26281        });
26282
26283        let commands = worker
26284            .execute_workflow_task(workflow_task(
26285                "rust.failing-after-side-effect",
26286                Vec::new(),
26287                DEFAULT_CODEC,
26288            ))
26289            .expect("ordinary failure remains a workflow decision");
26290
26291        assert_eq!(commands.len(), 2);
26292        assert_eq!(commands[0]["type"], "record_side_effect");
26293        assert_eq!(commands[1]["type"], "fail_workflow");
26294    }
26295
26296    #[test]
26297    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
26298        let client = Client::new("http://127.0.0.1:8080").expect("client");
26299        let mut worker = Worker::new(client, "rust-workers");
26300        worker.register_workflow("rust.redrive", |ctx, _input| async move {
26301            ctx.activity("greet", json!([])).await?;
26302            Ok(Value::Null)
26303        });
26304        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
26305            match ctx.activity("greet", json!([])).await {
26306                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
26307                result => result,
26308            }
26309        });
26310
26311        let failed = history_event(
26312            "ActivityFailed",
26313            json!({
26314                "sequence": 1,
26315                "activity_type": "greet",
26316                "activity_execution_id": "activity-1",
26317                "message": "failed"
26318            }),
26319        );
26320        let commands = worker
26321            .execute_workflow_task(workflow_task(
26322                "rust.redrive",
26323                vec![failed.clone()],
26324                DEFAULT_CODEC,
26325            ))
26326            .expect("recorded failure becomes a workflow command");
26327        assert_eq!(commands[0]["type"], "fail_workflow");
26328        assert_eq!(commands[0]["failed_step_sequence"], 1);
26329        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
26330
26331        let translated = worker
26332            .execute_workflow_task(workflow_task(
26333                "rust.redrive-translated",
26334                vec![failed],
26335                DEFAULT_CODEC,
26336            ))
26337            .expect("translated failure becomes a workflow command");
26338        assert_eq!(translated[0]["type"], "fail_workflow");
26339        assert!(translated[0].get("failed_step_sequence").is_none());
26340        assert!(translated[0].get("failed_activity_execution_id").is_none());
26341
26342        let without_identity = worker
26343            .execute_workflow_task(workflow_task(
26344                "rust.redrive",
26345                vec![history_event(
26346                    "ActivityFailed",
26347                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
26348                )],
26349                DEFAULT_CODEC,
26350            ))
26351            .expect("incomplete identity still fails the workflow");
26352        assert!(without_identity[0].get("failed_step_sequence").is_none());
26353
26354        let timed_out = worker
26355            .execute_workflow_task(workflow_task(
26356                "rust.redrive",
26357                vec![history_event(
26358                    "ActivityTimedOut",
26359                    json!({
26360                        "sequence": 1,
26361                        "activity_type": "greet",
26362                        "activity_execution_id": "activity-timeout",
26363                    }),
26364                )],
26365                DEFAULT_CODEC,
26366            ))
26367            .expect("timeout still fails the workflow");
26368        assert!(timed_out[0].get("failed_step_sequence").is_none());
26369    }
26370
26371    #[test]
26372    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
26373        let client = Client::new("http://127.0.0.1:8080").expect("client");
26374        let mut worker = Worker::new(client, "rust-workers");
26375        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
26376            let first = ctx.activity("first", json!([])).await?;
26377            let second = ctx.activity("second", json!([first.clone()])).await?;
26378            Ok(json!({"first": first, "second": second}))
26379        });
26380        let first = history_event(
26381            "ActivityCompleted",
26382            json!({
26383                "sequence": 1,
26384                "activity_type": "first",
26385                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
26386                "payload_codec": DEFAULT_CODEC,
26387                "reused_from_run_id": "failed-run",
26388                "reused_activity_execution_id": "original-first",
26389            }),
26390        );
26391
26392        let retry = worker
26393            .execute_workflow_task(workflow_task(
26394                "rust.redrive-successor",
26395                vec![first.clone()],
26396                DEFAULT_CODEC,
26397            ))
26398            .expect("reused result replays before failed step");
26399        assert_eq!(retry.len(), 1);
26400        assert_eq!(retry[0]["type"], "schedule_activity");
26401        assert_eq!(retry[0]["activity_type"], "second");
26402        assert_eq!(
26403            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
26404            json!(["recorded"]),
26405        );
26406
26407        let second = history_event(
26408            "ActivityCompleted",
26409            json!({
26410                "sequence": 2,
26411                "activity_type": "second",
26412                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
26413                "payload_codec": DEFAULT_CODEC,
26414            }),
26415        );
26416        let completed = worker
26417            .execute_workflow_task(workflow_task(
26418                "rust.redrive-successor",
26419                vec![first, second],
26420                DEFAULT_CODEC,
26421            ))
26422            .expect("retried step completes the successor");
26423        assert_eq!(completed.len(), 1);
26424        assert_eq!(completed[0]["type"], "complete_workflow");
26425        assert_eq!(
26426            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
26427            json!({"first": "recorded", "second": "retried"}),
26428        );
26429    }
26430
26431    #[test]
26432    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
26433        let client = Client::new("http://127.0.0.1:8080").expect("client");
26434        let mut worker = Worker::new(client, "rust-workers");
26435        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
26436            Err(Error::WorkerLoop("application failure".to_string()))
26437        });
26438        let result =
26439            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
26440
26441        let error = worker
26442            .execute_workflow_task(workflow_task(
26443                "rust.removed-side-effect",
26444                vec![history_event(
26445                    "SideEffectRecorded",
26446                    json!({"sequence": 1, "result": result}),
26447                )],
26448                DEFAULT_CODEC,
26449            ))
26450            .expect_err("removed committed history must not become fail_workflow");
26451
26452        let Error::NonDeterministicReplay(failure) = error else {
26453            panic!("expected typed replay failure");
26454        };
26455        assert_eq!(failure.reason, "recorded_commands_unconsumed");
26456        assert_eq!(failure.sequence, Some(1));
26457        assert_eq!(failure.expected.as_deref(), Some("side effect"));
26458    }
26459
26460    #[test]
26461    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
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(
26465            "rust.side-effect-before-marker-error",
26466            |ctx, _input| async move {
26467                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
26468                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
26469                ctx.get_version("restart-safe", 2, 2)?;
26470                Ok(Value::Null)
26471            },
26472        );
26473
26474        let error = worker
26475            .execute_workflow_task(workflow_task(
26476                "rust.side-effect-before-marker-error",
26477                vec![history_event(
26478                    "VersionMarkerRecorded",
26479                    json!({
26480                        "sequence": 1,
26481                        "change_id": "restart-safe",
26482                        "version": 1,
26483                        "min_supported": 1,
26484                        "max_supported": 1,
26485                    }),
26486                )],
26487                DEFAULT_CODEC,
26488            ))
26489            .expect_err("replay error must return no queued workflow commands");
26490
26491        let Error::NonDeterministicReplay(failure) = error else {
26492            panic!("expected typed replay failure");
26493        };
26494        assert_eq!(failure.reason, "version_marker_incompatible_range");
26495        assert_eq!(failure.sequence, Some(1));
26496    }
26497
26498    #[test]
26499    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
26500        let client = Client::new("http://127.0.0.1:8080").expect("client");
26501        let mut worker = Worker::new(client, "rust-workers");
26502        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
26503            ctx.sleep(Duration::from_secs(5)).await?;
26504            Ok(json!({"status": "timer fired"}))
26505        });
26506
26507        let task = WorkflowTask {
26508            task_id: "wft-rust-timer-pending".to_string(),
26509            observability_context: None,
26510            dispatch_observability_context: None,
26511            observability_links: None,
26512            workflow_command_id: None,
26513            workflow_id: Some("wf-rust-timer".to_string()),
26514            run_id: Some("run-rust-timer".to_string()),
26515            workflow_type: "rust.timer.pending".to_string(),
26516            cancel_requested: false,
26517            payload_codec: DEFAULT_CODEC.to_string(),
26518            arguments: Some(
26519                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26520            ),
26521            history_events: vec![history_event(
26522                "TimerScheduled",
26523                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26524            )],
26525            total_history_events: Some(1),
26526            history_size_bytes: None,
26527            continue_as_new_recommended: None,
26528            history_budget_pressure: None,
26529            next_history_page_token: None,
26530            workflow_task_attempt: 1,
26531            workflow_signal_id: None,
26532            signal_name: None,
26533            signal_arguments: None,
26534            workflow_update_id: None,
26535            update_name: None,
26536            lease_owner: Some("rust-worker".to_string()),
26537        };
26538
26539        for _redelivery_or_restart in 0..2 {
26540            let commands = worker
26541                .execute_workflow_task(task.clone())
26542                .expect("recorded timer remains pending");
26543            assert!(
26544                commands.is_empty(),
26545                "recorded timer must not be rescheduled"
26546            );
26547        }
26548    }
26549
26550    #[test]
26551    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
26552        let client = Client::new("http://127.0.0.1:8080").expect("client");
26553        let mut worker = Worker::new(client, "rust-workers");
26554        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
26555            Ok(json!({"status": "completed"}))
26556        });
26557        let task = WorkflowTask {
26558            task_id: "wft-rust-timer-removed".to_string(),
26559            observability_context: None,
26560            dispatch_observability_context: None,
26561            observability_links: None,
26562            workflow_command_id: None,
26563            workflow_id: Some("wf-rust-timer".to_string()),
26564            run_id: Some("run-rust-timer".to_string()),
26565            workflow_type: "rust.timer.removed".to_string(),
26566            cancel_requested: false,
26567            payload_codec: DEFAULT_CODEC.to_string(),
26568            arguments: Some(
26569                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
26570            ),
26571            history_events: vec![
26572                history_event(
26573                    "TimerScheduled",
26574                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26575                ),
26576                history_event(
26577                    "TimerFired",
26578                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26579                ),
26580            ],
26581            total_history_events: Some(2),
26582            history_size_bytes: None,
26583            continue_as_new_recommended: None,
26584            history_budget_pressure: None,
26585            next_history_page_token: None,
26586            workflow_task_attempt: 1,
26587            workflow_signal_id: None,
26588            signal_name: None,
26589            signal_arguments: None,
26590            workflow_update_id: None,
26591            update_name: None,
26592            lease_owner: Some("rust-worker".to_string()),
26593        };
26594
26595        let Error::NonDeterministicReplay(failure) = worker
26596            .execute_workflow_task(task)
26597            .expect_err("removed timer must fail replay")
26598        else {
26599            panic!("expected typed replay failure");
26600        };
26601        assert_eq!(failure.reason, "recorded_commands_unconsumed");
26602        assert_eq!(failure.sequence, Some(1));
26603    }
26604
26605    #[test]
26606    fn workflow_context_emits_explicit_child_workflow_contract() {
26607        let ctx = WorkflowContext {
26608            cancellation_scope_id: "root".into(),
26609            state: Arc::new(Mutex::new(
26610                WorkflowState::new_with_identity(
26611                    Vec::new(),
26612                    Some("wf-parent".to_string()),
26613                    Some("run-parent".to_string()),
26614                    "parent-workers".to_string(),
26615                    DEFAULT_CODEC.to_string(),
26616                    None,
26617                )
26618                .expect("workflow state"),
26619            )),
26620        };
26621        let options = ChildWorkflowOptions::new("python-workers")
26622            .parent_close_policy(ParentClosePolicy::RequestCancel)
26623            .retry_policy(ChildWorkflowRetryPolicy {
26624                max_attempts: Some(3),
26625                backoff_seconds: vec![1, 5],
26626                non_retryable_error_types: vec!["ValidationError".to_string()],
26627            })
26628            .execution_timeout_seconds(600)
26629            .run_timeout_seconds(120);
26630        let mut call = Box::pin(ctx.start_child_workflow(
26631            "python.fulfil-order",
26632            options,
26633            json!([{"order_id": "order-42"}]),
26634        ));
26635        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26636
26637        assert!(matches!(
26638            call.as_mut().poll(&mut task_context),
26639            Poll::Pending
26640        ));
26641        let commands = ctx.take_commands().expect("commands");
26642        assert_eq!(commands.len(), 1);
26643        let command = &commands[0];
26644        assert_eq!(command["type"], "start_child_workflow");
26645        assert_eq!(command["workflow_type"], "python.fulfil-order");
26646        assert_eq!(command["queue"], "python-workers");
26647        assert_eq!(command["parent_close_policy"], "request_cancel");
26648        assert_eq!(command["retry_policy"]["max_attempts"], 3);
26649        assert_eq!(command["execution_timeout_seconds"], 600);
26650        assert_eq!(command["run_timeout_seconds"], 120);
26651        assert_eq!(
26652            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
26653            json!([{"order_id": "order-42"}])
26654        );
26655    }
26656
26657    fn child_parent_worker() -> Worker {
26658        let client = Client::new("http://127.0.0.1:8080").expect("client");
26659        let mut worker = Worker::new(client, "rust-parent-workers");
26660        worker.register_workflow("rust.parent", |ctx, _input| async move {
26661            let child = ctx
26662                .start_child_workflow(
26663                    "python.child",
26664                    ChildWorkflowOptions::new("python-child-workers")
26665                        .parent_close_policy(ParentClosePolicy::Terminate),
26666                    json!([{"codec_probe": [1, true, "rust"]}]),
26667                )
26668                .await?;
26669            Ok(json!({
26670                "parent_workflow_id": child.parent.workflow_id,
26671                "parent_run_id": child.parent.run_id,
26672                "child_workflow_id": child.child.workflow_id,
26673                "child_run_id": child.child.run_id,
26674                "child_workflow_type": child.child_workflow_type,
26675                "result": child.result,
26676            }))
26677        });
26678        worker
26679    }
26680
26681    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
26682        WorkflowTask {
26683            task_id: "wft-child-parent".to_string(),
26684            observability_context: None,
26685            dispatch_observability_context: None,
26686            observability_links: None,
26687            workflow_command_id: None,
26688            workflow_id: Some("wf-parent".to_string()),
26689            run_id: Some("run-parent".to_string()),
26690            workflow_type: "rust.parent".to_string(),
26691            cancel_requested: false,
26692            payload_codec: DEFAULT_CODEC.to_string(),
26693            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26694            history_events: vec![
26695                HistoryEvent {
26696                    event_type: "ChildWorkflowScheduled".to_string(),
26697                    payload: json!({
26698                        "sequence": 1,
26699                        "child_call_id": "call-child",
26700                        "child_workflow_instance_id": "wf-child",
26701                        "child_workflow_run_id": "run-child",
26702                        "child_workflow_type": "python.child",
26703                        "parent_close_policy": "terminate",
26704                    }),
26705                    raw: HashMap::new(),
26706                },
26707                HistoryEvent {
26708                    event_type: event_type.to_string(),
26709                    payload,
26710                    raw: HashMap::new(),
26711                },
26712            ],
26713            total_history_events: Some(2),
26714            history_size_bytes: None,
26715            continue_as_new_recommended: None,
26716            history_budget_pressure: None,
26717            next_history_page_token: None,
26718            workflow_task_attempt: 1,
26719            workflow_signal_id: None,
26720            signal_name: None,
26721            signal_arguments: None,
26722            workflow_update_id: None,
26723            update_name: None,
26724            lease_owner: Some("rust-worker".to_string()),
26725        }
26726    }
26727
26728    #[test]
26729    fn committed_child_result_replays_without_starting_a_duplicate() {
26730        let worker = child_parent_worker();
26731        let task = child_parent_task(
26732            "ChildRunCompleted",
26733            json!({
26734                "sequence": 1,
26735                "child_call_id": "call-child",
26736                "child_workflow_instance_id": "wf-child",
26737                "child_workflow_run_id": "run-child",
26738                "child_workflow_type": "python.child",
26739                "payload_codec": DEFAULT_CODEC,
26740                "result": fixture_envelope(json!({"from":"python","ok":true})),
26741            }),
26742        );
26743
26744        for _restart in 0..2 {
26745            let commands = worker
26746                .execute_workflow_task(task.clone())
26747                .expect("replayed parent task");
26748            assert_eq!(commands.len(), 1);
26749            assert_eq!(commands[0]["type"], "complete_workflow");
26750            assert!(!commands
26751                .iter()
26752                .any(|command| command["type"] == "start_child_workflow"));
26753            let output =
26754                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26755            assert_eq!(output["parent_workflow_id"], "wf-parent");
26756            assert_eq!(output["parent_run_id"], "run-parent");
26757            assert_eq!(output["child_workflow_id"], "wf-child");
26758            assert_eq!(output["child_run_id"], "run-child");
26759            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
26760        }
26761    }
26762
26763    #[test]
26764    fn typed_child_arguments_and_results_survive_replay() {
26765        let client = Client::new("http://127.0.0.1:8080").expect("client");
26766        let mut worker = Worker::new(client, "rust-parent-workers");
26767        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
26768            let child = ctx
26769                .start_child_workflow_avro_value(
26770                    "python.typed-child",
26771                    ChildWorkflowOptions::new("python-workers"),
26772                    AvroValue::Array(vec![typed_fidelity_probe()]),
26773                )
26774                .await?;
26775            Ok(child.result)
26776        });
26777
26778        let initial = worker
26779            .execute_workflow_task(workflow_task(
26780                "rust.typed-parent",
26781                Vec::new(),
26782                DEFAULT_CODEC,
26783            ))
26784            .expect("typed child start");
26785        assert_eq!(initial[0]["type"], "start_child_workflow");
26786        assert_eq!(
26787            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
26788                .expect("typed child arguments"),
26789            AvroValue::Array(vec![typed_fidelity_probe()])
26790        );
26791
26792        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
26793            .expect("typed child result");
26794        let task = workflow_task(
26795            "rust.typed-parent",
26796            vec![
26797                history_event(
26798                    "ChildWorkflowScheduled",
26799                    json!({
26800                        "sequence": 1,
26801                        "child_call_id": "call-typed",
26802                        "child_workflow_instance_id": "wf-child",
26803                        "child_workflow_run_id": "run-child",
26804                        "child_workflow_type": "python.typed-child",
26805                    }),
26806                ),
26807                history_event(
26808                    "ChildRunCompleted",
26809                    json!({
26810                        "sequence": 1,
26811                        "child_call_id": "call-typed",
26812                        "child_workflow_instance_id": "wf-child",
26813                        "child_workflow_run_id": "run-child",
26814                        "child_workflow_type": "python.typed-child",
26815                        "payload_codec": DEFAULT_CODEC,
26816                        "result": result,
26817                    }),
26818                ),
26819            ],
26820            DEFAULT_CODEC,
26821        );
26822
26823        let commands = worker
26824            .execute_workflow_task(task)
26825            .expect("typed child replay");
26826        assert_eq!(commands[0]["type"], "complete_workflow");
26827        assert_eq!(
26828            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
26829                .expect("typed parent result"),
26830            typed_fidelity_probe()
26831        );
26832    }
26833
26834    #[test]
26835    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
26836        let worker = child_parent_worker();
26837        let mut task = child_parent_task("unused", Value::Null);
26838        task.history_events.truncate(1);
26839        task.total_history_events = Some(1);
26840
26841        for _redelivery_or_restart in 0..2 {
26842            let commands = worker
26843                .execute_workflow_task(task.clone())
26844                .expect("recorded child remains pending");
26845            assert!(
26846                commands.is_empty(),
26847                "recorded pending child must not be started again"
26848            );
26849        }
26850    }
26851
26852    #[test]
26853    fn child_cancellation_becomes_stable_parent_failure_command() {
26854        let worker = child_parent_worker();
26855        let task = child_parent_task(
26856            "ChildRunCancelled",
26857            json!({
26858                "sequence": 1,
26859                "child_workflow_instance_id": "wf-child",
26860                "child_workflow_run_id": "run-child",
26861                "child_workflow_type": "python.child",
26862                "failure_id": "failure-child",
26863                "failure_category": "cancelled",
26864                "message": "cancelled by parent-close policy",
26865            }),
26866        );
26867
26868        let commands = worker
26869            .execute_workflow_task(task)
26870            .expect("parent settlement");
26871        assert_eq!(commands.len(), 1);
26872        assert_eq!(commands[0]["type"], "fail_workflow");
26873        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
26874        assert_eq!(
26875            commands[0]["exception"]["properties"]["reason"],
26876            "cancelled"
26877        );
26878        assert_eq!(
26879            commands[0]["exception"]["properties"]["child_workflow_run_id"],
26880            "run-child"
26881        );
26882    }
26883
26884    #[test]
26885    fn workflow_can_handle_typed_child_failure() {
26886        let client = Client::new("http://127.0.0.1:8080").expect("client");
26887        let mut worker = Worker::new(client, "rust-parent-workers");
26888        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
26889            match ctx
26890                .start_child_workflow(
26891                    "python.child",
26892                    ChildWorkflowOptions::new("python-child-workers"),
26893                    json!([]),
26894                )
26895                .await
26896            {
26897                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
26898                    "reason": failure.reason,
26899                    "failure_id": failure.failure_id,
26900                    "exception_class": failure.exception_class,
26901                    "child_run_id": failure.child_workflow_run_id,
26902                })),
26903                Err(error) => Err(error),
26904                Ok(_) => Err(Error::WorkerLoop(
26905                    "child unexpectedly succeeded".to_string(),
26906                )),
26907            }
26908        });
26909        let mut task = child_parent_task(
26910            "ChildRunFailed",
26911            json!({
26912                "sequence": 1,
26913                "child_workflow_instance_id": "wf-child",
26914                "child_workflow_run_id": "run-child",
26915                "child_workflow_type": "python.child",
26916                "failure_id": "failure-child",
26917                "failure_category": "child_workflow",
26918                "message": "payment rejected",
26919                "exception": {
26920                    "type": "PaymentRejected",
26921                    "class": "payments.PaymentRejected",
26922                    "message": "payment rejected"
26923                }
26924            }),
26925        );
26926        task.workflow_type = "rust.handled-parent".to_string();
26927        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
26928
26929        let commands = worker.execute_workflow_task(task).expect("handled failure");
26930        assert_eq!(commands[0]["type"], "complete_workflow");
26931        let output =
26932            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
26933        assert_eq!(output["reason"], "child_workflow");
26934        assert_eq!(output["failure_id"], "failure-child");
26935        assert_eq!(output["exception_class"], "payments.PaymentRejected");
26936        assert_eq!(output["child_run_id"], "run-child");
26937    }
26938
26939    #[test]
26940    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
26941        let client = Client::new("http://127.0.0.1:8080").expect("client");
26942        let mut worker = Worker::new(client, "rust-workers");
26943
26944        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
26945            let signal = ctx.wait_signal("start").await?;
26946            let name = signal
26947                .first()
26948                .and_then(|value| value.as_str())
26949                .unwrap_or("world");
26950            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
26951            Ok(json!({
26952                "greeting": greeting,
26953                "language": "rust"
26954            }))
26955        });
26956
26957        let signal_arguments =
26958            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
26959        let task = WorkflowTask {
26960            task_id: "wft-rust-signal-1".to_string(),
26961            observability_context: None,
26962            dispatch_observability_context: None,
26963            observability_links: None,
26964            workflow_command_id: None,
26965            workflow_id: Some("wf-rust-hello".to_string()),
26966            run_id: Some("run-rust-hello".to_string()),
26967            workflow_type: "rust.hello_workflow".to_string(),
26968            cancel_requested: false,
26969            payload_codec: DEFAULT_CODEC.to_string(),
26970            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
26971            history_events: vec![HistoryEvent {
26972                event_type: "SignalReceived".to_string(),
26973                payload: json!({
26974                    "signal_id": "sig-rust-1",
26975                    "signal_name": "start"
26976                }),
26977                raw: HashMap::new(),
26978            }],
26979            total_history_events: Some(1),
26980            history_size_bytes: None,
26981            continue_as_new_recommended: None,
26982            history_budget_pressure: None,
26983            next_history_page_token: None,
26984            workflow_task_attempt: 1,
26985            workflow_signal_id: Some("sig-rust-1".to_string()),
26986            signal_name: Some("start".to_string()),
26987            signal_arguments: Some(signal_arguments),
26988            workflow_update_id: None,
26989            update_name: None,
26990            lease_owner: Some("rust-worker".to_string()),
26991        };
26992
26993        let commands = worker.execute_workflow_task(task).expect("workflow task");
26994
26995        assert_eq!(commands.len(), 1);
26996        assert_eq!(commands[0]["type"], "schedule_activity");
26997        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
26998        assert_eq!(
26999            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
27000            json!(["Rust"])
27001        );
27002    }
27003
27004    #[test]
27005    fn workflow_task_appends_paginated_history_events() {
27006        let mut task = WorkflowTask {
27007            task_id: "wft-rust-pages-1".to_string(),
27008            observability_context: None,
27009            dispatch_observability_context: None,
27010            observability_links: None,
27011            workflow_command_id: None,
27012            workflow_id: Some("wf-rust-pages".to_string()),
27013            run_id: Some("run-rust-pages".to_string()),
27014            workflow_type: "rust.hello_workflow".to_string(),
27015            cancel_requested: false,
27016            payload_codec: DEFAULT_CODEC.to_string(),
27017            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
27018            history_events: vec![HistoryEvent {
27019                event_type: "WorkflowStarted".to_string(),
27020                payload: json!({}),
27021                raw: HashMap::new(),
27022            }],
27023            total_history_events: Some(3),
27024            history_size_bytes: None,
27025            continue_as_new_recommended: None,
27026            history_budget_pressure: None,
27027            next_history_page_token: Some("MQ==".to_string()),
27028            workflow_task_attempt: 1,
27029            workflow_signal_id: None,
27030            signal_name: None,
27031            signal_arguments: None,
27032            workflow_update_id: None,
27033            update_name: None,
27034            lease_owner: Some("rust-worker".to_string()),
27035        };
27036
27037        task.append_history_page(WorkflowTaskHistoryPage {
27038            history_events: vec![
27039                HistoryEvent {
27040                    event_type: "SignalReceived".to_string(),
27041                    payload: json!({
27042                        "signal_id": "sig-rust-1",
27043                        "signal_name": "start",
27044                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
27045                            .expect("signal arguments")
27046                    }),
27047                    raw: HashMap::new(),
27048                },
27049                HistoryEvent {
27050                    event_type: "MarkerRecorded".to_string(),
27051                    payload: json!({"sequence": 3}),
27052                    raw: HashMap::new(),
27053                },
27054            ],
27055            total_history_events: Some(3),
27056            next_history_page_token: None,
27057        });
27058
27059        assert_eq!(task.history_events.len(), 3);
27060        assert_eq!(task.total_history_events, Some(3));
27061        assert_eq!(task.next_history_page_token, None);
27062
27063        let signal = task
27064            .history_events
27065            .iter()
27066            .find(|event| event.event_type == "SignalReceived")
27067            .expect("signal event");
27068        assert_eq!(
27069            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
27070            vec![AvroValue::String("Rust".to_string())]
27071        );
27072    }
27073
27074    #[tokio::test]
27075    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
27076        let client = Client::new("http://127.0.0.1:8080").expect("client");
27077        let mut worker = Worker::new(client, "rust-workers");
27078        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27079        worker.register_query("counter", "current", |ctx, _args| async move {
27080            let mut count = 0_i64;
27081            for signal in ctx.signal_events() {
27082                let value = signal
27083                    .arguments
27084                    .first()
27085                    .and_then(Value::as_i64)
27086                    .unwrap_or_default();
27087                match signal.name.as_str() {
27088                    "increment" => count += value,
27089                    "set" => count = value,
27090                    _ => {}
27091                }
27092            }
27093            Ok(json!(count))
27094        });
27095
27096        let task = QueryTask {
27097            query_task_id: "query-rust-counter".to_string(),
27098            observability_context: None,
27099            dispatch_observability_context: None,
27100            observability_links: None,
27101            query_task_attempt: 1,
27102            lease_owner: Some("rust-worker".to_string()),
27103            workflow_id: Some("counter-1".to_string()),
27104            run_id: Some("run-counter-1".to_string()),
27105            workflow_type: "counter".to_string(),
27106            query_name: "current".to_string(),
27107            payload_codec: DEFAULT_CODEC.to_string(),
27108            workflow_arguments: Some(
27109                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
27110            ),
27111            query_arguments: Some(
27112                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
27113            ),
27114            history_events: vec![
27115                HistoryEvent {
27116                    event_type: "SignalReceived".to_string(),
27117                    payload: json!({
27118                        "signal_id": "php-signal-1",
27119                        "signal_name": "increment",
27120                        "workflow_sequence": 1,
27121                        "payload_codec": DEFAULT_CODEC,
27122                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
27123                    }),
27124                    raw: HashMap::new(),
27125                },
27126                HistoryEvent {
27127                    event_type: "SignalReceived".to_string(),
27128                    payload: json!({
27129                        "signal_id": "python-signal-2",
27130                        "signal_name": "increment",
27131                        "workflow_sequence": 2,
27132                        "payload_codec": DEFAULT_CODEC,
27133                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
27134                    }),
27135                    raw: HashMap::new(),
27136                },
27137                HistoryEvent {
27138                    event_type: "SignalReceived".to_string(),
27139                    payload: json!({
27140                        "signal_id": "rust-signal-3",
27141                        "signal_name": "set",
27142                        "workflow_sequence": 3,
27143                        "payload_codec": DEFAULT_CODEC,
27144                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
27145                    }),
27146                    raw: HashMap::new(),
27147                },
27148            ],
27149            history_export: None,
27150            run_status: Some("completed".to_string()),
27151        };
27152
27153        let result = worker.execute_query_task(task).await.expect("query result");
27154        assert_eq!(result.into_json().expect("query projection"), json!(0));
27155    }
27156
27157    #[tokio::test]
27158    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
27159        let worker = replay_counter_worker();
27160        let running_history = json!([
27161            {
27162                "type": "ActivityCompleted",
27163                "payload": {
27164                    "sequence": 1,
27165                    "activity_type": "load-counter",
27166                    "payload_codec": DEFAULT_CODEC,
27167                    "result": fixture_envelope(json!("loaded"))
27168                }
27169            },
27170            {
27171                "type": "SignalWaitOpened",
27172                "payload": {
27173                    "sequence": 3,
27174                    "signal_name": "increment"
27175                }
27176            },
27177            {
27178                "type": "SignalReceived",
27179                "payload": {
27180                    "signal_id": "signal-3",
27181                    "signal_name": "increment",
27182                    "workflow_sequence": 2,
27183                    "payload_codec": DEFAULT_CODEC,
27184                    "arguments": fixture_envelope(json!([3]))
27185                }
27186            },
27187            {
27188                "type": "SignalApplied",
27189                "payload": {
27190                    "sequence": 3,
27191                    "signal_id": "signal-3",
27192                    "signal_name": "increment",
27193                    "payload_codec": DEFAULT_CODEC,
27194                    "value": fixture_envelope(json!([3]))
27195                }
27196            }
27197        ]);
27198
27199        let running = worker
27200            .execute_query_task(replay_counter_query(
27201                "current",
27202                running_history.clone(),
27203                "running",
27204            ))
27205            .await
27206            .expect("running replay query");
27207        assert_eq!(
27208            running.clone().into_json().expect("query projection"),
27209            json!({"loaded": "loaded", "count": 3, "finished": false})
27210        );
27211
27212        let detached = worker
27213            .execute_query_task(replay_counter_query(
27214                "detached-mutation",
27215                running_history.clone(),
27216                "running",
27217            ))
27218            .await
27219            .expect("query mutates only its detached state clone");
27220        assert_eq!(detached.into_json().expect("query projection"), json!(999));
27221        let failed = worker
27222            .execute_query_task(replay_counter_query(
27223                "failed-mutation",
27224                running_history.clone(),
27225                "running",
27226            ))
27227            .await
27228            .expect_err("failed query");
27229        assert_eq!(failed.reason, "query_rejected");
27230        let unchanged = worker
27231            .execute_query_task(replay_counter_query("current", running_history, "running"))
27232            .await
27233            .expect("later query reconstructs unchanged state");
27234        assert_eq!(unchanged, running);
27235
27236        let restarted_worker = replay_counter_worker();
27237        let empty_arguments = fixture_envelope(json!([]));
27238        let loaded_result = fixture_envelope(json!("loaded"));
27239        let signal_three = fixture_blob(json!([3]));
27240        let signal_five = fixture_blob(json!([5]));
27241        let restarted_task: QueryTask = serde_json::from_value(json!({
27242            "query_task_id": "query-after-restart",
27243            "workflow_id": "counter-1",
27244            "run_id": "run-counter-1",
27245            "workflow_type": "replay-counter",
27246            "query_name": "current",
27247            "payload_codec": DEFAULT_CODEC,
27248            "workflow_arguments": empty_arguments.clone(),
27249            "query_arguments": empty_arguments,
27250            "history_events": [],
27251            "history_export": {
27252                "payloads": {"codec": DEFAULT_CODEC},
27253                "history_events": [
27254                    {
27255                        "type": "ActivityCompleted",
27256                        "payload": {
27257                            "sequence": 1,
27258                            "activity_type": "load-counter",
27259                            "payload_codec": DEFAULT_CODEC,
27260                            "result": null
27261                        }
27262                    },
27263                    {
27264                        "type": "SignalWaitOpened",
27265                        "payload": {
27266                            "sequence": 3,
27267                            "signal_name": "increment"
27268                        }
27269                    },
27270                    {
27271                        "type": "SignalReceived",
27272                        "payload": {
27273                            "signal_id": "signal-3",
27274                            "signal_name": "increment",
27275                            "workflow_sequence": 2
27276                        }
27277                    },
27278                    {
27279                        "type": "SignalApplied",
27280                        "payload": {
27281                            "sequence": 3,
27282                            "signal_id": "signal-3",
27283                            "signal_name": "increment"
27284                        }
27285                    },
27286                    {
27287                        "type": "SignalWaitOpened",
27288                        "payload": {
27289                            "sequence": 5,
27290                            "signal_name": "increment"
27291                        }
27292                    },
27293                    {
27294                        "type": "SignalReceived",
27295                        "payload": {
27296                            "signal_id": "signal-5",
27297                            "signal_name": "increment",
27298                            "workflow_sequence": 4
27299                        }
27300                    },
27301                    {
27302                        "type": "SignalApplied",
27303                        "payload": {
27304                            "sequence": 5,
27305                            "signal_id": "signal-5",
27306                            "signal_name": "increment"
27307                        }
27308                    }
27309                ],
27310                "activities": [{
27311                    "sequence": 1,
27312                    "activity_type": "load-counter",
27313                    "payload_codec": DEFAULT_CODEC,
27314                    "result": loaded_result
27315                }],
27316                "signals": [
27317                    {
27318                        "id": "signal-3",
27319                        "name": "increment",
27320                        "workflow_sequence": 2,
27321                        "payload_codec": DEFAULT_CODEC,
27322                        "arguments": signal_three
27323                    },
27324                    {
27325                        "id": "signal-5",
27326                        "name": "increment",
27327                        "workflow_sequence": 4,
27328                        "payload_codec": DEFAULT_CODEC,
27329                        "arguments": signal_five
27330                    }
27331                ]
27332            },
27333            "run_status": "completed"
27334        }))
27335        .expect("cold replay query task");
27336        let completed = restarted_worker
27337            .execute_query_task(restarted_task)
27338            .await
27339            .expect("completed cold replay query");
27340        assert_eq!(
27341            completed.into_json().expect("query projection"),
27342            json!({"loaded": "loaded", "count": 8, "finished": true})
27343        );
27344    }
27345
27346    #[tokio::test]
27347    async fn replayed_query_replay_failures_are_machine_readable() {
27348        let worker = replay_counter_worker();
27349        let task = replay_counter_query(
27350            "current",
27351            json!([{
27352                "type": "ActivityCompleted",
27353                "payload": {
27354                    "sequence": 1,
27355                    "payload_codec": DEFAULT_CODEC,
27356                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
27357                }
27358            }]),
27359            "running",
27360        );
27361        let failure = worker
27362            .execute_query_task(task)
27363            .await
27364            .expect_err("invalid replay history payload");
27365        assert_eq!(failure.reason, "query_payload_decode_failed");
27366        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
27367        assert!(failure.message.contains("invalid_payload_framing"));
27368    }
27369
27370    #[tokio::test]
27371    async fn query_task_restores_compact_history_from_export() {
27372        let client = Client::new("http://127.0.0.1:8080").expect("client");
27373        let mut worker = Worker::new(client, "rust-workers");
27374        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27375        worker.register_query("counter", "current", |ctx, _args| async move {
27376            Ok(json!(ctx.signals("increment")[0][0]))
27377        });
27378        let empty_arguments = fixture_envelope(json!([]));
27379        let exported_signal = fixture_blob(json!([9]));
27380        let task: QueryTask = serde_json::from_value(json!({
27381            "query_task_id": "query-export",
27382            "workflow_type": "counter",
27383            "query_name": "current",
27384            "payload_codec": DEFAULT_CODEC,
27385            "workflow_arguments": empty_arguments.clone(),
27386            "query_arguments": empty_arguments,
27387            "history_events": [],
27388            "history_export": {
27389                "payloads": {"codec": DEFAULT_CODEC},
27390                "history_events": [{
27391                    "type": "SignalReceived",
27392                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
27393                }],
27394                "signals": [{
27395                    "id": "signal-export",
27396                    "name": "increment",
27397                    "status": "applied",
27398                    "workflow_sequence": 1,
27399                    "payload_codec": DEFAULT_CODEC,
27400                    "arguments": exported_signal
27401                }]
27402            }
27403        }))
27404        .expect("query task");
27405
27406        let result = worker.execute_query_task(task).await.expect("query result");
27407        assert_eq!(result.into_json().expect("query projection"), json!(9));
27408    }
27409
27410    #[tokio::test]
27411    async fn query_task_failures_have_stable_reasons() {
27412        let client = Client::new("http://127.0.0.1:8080").expect("client");
27413        let mut worker = Worker::new(client, "rust-workers");
27414        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27415        worker.register_query(
27416            "counter",
27417            "current",
27418            |_ctx, _args| async move { Ok(json!(0)) },
27419        );
27420
27421        let base_task = QueryTask {
27422            query_task_id: "query-errors".to_string(),
27423            observability_context: None,
27424            dispatch_observability_context: None,
27425            observability_links: None,
27426            query_task_attempt: 1,
27427            lease_owner: None,
27428            workflow_id: Some("counter-errors".to_string()),
27429            run_id: Some("run-errors".to_string()),
27430            workflow_type: "counter".to_string(),
27431            query_name: "missing".to_string(),
27432            payload_codec: DEFAULT_CODEC.to_string(),
27433            workflow_arguments: Some(fixture_envelope(json!([]))),
27434            query_arguments: Some(fixture_envelope(json!([]))),
27435            history_events: Vec::new(),
27436            history_export: None,
27437            run_status: Some("running".to_string()),
27438        };
27439
27440        let unknown = worker
27441            .execute_query_task(base_task.clone())
27442            .await
27443            .expect_err("unknown query");
27444        assert_eq!(unknown.reason, "rejected_unknown_query");
27445
27446        let mut malformed = base_task;
27447        malformed.query_name = "current".to_string();
27448        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
27449        let malformed = worker
27450            .execute_query_task(malformed)
27451            .await
27452            .expect_err("malformed payload");
27453        assert_eq!(malformed.reason, "query_payload_decode_failed");
27454
27455        let client = Client::new("http://127.0.0.1:8080").expect("client");
27456        let mut unavailable_worker = Worker::new(client, "rust-workers");
27457        unavailable_worker
27458            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
27459        let empty_arguments = fixture_envelope(json!([]));
27460        let unavailable_task: QueryTask = serde_json::from_value(json!({
27461            "query_task_id": "query-unavailable",
27462            "workflow_type": "counter",
27463            "query_name": "current",
27464            "payload_codec": DEFAULT_CODEC,
27465            "workflow_arguments": empty_arguments.clone(),
27466            "query_arguments": empty_arguments
27467        }))
27468        .expect("query task");
27469        let unavailable = unavailable_worker
27470            .execute_query_task(unavailable_task)
27471            .await
27472            .expect_err("query handler unavailable");
27473        assert_eq!(unavailable.reason, "query_handler_unavailable");
27474    }
27475
27476    #[tokio::test]
27477    async fn client_query_decodes_result_and_typed_failure() {
27478        let server = MockWorkerServer::start();
27479        let client = Client::builder(server.base_url())
27480            .timeout(Duration::from_secs(2))
27481            .build()
27482            .expect("client");
27483
27484        let result = client
27485            .query_workflow("counter-1", "current", json!([]))
27486            .await
27487            .expect("query result");
27488        assert_eq!(result, json!({"count": 8}));
27489
27490        let error = client
27491            .query_workflow("counter-1", "missing", json!([]))
27492            .await
27493            .expect_err("unknown query");
27494        let Error::QueryFailed(failure) = error else {
27495            panic!("expected typed query failure");
27496        };
27497        assert_eq!(failure.status, 404);
27498        assert_eq!(failure.reason, "rejected_unknown_query");
27499    }
27500
27501    const KEYED_SIGNAL_PATH: &str = "/api/workflows/keyed-1/signal/approve";
27502    const KEYED_RUN_SIGNAL_PATH: &str = "/api/workflows/keyed-1/runs/run-keyed-1/signal/approve";
27503    const KEYED_UPDATE_PATH: &str = "/api/workflows/keyed-1/update/adjust";
27504
27505    #[cfg(feature = "telemetry")]
27506    #[tokio::test]
27507    async fn optional_observability_client_uses_actual_discovery_and_preserves_business_intent() {
27508        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
27509        static PHASE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
27510        PHASE.store(0, Ordering::SeqCst);
27511        use opentelemetry::{
27512            propagation::TextMapPropagator,
27513            trace::{FutureExt, TracerProvider},
27514        };
27515        use opentelemetry_sdk::propagation::TraceContextPropagator;
27516        struct Restore;
27517        impl Drop for Restore {
27518            fn drop(&mut self) {
27519                opentelemetry::global::set_text_map_propagator(
27520                    opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
27521                );
27522            }
27523        }
27524        let _restore = Restore;
27525        opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());
27526        let headers = HashMap::from([(
27527            "traceparent".to_string(),
27528            "00-12345678901234567890123456789012-1234567890123456-01".to_string(),
27529        )]);
27530        let parent = TraceContextPropagator::new().extract(&headers);
27531        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27532            request_override: Some(|path, body, _number| {
27533                if path == "/api/cluster/info" {
27534                    return Some(if PHASE.load(Ordering::SeqCst) == 2 {
27535                        ("503 Service Unavailable", "{}".into())
27536                    } else {
27537                        ("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
27538                            "supported": true, "schema": "durable-workflow.trace-context", "version": if PHASE.load(Ordering::SeqCst) == 0 {1} else {99},
27539                            "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
27540                            "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
27541                        }}}}).to_string())
27542                    });
27543                }
27544                let body: Value = serde_json::from_str(body).ok()?;
27545                Some(("200 OK", json!({"workflow_id": "order", "run_id": "run", "workflow_type": "orders",
27546                    "outcome": "accepted", "command_id": "command", "request_id": body["request_id"],
27547                    "result": "original"}).to_string()))
27548            }),
27549            ..MockWorkerBehavior::default()
27550        });
27551        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder().build();
27552        let client = Client::new(server.base_url()).unwrap().with_telemetry(
27553            telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test")),
27554        );
27555        let input = json!([{"observability_context": {"business": "preserved"}}]);
27556        async {
27557            client
27558                .start_workflow("orders", "orders", "order", &input)
27559                .await
27560                .unwrap();
27561            assert!(server
27562                .request_body("/api/workflows")
27563                .get("observability_context")
27564                .is_none());
27565            client.cluster_info().await.unwrap();
27566            client
27567                .start_workflow("orders", "orders", "order", &input)
27568                .await
27569                .unwrap();
27570            client
27571                .signal_workflow_with_request_id("order", "ready", &input, "signal-original")
27572                .await
27573                .unwrap();
27574            client
27575                .update_workflow("order", "status", &input, Some("update-original"))
27576                .await
27577                .unwrap();
27578            client
27579                .cancel_workflow("order", WorkflowCommandOptions::default())
27580                .await
27581                .unwrap();
27582            for path in [
27583                "/api/workflows",
27584                "/api/workflows/order/signal/ready",
27585                "/api/workflows/order/update/status",
27586                "/api/workflows/order/cancel",
27587            ] {
27588                let bodies = server.request_bodies(path);
27589                let body = bodies.last().unwrap();
27590                assert_eq!(
27591                    body["observability_context"]["carrier"]["traceparent"],
27592                    headers["traceparent"]
27593                );
27594                assert!(body["observability_context"]["carrier"]
27595                    .get("baggage")
27596                    .is_none());
27597            }
27598            let starts = server.request_bodies("/api/workflows");
27599            assert_eq!(
27600                decode_wire_value(&starts[1]["input"], DEFAULT_CODEC).unwrap(),
27601                input
27602            );
27603            assert_eq!(
27604                server.request_body("/api/workflows/order/signal/ready")["request_id"],
27605                "signal-original"
27606            );
27607            assert_eq!(
27608                server.request_body("/api/workflows/order/update/status")["request_id"],
27609                "update-original"
27610            );
27611            PHASE.store(1, Ordering::SeqCst);
27612            client.cluster_info().await.unwrap();
27613            client
27614                .start_workflow("orders", "orders", "order", &input)
27615                .await
27616                .unwrap();
27617            assert!(server
27618                .request_bodies("/api/workflows")
27619                .last()
27620                .unwrap()
27621                .get("observability_context")
27622                .is_none());
27623            PHASE.store(2, Ordering::SeqCst);
27624            assert!(client.cluster_info().await.is_err());
27625            let before = server.captured_paths().len();
27626            client
27627                .start_workflow("orders", "orders", "order", &input)
27628                .await
27629                .unwrap();
27630            assert_eq!(server.captured_paths().len(), before + 1);
27631            assert!(server
27632                .request_bodies("/api/workflows")
27633                .last()
27634                .unwrap()
27635                .get("observability_context")
27636                .is_none());
27637        }
27638        .with_context(parent)
27639        .await;
27640    }
27641
27642    #[cfg(feature = "telemetry")]
27643    fn observability_worker_server(
27644        path: &str,
27645        _body: &str,
27646        _: usize,
27647    ) -> Option<(&'static str, String)> {
27648        let context = json!({"schema": "durable-workflow.trace-context", "version": 1,
27649            "carrier": {"traceparent": "00-12345678901234567890123456789012-1234567890123456-01",
27650                        "baggage": "credential=private"}});
27651        let link_context = json!({"schema": "durable-workflow.trace-context", "version": 1,
27652            "carrier": {"traceparent": "00-abcdef78901234567890123456789012-abcdef7890123456-01"}});
27653        if path == "/api/cluster/info" {
27654            return Some(("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
27655                "supported": true, "schema": "durable-workflow.trace-context", "version": 1,
27656                "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
27657                "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
27658            }}}}).to_string()));
27659        }
27660        if path.ends_with("/complete") {
27661            return Some(("200 OK", json!({"recorded": true}).to_string()));
27662        }
27663        let task_id = match path {
27664            "/api/worker/workflow-tasks/poll" => "workflow-task",
27665            "/api/worker/activity-tasks/poll" => "activity-task",
27666            "/api/worker/query-tasks/poll" => "query-task",
27667            _ => return None,
27668        };
27669        let input = encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap();
27670        let mut task = json!({"task_id": task_id, "query_task_id": task_id,
27671        "workflow_id": "workflow", "run_id": "run", "workflow_type": "wire.workflow",
27672        "activity_type": "wire.activity", "activity_execution_id": "activity",
27673        "activity_attempt_id": "attempt", "attempt_number": 3, "workflow_task_attempt": 1,
27674        "query_task_attempt": 1, "query_name": "state", "lease_owner": "test-worker",
27675        "namespace": "shipping", "task_queue": "shipping", "lease_expires_at": "2099-01-01T00:00:00Z",
27676        "payload_codec": DEFAULT_CODEC, "arguments": input, "workflow_arguments": input,
27677        "query_arguments": input, "history_events": [], "observability_context": context,
27678        "dispatch_observability_context": {"schema": "durable-workflow.queue-trace", "version": 1,
27679            "task_id": task_id, "context": link_context},
27680        "observability_links": {"schema": "durable-workflow.trace-links", "version": 1,
27681            "task_id": task_id, "run_id": "run", "namespace": "shipping", "links": [
27682                {"kind": "command", "command_id": "accepted-command", "context": link_context},
27683                {"kind": "child_outcome", "workflow_link_id": "link", "child_run_id": "child",
27684                 "child_task_id": null, "event_id": "terminal", "sequence": 7,
27685                 "event_type": "WorkflowCancelled", "context": link_context}
27686            ]}});
27687        if task_id == "workflow-task" {
27688            task["arguments"] = encode_value_envelope(
27689                &json!([{"observability_context": {"business": "preserved"}}]),
27690                DEFAULT_CODEC,
27691            )
27692            .unwrap();
27693        }
27694        Some((
27695            "200 OK",
27696            json!({"task": task, "poll_status": "leased"}).to_string(),
27697        ))
27698    }
27699
27700    #[cfg(feature = "telemetry")]
27701    #[tokio::test]
27702    async fn observability_polled_tasks_recover_parent_links_and_capture_the_actual_child_producer()
27703    {
27704        use opentelemetry::trace::TracerProvider;
27705        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
27706        opentelemetry::global::set_text_map_propagator(
27707            opentelemetry_sdk::propagation::TraceContextPropagator::new(),
27708        );
27709        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
27710        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
27711            .with_simple_exporter(exporter.clone())
27712            .build();
27713        let telemetry = telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test"));
27714        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27715            request_override: Some(observability_worker_server),
27716            ..MockWorkerBehavior::default()
27717        });
27718        let client = Client::builder(server.base_url())
27719            .namespace("shipping")
27720            .build()
27721            .unwrap();
27722        client.cluster_info().await.unwrap();
27723        let mut worker = Worker::new(client, "shipping")
27724            .worker_id("test-worker")
27725            .telemetry(telemetry);
27726        worker.register_workflow("wire.workflow", |ctx, input| async move {
27727            assert_eq!(telemetry::current_log_context()["workflow_run_id"], "run");
27728            assert_eq!(
27729                input,
27730                json!([{"observability_context": {"business": "preserved"}}])
27731            );
27732            ctx.start_child_workflow("child", ChildWorkflowOptions::new("child-workers"), input)
27733                .await?;
27734            Ok(Value::Null)
27735        });
27736        worker.register_activity("wire.activity", |_, _| async {
27737            let fields = telemetry::current_log_context();
27738            assert_eq!(fields["workflow_run_id"], "run");
27739            assert_eq!(fields["activity_id"], "activity");
27740            assert_eq!(fields["activity_attempt_id"], "attempt");
27741            assert_eq!(fields["activity_attempt_number"], "3");
27742            Ok(json!("original-result"))
27743        });
27744        worker.register_query("wire.workflow", "state", |_, _| async {
27745            assert_eq!(telemetry::current_log_context()["task_id"], "query-task");
27746            Ok(json!("original-query"))
27747        });
27748        assert_eq!(worker.run_once().await.unwrap(), 3);
27749        let spans = exporter.get_finished_spans().unwrap();
27750        assert_eq!(spans.len(), 4);
27751        let origin_trace = "12345678901234567890123456789012";
27752        for span in spans
27753            .iter()
27754            .filter(|span| span.name.as_ref() != "durable.activity.attempt")
27755        {
27756            assert_eq!(span.span_context.trace_id().to_string(), origin_trace);
27757            assert_eq!(span.parent_span_id.to_string(), "1234567890123456");
27758            assert_eq!(span.links.len(), 3);
27759            assert!(!format!("{:?}", span.attributes).contains("credential"));
27760        }
27761        let task = spans
27762            .iter()
27763            .find(|span| span.name.as_ref() == "durable.workflow.task")
27764            .unwrap();
27765        let body = server.request_body("/api/worker/workflow-tasks/workflow-task/complete");
27766        assert_eq!(body["commands"][0]["type"], "start_child_workflow");
27767        let parent = body["commands"][0]["observability_context"]["carrier"]["traceparent"]
27768            .as_str()
27769            .unwrap();
27770        assert_eq!(&parent[36..52], task.span_context.span_id().to_string());
27771        assert!(telemetry::current_log_context().is_empty());
27772        opentelemetry::global::set_text_map_propagator(
27773            opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
27774        );
27775    }
27776
27777    #[cfg(feature = "telemetry")]
27778    #[tokio::test]
27779    async fn observability_never_enters_a_query_with_a_refused_original_claim() {
27780        use opentelemetry::trace::TracerProvider;
27781        static REFUSAL: AtomicUsize = AtomicUsize::new(0);
27782        fn refused_query(path: &str, body: &str, count: usize) -> Option<(&'static str, String)> {
27783            let (status, reply) = observability_worker_server(path, body, count)?;
27784            if path != "/api/worker/query-tasks/poll" {
27785                return Some((status, reply));
27786            }
27787            let mut reply: Value = serde_json::from_str(&reply).unwrap();
27788            match REFUSAL.load(Ordering::SeqCst) {
27789                0 => reply["task"]["lease_owner"] = json!("other-worker"),
27790                1 => reply["task"]["query_task_attempt"] = json!(0),
27791                _ => reply["task"]["lease_expires_at"] = json!("2000-01-01T00:00:00Z"),
27792            }
27793            Some((status, reply.to_string()))
27794        }
27795        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
27796        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
27797            .with_simple_exporter(exporter.clone())
27798            .build();
27799        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27800            request_override: Some(refused_query),
27801            ..MockWorkerBehavior::default()
27802        });
27803        let client = Client::builder(server.base_url())
27804            .namespace("shipping")
27805            .build()
27806            .unwrap();
27807        client.cluster_info().await.unwrap();
27808        let mut worker = Worker::new(client, "shipping")
27809            .worker_id("test-worker")
27810            .telemetry(telemetry::ExecutionTelemetry::from_tracer(
27811                provider.tracer("test"),
27812            ));
27813        let calls = Arc::new(AtomicUsize::new(0));
27814        let query_calls = calls.clone();
27815        worker.register_query("wire.workflow", "state", move |_, _| {
27816            query_calls.fetch_add(1, Ordering::SeqCst);
27817            async { Ok(Value::Null) }
27818        });
27819        for refusal in 0..3 {
27820            REFUSAL.store(refusal, Ordering::SeqCst);
27821            assert!(matches!(
27822                worker.poll_query_once().await.unwrap(),
27823                ManagedPollOutcome::Handled
27824            ));
27825            assert_eq!(calls.load(Ordering::SeqCst), 0);
27826            assert!(exporter.get_finished_spans().unwrap().is_empty());
27827            assert!(telemetry::current_log_context().is_empty());
27828        }
27829        assert!(!server
27830            .captured_paths()
27831            .iter()
27832            .any(|path| path.ends_with("/complete") || path.ends_with("/fail")));
27833    }
27834
27835    fn keyed_command_request(path: &str, body: &str) -> Option<Value> {
27836        if path != KEYED_SIGNAL_PATH && path != KEYED_RUN_SIGNAL_PATH && path != KEYED_UPDATE_PATH {
27837            return None;
27838        }
27839        serde_json::from_str(body).ok()
27840    }
27841
27842    /// A #216 Server: echoes the key with `retained` and `intent_verified`.
27843    fn keyed_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27844        let request = keyed_command_request(path, body)?;
27845        let mut receipt = json!({
27846            "outcome": "accepted",
27847            "command_status": "accepted",
27848            "command_id": "cmd-keyed-1",
27849            "request_id": request["request_id"],
27850            "retained": false,
27851            "intent_verified": true,
27852        });
27853        if path == KEYED_UPDATE_PATH {
27854            receipt["update_id"] = json!("upd-keyed-1");
27855            receipt["result_envelope"] =
27856                encode_typed_envelope(&AvroValue::Long(42), DEFAULT_CODEC).expect("result");
27857        }
27858        Some(("202 Accepted", receipt.to_string()))
27859    }
27860
27861    /// A Server released before #216: accepts the body field but echoes nothing.
27862    fn legacy_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27863        keyed_command_request(path, body)?;
27864        Some((
27865            "202 Accepted",
27866            r#"{"outcome":"accepted","command_status":"accepted","command_id":"cmd-legacy"}"#
27867                .to_string(),
27868        ))
27869    }
27870
27871    fn retained_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
27872        let request = keyed_command_request(path, body)?;
27873        Some((
27874            "202 Accepted",
27875            json!({
27876                "outcome": "accepted",
27877                "command_status": "accepted",
27878                "command_id": "cmd-first",
27879                "request_id": request["request_id"],
27880                "retained": true,
27881                "intent_verified": true,
27882            })
27883            .to_string(),
27884        ))
27885    }
27886
27887    fn conflicting_command_server(
27888        path: &str,
27889        body: &str,
27890        _: usize,
27891    ) -> Option<(&'static str, String)> {
27892        let request = keyed_command_request(path, body)?;
27893        let retained_type = if path == KEYED_UPDATE_PATH {
27894            "update"
27895        } else {
27896            "signal"
27897        };
27898        Some((
27899            "409 Conflict",
27900            json!({
27901                "reason": "request_id_conflict",
27902                "message": format!("request id is retained for a different {retained_type} intent"),
27903                "request_id": request["request_id"],
27904                "retained_command_id": "cmd-retained-1",
27905                "retained_command_type": retained_type,
27906                "retained_outcome": "accepted",
27907                "conflict": ["arguments", "target"],
27908                "control_plane": {"operation": retained_type},
27909            })
27910            .to_string(),
27911        ))
27912    }
27913
27914    fn closed_run_command_server(
27915        path: &str,
27916        body: &str,
27917        _: usize,
27918    ) -> Option<(&'static str, String)> {
27919        let request = keyed_command_request(path, body)?;
27920        Some((
27921            "409 Conflict",
27922            json!({
27923                "reason": "run_not_active",
27924                "message": "run is closed",
27925                "request_id": request["request_id"],
27926            })
27927            .to_string(),
27928        ))
27929    }
27930
27931    fn drop_first_keyed_signal(path: &str, request_number: usize) -> bool {
27932        path == KEYED_SIGNAL_PATH && request_number == 1
27933    }
27934
27935    fn keyed_client(server: &MockWorkerServer) -> Client {
27936        Client::builder(server.base_url())
27937            .timeout(Duration::from_secs(2))
27938            .build()
27939            .expect("client")
27940    }
27941
27942    fn keyed_handle(client: &Client) -> WorkflowHandle {
27943        WorkflowHandle {
27944            client: client.clone(),
27945            workflow_id: "keyed-1".to_string(),
27946            run_id: Some("run-keyed-1".to_string()),
27947            workflow_type: "keyed".to_string(),
27948        }
27949    }
27950
27951    fn assert_generated_request_id(request_id: &str, prefix: &str) {
27952        let suffix = request_id
27953            .strip_prefix(prefix)
27954            .unwrap_or_else(|| panic!("{request_id:?} does not start with {prefix:?}"));
27955        assert_eq!(suffix.len(), 32, "uuid4 simple hex suffix: {request_id:?}");
27956        assert!(
27957            suffix
27958                .bytes()
27959                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()),
27960            "lowercase hex suffix: {request_id:?}"
27961        );
27962        assert!(request_id.len() <= MAX_REQUEST_ID_CHARACTERS);
27963    }
27964
27965    fn assert_key_sent_only_in_body(server: &MockWorkerServer, path: &str) {
27966        let headers = server.request_headers(path);
27967        assert!(!headers.is_empty(), "no request captured for {path}");
27968        for headers in headers {
27969            let header_names: Vec<String> = headers
27970                .lines()
27971                .skip(1)
27972                .filter_map(|line| line.split_once(':'))
27973                .map(|(name, _)| name.trim().to_ascii_lowercase())
27974                .collect();
27975            assert!(
27976                !header_names.iter().any(|name| name == "x-request-id"),
27977                "the caller command key is a body field, never an X-Request-Id header: {headers}"
27978            );
27979        }
27980    }
27981
27982    #[tokio::test]
27983    async fn signal_without_key_sends_a_generated_sdk_rust_signal_key_and_returns_it() {
27984        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
27985            request_override: Some(legacy_command_server),
27986            ..MockWorkerBehavior::default()
27987        });
27988        let client = keyed_client(&server);
27989
27990        let receipt = client
27991            .signal_workflow("keyed-1", "approve", json!(["ok"]))
27992            .await
27993            .expect("signal receipt");
27994
27995        let sent = server.request_body(KEYED_SIGNAL_PATH);
27996        let request_id = sent["request_id"].as_str().expect("generated request_id");
27997        assert_generated_request_id(request_id, "sdk-rust-signal-");
27998        assert_eq!(
27999            receipt,
28000            json!({
28001                "outcome": "accepted",
28002                "command_status": "accepted",
28003                "command_id": "cmd-legacy",
28004                "request_id": request_id,
28005            }),
28006            "the sent key is added when an older Server omits it"
28007        );
28008        assert_key_sent_only_in_body(&server, KEYED_SIGNAL_PATH);
28009
28010        let receipt = keyed_handle(&client)
28011            .signal_selected_run("approve", json!(["ok"]))
28012            .await
28013            .expect("selected-run signal receipt");
28014        let run_sent = server.request_body(KEYED_RUN_SIGNAL_PATH);
28015        let run_request_id = run_sent["request_id"]
28016            .as_str()
28017            .expect("generated request_id");
28018        assert_generated_request_id(run_request_id, "sdk-rust-signal-");
28019        assert_eq!(receipt["request_id"], run_request_id);
28020        assert_ne!(
28021            run_request_id, request_id,
28022            "each logical call gets its own key"
28023        );
28024        assert_key_sent_only_in_body(&server, KEYED_RUN_SIGNAL_PATH);
28025    }
28026
28027    #[tokio::test]
28028    async fn update_without_key_sends_a_generated_sdk_rust_update_key() {
28029        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28030            request_override: Some(keyed_command_server),
28031            ..MockWorkerBehavior::default()
28032        });
28033        let client = keyed_client(&server);
28034
28035        let result = client
28036            .update_workflow("keyed-1", "adjust", json!([1]), None)
28037            .await
28038            .expect("update result");
28039        assert_eq!(
28040            result,
28041            json!(42),
28042            "the decoded update result is returned unchanged"
28043        );
28044        let typed = client
28045            .update_workflow_avro_value("keyed-1", "adjust", json!([1]), None)
28046            .await
28047            .expect("typed update result");
28048        assert_eq!(typed, AvroValue::Long(42));
28049        keyed_handle(&client)
28050            .update("adjust", json!([1]), None)
28051            .await
28052            .expect("handle update result");
28053
28054        let bodies = server.request_bodies(KEYED_UPDATE_PATH);
28055        assert_eq!(bodies.len(), 3);
28056        for body in &bodies {
28057            assert_generated_request_id(
28058                body["request_id"].as_str().expect("generated request_id"),
28059                "sdk-rust-update-",
28060            );
28061            assert_eq!(body["wait_for"], "completed");
28062        }
28063        assert_ne!(bodies[0]["request_id"], bodies[1]["request_id"]);
28064        assert_ne!(bodies[1]["request_id"], bodies[2]["request_id"]);
28065        assert_key_sent_only_in_body(&server, KEYED_UPDATE_PATH);
28066    }
28067
28068    #[tokio::test]
28069    async fn explicit_command_keys_are_sent_verbatim_as_the_request_id_body_field() {
28070        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28071            request_override: Some(keyed_command_server),
28072            ..MockWorkerBehavior::default()
28073        });
28074        let client = keyed_client(&server);
28075        let handle = keyed_handle(&client);
28076
28077        let receipt = client
28078            .signal_workflow_with_request_id(
28079                "keyed-1",
28080                "approve",
28081                json!(["ok"]),
28082                "Order-42/approve",
28083            )
28084            .await
28085            .expect("signal receipt");
28086        assert_eq!(receipt["request_id"], "Order-42/approve");
28087        assert_eq!(receipt["retained"], false);
28088        assert_eq!(receipt["intent_verified"], true);
28089        handle
28090            .signal_with_request_id("approve", json!(["ok"]), "handle-signal-key")
28091            .await
28092            .expect("handle signal receipt");
28093        client
28094            .signal_workflow_run_with_request_id(
28095                "keyed-1",
28096                "run-keyed-1",
28097                "approve",
28098                json!(["ok"]),
28099                "run-signal-key",
28100            )
28101            .await
28102            .expect("selected-run signal receipt");
28103        handle
28104            .signal_selected_run_with_request_id("approve", json!(["ok"]), "handle-run-signal-key")
28105            .await
28106            .expect("handle selected-run signal receipt");
28107        let result = client
28108            .update_workflow("keyed-1", "adjust", json!([1]), Some("update-key"))
28109            .await
28110            .expect("update result");
28111        assert_eq!(result, json!(42));
28112        handle
28113            .update("adjust", json!([1]), Some("handle-update-key"))
28114            .await
28115            .expect("handle update result");
28116        handle
28117            .update_avro_value("adjust", json!([1]), Some("handle-typed-update-key"))
28118            .await
28119            .expect("handle typed update result");
28120
28121        let signal_keys: Vec<Value> = server
28122            .request_bodies(KEYED_SIGNAL_PATH)
28123            .into_iter()
28124            .map(|body| body["request_id"].clone())
28125            .collect();
28126        assert_eq!(
28127            signal_keys,
28128            [json!("Order-42/approve"), json!("handle-signal-key")]
28129        );
28130        let run_signal_keys: Vec<Value> = server
28131            .request_bodies(KEYED_RUN_SIGNAL_PATH)
28132            .into_iter()
28133            .map(|body| body["request_id"].clone())
28134            .collect();
28135        assert_eq!(
28136            run_signal_keys,
28137            [json!("run-signal-key"), json!("handle-run-signal-key")]
28138        );
28139        let update_keys: Vec<Value> = server
28140            .request_bodies(KEYED_UPDATE_PATH)
28141            .into_iter()
28142            .map(|body| body["request_id"].clone())
28143            .collect();
28144        assert_eq!(
28145            update_keys,
28146            [
28147                json!("update-key"),
28148                json!("handle-update-key"),
28149                json!("handle-typed-update-key")
28150            ]
28151        );
28152        for path in [KEYED_SIGNAL_PATH, KEYED_RUN_SIGNAL_PATH, KEYED_UPDATE_PATH] {
28153            assert_key_sent_only_in_body(&server, path);
28154        }
28155    }
28156
28157    #[tokio::test]
28158    async fn retained_receipts_are_returned_unchanged() {
28159        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28160            request_override: Some(retained_command_server),
28161            ..MockWorkerBehavior::default()
28162        });
28163        let client = keyed_client(&server);
28164
28165        let receipt = client
28166            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "retry-key")
28167            .await
28168            .expect("retained receipt");
28169
28170        assert_eq!(
28171            receipt,
28172            json!({
28173                "outcome": "accepted",
28174                "command_status": "accepted",
28175                "command_id": "cmd-first",
28176                "request_id": "retry-key",
28177                "retained": true,
28178                "intent_verified": true,
28179            })
28180        );
28181    }
28182
28183    #[tokio::test]
28184    async fn request_id_conflict_refusal_keeps_error_http_and_classifies_the_sent_key() {
28185        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28186            request_override: Some(conflicting_command_server),
28187            ..MockWorkerBehavior::default()
28188        });
28189        let client = keyed_client(&server);
28190
28191        let error = client
28192            .signal_workflow_with_request_id(
28193                "keyed-1",
28194                "approve",
28195                json!(["changed"]),
28196                "Order-42/approve",
28197            )
28198            .await
28199            .expect_err("different intent under a retained key");
28200        assert!(
28201            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT),
28202            "existing Error::Http matching keeps working: {error:?}"
28203        );
28204        assert!(error.is_request_id_conflict());
28205        assert_eq!(error.request_id().as_deref(), Some("Order-42/approve"));
28206        let conflict = error.request_id_conflict().expect("conflict details");
28207        assert_eq!(conflict.status, 409);
28208        assert_eq!(conflict.request_id, "Order-42/approve");
28209        assert_eq!(
28210            conflict.message,
28211            "request id is retained for a different signal intent"
28212        );
28213        assert_eq!(
28214            conflict.retained_command_id.as_deref(),
28215            Some("cmd-retained-1")
28216        );
28217        assert_eq!(conflict.retained_command_type.as_deref(), Some("signal"));
28218        assert_eq!(conflict.retained_outcome.as_deref(), Some("accepted"));
28219        assert_eq!(conflict.conflict, ["arguments", "target"]);
28220        assert_eq!(conflict.body["control_plane"]["operation"], "signal");
28221
28222        let error = client
28223            .update_workflow("keyed-1", "adjust", json!([2]), None)
28224            .await
28225            .expect_err("different intent under a retained generated key");
28226        let sent = server.request_body(KEYED_UPDATE_PATH);
28227        assert_eq!(
28228            error.request_id(),
28229            sent["request_id"].as_str().map(str::to_string)
28230        );
28231        assert_eq!(
28232            error
28233                .request_id_conflict()
28234                .expect("conflict details")
28235                .retained_command_type
28236                .as_deref(),
28237            Some("update")
28238        );
28239    }
28240
28241    #[tokio::test]
28242    async fn other_refusals_echoing_the_key_are_not_request_id_conflicts() {
28243        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28244            request_override: Some(closed_run_command_server),
28245            ..MockWorkerBehavior::default()
28246        });
28247        let client = keyed_client(&server);
28248
28249        let error = client
28250            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "closed-key")
28251            .await
28252            .expect_err("closed run");
28253
28254        assert!(matches!(error, Error::Http { status, .. } if status.as_u16() == 409));
28255        assert!(!error.is_request_id_conflict());
28256        assert_eq!(error.request_id_conflict(), None);
28257        assert_eq!(error.request_id().as_deref(), Some("closed-key"));
28258    }
28259
28260    #[tokio::test]
28261    async fn transport_failure_keeps_error_transport_and_the_held_key_retries_identically() {
28262        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
28263            request_override: Some(keyed_command_server),
28264            drop_request: Some(drop_first_keyed_signal),
28265            ..MockWorkerBehavior::default()
28266        });
28267        let client = keyed_client(&server);
28268        let request_id = Client::generate_signal_request_id();
28269
28270        let error = client
28271            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
28272            .await
28273            .expect_err("connection closed before any response");
28274        assert!(
28275            matches!(error, Error::Transport(_)),
28276            "the transport variant is unchanged: {error:?}"
28277        );
28278        assert_eq!(
28279            error.request_id(),
28280            None,
28281            "nothing was echoed; the application holds the key it chose"
28282        );
28283
28284        let receipt = client
28285            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
28286            .await
28287            .expect("manual retry with the same key");
28288        assert_eq!(receipt["request_id"], request_id);
28289        let bodies = server.request_bodies(KEYED_SIGNAL_PATH);
28290        assert_eq!(bodies.len(), 2, "one attempt per call, no automatic retry");
28291        assert_eq!(
28292            bodies[0], bodies[1],
28293            "the retry resends the identical key and input"
28294        );
28295        assert_eq!(bodies[0]["request_id"], request_id);
28296    }
28297
28298    #[tokio::test]
28299    async fn invalid_command_keys_are_refused_before_sending() {
28300        let server = MockWorkerServer::start();
28301        let client = keyed_client(&server);
28302        let too_long = "k".repeat(MAX_REQUEST_ID_CHARACTERS + 1);
28303
28304        for request_id in ["", too_long.as_str()] {
28305            let error = client
28306                .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), request_id)
28307                .await
28308                .expect_err("invalid signal key");
28309            assert!(
28310                matches!(error, Error::Codec(ref message) if message.contains("1 to 255 Unicode characters")),
28311                "{error:?}"
28312            );
28313            let error = client
28314                .update_workflow("keyed-1", "adjust", json!([1]), Some(request_id))
28315                .await
28316                .expect_err("invalid update key");
28317            assert!(matches!(error, Error::Codec(_)), "{error:?}");
28318        }
28319        assert!(server.captured_paths().is_empty(), "nothing was sent");
28320
28321        let longest = "k".repeat(MAX_REQUEST_ID_CHARACTERS);
28322        let _ = client
28323            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &longest)
28324            .await;
28325        assert_eq!(
28326            server.request_body(KEYED_SIGNAL_PATH)["request_id"],
28327            longest
28328        );
28329    }
28330
28331    #[test]
28332    fn generated_command_keys_are_distinct_and_well_formed() {
28333        let signal = Client::generate_signal_request_id();
28334        let update = Client::generate_update_request_id();
28335        assert_generated_request_id(&signal, "sdk-rust-signal-");
28336        assert_generated_request_id(&update, "sdk-rust-update-");
28337        assert_ne!(Client::generate_signal_request_id(), signal);
28338        assert!(validate_request_id(&signal).is_ok());
28339    }
28340
28341    #[test]
28342    fn command_keys_preserve_the_published_server_unicode_character_limit() {
28343        assert!(validate_request_id(&"é".repeat(255)).is_ok());
28344        assert!(validate_request_id(&"😀".repeat(255)).is_ok());
28345        assert!(validate_request_id(&"é".repeat(256)).is_err());
28346    }
28347
28348    #[test]
28349    fn request_id_accessors_read_only_echoed_refusal_bodies() {
28350        let conflict = Error::Http {
28351            status: reqwest::StatusCode::CONFLICT,
28352            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(),
28353        };
28354        assert!(conflict.is_request_id_conflict());
28355        assert_eq!(conflict.request_id().as_deref(), Some("k1"));
28356        let details = conflict.request_id_conflict().expect("conflict details");
28357        assert_eq!(details.conflict, ["name"]);
28358        assert_eq!(
28359            details.message,
28360            "request id is retained for a different command intent"
28361        );
28362
28363        let echoed = Error::Http {
28364            status: reqwest::StatusCode::CONFLICT,
28365            body: r#"{"reason":"run_not_active","request_id":"k2"}"#.to_string(),
28366        };
28367        assert!(!echoed.is_request_id_conflict());
28368        assert_eq!(echoed.request_id().as_deref(), Some("k2"));
28369
28370        let blank = Error::Http {
28371            status: reqwest::StatusCode::UNPROCESSABLE_ENTITY,
28372            body: r#"{"request_id":""}"#.to_string(),
28373        };
28374        assert_eq!(blank.request_id(), None);
28375        let text = Error::Http {
28376            status: reqwest::StatusCode::BAD_GATEWAY,
28377            body: "upstream unavailable".to_string(),
28378        };
28379        assert_eq!(text.request_id(), None);
28380        assert!(!text.is_request_id_conflict());
28381
28382        let rejection = Error::WorkflowCommandRejected(WorkflowCommandRejection {
28383            command: WorkflowCommandKind::Cancel,
28384            status: 409,
28385            reason: "request_id_conflict".to_string(),
28386            message: "retained".to_string(),
28387            workflow_id: "wf".to_string(),
28388            run_id: None,
28389            target_scope: None,
28390            body: json!({"reason": "request_id_conflict", "request_id": "k3", "conflict": []}),
28391        });
28392        assert!(rejection.is_request_id_conflict());
28393        assert_eq!(rejection.request_id().as_deref(), Some("k3"));
28394
28395        assert_eq!(Error::Timeout.request_id(), None);
28396        assert!(!Error::Codec("local".to_string()).is_request_id_conflict());
28397    }
28398
28399    #[tokio::test]
28400    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
28401        let server = MockWorkerServer::start();
28402        let client = Client::builder(server.base_url())
28403            .timeout(Duration::from_secs(2))
28404            .build()
28405            .expect("client");
28406        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
28407
28408        client
28409            .start_workflow(
28410                "typed.echo",
28411                "rust-workers",
28412                "typed-start",
28413                arguments.clone(),
28414            )
28415            .await
28416            .expect("typed workflow start");
28417        assert_eq!(
28418            decode_wire_avro_value(
28419                &server.request_body("/api/workflows")["input"],
28420                DEFAULT_CODEC,
28421            )
28422            .expect("typed start input"),
28423            arguments
28424        );
28425
28426        client
28427            .signal_workflow("typed-1", "changed", arguments.clone())
28428            .await
28429            .expect("typed signal");
28430        assert_eq!(
28431            decode_wire_avro_value(
28432                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
28433                DEFAULT_CODEC,
28434            )
28435            .expect("typed signal input"),
28436            arguments
28437        );
28438
28439        assert_eq!(
28440            client
28441                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
28442                .await
28443                .expect("typed query"),
28444            typed_fidelity_probe()
28445        );
28446        assert_eq!(
28447            decode_wire_avro_value(
28448                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
28449                DEFAULT_CODEC,
28450            )
28451            .expect("typed query input"),
28452            arguments
28453        );
28454
28455        assert_eq!(
28456            client
28457                .update_workflow_avro_value(
28458                    "typed-1",
28459                    "replace",
28460                    arguments.clone(),
28461                    Some("typed-request"),
28462                )
28463                .await
28464                .expect("typed update"),
28465            typed_fidelity_probe()
28466        );
28467        let update = server.request_body("/api/workflows/typed-1/update/replace");
28468        assert_eq!(update["request_id"], "typed-request");
28469        assert_eq!(
28470            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
28471            arguments
28472        );
28473
28474        let handle = WorkflowHandle {
28475            client: client.clone(),
28476            workflow_id: "typed-1".to_string(),
28477            run_id: Some("run-typed-1".to_string()),
28478            workflow_type: "typed.echo".to_string(),
28479        };
28480        assert_eq!(
28481            handle
28482                .result_avro_value(WorkflowResultOptions::default())
28483                .await
28484                .expect("typed workflow result"),
28485            typed_fidelity_probe()
28486        );
28487
28488        client
28489            .complete_activity_task(
28490                "activity-typed",
28491                "attempt-typed",
28492                "rust-worker",
28493                typed_fidelity_probe(),
28494                DEFAULT_CODEC,
28495            )
28496            .await
28497            .expect("typed activity completion");
28498        assert_eq!(
28499            decode_wire_avro_value(
28500                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
28501                    ["result"],
28502                DEFAULT_CODEC,
28503            )
28504            .expect("typed activity result"),
28505            typed_fidelity_probe()
28506        );
28507        client
28508            .fail_activity_task(
28509                "activity-typed",
28510                "attempt-typed",
28511                "rust-worker",
28512                "typed failure",
28513                true,
28514            )
28515            .await
28516            .expect("activity failure");
28517    }
28518
28519    #[tokio::test]
28520    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
28521        let server = MockWorkerServer::start();
28522        let client = Client::builder(server.base_url())
28523            .timeout(Duration::from_secs(2))
28524            .build()
28525            .expect("client");
28526
28527        let options = WorkflowCommandOptions::new()
28528            .reason("cleanup requested")
28529            .request_id("cancel-17");
28530        let cancelled = client
28531            .cancel_workflow("wf-lifecycle", options)
28532            .await
28533            .expect("instance cancellation");
28534        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
28535        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
28536        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
28537        assert_eq!(
28538            server.request_body("/api/workflows/wf-lifecycle/cancel"),
28539            json!({"reason":"cleanup requested","request_id":"cancel-17"})
28540        );
28541
28542        let terminated = client
28543            .terminate_workflow(
28544                "wf-lifecycle",
28545                WorkflowCommandOptions::new().reason("forced stop"),
28546            )
28547            .await
28548            .expect("instance termination");
28549        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
28550        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
28551
28552        client
28553            .cancel_workflow_run(
28554                "wf-lifecycle",
28555                "run-current",
28556                WorkflowCommandOptions::default(),
28557            )
28558            .await
28559            .expect("selected run cancellation");
28560        client
28561            .terminate_workflow_run(
28562                "wf-lifecycle",
28563                "run-current",
28564                WorkflowCommandOptions::default(),
28565            )
28566            .await
28567            .expect("selected run termination");
28568
28569        for (command, error) in [
28570            (
28571                WorkflowCommandKind::Cancel,
28572                client
28573                    .cancel_workflow_run(
28574                        "wf-lifecycle",
28575                        "run-stale",
28576                        WorkflowCommandOptions::default(),
28577                    )
28578                    .await
28579                    .expect_err("stale cancellation must be rejected"),
28580            ),
28581            (
28582                WorkflowCommandKind::Terminate,
28583                client
28584                    .terminate_workflow_run(
28585                        "wf-lifecycle",
28586                        "run-stale",
28587                        WorkflowCommandOptions::default(),
28588                    )
28589                    .await
28590                    .expect_err("stale termination must be rejected"),
28591            ),
28592        ] {
28593            let Error::WorkflowCommandRejected(rejection) = error else {
28594                panic!("expected typed command rejection");
28595            };
28596            assert_eq!(rejection.command, command);
28597            assert_eq!(rejection.status, 409);
28598            assert_eq!(rejection.reason, "historical_run_command_rejected");
28599            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
28600            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
28601        }
28602    }
28603
28604    #[tokio::test]
28605    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
28606        let server = MockWorkerServer::start();
28607        let client = Client::builder(server.base_url())
28608            .timeout(Duration::from_secs(2))
28609            .build()
28610            .expect("client");
28611
28612        let result = client
28613            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
28614            .await
28615            .expect("redrive accepted");
28616        assert_eq!(result.workflow_id, "wf-lifecycle");
28617        assert_eq!(result.source_run_id, "run-failed");
28618        assert_eq!(result.run_id, "run-successor");
28619        assert_eq!(result.resume_step_sequence, 2);
28620        assert_eq!(
28621            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
28622            json!({"request_id":"retry-1"})
28623        );
28624
28625        let repeated = client
28626            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
28627            .await
28628            .expect("idempotent redrive response accepted");
28629        assert_eq!(repeated.run_id, "run-successor");
28630
28631        let error = client
28632            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
28633            .await
28634            .expect_err("completed run must be rejected");
28635        let Error::Http { status, body } = error else {
28636            panic!("expected HTTP redrive rejection");
28637        };
28638        assert_eq!(status.as_u16(), 409);
28639        assert!(body.contains("run_not_failed"));
28640        assert_eq!(
28641            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
28642            json!({})
28643        );
28644
28645        let handle = WorkflowHandle {
28646            client: client.clone(),
28647            workflow_id: "wf-lifecycle".to_string(),
28648            run_id: Some("run-failed".to_string()),
28649            workflow_type: "test".to_string(),
28650        };
28651        assert_eq!(
28652            handle.redrive(None).await.expect("handle redrive").run_id,
28653            "run-successor"
28654        );
28655        let missing_run = WorkflowHandle {
28656            run_id: None,
28657            ..handle
28658        };
28659        assert!(matches!(
28660            missing_run.redrive(None).await,
28661            Err(Error::Codec(_))
28662        ));
28663    }
28664
28665    #[tokio::test]
28666    async fn workflow_start_options_send_server_enforced_deadlines() {
28667        let server = MockWorkerServer::start();
28668        let client = Client::builder(server.base_url())
28669            .timeout(Duration::from_secs(2))
28670            .build()
28671            .expect("client");
28672
28673        let handle = client
28674            .start_workflow_with_options(
28675                "rust.timeout",
28676                "rust-timeouts",
28677                "wf-start-options",
28678                WorkflowStartOptions::new()
28679                    .execution_timeout_seconds(30)
28680                    .run_timeout_seconds(1),
28681                json!([]),
28682            )
28683            .await
28684            .expect("workflow start");
28685
28686        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
28687        let body = server.request_body("/api/workflows");
28688        assert_eq!(body["execution_timeout_seconds"], 30);
28689        assert_eq!(body["run_timeout_seconds"], 1);
28690
28691        let invalid = client
28692            .start_workflow_with_options(
28693                "rust.timeout",
28694                "rust-timeouts",
28695                "wf-invalid-options",
28696                WorkflowStartOptions::new()
28697                    .execution_timeout_seconds(1)
28698                    .run_timeout_seconds(2),
28699                json!([]),
28700            )
28701            .await
28702            .expect_err("invalid deadline ordering");
28703        assert!(invalid
28704            .to_string()
28705            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
28706    }
28707
28708    #[tokio::test]
28709    async fn workflow_result_returns_each_typed_terminal_outcome() {
28710        let server = MockWorkerServer::start();
28711        let client = Client::builder(server.base_url())
28712            .timeout(Duration::from_secs(2))
28713            .build()
28714            .expect("client");
28715        let options = WorkflowResultOptions {
28716            poll_interval: Duration::ZERO,
28717            timeout: Duration::from_secs(1),
28718        };
28719
28720        let failed = WorkflowHandle {
28721            client: client.clone(),
28722            workflow_id: "wf-failed".to_string(),
28723            run_id: Some("run-failed".to_string()),
28724            workflow_type: "failure".to_string(),
28725        }
28726        .result(options)
28727        .await
28728        .expect_err("failed outcome");
28729        let Error::WorkflowFailed(failure) = failed else {
28730            panic!("expected WorkflowFailed");
28731        };
28732        assert_eq!(failure.workflow_id, "wf-failed");
28733        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
28734        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
28735        assert_eq!(failure.failure_category.as_deref(), Some("application"));
28736        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
28737        assert_eq!(
28738            failure.exception_class.as_deref(),
28739            Some("billing::PaymentError")
28740        );
28741        assert_eq!(failure.non_retryable, Some(true));
28742
28743        for (workflow_id, expected_kind, expected_reason) in [
28744            (
28745                "wf-cancelled",
28746                WorkflowTerminalKind::Cancelled,
28747                "cleanup requested",
28748            ),
28749            (
28750                "wf-terminated",
28751                WorkflowTerminalKind::Terminated,
28752                "forced stop",
28753            ),
28754            (
28755                "wf-timed-out",
28756                WorkflowTerminalKind::TimedOut,
28757                "run_timeout",
28758            ),
28759        ] {
28760            let error = WorkflowHandle {
28761                client: client.clone(),
28762                workflow_id: workflow_id.to_string(),
28763                run_id: None,
28764                workflow_type: "terminal".to_string(),
28765            }
28766            .result(options)
28767            .await
28768            .expect_err("typed terminal outcome");
28769            let outcome = match error {
28770                Error::WorkflowCancelled(outcome) => outcome,
28771                Error::WorkflowTerminated(outcome) => outcome,
28772                Error::WorkflowTimedOut(outcome) => outcome,
28773                other => panic!("unexpected terminal error: {other}"),
28774            };
28775            assert_eq!(outcome.kind, expected_kind);
28776            assert_eq!(outcome.workflow_id, workflow_id);
28777            assert_eq!(outcome.reason, expected_reason);
28778        }
28779
28780        let wait_timeout = WorkflowHandle {
28781            client,
28782            workflow_id: "wf-waiting".to_string(),
28783            run_id: Some("run-waiting".to_string()),
28784            workflow_type: "waiting".to_string(),
28785        }
28786        .result(WorkflowResultOptions {
28787            poll_interval: Duration::ZERO,
28788            timeout: Duration::ZERO,
28789        })
28790        .await
28791        .expect_err("client wait timeout");
28792        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
28793            panic!("expected typed client timeout");
28794        };
28795        assert_eq!(timeout.reason, "result_wait_timeout");
28796        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
28797        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
28798    }
28799
28800    #[tokio::test]
28801    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
28802        let server = MockWorkerServer::start();
28803        let client = Client::builder(server.base_url())
28804            .timeout(Duration::from_secs(2))
28805            .build()
28806            .expect("client");
28807
28808        let handle = WorkflowHandle {
28809            client,
28810            workflow_id: "wf-selected".to_string(),
28811            run_id: Some("run-selected".to_string()),
28812            workflow_type: "selected".to_string(),
28813        };
28814        let options = WorkflowResultOptions {
28815            poll_interval: Duration::ZERO,
28816            timeout: Duration::from_secs(1),
28817        };
28818
28819        let current = handle
28820            .result(options)
28821            .await
28822            .expect("instance result follows the current run");
28823        assert_eq!(current, json!("current run output"));
28824
28825        let error = handle
28826            .result_selected_run(options)
28827            .await
28828            .expect_err("the selected run is cancelled even though the current run completed");
28829
28830        let Error::WorkflowCancelled(outcome) = error else {
28831            panic!("expected selected run cancellation");
28832        };
28833        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
28834        assert_eq!(outcome.reason, "selected run cancelled");
28835        assert_eq!(
28836            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
28837            1
28838        );
28839        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
28840    }
28841
28842    #[tokio::test]
28843    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
28844        let server = MockWorkerServer::draining_polls();
28845        let client = Client::builder(server.base_url())
28846            .timeout(Duration::from_secs(2))
28847            .build()
28848            .expect("client");
28849
28850        let workflow = client
28851            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
28852            .await
28853            .expect("workflow drain response");
28854        let activity = client
28855            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
28856            .await
28857            .expect("activity drain response");
28858        let query = client
28859            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
28860            .await
28861            .expect("query drain response");
28862
28863        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
28864            assert_eq!(
28865                outcome,
28866                WorkerPollOutcome::Stop {
28867                    poll_status: Some("draining".to_string()),
28868                    reason: Some("worker_draining".to_string()),
28869                }
28870            );
28871        }
28872
28873        assert!(client
28874            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
28875            .await
28876            .expect("compatibility poll")
28877            .is_none());
28878    }
28879
28880    #[tokio::test]
28881    async fn managed_worker_honors_drain_stop_for_every_task_family() {
28882        let server = MockWorkerServer::draining_polls();
28883        let client = Client::builder(server.base_url())
28884            .timeout(Duration::from_secs(2))
28885            .build()
28886            .expect("client");
28887
28888        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
28889            .worker_id("draining-workflow-worker")
28890            .poll_timeout(Duration::ZERO);
28891        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
28892        workflow_worker
28893            .run()
28894            .await
28895            .expect("workflow drain is a clean stop");
28896
28897        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
28898            .worker_id("draining-activity-worker")
28899            .poll_timeout(Duration::ZERO);
28900        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
28901        activity_worker
28902            .run()
28903            .await
28904            .expect("activity drain is a clean stop");
28905
28906        let mut query_worker = Worker::new(client, "rust-workers")
28907            .worker_id("draining-query-worker")
28908            .poll_timeout(Duration::ZERO);
28909        query_worker.register_query("counter", "current", |_ctx, _args| async {
28910            Ok(Value::Null)
28911        });
28912        query_worker
28913            .run()
28914            .await
28915            .expect("query drain is a clean stop");
28916    }
28917
28918    #[tokio::test]
28919    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
28920        let server = MockWorkerServer::start();
28921        let client = Client::builder(server.base_url())
28922            .timeout(Duration::from_secs(2))
28923            .build()
28924            .expect("client");
28925
28926        let details: Value = serde_json::from_str(include_str!(
28927            "../tests/fixtures/activity-heartbeat-progress.json"
28928        ))
28929        .expect("heartbeat progress fixture");
28930        // Every individual field fits Server's progress contract, while the
28931        // obsolete encoded envelope exceeded its 191-character string limit.
28932        assert!(
28933            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
28934                .unwrap()["blob"]
28935                .as_str()
28936                .unwrap()
28937                .len()
28938                > 191
28939        );
28940        let heartbeat = client
28941            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
28942            .await
28943            .expect("cancellation heartbeat");
28944        assert!(heartbeat.cancel_requested);
28945        assert!(heartbeat.should_stop());
28946        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
28947        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
28948        let heartbeat_body =
28949            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
28950        assert_eq!(heartbeat_body["details"], details);
28951        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
28952        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
28953
28954        let error = client
28955            .complete_activity_task(
28956                "activity-cancel",
28957                "attempt-cancel",
28958                "rust-worker",
28959                json!({"late":true}),
28960                DEFAULT_CODEC,
28961            )
28962            .await
28963            .expect_err("late completion must be refused");
28964        assert!(activity_task_rejection_is_final(&error));
28965        let Error::ActivityTaskRejected(rejection) = error else {
28966            panic!("expected typed activity rejection");
28967        };
28968        assert_eq!(rejection.status, 409);
28969        assert_eq!(rejection.reason, "run_cancelled");
28970        assert!(rejection.cancel_requested);
28971        assert_eq!(rejection.can_continue, Some(false));
28972    }
28973
28974    #[tokio::test]
28975    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
28976        let server = MockWorkerServer::cancelled_activity();
28977        let client = Client::builder(server.base_url())
28978            .timeout(Duration::from_secs(2))
28979            .build()
28980            .expect("client");
28981        let cancellation_observed = Arc::new(AtomicBool::new(false));
28982        let observed = Arc::clone(&cancellation_observed);
28983        let mut worker = Worker::new(client.clone(), "rust-workers")
28984            .worker_id("rust-cancel-worker")
28985            .poll_timeout(Duration::from_millis(10));
28986        worker.register_activity("cancel-aware", move |ctx, _args| {
28987            let observed = Arc::clone(&observed);
28988            async move {
28989                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
28990                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
28991                Ok(json!({"late":"completion"}))
28992            }
28993        });
28994
28995        assert_eq!(
28996            worker.run_once().await.expect("cancelled attempt handled"),
28997            1
28998        );
28999        assert!(cancellation_observed.load(Ordering::SeqCst));
29000        assert_eq!(
29001            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
29002            1
29003        );
29004
29005        let mut restarted = Worker::new(client, "rust-workers")
29006            .worker_id("rust-cancel-worker-restarted")
29007            .poll_timeout(Duration::from_millis(10));
29008        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
29009        assert_eq!(
29010            restarted
29011                .run_once()
29012                .await
29013                .expect("replacement worker continues polling"),
29014            0
29015        );
29016    }
29017
29018    #[tokio::test]
29019    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
29020        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"}"#;
29021        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
29022        let client = Client::builder(server.base_url())
29023            .timeout(Duration::from_secs(2))
29024            .build()
29025            .expect("client");
29026
29027        let direct_error = client
29028            .complete_workflow_task(
29029                "workflow-timeout-task",
29030                "timeout-worker",
29031                3,
29032                vec![json!({
29033                    "type": "complete_workflow",
29034                    "result": fixture_envelope(Value::Null)
29035                })],
29036            )
29037            .await
29038            .expect_err("the low-level client preserves the completion rejection");
29039        let Error::Http { status, body } = direct_error else {
29040            panic!("expected the original HTTP completion rejection");
29041        };
29042        assert_eq!(status, reqwest::StatusCode::CONFLICT);
29043        assert_eq!(
29044            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
29045            "run_timed_out"
29046        );
29047
29048        let mut worker = Worker::new(client, "rust-workers")
29049            .worker_id("timeout-worker")
29050            .poll_timeout(Duration::from_millis(10));
29051        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
29052            Ok(json!({"late": "result"}))
29053        });
29054
29055        assert_eq!(
29056            worker
29057                .run_once()
29058                .await
29059                .expect("authoritative selected-run timeout settles the tick"),
29060            1
29061        );
29062        assert_eq!(
29063            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
29064            2,
29065            "both the direct client proof and managed worker must see the rejection"
29066        );
29067    }
29068
29069    #[tokio::test]
29070    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
29071        for (name, status, response) in [
29072            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
29073            (
29074                "command was recorded",
29075                "409 Conflict",
29076                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29077            ),
29078            (
29079                "lease conflict",
29080                "409 Conflict",
29081                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
29082            ),
29083            (
29084                "nonterminal run",
29085                "409 Conflict",
29086                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
29087            ),
29088            (
29089                "different selected run",
29090                "409 Conflict",
29091                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"}"#,
29092            ),
29093            (
29094                "different task attempt",
29095                "409 Conflict",
29096                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29097            ),
29098            (
29099                "authentication failure",
29100                "401 Unauthorized",
29101                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29102            ),
29103            (
29104                "authorization failure",
29105                "403 Forbidden",
29106                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29107            ),
29108            (
29109                "protocol failure",
29110                "400 Bad Request",
29111                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
29112            ),
29113            (
29114                "malformed command",
29115                "422 Unprocessable Entity",
29116                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29117            ),
29118            (
29119                "transient server failure",
29120                "503 Service Unavailable",
29121                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
29122            ),
29123        ] {
29124            let server = MockWorkerServer::workflow_completion(status, response);
29125            let client = Client::builder(server.base_url())
29126                .timeout(Duration::from_secs(2))
29127                .build()
29128                .expect("client");
29129            let mut worker = Worker::new(client, "rust-workers")
29130                .worker_id("timeout-worker")
29131                .poll_timeout(Duration::from_millis(10));
29132            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
29133                Ok(json!({"late": "result"}))
29134            });
29135
29136            let error = worker
29137                .run_once()
29138                .await
29139                .expect_err(&format!("{name} must remain an error"));
29140            assert!(
29141                matches!(error, Error::Http { .. } | Error::Protocol(_)),
29142                "{name} returned an unexpected error variant: {error}"
29143            );
29144        }
29145    }
29146
29147    #[tokio::test]
29148    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
29149        let server = MockWorkerServer::start();
29150        let client = Client::builder(server.base_url())
29151            .worker_token(Some("worker-secret".to_string()))
29152            .namespace("orders")
29153            .timeout(Duration::from_secs(2))
29154            .build()
29155            .expect("client");
29156        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
29157
29158        let result = client
29159            .deregister_worker_registration("worker/α space")
29160            .await
29161            .expect("deregister worker registration");
29162
29163        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
29164        assert_eq!(
29165            server.worker_protocol_for(path).as_deref(),
29166            Some(WORKER_PROTOCOL_VERSION)
29167        );
29168        assert_eq!(server.control_protocol_for(path), None);
29169        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
29170        assert_eq!(
29171            server.authorization_for(path).as_deref(),
29172            Some("Bearer worker-secret")
29173        );
29174        assert_eq!(
29175            result,
29176            WorkerDeregistrationEnvelope {
29177                worker_id: "deregistered-worker".to_string(),
29178                outcome: "deregistered".to_string(),
29179                recovered_workflow_task_count: 2,
29180            }
29181        );
29182    }
29183
29184    #[tokio::test]
29185    async fn low_level_registration_rejects_update_validators_before_transport() {
29186        let server = MockWorkerServer::start();
29187        let client = Client::builder(server.base_url())
29188            .timeout(Duration::from_secs(2))
29189            .build()
29190            .expect("client");
29191
29192        for update_validators in [json!(["approve"]), json!("approve")] {
29193            let error = client
29194                .register_worker_with_command_contracts(
29195                    "validator-claiming-worker",
29196                    "rust-workers",
29197                    vec!["orders".to_string()],
29198                    vec![],
29199                    1,
29200                    1,
29201                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
29202                    json!({
29203                        "orders": {
29204                            "queries": ["current"],
29205                            "updates": ["approve"],
29206                            "update_validators": update_validators,
29207                        },
29208                    }),
29209                )
29210                .await
29211                .expect_err("unsupported validator claims must fail before registration");
29212
29213            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
29214                panic!("expected typed unsupported-validator failure");
29215            };
29216            assert_eq!(workflow_type, "orders");
29217        }
29218        assert_eq!(server.request_count("/api/worker/register"), 0);
29219    }
29220
29221    #[tokio::test]
29222    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
29223        let server = MockWorkerServer::start();
29224        let client = Client::builder(server.base_url())
29225            .timeout(Duration::from_secs(2))
29226            .build()
29227            .expect("client");
29228        let mut worker = Worker::new(client, "rust-workers");
29229        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
29230        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
29231        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
29232        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
29233        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
29234        worker
29235            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
29236            .expect("declare workflow signals");
29237
29238        worker.register().await.expect("register handler contracts");
29239
29240        let declaration =
29241            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
29242        let expected_contracts = json!([
29243            {
29244                "name": "a-avro",
29245                "parameters": [{
29246                    "name": "args", "position": 0, "required": false,
29247                    "variadic": true, "type": null, "allows_null": true,
29248                    "default_available": false, "default": null,
29249                }],
29250            },
29251            {
29252                "name": "z-json",
29253                "parameters": [{
29254                    "name": "args", "position": 0, "required": false,
29255                    "variadic": true, "type": null, "allows_null": true,
29256                    "default_available": false, "default": null,
29257                }],
29258            },
29259        ]);
29260        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
29261        assert_eq!(declaration["query_contracts"], expected_contracts);
29262        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
29263        assert_eq!(declaration["update_contracts"], expected_contracts);
29264        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
29265        assert_eq!(declaration["signal_contracts"], expected_contracts);
29266        assert_eq!(declaration["update_validators"], json!([]));
29267    }
29268
29269    #[tokio::test]
29270    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
29271        let server = MockWorkerServer::start();
29272        let client = Client::new(server.base_url()).expect("client");
29273        let mut worker = Worker::new(client, "rust-workers");
29274        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
29275        assert!(worker
29276            .declare_workflow_signals("missing", &["finish"])
29277            .is_err());
29278        worker
29279            .declare_workflow_signals("orders", &["finish"])
29280            .unwrap();
29281        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
29282            assert!(worker.declare_workflow_signals("orders", names).is_err());
29283        }
29284        worker.register().await.unwrap();
29285        assert_eq!(
29286            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
29287                ["signals"],
29288            json!(["finish"])
29289        );
29290        worker.declare_workflow_signals("orders", &[]).unwrap();
29291        worker.register().await.unwrap();
29292        let registrations = server.request_bodies("/api/worker/register");
29293        assert_eq!(
29294            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
29295            json!([])
29296        );
29297        assert_eq!(
29298            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
29299            json!([])
29300        );
29301    }
29302
29303    #[tokio::test]
29304    async fn low_level_registration_preserves_query_and_update_contracts() {
29305        let server = MockWorkerServer::start();
29306        let client = Client::builder(server.base_url())
29307            .timeout(Duration::from_secs(2))
29308            .build()
29309            .expect("client");
29310        let contracts = json!({
29311            "orders": {
29312                "queries": ["current"],
29313                "updates": ["approve"],
29314                "update_validators": [],
29315            },
29316            "payments": {
29317                "queries": ["status"],
29318                "updates": ["capture"],
29319            },
29320        });
29321
29322        client
29323            .register_worker_with_command_contracts(
29324                "command-worker",
29325                "rust-workers",
29326                vec!["orders".to_string(), "payments".to_string()],
29327                vec![],
29328                1,
29329                1,
29330                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
29331                contracts.clone(),
29332            )
29333            .await
29334            .expect("query and update contracts must remain supported");
29335
29336        assert_eq!(
29337            server.request_body("/api/worker/register")["workflow_command_contracts"],
29338            contracts
29339        );
29340        assert!(server
29341            .request_body("/api/worker/register")
29342            .get("workflow_definition_fingerprints")
29343            .is_none());
29344    }
29345
29346    #[tokio::test]
29347    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
29348        let server = MockWorkerServer::start();
29349        let client = Client::builder(server.base_url())
29350            .timeout(Duration::from_secs(2))
29351            .build()
29352            .expect("client");
29353        let mut worker = Worker::new(client.clone(), "rust-workers");
29354        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
29355
29356        assert!(worker
29357            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
29358            .is_err());
29359        assert!(worker
29360            .set_workflow_definition_sources("orders", &[])
29361            .is_err());
29362        worker
29363            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
29364            .expect("embed workflow source");
29365        worker.register().await.expect("register worker");
29366        let first = server.request_bodies("/api/worker/register")[0]
29367            ["workflow_definition_fingerprints"]["orders"]
29368            .as_str()
29369            .expect("source-backed fingerprint")
29370            .to_string();
29371        assert!(first.starts_with("sha256:"));
29372
29373        worker
29374            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
29375            .expect("change embedded helper source");
29376        worker.register().await.expect("register changed source");
29377        let changed = server.request_bodies("/api/worker/register")[1]
29378            ["workflow_definition_fingerprints"]["orders"]
29379            .as_str()
29380            .expect("changed fingerprint")
29381            .to_string();
29382        assert_ne!(first, changed);
29383
29384        let mut replacement =
29385            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
29386        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
29387        replacement
29388            .register()
29389            .await
29390            .expect("register replacement handler");
29391        assert_eq!(
29392            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
29393            json!({})
29394        );
29395    }
29396
29397    #[tokio::test]
29398    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
29399        let server = MockWorkerServer::start();
29400        let control_only = Client::builder(server.base_url())
29401            .control_token(Some("control-secret".to_string()))
29402            .build()
29403            .expect("control client");
29404
29405        let error = control_only
29406            .register_worker("worker", "queue", vec![], vec![], 1, 1)
29407            .await
29408            .expect_err("control token must not authorize a worker request");
29409        assert!(matches!(
29410            error,
29411            Error::MissingRoleCredentials { role: "worker", .. }
29412        ));
29413        assert_eq!(server.request_count("/api/worker/register"), 0);
29414
29415        let worker_only = Client::builder(server.base_url())
29416            .worker_token(Some("worker-secret".to_string()))
29417            .build()
29418            .expect("worker client");
29419        let error = worker_only
29420            .health()
29421            .await
29422            .expect_err("worker token must not authorize a control request");
29423        assert!(matches!(
29424            error,
29425            Error::MissingRoleCredentials {
29426                role: "control",
29427                ..
29428            }
29429        ));
29430        assert_eq!(server.request_count("/api/health"), 0);
29431    }
29432
29433    #[tokio::test]
29434    async fn shared_token_supports_worker_and_control_planes() {
29435        let server = MockWorkerServer::start();
29436        let client = Client::builder(server.base_url())
29437            .token(Some("shared-secret".to_string()))
29438            .build()
29439            .expect("client");
29440
29441        client.health().await.expect("control request");
29442        client
29443            .register_worker("worker", "queue", vec![], vec![], 1, 1)
29444            .await
29445            .expect("worker request");
29446
29447        assert_eq!(
29448            server.authorization_for("/api/health").as_deref(),
29449            Some("Bearer shared-secret")
29450        );
29451        assert_eq!(
29452            server.control_protocol_for("/api/health").as_deref(),
29453            Some(CONTROL_PLANE_VERSION)
29454        );
29455        assert_eq!(
29456            server.authorization_for("/api/worker/register").as_deref(),
29457            Some("Bearer shared-secret")
29458        );
29459        assert_eq!(
29460            server
29461                .worker_protocol_for("/api/worker/register")
29462                .as_deref(),
29463            Some(WORKER_PROTOCOL_VERSION)
29464        );
29465    }
29466
29467    #[tokio::test]
29468    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
29469        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
29470        let server = MockWorkerServer::start();
29471        let client = Client::builder(server.base_url())
29472            .timeout(Duration::from_secs(2))
29473            .build()
29474            .expect("client");
29475
29476        client
29477            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
29478            .await
29479            .expect("register");
29480        client
29481            .heartbeat_worker("capture-worker", 1, 1)
29482            .await
29483            .expect("heartbeat");
29484        client
29485            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
29486            .await
29487            .expect("workflow poll");
29488        client
29489            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
29490            .await
29491            .expect("activity poll");
29492
29493        for path in [
29494            "/api/worker/register",
29495            "/api/worker/heartbeat",
29496            "/api/worker/workflow-tasks/poll",
29497            "/api/worker/activity-tasks/poll",
29498        ] {
29499            assert_eq!(
29500                server.worker_protocol_for(path).as_deref(),
29501                Some(WORKER_PROTOCOL_VERSION),
29502                "unexpected protocol for {path}"
29503            );
29504        }
29505
29506        assert_eq!(
29507            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
29508            1
29509        );
29510        assert_eq!(
29511            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
29512            500
29513        );
29514        assert_eq!(
29515            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
29516            1
29517        );
29518        assert!(
29519            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
29520                .as_str()
29521                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
29522        );
29523        assert!(
29524            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
29525                .as_str()
29526                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
29527        );
29528        let registration = server.request_body("/api/worker/register");
29529        for optional in [
29530            "cooperative_cancellation",
29531            "local_activities",
29532            "worker_sessions",
29533            "sticky_execution",
29534        ] {
29535            assert!(!registration["capabilities"]
29536                .as_array()
29537                .is_some_and(|capabilities| capabilities
29538                    .iter()
29539                    .any(|capability| capability.as_str() == Some(optional))));
29540        }
29541    }
29542
29543    #[tokio::test]
29544    async fn explicit_previous_worker_protocol_preserves_headers() {
29545        let server = MockWorkerServer::start();
29546        let client = Client::builder(server.base_url())
29547            .worker_protocol_version(WorkerProtocolVersion::V119)
29548            .timeout(Duration::from_secs(2))
29549            .build()
29550            .expect("client");
29551        client
29552            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
29553            .await
29554            .expect("register");
29555        client
29556            .heartbeat_worker("legacy-worker", 1, 1)
29557            .await
29558            .expect("heartbeat");
29559        client
29560            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
29561            .await
29562            .expect("workflow poll");
29563        client
29564            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
29565            .await
29566            .expect("activity poll");
29567        client
29568            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
29569            .await
29570            .expect("query poll");
29571        client
29572            .deregister_worker_registration("legacy-worker")
29573            .await
29574            .expect("deregister");
29575        for path in [
29576            "/api/worker/register",
29577            "/api/worker/heartbeat",
29578            "/api/worker/workflow-tasks/poll",
29579            "/api/worker/activity-tasks/poll",
29580            "/api/worker/query-tasks/poll",
29581            "/api/worker/registrations/legacy-worker",
29582        ] {
29583            assert_eq!(
29584                server.worker_protocol_for(path).as_deref(),
29585                Some("1.19"),
29586                "{path}"
29587            );
29588            assert_eq!(server.control_protocol_for(path), None, "{path}");
29589        }
29590    }
29591
29592    #[tokio::test]
29593    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
29594        let server = MockWorkerServer::start();
29595        let client = Client::builder(server.base_url())
29596            .worker_protocol_version(WorkerProtocolVersion::V119)
29597            .timeout(Duration::from_secs(2))
29598            .build()
29599            .expect("client");
29600        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
29601        let error = worker
29602            .register()
29603            .await
29604            .expect_err("legacy cooperation must be refused");
29605        assert!(matches!(
29606            error,
29607            Error::CooperativeCancellationUnavailable(_)
29608        ));
29609        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
29610    }
29611
29612    #[tokio::test]
29613    async fn query_task_endpoints_send_the_selected_worker_protocol() {
29614        let server = MockWorkerServer::start();
29615        let client = Client::builder(server.base_url())
29616            .timeout(Duration::from_secs(2))
29617            .build()
29618            .expect("client");
29619
29620        client
29621            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
29622            .await
29623            .expect("query poll");
29624        client
29625            .complete_query_task(
29626                "query-capture",
29627                "capture-worker",
29628                1,
29629                json!(8),
29630                DEFAULT_CODEC,
29631            )
29632            .await
29633            .expect("query complete");
29634        client
29635            .fail_query_task(
29636                "query-capture",
29637                "capture-worker",
29638                1,
29639                "failed",
29640                "query_rejected",
29641                "QueryFailed",
29642            )
29643            .await
29644            .expect("query fail");
29645
29646        for path in [
29647            "/api/worker/query-tasks/poll",
29648            "/api/worker/query-tasks/query-capture/complete",
29649            "/api/worker/query-tasks/query-capture/fail",
29650        ] {
29651            assert_eq!(
29652                server.worker_protocol_for(path).as_deref(),
29653                Some(WORKER_PROTOCOL_VERSION),
29654                "unexpected protocol for {path}"
29655            );
29656        }
29657
29658        assert_eq!(
29659            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
29660            1
29661        );
29662        assert!(
29663            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
29664                .as_str()
29665                .is_some_and(|id| id.starts_with("rust-query-poll-"))
29666        );
29667    }
29668
29669    #[tokio::test]
29670    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
29671        let server = MockWorkerServer::transient_worker_failures();
29672        let client = Client::builder(server.base_url())
29673            .timeout(Duration::from_secs(2))
29674            .build()
29675            .expect("client");
29676
29677        client
29678            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
29679            .await
29680            .expect("workflow poll retry");
29681        client
29682            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
29683            .await
29684            .expect("activity poll retry");
29685        client
29686            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
29687            .await
29688            .expect("query poll retry");
29689
29690        for path in [
29691            "/api/worker/workflow-tasks/poll",
29692            "/api/worker/activity-tasks/poll",
29693            "/api/worker/query-tasks/poll",
29694        ] {
29695            let bodies = server.request_bodies(path);
29696            assert_eq!(bodies.len(), 2, "{path} must be retried once");
29697            assert_eq!(
29698                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
29699                "{path} must preserve the request binding across retry"
29700            );
29701        }
29702    }
29703
29704    #[tokio::test]
29705    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
29706        let server = MockWorkerServer::consecutive_poll_failures(2);
29707        let client = Client::builder(server.base_url())
29708            .timeout(Duration::from_secs(2))
29709            .build()
29710            .expect("client");
29711        let mut worker = Worker::new(client, "capture")
29712            .worker_id("capture-worker")
29713            .poll_timeout(Duration::from_millis(10))
29714            .retry_policy(WorkerRetryPolicy {
29715                max_retries: 2,
29716                initial_backoff: Duration::from_millis(1),
29717                max_backoff: Duration::from_millis(1),
29718            });
29719        worker.register_workflow(
29720            "capture.workflow",
29721            |_ctx, _input| async move { Ok(Value::Null) },
29722        );
29723        worker.register_activity(
29724            "capture.activity",
29725            |_ctx, _input| async move { Ok(Value::Null) },
29726        );
29727        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
29728            Ok(Value::Null)
29729        });
29730
29731        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
29732
29733        for path in [
29734            "/api/worker/workflow-tasks/poll",
29735            "/api/worker/activity-tasks/poll",
29736            "/api/worker/query-tasks/poll",
29737        ] {
29738            let bodies = server.request_bodies(path);
29739            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
29740            assert!(
29741                bodies
29742                    .iter()
29743                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
29744                "{path} must preserve one request binding across every retry"
29745            );
29746        }
29747    }
29748
29749    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
29750        let reason = if unavailable {
29751            "storage_admission_unavailable"
29752        } else {
29753            "storage_pressure"
29754        };
29755        let mut body = json!({
29756            "reason": reason,
29757            "storage_state": if unavailable { "fenced" } else { "draining" },
29758            "retryable": true,
29759            "retry_after_seconds": 1,
29760        });
29761        if !mid_poll {
29762            body["request_admitted"] = json!(false);
29763        }
29764        if let Some(id) = poll_id {
29765            body["task"] = Value::Null;
29766            body["poll_status"] = json!(reason);
29767            body["poll_request_id"] = json!(id);
29768            body["retry_same_poll_request_id"] = json!(true);
29769            body["claim_admitted"] = json!(false);
29770        }
29771        body
29772    }
29773
29774    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
29775        let operation = match path {
29776            "/api/worker/register" => "register_worker",
29777            "/api/worker/heartbeat" => "heartbeat_worker",
29778            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
29779            "/api/worker/activity-tasks/poll" => "poll_activity_task",
29780            "/api/worker/query-tasks/poll" => "poll_query_task",
29781            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
29782            _ => return None,
29783        };
29784        let request: Value = serde_json::from_str(request).ok()?;
29785        let mut response = json!({
29786            "reason": "backend_unavailable",
29787            "operation": operation,
29788            "outcome": "unknown",
29789            "retryable": true,
29790            "retry_after_seconds": 1,
29791            "worker_id": request["worker_id"],
29792            "task_queue": request.get("task_queue"),
29793        });
29794        if path.ends_with("/poll") {
29795            response["task"] = Value::Null;
29796            response["poll_status"] = json!("backend_unavailable");
29797            response["poll_request_id"] = request["poll_request_id"].clone();
29798            response["retry_same_poll_request_id"] = json!(true);
29799        }
29800        Some(response)
29801    }
29802
29803    fn backend_retry_override(
29804        path: &str,
29805        request: &str,
29806        number: usize,
29807    ) -> Option<(&'static str, String)> {
29808        if number > 8 {
29809            return None;
29810        }
29811        Some((
29812            "503 Service Unavailable",
29813            backend_refusal(path, request)?.to_string(),
29814        ))
29815    }
29816
29817    fn backend_unavailable_override(
29818        path: &str,
29819        request: &str,
29820        _number: usize,
29821    ) -> Option<(&'static str, String)> {
29822        Some((
29823            "503 Service Unavailable",
29824            backend_refusal(path, request)?.to_string(),
29825        ))
29826    }
29827
29828    fn storage_worker(server: &MockWorkerServer) -> Worker {
29829        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
29830            .worker_id("storage-worker")
29831            .retry_policy(WorkerRetryPolicy {
29832                max_retries: 1,
29833                initial_backoff: Duration::from_millis(1),
29834                max_backoff: Duration::from_millis(1),
29835            })
29836    }
29837
29838    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
29839        let requests = server.requests.lock().expect("requests");
29840        let bodies: Vec<_> = requests
29841            .iter()
29842            .filter(|request| request.path == path)
29843            .map(|request| &request.body)
29844            .collect();
29845        assert_eq!(bodies.len(), count, "{path}");
29846        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
29847    }
29848
29849    #[test]
29850    fn backend_recovery_requires_the_explicit_worker_contract() {
29851        for (path, operation) in [
29852            ("/worker/register", "register_worker"),
29853            ("/worker/heartbeat", "heartbeat_worker"),
29854            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
29855            ("/worker/activity-tasks/poll", "poll_activity_task"),
29856            ("/worker/query-tasks/poll", "poll_query_task"),
29857            (
29858                "/worker/update-validation-tasks/poll",
29859                "poll_update_validation_task",
29860            ),
29861        ] {
29862            let poll_id = path.ends_with("/poll").then_some("same-poll");
29863            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
29864            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
29865                .expect("worker operation");
29866            assert_eq!(body["operation"], operation);
29867            let error = Error::Http {
29868                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29869                body: body.to_string(),
29870            };
29871            assert_eq!(
29872                worker_backend_unavailable_retry_after(&error, path, poll_id),
29873                Some(Duration::from_secs(1))
29874            );
29875            assert!(!worker_operation_is_retryable(&error));
29876            for (field, value) in [
29877                ("operation", json!("wrong_operation")),
29878                ("outcome", json!("completed")),
29879                ("retryable", json!(false)),
29880                ("retry_after_seconds", json!(0)),
29881                ("worker_id", json!("")),
29882            ] {
29883                let mut invalid = body.clone();
29884                invalid[field] = value;
29885                let error = Error::Http {
29886                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29887                    body: invalid.to_string(),
29888                };
29889                assert!(
29890                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
29891                    "{path}: {field}"
29892                );
29893                assert!(!worker_operation_is_retryable(&error));
29894            }
29895            if let Some(poll_id) = poll_id {
29896                for (field, value) in [
29897                    ("poll_request_id", json!("wrong-poll")),
29898                    ("poll_status", json!("empty")),
29899                    ("task", json!({"task_id":"claimed"})),
29900                    ("retry_same_poll_request_id", json!(false)),
29901                ] {
29902                    let mut invalid = body.clone();
29903                    invalid[field] = value;
29904                    let error = Error::Http {
29905                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29906                        body: invalid.to_string(),
29907                    };
29908                    assert!(
29909                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
29910                            .is_none(),
29911                        "{path}: {field}"
29912                    );
29913                }
29914            }
29915            let error = Error::Http {
29916                status: reqwest::StatusCode::UNAUTHORIZED,
29917                body: body.to_string(),
29918            };
29919            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
29920            assert!(!worker_operation_is_retryable(&error));
29921        }
29922    }
29923
29924    #[tokio::test]
29925    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
29926        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29927            request_override: Some(backend_retry_override),
29928            ..MockWorkerBehavior::default()
29929        });
29930        let mut worker =
29931            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
29932        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
29933        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
29934        worker.register_query("backend.workflow", "state", |_, _| async {
29935            Ok(Value::Null)
29936        });
29937        worker.register().await.expect("registration recovery");
29938        worker
29939            .client
29940            .heartbeat_worker("storage-worker", 1, 1)
29941            .await
29942            .expect("heartbeat recovery");
29943        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
29944        for path in [
29945            "/api/worker/register",
29946            "/api/worker/heartbeat",
29947            "/api/worker/workflow-tasks/poll",
29948            "/api/worker/activity-tasks/poll",
29949            "/api/worker/query-tasks/poll",
29950        ] {
29951            assert_identical_requests(&server, path, 9);
29952        }
29953    }
29954
29955    #[tokio::test]
29956    async fn backend_recovery_wait_stops_with_worker() {
29957        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29958            request_override: Some(backend_unavailable_override),
29959            ..MockWorkerBehavior::default()
29960        });
29961        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
29962            max_retries: 1,
29963            initial_backoff: Duration::from_secs(2),
29964            max_backoff: Duration::from_secs(2),
29965        });
29966        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
29967        let started = tokio::time::Instant::now();
29968        let _ = tokio::time::timeout(
29969            Duration::from_secs(1),
29970            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
29971        )
29972        .await
29973        .expect("shutdown interrupts backend wait");
29974        assert!(started.elapsed() < Duration::from_secs(1));
29975        assert!(server.request_count("/api/worker/register") >= 1);
29976    }
29977
29978    #[test]
29979    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
29980        for unavailable in [false, true] {
29981            for mid_poll in [false, true] {
29982                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
29983                let error = Error::Http {
29984                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
29985                    body: body.to_string(),
29986                };
29987                assert_eq!(
29988                    worker_storage_admission_retry_after(&error, Some("same-poll")),
29989                    Some(Duration::from_secs(1))
29990                );
29991                assert!(
29992                    !worker_operation_is_retryable(&error),
29993                    "storage is not a bounded generic retry"
29994                );
29995                for (field, value) in [
29996                    ("poll_request_id", json!("wrong-poll")),
29997                    ("task", json!({"task_id":"claimed"})),
29998                    ("retryable", json!(false)),
29999                    ("retry_after_seconds", json!(0)),
30000                    ("retry_after_seconds", json!(true)),
30001                    ("retry_after_seconds", json!(1.0)),
30002                    ("storage_state", json!("normal")),
30003                    ("poll_status", json!("empty")),
30004                    ("claim_admitted", json!(true)),
30005                    ("retry_same_poll_request_id", json!(false)),
30006                    ("request_admitted", json!(true)),
30007                ] {
30008                    let mut invalid = body.clone();
30009                    invalid[field] = value;
30010                    let error = Error::Http {
30011                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30012                        body: invalid.to_string(),
30013                    };
30014                    assert!(
30015                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
30016                        "{field}"
30017                    );
30018                }
30019            }
30020        }
30021        let body = storage_refusal(None, false, false);
30022        let error = Error::Http {
30023            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30024            body: body.to_string(),
30025        };
30026        assert!(worker_storage_admission_retry_after(&error, None).is_some());
30027        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
30028        let error = Error::Http {
30029            status: reqwest::StatusCode::FORBIDDEN,
30030            body: body.to_string(),
30031        };
30032        assert!(worker_storage_admission_retry_after(&error, None).is_none());
30033        let body = storage_refusal(None, false, true);
30034        let error = Error::Http {
30035            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30036            body: body.to_string(),
30037        };
30038        assert!(worker_storage_admission_retry_after(&error, None).is_none());
30039    }
30040
30041    #[tokio::test]
30042    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
30043        for unavailable in [false, true] {
30044            for mid_poll in [false, true] {
30045                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30046                    poll_failures_per_path: 1,
30047                    storage_refusals: 7,
30048                    storage_path: Some("/poll"),
30049                    storage_unavailable: unavailable,
30050                    storage_mid_poll: mid_poll,
30051                    ..MockWorkerBehavior::default()
30052                });
30053                let mut worker = storage_worker(&server);
30054                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
30055                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
30056                for path in [
30057                    "/api/worker/workflow-tasks/poll",
30058                    "/api/worker/activity-tasks/poll",
30059                    "/api/worker/query-tasks/poll",
30060                ] {
30061                    assert_identical_requests(&server, path, 9);
30062                }
30063            }
30064        }
30065    }
30066
30067    #[tokio::test]
30068    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
30069        struct CountedBody(Arc<AtomicUsize>);
30070        impl Serialize for CountedBody {
30071            fn serialize<S: Serializer>(
30072                &self,
30073                serializer: S,
30074            ) -> std::result::Result<S::Ok, S::Error> {
30075                let count = self.0.fetch_add(1, Ordering::SeqCst);
30076                json!({"serialization":count,"lease_owner":"worker","attempt":7})
30077                    .serialize(serializer)
30078            }
30079        }
30080        for path in [
30081            "/api/worker/register",
30082            "/api/worker/heartbeat",
30083            "/api/worker/workflow-tasks/storage-task/complete",
30084            "/api/worker/workflow-tasks/storage-task/fail",
30085            "/api/worker/activity-tasks/storage-task/complete",
30086            "/api/worker/activity-tasks/storage-task/fail",
30087            "/api/worker/activity-tasks/storage-task/heartbeat",
30088            "/api/worker/query-tasks/storage-task/complete",
30089            "/api/worker/query-tasks/storage-task/fail",
30090        ] {
30091            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30092                storage_refusals: 7,
30093                storage_path: Some(path),
30094                ..MockWorkerBehavior::default()
30095            });
30096            let worker =
30097                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
30098            let calls = Arc::new(AtomicUsize::new(0));
30099            let _: Value = worker
30100                .client
30101                .request_json(
30102                    reqwest::Method::POST,
30103                    &path[4..],
30104                    RequestProtocol::DefaultWorker,
30105                    Some(&CountedBody(Arc::clone(&calls))),
30106                )
30107                .await
30108                .expect("prepared request recovery");
30109            assert_eq!(calls.load(Ordering::SeqCst), 1);
30110            assert_identical_requests(&server, path, 8);
30111        }
30112        for worker_scope in [false, true] {
30113            let path = if worker_scope {
30114                "/api/health"
30115            } else {
30116                "/api/worker/register"
30117            };
30118            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30119                storage_refusals: usize::MAX,
30120                storage_path: Some(path),
30121                ..MockWorkerBehavior::default()
30122            });
30123            let worker = storage_worker(&server);
30124            let client = worker.client.clone();
30125            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
30126            let error = if worker_scope {
30127                worker
30128                    .client
30129                    .health()
30130                    .await
30131                    .expect_err("control plane is not retried")
30132            } else {
30133                client
30134                    .request_json::<Value, Value>(
30135                        reqwest::Method::POST,
30136                        "/worker/register",
30137                        RequestProtocol::DefaultWorker,
30138                        Some(&json!({})),
30139                    )
30140                    .await
30141                    .expect_err("direct client is not retried")
30142            };
30143            assert!(worker_storage_admission_body(&error).is_some());
30144            assert_eq!(server.request_count(path), 1);
30145        }
30146    }
30147
30148    #[tokio::test]
30149    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
30150        for fail in [false, true] {
30151            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30152                storage_activity: true,
30153                storage_refusals: 7,
30154                storage_path: Some("/storage-activity/"),
30155                ..MockWorkerBehavior::default()
30156            });
30157            let mut worker = storage_worker(&server);
30158            let calls = Arc::new(AtomicUsize::new(0));
30159            let observed = Arc::clone(&calls);
30160            worker.register_activity("storage.activity", move |ctx, _| {
30161                let calls = Arc::clone(&observed);
30162                async move {
30163                    calls.fetch_add(1, Ordering::SeqCst);
30164                    ctx.heartbeat(json!({"step":2})).await?;
30165                    if fail {
30166                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
30167                    } else {
30168                        Ok(json!({"receipt":true}))
30169                    }
30170                }
30171            });
30172            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
30173            assert_eq!(calls.load(Ordering::SeqCst), 1);
30174            assert_identical_requests(
30175                &server,
30176                "/api/worker/activity-tasks/storage-activity/heartbeat",
30177                8,
30178            );
30179            let suffix = if fail { "fail" } else { "complete" };
30180            assert_identical_requests(
30181                &server,
30182                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
30183                8,
30184            );
30185            let other = if fail { "complete" } else { "fail" };
30186            assert_eq!(
30187                server.request_count(&format!(
30188                    "/api/worker/activity-tasks/storage-activity/{other}"
30189                )),
30190                0
30191            );
30192        }
30193    }
30194
30195    #[tokio::test]
30196    async fn storage_waits_are_interruptible_without_false_activity_failure() {
30197        for path in [
30198            "/api/worker/register",
30199            "/api/worker/heartbeat",
30200            "/api/worker/activity-tasks/poll",
30201            "/api/worker/activity-tasks/storage-activity/heartbeat",
30202            "/api/worker/activity-tasks/storage-activity/complete",
30203        ] {
30204            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30205                storage_activity: true,
30206                storage_refusals: usize::MAX,
30207                storage_path: Some(path),
30208                ..MockWorkerBehavior::default()
30209            });
30210            let mut worker = storage_worker(&server)
30211                .max_concurrent_workflow_tasks(1)
30212                .max_concurrent_activity_tasks(1)
30213                .retry_policy(WorkerRetryPolicy::default());
30214            worker.register_activity("storage.activity", |ctx, _| async move {
30215                ctx.heartbeat(json!({"step":2})).await?;
30216                Ok(json!({"receipt":true}))
30217            });
30218            let shutdown = async {
30219                while server.request_count(path) == 0 {
30220                    tokio::time::sleep(Duration::from_millis(1)).await;
30221                }
30222            };
30223            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
30224                .await
30225                .expect("shutdown interrupts admission");
30226            assert!(
30227                result.is_err(),
30228                "a refused operation must not appear acknowledged: {path}, {result:?}"
30229            );
30230            assert_eq!(server.request_count(path), 1);
30231            assert_eq!(
30232                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
30233                0
30234            );
30235            assert_eq!(
30236                server.request_count("/api/worker/registrations/mock-worker"),
30237                usize::from(!path.ends_with("/register"))
30238            );
30239        }
30240    }
30241
30242    #[tokio::test]
30243    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
30244        for fail in [false, true] {
30245            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30246                storage_query: true,
30247                storage_refusals: 7,
30248                storage_path: Some("/storage-query/"),
30249                ..MockWorkerBehavior::default()
30250            });
30251            let mut worker = storage_worker(&server);
30252            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
30253            let calls = Arc::new(AtomicUsize::new(0));
30254            let observed = Arc::clone(&calls);
30255            worker.register_query("storage.workflow", "state", move |_, _| {
30256                let calls = Arc::clone(&observed);
30257                async move {
30258                    calls.fetch_add(1, Ordering::SeqCst);
30259                    if fail {
30260                        Err(Error::WorkerLoop("intentional query failure".to_string()))
30261                    } else {
30262                        Ok(json!({"state":"waiting"}))
30263                    }
30264                }
30265            });
30266            assert_eq!(worker.run_once().await.expect("query settled"), 1);
30267            assert_eq!(calls.load(Ordering::SeqCst), 1);
30268            let suffix = if fail { "fail" } else { "complete" };
30269            assert_identical_requests(
30270                &server,
30271                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
30272                8,
30273            );
30274            let other = if fail { "complete" } else { "fail" };
30275            assert_eq!(
30276                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
30277                0
30278            );
30279        }
30280    }
30281
30282    #[tokio::test]
30283    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
30284        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30285            storage_refusals: 7,
30286            storage_path: Some("/poll"),
30287            unauthorized_polls: true,
30288            ..MockWorkerBehavior::default()
30289        });
30290        let error = storage_worker(&server)
30291            .run_once()
30292            .await
30293            .expect_err("auth remains terminal");
30294        assert!(matches!(
30295            error,
30296            Error::Http {
30297                status: reqwest::StatusCode::UNAUTHORIZED,
30298                ..
30299            }
30300        ));
30301        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
30302
30303        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30304            storage_refusals: 7,
30305            storage_path: Some("/activity-cancel/complete"),
30306            ..MockWorkerBehavior::default()
30307        });
30308        let worker =
30309            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
30310        let error = worker
30311            .client
30312            .complete_activity_task(
30313                "activity-cancel",
30314                "attempt-cancel",
30315                "worker",
30316                json!({}),
30317                DEFAULT_CODEC,
30318            )
30319            .await
30320            .expect_err("cancellation remains terminal");
30321        assert!(activity_task_rejection_is_final(&error));
30322        assert_identical_requests(
30323            &server,
30324            "/api/worker/activity-tasks/activity-cancel/complete",
30325            8,
30326        );
30327
30328        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30329            storage_refusals: usize::MAX,
30330            storage_path: Some("/poll"),
30331            storage_wrong_poll_id: true,
30332            ..MockWorkerBehavior::default()
30333        });
30334        assert!(storage_worker(&server).run_once().await.is_err());
30335        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
30336    }
30337
30338    #[tokio::test]
30339    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
30340        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30341            storage_refusals: usize::MAX,
30342            storage_path: Some("/poll"),
30343            ..MockWorkerBehavior::default()
30344        });
30345        let mut worker = storage_worker(&server)
30346            .max_concurrent_workflow_tasks(1)
30347            .max_concurrent_activity_tasks(1)
30348            .retry_policy(WorkerRetryPolicy::default());
30349        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
30350        let run = tokio::spawn(async move { worker.run().await });
30351        tokio::time::timeout(Duration::from_secs(2), async {
30352            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
30353                tokio::time::sleep(Duration::from_millis(1)).await;
30354            }
30355        })
30356        .await
30357        .expect("poll started");
30358        run.abort();
30359        assert!(run.await.expect_err("cancelled run").is_cancelled());
30360        tokio::time::sleep(Duration::from_millis(250)).await;
30361        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
30362    }
30363
30364    #[tokio::test]
30365    async fn query_protocol_rejection_from_older_server_is_typed() {
30366        let server = MockWorkerServer::reject_query_protocol();
30367        let client = Client::builder(server.base_url())
30368            .timeout(Duration::from_secs(2))
30369            .build()
30370            .expect("client");
30371
30372        let error = client
30373            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
30374            .await
30375            .expect_err("server below query protocol floor must reject");
30376        let Error::Protocol(failure) = error else {
30377            panic!("expected typed protocol failure");
30378        };
30379
30380        assert_eq!(failure.status, 400);
30381        assert_eq!(failure.reason, "unsupported_protocol_version");
30382        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
30383        assert_eq!(
30384            failure.requested_version.as_deref(),
30385            Some(WORKER_PROTOCOL_VERSION)
30386        );
30387        assert_eq!(
30388            server
30389                .worker_protocol_for("/api/worker/query-tasks/poll")
30390                .as_deref(),
30391            Some(WORKER_PROTOCOL_VERSION)
30392        );
30393    }
30394
30395    #[tokio::test]
30396    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
30397        let server = MockWorkerServer::reject_query_protocol();
30398        let client = Client::builder(server.base_url())
30399            .timeout(Duration::from_secs(2))
30400            .build()
30401            .expect("client");
30402        let mut worker = Worker::new(client, "rust-workers")
30403            .worker_id("baseline-worker")
30404            .poll_timeout(Duration::from_millis(10));
30405
30406        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
30407            Ok(Value::Null)
30408        });
30409
30410        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
30411        assert_eq!(
30412            server
30413                .worker_protocol_for("/api/worker/workflow-tasks/poll")
30414                .as_deref(),
30415            Some(WORKER_PROTOCOL_VERSION)
30416        );
30417        assert_eq!(
30418            server.worker_protocol_for("/api/worker/query-tasks/poll"),
30419            None,
30420            "a worker without query handlers must not use the query-task endpoint"
30421        );
30422    }
30423
30424    #[tokio::test]
30425    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
30426        let server = MockWorkerServer::reject_query_completion();
30427        let client = Client::builder(server.base_url())
30428            .timeout(Duration::from_secs(2))
30429            .build()
30430            .expect("client");
30431
30432        let error = client
30433            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
30434            .await
30435            .expect_err("expired completion must be rejected");
30436        let Error::QueryFailed(failure) = error else {
30437            panic!("expected typed query failure");
30438        };
30439        assert_eq!(failure.status, 409);
30440        assert_eq!(failure.reason, "query_task_timed_out");
30441
30442        let mut worker = Worker::new(client, "rust-workers")
30443            .worker_id("late-worker")
30444            .poll_timeout(Duration::from_millis(10));
30445        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
30446        worker.register_query(
30447            "counter",
30448            "current",
30449            |_ctx, _args| async move { Ok(json!(8)) },
30450        );
30451
30452        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
30453        assert_eq!(
30454            worker
30455                .run_once()
30456                .await
30457                .expect("worker continues after late completion"),
30458            0
30459        );
30460        assert_eq!(
30461            server.request_count("/api/worker/query-tasks/query-late/complete"),
30462            2
30463        );
30464        assert_eq!(
30465            server.request_count("/api/worker/query-tasks/query-late/fail"),
30466            0,
30467            "a server completion rejection must not be reported as an encoding failure"
30468        );
30469    }
30470
30471    #[tokio::test]
30472    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
30473        let server = MockWorkerServer::start();
30474        let client = Client::builder(server.base_url())
30475            .timeout(Duration::from_secs(2))
30476            .build()
30477            .expect("client");
30478        let mut worker = Worker::new(client, "rust-workers")
30479            .worker_id("joined-worker")
30480            .poll_timeout(Duration::from_millis(10));
30481        worker.register_workflow(
30482            "joined.workflow",
30483            |_ctx, _input| async move { Ok(Value::Null) },
30484        );
30485        worker.register_activity(
30486            "joined.activity",
30487            |_ctx, _input| async move { Ok(Value::Null) },
30488        );
30489        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
30490            Ok(Value::Null)
30491        });
30492
30493        worker
30494            .run_until(tokio::time::sleep(Duration::from_millis(20)))
30495            .await
30496            .expect("normal shutdown");
30497
30498        let deregistration_path = "/api/worker/registrations/mock-worker";
30499        assert_eq!(server.request_count(deregistration_path), 1);
30500        for poll_path in [
30501            "/api/worker/workflow-tasks/poll",
30502            "/api/worker/activity-tasks/poll",
30503            "/api/worker/query-tasks/poll",
30504        ] {
30505            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
30506        }
30507        assert_eq!(
30508            server.captured_paths().last().map(String::as_str),
30509            Some(deregistration_path),
30510            "deregistration must start only after every poller has joined"
30511        );
30512    }
30513
30514    #[tokio::test]
30515    async fn registration_failure_does_not_deregister() {
30516        let server = MockWorkerServer::rejected_registration();
30517        let client = Client::builder(server.base_url())
30518            .timeout(Duration::from_secs(2))
30519            .build()
30520            .expect("client");
30521        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
30522
30523        let error = worker
30524            .run_until(async {})
30525            .await
30526            .expect_err("registration must fail");
30527        assert!(matches!(
30528            error,
30529            Error::Http {
30530                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
30531                ..
30532            }
30533        ));
30534        assert!(server
30535            .captured_paths()
30536            .iter()
30537            .all(|path| !path.starts_with("/api/worker/registrations/")));
30538    }
30539
30540    #[tokio::test]
30541    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
30542        let server = MockWorkerServer::rejected_registration_protocol();
30543        let client = Client::builder(server.base_url())
30544            .timeout(Duration::from_secs(2))
30545            .build()
30546            .expect("client");
30547        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
30548
30549        let error = worker
30550            .run_until(async {})
30551            .await
30552            .expect_err("a protocol 1.16 server must reject this worker");
30553        let Error::Protocol(failure) = error else {
30554            panic!("expected typed protocol rejection");
30555        };
30556        assert_eq!(failure.reason, "unsupported_protocol_version");
30557        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
30558        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
30559        assert_eq!(
30560            server
30561                .worker_protocol_for("/api/worker/register")
30562                .as_deref(),
30563            Some(WORKER_PROTOCOL_VERSION)
30564        );
30565    }
30566
30567    #[tokio::test]
30568    async fn declined_registration_does_not_deregister() {
30569        let server = MockWorkerServer::declined_registration();
30570        let client = Client::builder(server.base_url())
30571            .timeout(Duration::from_secs(2))
30572            .build()
30573            .expect("client");
30574        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
30575
30576        let error = worker
30577            .run_until(async {})
30578            .await
30579            .expect_err("declined registration must fail");
30580        assert!(matches!(error, Error::WorkerLoop(_)));
30581        assert!(error.to_string().contains("was not accepted"));
30582        assert!(server
30583            .captured_paths()
30584            .iter()
30585            .all(|path| !path.starts_with("/api/worker/registrations/")));
30586    }
30587
30588    #[tokio::test]
30589    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
30590        let server = MockWorkerServer::rejected_deregistration();
30591        let client = Client::builder(server.base_url())
30592            .timeout(Duration::from_secs(2))
30593            .build()
30594            .expect("client");
30595        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
30596
30597        let error = worker
30598            .run_until(async {})
30599            .await
30600            .expect_err("deregistration must fail");
30601        assert!(matches!(
30602            error,
30603            Error::Http {
30604                status: reqwest::StatusCode::FORBIDDEN,
30605                ..
30606            }
30607        ));
30608        assert_eq!(
30609            server.request_count("/api/worker/registrations/mock-worker"),
30610            1
30611        );
30612    }
30613
30614    #[tokio::test]
30615    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
30616        let server = MockWorkerServer::rejected_deregistration_protocol();
30617        let client = Client::builder(server.base_url())
30618            .timeout(Duration::from_secs(2))
30619            .build()
30620            .expect("client");
30621        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
30622
30623        let error = worker
30624            .run_until(async {})
30625            .await
30626            .expect_err("protocol rejection must fail shutdown");
30627        let Error::Protocol(failure) = error else {
30628            panic!("expected typed protocol failure");
30629        };
30630        assert_eq!(failure.reason, "unsupported_protocol_version");
30631        assert_eq!(
30632            failure.requested_version.as_deref(),
30633            Some(WORKER_PROTOCOL_VERSION)
30634        );
30635        assert_eq!(
30636            server.request_count("/api/worker/registrations/mock-worker"),
30637            1
30638        );
30639    }
30640
30641    #[tokio::test]
30642    async fn primary_poller_error_retains_deregistration_failure_context() {
30643        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
30644        let client = Client::builder(server.base_url())
30645            .timeout(Duration::from_secs(2))
30646            .build()
30647            .expect("client");
30648        let mut worker = Worker::new(client, "rust-workers")
30649            .worker_id("combined-failure")
30650            .poll_timeout(Duration::from_millis(10));
30651        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
30652            Ok(Value::Null)
30653        });
30654
30655        let error = worker
30656            .run()
30657            .await
30658            .expect_err("worker and cleanup must fail");
30659        let summary = error.to_string();
30660        assert!(summary.contains("authentication_failed"));
30661        assert!(summary.contains("worker cannot deregister"));
30662        let Error::WorkerShutdown {
30663            primary,
30664            deregistration,
30665        } = error
30666        else {
30667            panic!("expected combined worker shutdown error");
30668        };
30669        assert!(matches!(
30670            *primary,
30671            Error::Http {
30672                status: reqwest::StatusCode::UNAUTHORIZED,
30673                ..
30674            }
30675        ));
30676        assert!(matches!(
30677            *deregistration,
30678            Error::Http {
30679                status: reqwest::StatusCode::FORBIDDEN,
30680                ..
30681            }
30682        ));
30683        assert_eq!(
30684            server.request_count("/api/worker/registrations/mock-worker"),
30685            1
30686        );
30687    }
30688
30689    #[tokio::test]
30690    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
30691        let server = MockWorkerServer::start();
30692        let client = Client::builder(server.base_url())
30693            .timeout(Duration::from_secs(2))
30694            .build()
30695            .expect("client");
30696        let mut worker = Worker::new(client, "rust-workers")
30697            .worker_id("activity-only-worker")
30698            .poll_timeout(Duration::from_millis(10));
30699
30700        worker.register_activity(
30701            "activity.only",
30702            |_ctx, _args| async move { Ok(Value::Null) },
30703        );
30704
30705        worker.run_until(async {}).await.expect("run worker");
30706    }
30707
30708    #[tokio::test]
30709    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
30710        let server = MockWorkerServer::start();
30711        let client = Client::builder(server.base_url())
30712            .timeout(Duration::from_secs(2))
30713            .build()
30714            .expect("client");
30715        let mut worker = Worker::new(client, "rust-workers")
30716            .worker_id("workflow-only-worker")
30717            .poll_timeout(Duration::from_millis(10));
30718
30719        worker.register_workflow(
30720            "workflow.only",
30721            |_ctx, _input| async move { Ok(Value::Null) },
30722        );
30723
30724        worker.run_until(async {}).await.expect("run worker");
30725    }
30726
30727    #[tokio::test]
30728    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
30729        let server = MockWorkerServer::start();
30730        let client = Client::builder(server.base_url())
30731            .timeout(Duration::from_secs(2))
30732            .build()
30733            .expect("client");
30734        let observations = Arc::new(Mutex::new(Vec::new()));
30735        let observed = Arc::clone(&observations);
30736        let mut worker = Worker::new(client, "rust-workers")
30737            .worker_id("observed-heartbeat-worker")
30738            .poll_timeout(Duration::from_millis(10))
30739            .on_worker_heartbeat(move |observation| {
30740                observed
30741                    .lock()
30742                    .expect("heartbeat observations")
30743                    .push(observation.clone());
30744            });
30745
30746        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
30747            Ok(Value::Null)
30748        });
30749        let acknowledged = Arc::clone(&observations);
30750        worker
30751            .run_until(async move {
30752                tokio::time::timeout(Duration::from_secs(2), async move {
30753                    loop {
30754                        if !acknowledged
30755                            .lock()
30756                            .expect("heartbeat observations")
30757                            .is_empty()
30758                        {
30759                            break;
30760                        }
30761                        tokio::time::sleep(Duration::from_millis(1)).await;
30762                    }
30763                })
30764                .await
30765                .expect("heartbeat acknowledgement within timeout");
30766            })
30767            .await
30768            .expect("run worker");
30769
30770        let observations = observations.lock().expect("heartbeat observations");
30771        let first = observations.first().expect("heartbeat acknowledgement");
30772        assert_eq!(first.worker_id, "observed-heartbeat-worker");
30773        assert_eq!(first.task_queue, "rust-workers");
30774        assert!(first.acknowledged_at_unix_millis > 0);
30775        assert_eq!(first.acknowledgement, json!({}));
30776    }
30777
30778    #[tokio::test]
30779    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
30780        let server = MockWorkerServer::delayed_heartbeat_worker();
30781        let client = Client::builder(server.base_url())
30782            .timeout(Duration::from_secs(3))
30783            .build()
30784            .expect("client");
30785        let observations = Arc::new(Mutex::new(Vec::new()));
30786        let observed = Arc::clone(&observations);
30787        let mut worker = Worker::new(client, "rust-snapshot-workers")
30788            .max_concurrent_workflow_tasks(1)
30789            .max_concurrent_activity_tasks(1)
30790            .worker_id("rust-snapshot-worker")
30791            .poll_timeout(Duration::from_millis(10))
30792            .on_worker_heartbeat(move |observation| {
30793                observed
30794                    .lock()
30795                    .expect("heartbeat observations")
30796                    .push(observation.clone());
30797            });
30798
30799        worker.register_workflow("snapshot", |ctx, _input| async move {
30800            ctx.wait_signal("finish").await?;
30801            Ok(json!({"status": "finished"}))
30802        });
30803        worker.register_query("snapshot", "current", |ctx, _args| async move {
30804            Ok(json!(ctx
30805                .signals("increment")
30806                .iter()
30807                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
30808                .sum::<i64>()))
30809        });
30810        worker.register_activity("cancel-aware", |_ctx, _args| async move {
30811            Ok(json!({"late": "completion"}))
30812        });
30813
30814        worker
30815            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
30816            .await
30817            .expect("delayed heartbeat must allow a clean worker shutdown");
30818
30819        let observations = observations.lock().expect("heartbeat observations");
30820        assert!(
30821            observations.len() >= 3,
30822            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
30823        );
30824        assert!(
30825            observations.windows(2).all(|pair| {
30826                pair[1].acknowledged_at_unix_millis
30827                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
30828                    >= 850
30829            }),
30830            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
30831        );
30832        drop(observations);
30833
30834        let heartbeat_times = server.request_times("/api/worker/heartbeat");
30835        let delayed_request_at = *heartbeat_times
30836            .get(1)
30837            .expect("intentionally delayed heartbeat request");
30838        let delay_window_start = delayed_request_at + Duration::from_millis(100);
30839        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
30840        for path in [
30841            "/api/worker/workflow-tasks/poll",
30842            "/api/worker/activity-tasks/poll",
30843            "/api/worker/query-tasks/poll",
30844        ] {
30845            assert!(
30846                server
30847                    .request_times(path)
30848                    .iter()
30849                    .any(|received_at| *received_at >= delay_window_start
30850                        && *received_at <= delay_window_end),
30851                "{path} must keep polling while a heartbeat acknowledgement is delayed"
30852            );
30853        }
30854        assert!(
30855            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
30856            "workflow work must be settled"
30857        );
30858        assert!(
30859            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
30860            "activity work must be settled"
30861        );
30862        assert!(
30863            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
30864            "query work must be settled"
30865        );
30866    }
30867
30868    #[tokio::test]
30869    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
30870        let server = MockWorkerServer::heartbeat_retry_worker();
30871        let client = Client::builder(server.base_url())
30872            .timeout(Duration::from_secs(2))
30873            .build()
30874            .expect("client");
30875        let observations = Arc::new(Mutex::new(Vec::new()));
30876        let observed = Arc::clone(&observations);
30877        let worker = Worker::new(client, "rust-workers")
30878            .worker_id("heartbeat-retry-worker")
30879            .retry_policy(WorkerRetryPolicy {
30880                max_retries: 1,
30881                initial_backoff: Duration::from_millis(300),
30882                max_backoff: Duration::from_millis(300),
30883            })
30884            .on_worker_heartbeat(move |observation| {
30885                observed
30886                    .lock()
30887                    .expect("heartbeat observations")
30888                    .push(observation.clone());
30889            });
30890
30891        worker
30892            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
30893            .await
30894            .expect("retryable heartbeat failure must remain bounded and recover");
30895
30896        let observations = observations.lock().expect("heartbeat observations");
30897        assert!(observations.len() >= 3, "heartbeat retry must recover");
30898        assert!(
30899            observations.windows(2).all(|pair| {
30900                pair[1]
30901                    .acknowledged_at_unix_millis
30902                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
30903                    >= 850
30904            }),
30905            "a successful retry must start a fresh advertised cadence: {observations:?}"
30906        );
30907        assert_eq!(
30908            server.request_count("/api/worker/heartbeat"),
30909            observations.len() + 1,
30910            "one retryable failure must add exactly one bounded request"
30911        );
30912    }
30913
30914    #[tokio::test]
30915    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
30916        let server = MockWorkerServer::waiting_query_worker();
30917        let client = Client::builder(server.base_url())
30918            .timeout(Duration::from_secs(2))
30919            .build()
30920            .expect("client");
30921        let observations = Arc::new(Mutex::new(Vec::new()));
30922        let observed = Arc::clone(&observations);
30923        let mut worker = Worker::new(client, "rust-snapshot-workers")
30924            .worker_id("rust-snapshot-worker")
30925            .poll_timeout(Duration::from_millis(10))
30926            .on_worker_heartbeat(move |observation| {
30927                observed
30928                    .lock()
30929                    .expect("heartbeat observations")
30930                    .push(observation.clone());
30931            });
30932
30933        worker.register_workflow("snapshot", |ctx, _input| async move {
30934            ctx.wait_signal("finish").await?;
30935            Ok(json!({"status": "finished"}))
30936        });
30937        worker.register_query("snapshot", "current", |ctx, _args| async move {
30938            let current = ctx
30939                .signals("increment")
30940                .iter()
30941                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
30942                .sum::<i64>();
30943            Ok(json!(current))
30944        });
30945        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
30946        worker
30947            .declare_workflow_signals("snapshot", &["finish"])
30948            .expect("declare finish signal");
30949
30950        worker
30951            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
30952            .await
30953            .expect("pending workflow and query poller must remain live until shutdown");
30954
30955        assert!(
30956            observations.lock().expect("heartbeat observations").len() >= 4,
30957            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
30958        );
30959        assert!(
30960            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
30961            "workflow polling must continue after empty replay acknowledgements"
30962        );
30963        assert!(
30964            server.request_count("/api/worker/query-tasks/poll") >= 2,
30965            "query polling must continue after serving the current query"
30966        );
30967        assert_eq!(
30968            server.request_body("/api/worker/register")["capabilities"],
30969            json!([
30970                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
30971                "workflow_entry_arguments_validation",
30972                DURABLE_SELECTION_CAPABILITY,
30973                MEMO_UPSERTS_CAPABILITY,
30974                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
30975                QUERY_TASKS_CAPABILITY,
30976                WORKFLOW_UPDATES_CAPABILITY,
30977                MESSAGE_STREAMS_CAPABILITY
30978            ])
30979        );
30980        assert_eq!(
30981            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
30982            json!({
30983                "queries": ["current"],
30984                "query_contracts": [{
30985                    "name": "current",
30986                    "parameters": [{
30987                        "name": "args", "position": 0, "required": false,
30988                        "variadic": true, "type": null, "allows_null": true,
30989                        "default_available": false, "default": null,
30990                    }],
30991                }],
30992                "signals": ["finish"],
30993                "signal_contracts": [{
30994                    "name": "finish",
30995                    "parameters": [{
30996                        "name": "args", "position": 0, "required": false,
30997                        "variadic": true, "type": null, "allows_null": true,
30998                        "default_available": false, "default": null,
30999                    }],
31000                }],
31001                "updates": ["replace"],
31002                "update_contracts": [{
31003                    "name": "replace",
31004                    "parameters": [{
31005                        "name": "args", "position": 0, "required": false,
31006                        "variadic": true, "type": null, "allows_null": true,
31007                        "default_available": false, "default": null,
31008                    }],
31009                }],
31010                "update_validators": [],
31011            })
31012        );
31013
31014        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
31015        assert_eq!(
31016            opened["commands"],
31017            json!([{
31018                "type": "open_signal_wait",
31019                "signal_name": "finish",
31020            }])
31021        );
31022
31023        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
31024            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
31025            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
31026            let failure = server.request_body(&fail_path);
31027            assert_eq!(
31028                failure["failure"]["type"],
31029                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
31030            );
31031            assert_eq!(server.request_count(&completion_path), 0);
31032        }
31033
31034        let query_completion =
31035            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
31036        assert_eq!(query_completion["result"], json!(8));
31037
31038        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
31039        assert_eq!(
31040            server.request_count(terminal_path),
31041            1,
31042            "the matching signal must settle the workflow exactly once"
31043        );
31044        let terminal = server.request_body(terminal_path);
31045        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
31046        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
31047        assert_eq!(
31048            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
31049                .expect("terminal workflow result"),
31050            json!({"status": "finished"})
31051        );
31052    }
31053
31054    #[tokio::test]
31055    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
31056        let server = MockWorkerServer::transient_worker_failures();
31057        let client = Client::builder(server.base_url())
31058            .timeout(Duration::from_secs(2))
31059            .build()
31060            .expect("client");
31061        let mut worker = Worker::new(client, "rust-workers")
31062            .max_concurrent_workflow_tasks(1)
31063            .max_concurrent_activity_tasks(1)
31064            .worker_id("retry-worker")
31065            .poll_timeout(Duration::from_millis(10))
31066            .retry_policy(WorkerRetryPolicy {
31067                max_retries: 2,
31068                initial_backoff: Duration::from_millis(1),
31069                max_backoff: Duration::from_millis(1),
31070            });
31071        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31072        worker.register_activity(
31073            "counter.activity",
31074            |_ctx, _input| async move { Ok(Value::Null) },
31075        );
31076        worker.register_query(
31077            "counter",
31078            "current",
31079            |_ctx, _args| async move { Ok(json!(8)) },
31080        );
31081
31082        worker
31083            .run_until(tokio::time::sleep(Duration::from_millis(75)))
31084            .await
31085            .expect("transient failures must not stop the worker");
31086
31087        for path in [
31088            "/api/worker/heartbeat",
31089            "/api/worker/workflow-tasks/poll",
31090            "/api/worker/activity-tasks/poll",
31091            "/api/worker/query-tasks/poll",
31092        ] {
31093            assert!(
31094                server.request_count(path) >= 2,
31095                "{path} must continue after its transient failure"
31096            );
31097        }
31098    }
31099
31100    #[tokio::test]
31101    async fn worker_continues_after_long_poll_capacity_backpressure() {
31102        let server = MockWorkerServer::capacity_limited_activity_poll();
31103        let client = Client::builder(server.base_url())
31104            .timeout(Duration::from_secs(2))
31105            .build()
31106            .expect("client");
31107        let mut worker = Worker::new(client, "rust-workers")
31108            .worker_id("capacity-worker")
31109            .poll_timeout(Duration::from_millis(10))
31110            .retry_policy(WorkerRetryPolicy {
31111                max_retries: 0,
31112                initial_backoff: Duration::from_millis(1),
31113                max_backoff: Duration::from_millis(1),
31114            });
31115        worker.register_activity("capacity.activity", |_ctx, _input| async move {
31116            Ok(json!({"handled": true}))
31117        });
31118
31119        worker
31120            .run_until(tokio::time::sleep(Duration::from_millis(50)))
31121            .await
31122            .expect("capacity backpressure must not stop the worker");
31123
31124        assert!(
31125            server.request_count("/api/worker/activity-tasks/poll") >= 2,
31126            "the activity poller must continue after capacity backpressure"
31127        );
31128        assert_eq!(
31129            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
31130            1,
31131            "the worker must complete work returned after capacity recovers"
31132        );
31133    }
31134
31135    #[test]
31136    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
31137        let capacity = Error::Http {
31138            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31139            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
31140        };
31141        assert_eq!(
31142            worker_poll_capacity_retry_after(&capacity),
31143            Some(Duration::from_secs(3))
31144        );
31145
31146        let rejected_capacity = Error::Http {
31147            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31148            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
31149        };
31150        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
31151        assert!(!worker_operation_is_retryable(&rejected_capacity));
31152
31153        let ordinary_rate_limit = Error::Http {
31154            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
31155            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
31156                .to_string(),
31157        };
31158        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
31159        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
31160    }
31161
31162    #[tokio::test]
31163    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
31164        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31165            poll_failures_per_path: 8,
31166            heartbeat_failures: 8,
31167            ..MockWorkerBehavior::default()
31168        });
31169        let client = Client::builder(server.base_url())
31170            .timeout(Duration::from_secs(2))
31171            .build()
31172            .expect("client");
31173        let acknowledgements = Arc::new(AtomicUsize::new(0));
31174        let observed = Arc::clone(&acknowledgements);
31175        let mut worker = Worker::new(client, "rust-workers")
31176            .max_concurrent_workflow_tasks(1)
31177            .max_concurrent_activity_tasks(1)
31178            .recover_transient_outages(true)
31179            .poll_timeout(Duration::from_millis(10))
31180            .retry_policy(WorkerRetryPolicy {
31181                max_retries: 2,
31182                initial_backoff: Duration::from_millis(2),
31183                max_backoff: Duration::from_millis(5),
31184            })
31185            .on_worker_heartbeat(move |_| {
31186                observed.fetch_add(1, Ordering::SeqCst);
31187            });
31188        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31189        worker.register_activity(
31190            "counter.activity",
31191            |_ctx, _input| async move { Ok(Value::Null) },
31192        );
31193        worker.register_query("counter", "current", |_ctx, _args| async move {
31194            Ok(Value::Null)
31195        });
31196
31197        worker
31198            .run_until(tokio::time::sleep(Duration::from_millis(500)))
31199            .await
31200            .expect("a recoverable outage must not stop the service worker");
31201
31202        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
31203        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
31204        for path in [
31205            "/api/worker/workflow-tasks/poll",
31206            "/api/worker/activity-tasks/poll",
31207            "/api/worker/query-tasks/poll",
31208        ] {
31209            let bodies = server.request_bodies(path);
31210            assert!(bodies.len() >= 10, "{path} must resume after recovery");
31211            let first = &bodies[0]["poll_request_id"];
31212            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
31213            for body in &bodies[..9] {
31214                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
31215            }
31216            assert_ne!(&bodies[9]["poll_request_id"], first);
31217            let times = server.request_times(path);
31218            for pair in times[..9].windows(2) {
31219                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
31220            }
31221        }
31222    }
31223
31224    #[tokio::test]
31225    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
31226        for heartbeat_outage in [false, true] {
31227            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31228                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
31229                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
31230                ..MockWorkerBehavior::default()
31231            });
31232            let client = Client::builder(server.base_url()).build().expect("client");
31233            let mut worker = Worker::new(client, "rust-workers")
31234                .max_concurrent_workflow_tasks(1)
31235                .max_concurrent_activity_tasks(1)
31236                .recover_transient_outages(true)
31237                .retry_policy(WorkerRetryPolicy {
31238                    max_retries: 1,
31239                    initial_backoff: Duration::from_secs(5),
31240                    max_backoff: Duration::from_secs(5),
31241                });
31242            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31243            let started = Instant::now();
31244            worker
31245                .run_until(tokio::time::sleep(Duration::from_millis(200)))
31246                .await
31247                .expect("shutdown during an outage is a normal stop");
31248            assert!(started.elapsed() < Duration::from_secs(1));
31249            let path = if heartbeat_outage {
31250                "/api/worker/heartbeat"
31251            } else {
31252                "/api/worker/workflow-tasks/poll"
31253            };
31254            assert_eq!(server.request_count(path), 1);
31255            assert_eq!(
31256                server.request_count("/api/worker/registrations/mock-worker"),
31257                1
31258            );
31259        }
31260    }
31261
31262    #[tokio::test]
31263    async fn worker_outage_recovery_keeps_run_once_bounded() {
31264        let server = MockWorkerServer::unavailable_polls();
31265        let client = Client::builder(server.base_url()).build().expect("client");
31266        let mut worker = Worker::new(client, "rust-workers")
31267            .recover_transient_outages(true)
31268            .retry_policy(WorkerRetryPolicy {
31269                max_retries: 2,
31270                initial_backoff: Duration::from_millis(1),
31271                max_backoff: Duration::from_millis(1),
31272            });
31273        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31274        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
31275        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
31276    }
31277
31278    #[tokio::test]
31279    async fn worker_outage_recovery_respects_disabled_retries() {
31280        let server = MockWorkerServer::unavailable_polls();
31281        let client = Client::builder(server.base_url()).build().expect("client");
31282        let mut worker = Worker::new(client, "rust-workers")
31283            .max_concurrent_workflow_tasks(1)
31284            .max_concurrent_activity_tasks(1)
31285            .recover_transient_outages(true)
31286            .retry_policy(WorkerRetryPolicy {
31287                max_retries: 0,
31288                ..WorkerRetryPolicy::default()
31289            });
31290        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31291        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
31292        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
31293    }
31294
31295    #[tokio::test]
31296    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
31297        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31298            heartbeat_failures: usize::MAX,
31299            unauthorized_polls: true,
31300            ..MockWorkerBehavior::default()
31301        });
31302        let client = Client::builder(server.base_url()).build().expect("client");
31303        let mut worker = Worker::new(client, "rust-workers")
31304            .max_concurrent_workflow_tasks(1)
31305            .max_concurrent_activity_tasks(1)
31306            .recover_transient_outages(true)
31307            .retry_policy(WorkerRetryPolicy {
31308                max_retries: 1,
31309                initial_backoff: Duration::from_secs(5),
31310                max_backoff: Duration::from_secs(5),
31311            });
31312        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31313        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
31314            .await
31315            .expect("fatal poll errors must interrupt heartbeat recovery")
31316            .expect_err("authentication failure is terminal");
31317        assert!(
31318            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
31319        );
31320        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
31321    }
31322
31323    #[tokio::test]
31324    async fn worker_bounds_transport_retries() {
31325        let server = MockWorkerServer::unavailable_polls();
31326        let client = Client::builder(server.base_url())
31327            .timeout(Duration::from_secs(2))
31328            .build()
31329            .expect("client");
31330        let mut worker = Worker::new(client, "rust-workers")
31331            .max_concurrent_workflow_tasks(1)
31332            .max_concurrent_activity_tasks(1)
31333            .worker_id("bounded-retry-worker")
31334            .poll_timeout(Duration::from_millis(10))
31335            .retry_policy(WorkerRetryPolicy {
31336                max_retries: 2,
31337                initial_backoff: Duration::from_millis(1),
31338                max_backoff: Duration::from_millis(1),
31339            });
31340        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31341
31342        let error = worker.run().await.expect_err("retry bound must terminate");
31343        assert!(matches!(error, Error::Transport(_)));
31344        assert_eq!(
31345            server.request_count("/api/worker/workflow-tasks/poll"),
31346            3,
31347            "one initial request plus exactly two retries"
31348        );
31349    }
31350
31351    #[tokio::test]
31352    async fn worker_retry_policy_can_disable_poll_retries() {
31353        let server = MockWorkerServer::unavailable_polls();
31354        let client = Client::builder(server.base_url())
31355            .timeout(Duration::from_secs(2))
31356            .build()
31357            .expect("client");
31358        let mut worker = Worker::new(client, "rust-workers")
31359            .worker_id("no-retry-worker")
31360            .poll_timeout(Duration::from_millis(10))
31361            .retry_policy(WorkerRetryPolicy {
31362                max_retries: 0,
31363                initial_backoff: Duration::from_millis(1),
31364                max_backoff: Duration::from_millis(1),
31365            });
31366        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31367
31368        let error = worker
31369            .run_once()
31370            .await
31371            .expect_err("disabled retries must return the first transport failure");
31372        assert!(matches!(error, Error::Transport(_)));
31373        assert_eq!(
31374            server.request_count("/api/worker/workflow-tasks/poll"),
31375            1,
31376            "max_retries=0 must send only the initial request"
31377        );
31378    }
31379
31380    #[tokio::test]
31381    async fn worker_does_not_retry_authentication_failures() {
31382        let server = MockWorkerServer::unauthorized_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            .max_concurrent_workflow_tasks(1)
31389            .max_concurrent_activity_tasks(1)
31390            .worker_id("unauthorized-worker")
31391            .recover_transient_outages(true)
31392            .poll_timeout(Duration::from_millis(10));
31393        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
31394
31395        let error = worker
31396            .run()
31397            .await
31398            .expect_err("authentication must terminate");
31399        let Error::Http { status, body } = error else {
31400            panic!("expected stable HTTP authentication error");
31401        };
31402        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
31403        assert!(body.contains("authentication_failed"));
31404        assert_eq!(
31405            server.request_count("/api/worker/workflow-tasks/poll"),
31406            1,
31407            "authentication failures must not be retried"
31408        );
31409    }
31410
31411    #[test]
31412    fn duplicate_registration_keeps_the_original_workflow() {
31413        let client = Client::new("http://127.0.0.1:9").expect("client");
31414        let mut worker = Worker::new(client, "registration-tests");
31415        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
31416        let original = Arc::clone(&worker.workflows["same"].execute);
31417        worker
31418            .set_workflow_definition_sources("same", &["first workflow source"])
31419            .expect("source identity");
31420        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
31421        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
31422        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
31423        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
31424    }
31425
31426    #[test]
31427    fn duplicate_registration_keeps_the_original_activity() {
31428        let client = Client::new("http://127.0.0.1:9").expect("client");
31429        let mut worker = Worker::new(client, "registration-tests");
31430        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
31431        let original = Arc::clone(&worker.activities["same"]);
31432        worker.register_activity_avro_value("same", |_ctx, _input| async {
31433            Ok(AvroValue::String("second".into()))
31434        });
31435        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
31436    }
31437
31438    #[test]
31439    fn duplicate_registration_keeps_original_query_and_update_handlers() {
31440        let client = Client::new("http://127.0.0.1:9").expect("client");
31441        let mut worker = Worker::new(client, "registration-tests");
31442        worker.register_query("orders", "same", |_ctx, _input| async {
31443            Ok(json!("first"))
31444        });
31445        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
31446            panic!("snapshot query");
31447        };
31448        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
31449            Ok(json!("second"))
31450        });
31451        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
31452            panic!("duplicate replaced the query adapter");
31453        };
31454        assert!(Arc::ptr_eq(&original, retained));
31455        worker.register_update("orders", "same", |_ctx, _input| async {
31456            Ok(json!("first"))
31457        });
31458        let original = Arc::clone(&worker.updates["orders"]["same"]);
31459        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
31460            Ok(AvroValue::Null)
31461        });
31462        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
31463    }
31464
31465    #[tokio::test]
31466    async fn duplicate_registration_fails_before_server_contact() {
31467        let server = MockWorkerServer::start();
31468        let client = Client::builder(server.base_url()).build().expect("client");
31469        let mut worker =
31470            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
31471        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
31472        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
31473        let error = worker
31474            .run_once()
31475            .await
31476            .expect_err("ambiguous worker must not poll");
31477        assert!(
31478            error.to_string().contains("duplicate_registration"),
31479            "{error}"
31480        );
31481        assert!(server.requests.lock().expect("requests").is_empty());
31482    }
31483
31484    #[derive(Clone, Debug)]
31485    struct CapturedRequest {
31486        headers: String,
31487        method: String,
31488        path: String,
31489        authorization: Option<String>,
31490        namespace: Option<String>,
31491        worker_protocol: Option<String>,
31492        control_protocol: Option<String>,
31493        body: String,
31494        received_at: Instant,
31495    }
31496
31497    struct MockWorkerServer {
31498        addr: SocketAddr,
31499        stop: Arc<AtomicBool>,
31500        requests: Arc<Mutex<Vec<CapturedRequest>>>,
31501        thread: Option<thread::JoinHandle<()>>,
31502    }
31503
31504    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
31505
31506    #[derive(Clone, Copy, Default)]
31507    struct MockWorkerBehavior {
31508        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
31509        request_override: Option<RequestOverride>,
31510        /// Close the connection after reading the request, without any response.
31511        drop_request: Option<fn(&str, usize) -> bool>,
31512        storage_refusals: usize,
31513        storage_path: Option<&'static str>,
31514        storage_unavailable: bool,
31515        storage_mid_poll: bool,
31516        storage_activity: bool,
31517        storage_query: bool,
31518        storage_wrong_poll_id: bool,
31519        reject_query_protocol: bool,
31520        reject_query_completion: bool,
31521        waiting_query_worker: bool,
31522        decline_registration: bool,
31523        complete_named_signal: bool,
31524        poll_failures_per_path: usize,
31525        long_poll_capacity_responses_per_path: usize,
31526        heartbeat_failures: usize,
31527        heartbeat_failure_request: Option<usize>,
31528        delayed_heartbeat_request: Option<usize>,
31529        heartbeat_response_delay: Duration,
31530        concurrent_requests: bool,
31531        unauthorized_polls: bool,
31532        reject_registration: bool,
31533        reject_registration_protocol: bool,
31534        reject_deregistration: bool,
31535        reject_deregistration_protocol: bool,
31536        cancelled_activity: bool,
31537        draining_polls: bool,
31538        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
31539        workflow_completion_status: Option<&'static str>,
31540        workflow_completion_body: Option<&'static str>,
31541    }
31542
31543    impl MockWorkerServer {
31544        fn start() -> Self {
31545            Self::start_with_behavior(MockWorkerBehavior::default())
31546        }
31547
31548        fn reject_query_protocol() -> Self {
31549            Self::start_with_behavior(MockWorkerBehavior {
31550                reject_query_protocol: true,
31551                ..MockWorkerBehavior::default()
31552            })
31553        }
31554
31555        fn reject_query_completion() -> Self {
31556            Self::start_with_behavior(MockWorkerBehavior {
31557                reject_query_completion: true,
31558                ..MockWorkerBehavior::default()
31559            })
31560        }
31561
31562        fn waiting_query_worker() -> Self {
31563            Self::start_with_behavior(MockWorkerBehavior {
31564                waiting_query_worker: true,
31565                complete_named_signal: true,
31566                ..MockWorkerBehavior::default()
31567            })
31568        }
31569
31570        fn transient_worker_failures() -> Self {
31571            Self::start_with_behavior(MockWorkerBehavior {
31572                poll_failures_per_path: 1,
31573                heartbeat_failures: 1,
31574                ..MockWorkerBehavior::default()
31575            })
31576        }
31577
31578        fn consecutive_poll_failures(count: usize) -> Self {
31579            Self::start_with_behavior(MockWorkerBehavior {
31580                poll_failures_per_path: count,
31581                ..MockWorkerBehavior::default()
31582            })
31583        }
31584
31585        fn capacity_limited_activity_poll() -> Self {
31586            Self::start_with_behavior(MockWorkerBehavior {
31587                long_poll_capacity_responses_per_path: 1,
31588                ..MockWorkerBehavior::default()
31589            })
31590        }
31591
31592        fn delayed_heartbeat_worker() -> Self {
31593            Self::start_with_behavior(MockWorkerBehavior {
31594                waiting_query_worker: true,
31595                delayed_heartbeat_request: Some(2),
31596                heartbeat_response_delay: Duration::from_millis(1_500),
31597                concurrent_requests: true,
31598                cancelled_activity: true,
31599                ..MockWorkerBehavior::default()
31600            })
31601        }
31602
31603        fn heartbeat_retry_worker() -> Self {
31604            Self::start_with_behavior(MockWorkerBehavior {
31605                waiting_query_worker: true,
31606                heartbeat_failure_request: Some(2),
31607                concurrent_requests: true,
31608                ..MockWorkerBehavior::default()
31609            })
31610        }
31611
31612        fn unavailable_polls() -> Self {
31613            Self::start_with_behavior(MockWorkerBehavior {
31614                poll_failures_per_path: usize::MAX,
31615                ..MockWorkerBehavior::default()
31616            })
31617        }
31618
31619        fn unauthorized_polls() -> Self {
31620            Self::start_with_behavior(MockWorkerBehavior {
31621                unauthorized_polls: true,
31622                ..MockWorkerBehavior::default()
31623            })
31624        }
31625
31626        fn rejected_registration() -> Self {
31627            Self::start_with_behavior(MockWorkerBehavior {
31628                reject_registration: true,
31629                ..MockWorkerBehavior::default()
31630            })
31631        }
31632
31633        fn rejected_registration_protocol() -> Self {
31634            Self::start_with_behavior(MockWorkerBehavior {
31635                reject_registration_protocol: true,
31636                ..MockWorkerBehavior::default()
31637            })
31638        }
31639
31640        fn declined_registration() -> Self {
31641            Self::start_with_behavior(MockWorkerBehavior {
31642                decline_registration: true,
31643                ..MockWorkerBehavior::default()
31644            })
31645        }
31646
31647        fn rejected_deregistration() -> Self {
31648            Self::start_with_behavior(MockWorkerBehavior {
31649                reject_deregistration: true,
31650                ..MockWorkerBehavior::default()
31651            })
31652        }
31653
31654        fn rejected_deregistration_protocol() -> Self {
31655            Self::start_with_behavior(MockWorkerBehavior {
31656                reject_deregistration_protocol: true,
31657                ..MockWorkerBehavior::default()
31658            })
31659        }
31660
31661        fn unauthorized_polls_and_rejected_deregistration() -> Self {
31662            Self::start_with_behavior(MockWorkerBehavior {
31663                unauthorized_polls: true,
31664                reject_deregistration: true,
31665                ..MockWorkerBehavior::default()
31666            })
31667        }
31668
31669        fn cancelled_activity() -> Self {
31670            Self::start_with_behavior(MockWorkerBehavior {
31671                cancelled_activity: true,
31672                ..MockWorkerBehavior::default()
31673            })
31674        }
31675
31676        fn draining_polls() -> Self {
31677            Self::start_with_behavior(MockWorkerBehavior {
31678                draining_polls: true,
31679                ..MockWorkerBehavior::default()
31680            })
31681        }
31682
31683        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
31684            Self::start_with_behavior(MockWorkerBehavior {
31685                invalid_task_payload_codec: Some(codec),
31686                ..MockWorkerBehavior::default()
31687            })
31688        }
31689
31690        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
31691            Self::start_with_behavior(MockWorkerBehavior {
31692                workflow_completion_status: Some(status),
31693                workflow_completion_body: Some(body),
31694                ..MockWorkerBehavior::default()
31695            })
31696        }
31697
31698        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
31699            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
31700            listener
31701                .set_nonblocking(true)
31702                .expect("configure mock listener");
31703            let addr = listener.local_addr().expect("mock server address");
31704            let stop = Arc::new(AtomicBool::new(false));
31705            let server_stop = Arc::clone(&stop);
31706            let requests = Arc::new(Mutex::new(Vec::new()));
31707            let server_requests = Arc::clone(&requests);
31708            let thread = thread::spawn(move || {
31709                let mut request_threads = Vec::new();
31710                while !server_stop.load(Ordering::SeqCst) {
31711                    match listener.accept() {
31712                        Ok((mut stream, _)) => {
31713                            if behavior.concurrent_requests {
31714                                let requests = Arc::clone(&server_requests);
31715                                request_threads.push(thread::spawn(move || {
31716                                    handle_mock_worker_request(&mut stream, &requests, behavior)
31717                                }));
31718                            } else {
31719                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
31720                            }
31721                        }
31722                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
31723                            let mut index = 0;
31724                            while index < request_threads.len() {
31725                                if request_threads[index].is_finished() {
31726                                    request_threads
31727                                        .swap_remove(index)
31728                                        .join()
31729                                        .expect("join mock request");
31730                                } else {
31731                                    index += 1;
31732                                }
31733                            }
31734                            thread::sleep(Duration::from_millis(5));
31735                        }
31736                        Err(_) => break,
31737                    }
31738                }
31739                for request_thread in request_threads {
31740                    request_thread.join().expect("join mock request");
31741                }
31742            });
31743
31744            Self {
31745                addr,
31746                stop,
31747                requests,
31748                thread: Some(thread),
31749            }
31750        }
31751
31752        fn base_url(&self) -> String {
31753            format!("http://{}", self.addr)
31754        }
31755
31756        fn worker_protocol_for(&self, path: &str) -> Option<String> {
31757            self.requests
31758                .lock()
31759                .expect("captured requests")
31760                .iter()
31761                .find(|request| request.path == path)
31762                .and_then(|request| request.worker_protocol.clone())
31763        }
31764
31765        fn control_protocol_for(&self, path: &str) -> Option<String> {
31766            self.requests
31767                .lock()
31768                .expect("captured requests")
31769                .iter()
31770                .find(|request| request.path == path)
31771                .and_then(|request| request.control_protocol.clone())
31772        }
31773
31774        fn method_for(&self, path: &str) -> Option<String> {
31775            self.requests
31776                .lock()
31777                .expect("captured requests")
31778                .iter()
31779                .find(|request| request.path == path)
31780                .map(|request| request.method.clone())
31781        }
31782
31783        fn authorization_for(&self, path: &str) -> Option<String> {
31784            self.requests
31785                .lock()
31786                .expect("captured requests")
31787                .iter()
31788                .find(|request| request.path == path)
31789                .and_then(|request| request.authorization.clone())
31790        }
31791
31792        fn namespace_for(&self, path: &str) -> Option<String> {
31793            self.requests
31794                .lock()
31795                .expect("captured requests")
31796                .iter()
31797                .find(|request| request.path == path)
31798                .and_then(|request| request.namespace.clone())
31799        }
31800
31801        fn request_count(&self, path: &str) -> usize {
31802            self.requests
31803                .lock()
31804                .expect("captured requests")
31805                .iter()
31806                .filter(|request| request.path == path)
31807                .count()
31808        }
31809
31810        fn captured_paths(&self) -> Vec<String> {
31811            self.requests
31812                .lock()
31813                .expect("captured requests")
31814                .iter()
31815                .map(|request| request.path.clone())
31816                .collect()
31817        }
31818
31819        fn request_times(&self, path: &str) -> Vec<Instant> {
31820            self.requests
31821                .lock()
31822                .expect("captured requests")
31823                .iter()
31824                .filter(|request| request.path == path)
31825                .map(|request| request.received_at)
31826                .collect()
31827        }
31828
31829        fn request_body(&self, path: &str) -> Value {
31830            let requests = self.requests.lock().expect("captured requests");
31831            let body = &requests
31832                .iter()
31833                .find(|request| request.path == path)
31834                .unwrap_or_else(|| panic!("missing request for {path}"))
31835                .body;
31836            serde_json::from_str(body).unwrap_or_else(|error| {
31837                panic!("invalid JSON request body for {path}: {error}: {body:?}")
31838            })
31839        }
31840
31841        fn request_bodies(&self, path: &str) -> Vec<Value> {
31842            self.requests
31843                .lock()
31844                .expect("captured requests")
31845                .iter()
31846                .filter(|request| request.path == path)
31847                .map(|request| {
31848                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
31849                        panic!(
31850                            "invalid JSON request body for {path}: {error}: {:?}",
31851                            request.body
31852                        )
31853                    })
31854                })
31855                .collect()
31856        }
31857
31858        fn request_headers(&self, path: &str) -> Vec<String> {
31859            self.requests
31860                .lock()
31861                .expect("captured requests")
31862                .iter()
31863                .filter(|request| request.path == path)
31864                .map(|request| request.headers.clone())
31865                .collect()
31866        }
31867    }
31868
31869    impl Drop for MockWorkerServer {
31870        fn drop(&mut self) {
31871            self.stop.store(true, Ordering::SeqCst);
31872            let _ = TcpStream::connect(self.addr);
31873
31874            if let Some(thread) = self.thread.take() {
31875                thread.join().expect("join mock server");
31876            }
31877        }
31878    }
31879
31880    #[test]
31881    fn closed_mock_connection_is_not_a_worker_request() {
31882        let listener = TcpListener::bind("127.0.0.1:0").expect("bind closed connection control");
31883        let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
31884        let (mut stream, _) = listener.accept().unwrap();
31885        drop(client);
31886        let requests = Arc::new(Mutex::new(Vec::new()));
31887        handle_mock_worker_request(
31888            &mut stream,
31889            &requests,
31890            MockWorkerBehavior {
31891                request_override: Some(|_, _, _| {
31892                    panic!("closed connection cannot invoke an HTTP handler")
31893                }),
31894                ..MockWorkerBehavior::default()
31895            },
31896        );
31897        assert!(requests.lock().unwrap().is_empty());
31898    }
31899
31900    fn handle_mock_worker_request(
31901        stream: &mut TcpStream,
31902        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
31903        behavior: MockWorkerBehavior,
31904    ) {
31905        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
31906        let mut buffer = [0_u8; 8192];
31907        let mut request = Vec::new();
31908
31909        loop {
31910            match stream.read(&mut buffer) {
31911                Ok(0) => break,
31912                Ok(read) => {
31913                    request.extend_from_slice(&buffer[..read]);
31914                    if mock_request_is_complete(&request) {
31915                        break;
31916                    }
31917                }
31918                Err(error)
31919                    if matches!(
31920                        error.kind(),
31921                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
31922                    ) =>
31923                {
31924                    break;
31925                }
31926                Err(_) => return,
31927            }
31928        }
31929
31930        if !mock_request_is_complete(&request) {
31931            return;
31932        }
31933
31934        let request = String::from_utf8_lossy(&request);
31935        let body = request
31936            .split_once("\r\n\r\n")
31937            .map(|(_, body)| body)
31938            .unwrap_or_default();
31939        let path = request
31940            .lines()
31941            .next()
31942            .and_then(|line| line.split_whitespace().nth(1))
31943            .unwrap_or_default();
31944        let method = request
31945            .lines()
31946            .next()
31947            .and_then(|line| line.split_whitespace().next())
31948            .unwrap_or_default();
31949        let authorization = request.lines().find_map(|line| {
31950            let (name, value) = line.split_once(':')?;
31951            name.eq_ignore_ascii_case("Authorization")
31952                .then(|| value.trim().to_string())
31953        });
31954        let namespace = request.lines().find_map(|line| {
31955            let (name, value) = line.split_once(':')?;
31956            name.eq_ignore_ascii_case("X-Namespace")
31957                .then(|| value.trim().to_string())
31958        });
31959        let worker_protocol = request.lines().find_map(|line| {
31960            let (name, value) = line.split_once(':')?;
31961            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
31962                .then(|| value.trim().to_string())
31963        });
31964        let control_protocol = request.lines().find_map(|line| {
31965            let (name, value) = line.split_once(':')?;
31966            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
31967                .then(|| value.trim().to_string())
31968        });
31969        let request_number = {
31970            let mut requests = requests.lock().expect("captured requests");
31971            requests.push(CapturedRequest {
31972                headers: request
31973                    .split_once("\r\n\r\n")
31974                    .map_or("", |(headers, _)| headers)
31975                    .to_owned(),
31976                method: method.to_string(),
31977                path: path.to_string(),
31978                authorization,
31979                namespace,
31980                worker_protocol: worker_protocol.clone(),
31981                control_protocol,
31982                body: body.to_string(),
31983                received_at: Instant::now(),
31984            });
31985            requests
31986                .iter()
31987                .filter(|request| request.path == path)
31988                .count()
31989        };
31990
31991        if behavior
31992            .drop_request
31993            .is_some_and(|dropped| dropped(path, request_number))
31994        {
31995            return;
31996        }
31997        if let Some(response) = behavior
31998            .request_override
31999            .and_then(|handler| handler(path, body, request_number))
32000        {
32001            write_mock_response(stream, response.0, &response.1);
32002            return;
32003        }
32004        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
32005            write_mock_response(stream, response.0, &response.1);
32006            return;
32007        }
32008        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
32009            return;
32010        }
32011        let pressure_path = behavior
32012            .storage_path
32013            .is_some_and(|part| path.contains(part));
32014        let prior_failures = if path.ends_with("/poll") {
32015            behavior.poll_failures_per_path
32016        } else {
32017            0
32018        };
32019        if pressure_path
32020            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
32021        {
32022            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
32023            let poll_id = path
32024                .ends_with("/poll")
32025                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
32026            let mut refusal = storage_refusal(
32027                poll_id,
32028                behavior.storage_unavailable,
32029                behavior.storage_mid_poll,
32030            );
32031            if behavior.storage_wrong_poll_id {
32032                refusal["poll_request_id"] = json!("wrong-poll");
32033            }
32034            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
32035            return;
32036        }
32037        if path.contains("/storage-task/")
32038            || path.contains("/storage-activity/")
32039            || path.contains("/storage-query/")
32040        {
32041            write_mock_response(stream, "200 OK", "{}");
32042            return;
32043        }
32044        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
32045            write_mock_response(stream, "200 OK", &json!({"task":{
32046                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
32047                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
32048                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32049                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32050                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
32051            }}).to_string());
32052            return;
32053        }
32054        if behavior.storage_activity
32055            && path == "/api/worker/activity-tasks/poll"
32056            && request_number == 1
32057        {
32058            write_mock_response(stream, "200 OK", &json!({"task":{
32059                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
32060                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
32061                "attempt_number":7, "lease_owner":"storage-worker"
32062            }}).to_string());
32063            return;
32064        }
32065
32066        if path == "/api/worker/register" {
32067            if behavior.reject_registration_protocol {
32068                write_mock_response(
32069                    stream,
32070                    "400 Bad Request",
32071                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
32072                );
32073                return;
32074            }
32075            if behavior.reject_registration {
32076                write_mock_response(
32077                    stream,
32078                    "503 Service Unavailable",
32079                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
32080                );
32081                return;
32082            }
32083        }
32084
32085        if path.starts_with("/api/worker/registrations/") {
32086            if behavior.reject_deregistration_protocol {
32087                write_mock_response(
32088                    stream,
32089                    "400 Bad Request",
32090                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
32091                );
32092            } else if behavior.reject_deregistration {
32093                write_mock_response(
32094                    stream,
32095                    "403 Forbidden",
32096                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
32097                );
32098            } else {
32099                write_mock_response(
32100                    stream,
32101                    "200 OK",
32102                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
32103                );
32104            }
32105            return;
32106        }
32107
32108        let is_poll = matches!(
32109            path,
32110            "/api/worker/workflow-tasks/poll"
32111                | "/api/worker/activity-tasks/poll"
32112                | "/api/worker/query-tasks/poll"
32113        );
32114        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
32115            write_mock_response(
32116                stream,
32117                "429 Too Many Requests",
32118                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
32119            );
32120            return;
32121        }
32122        if is_poll && request_number <= behavior.poll_failures_per_path {
32123            return;
32124        }
32125        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
32126            return;
32127        }
32128        if path == "/api/worker/heartbeat"
32129            && behavior.heartbeat_failure_request == Some(request_number)
32130        {
32131            return;
32132        }
32133        if path == "/api/worker/heartbeat"
32134            && behavior.delayed_heartbeat_request == Some(request_number)
32135        {
32136            thread::sleep(behavior.heartbeat_response_delay);
32137        }
32138        if behavior.unauthorized_polls && is_poll {
32139            write_mock_response(
32140                stream,
32141                "401 Unauthorized",
32142                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
32143            );
32144            return;
32145        }
32146        if behavior.draining_polls && is_poll {
32147            write_mock_response(
32148                stream,
32149                "409 Conflict",
32150                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
32151            );
32152            return;
32153        }
32154
32155        if let Some(codec_case) = behavior.invalid_task_payload_codec {
32156            if is_poll && request_number == 1 {
32157                let mut task = match path {
32158                    "/api/worker/workflow-tasks/poll" => json!({
32159                        "task_id": "codec-workflow",
32160                        "workflow_type": "codec.workflow",
32161                        "payload_codec": DEFAULT_CODEC,
32162                        "workflow_task_attempt": 1,
32163                        "lease_owner": "codec-worker"
32164                    }),
32165                    "/api/worker/activity-tasks/poll" => json!({
32166                        "task_id": "codec-activity",
32167                        "activity_attempt_id": "codec-activity-attempt",
32168                        "activity_type": "codec.activity",
32169                        "payload_codec": DEFAULT_CODEC,
32170                        "attempt_number": 1,
32171                        "lease_owner": "codec-worker"
32172                    }),
32173                    "/api/worker/query-tasks/poll" => json!({
32174                        "query_task_id": "codec-query",
32175                        "query_task_attempt": 1,
32176                        "workflow_type": "codec.workflow",
32177                        "query_name": "known",
32178                        "payload_codec": DEFAULT_CODEC,
32179                        "lease_owner": "codec-worker"
32180                    }),
32181                    _ => unreachable!("is_poll limits task codec probe paths"),
32182                };
32183                codec_case.apply(&mut task);
32184                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
32185                return;
32186            }
32187
32188            if matches!(
32189                path,
32190                "/api/worker/workflow-tasks/codec-workflow/fail"
32191                    | "/api/worker/activity-tasks/codec-activity/fail"
32192                    | "/api/worker/query-tasks/codec-query/fail"
32193            ) {
32194                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
32195                return;
32196            }
32197        }
32198
32199        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
32200            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
32201            let body = format!(
32202                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
32203            );
32204            write_mock_response(stream, "400 Bad Request", &body);
32205            return;
32206        }
32207
32208        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
32209        {
32210            write_mock_response(
32211                stream,
32212                "409 Conflict",
32213                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
32214            );
32215            return;
32216        }
32217
32218        if behavior.workflow_completion_status.is_some()
32219            && path == "/api/worker/workflow-tasks/poll"
32220            && request_number == 1
32221        {
32222            write_mock_response(
32223                stream,
32224                "200 OK",
32225                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"}}"#,
32226            );
32227            return;
32228        }
32229
32230        if path == "/api/worker/workflow-tasks/workflow-timeout-task/complete" {
32231            if let (Some(status), Some(body)) = (
32232                behavior.workflow_completion_status,
32233                behavior.workflow_completion_body,
32234            ) {
32235                write_mock_response(stream, status, body);
32236                return;
32237            }
32238        }
32239
32240        if behavior.waiting_query_worker {
32241            if behavior.complete_named_signal
32242                && path == "/api/worker/workflow-tasks/poll"
32243                && request_number == 1
32244            {
32245                let body = json!({
32246                    "task": {
32247                        "task_id": "snapshot-open",
32248                        "workflow_id": "snapshot-1",
32249                        "run_id": "snapshot-run-1",
32250                        "workflow_type": "snapshot",
32251                        "payload_codec": DEFAULT_CODEC,
32252                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32253                            .expect("Avro workflow arguments"),
32254                        "history_events": [],
32255                        "workflow_task_attempt": 1,
32256                        "lease_owner": "rust-snapshot-worker"
32257                    }
32258                })
32259                .to_string();
32260                write_mock_response(stream, "200 OK", &body);
32261                return;
32262            }
32263
32264            let signal_request = request_number - usize::from(behavior.complete_named_signal);
32265            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
32266            if path == "/api/worker/workflow-tasks/poll"
32267                && signal_request >= 1
32268                && signal_request <= signal_request_limit
32269            {
32270                let finish = behavior.complete_named_signal && signal_request == 3;
32271                let amounts = if signal_request == 1 {
32272                    vec![3]
32273                } else {
32274                    vec![3, 5]
32275                };
32276                let task_id = if signal_request == 1 {
32277                    "snapshot-wait-3"
32278                } else if finish {
32279                    "snapshot-finish"
32280                } else {
32281                    "snapshot-wait-5"
32282                };
32283                let mut history_events = std::iter::once(json!({
32284                    "event_type": "SignalWaitOpened",
32285                    "payload": {"sequence": 1, "signal_name": "finish"}
32286                }))
32287                .chain(amounts.iter().enumerate().map(|(index, amount)| {
32288                    json!({
32289                        "event_type": "SignalReceived",
32290                        "payload": {
32291                            "signal_id": format!("increment-{amount}"),
32292                            "signal_name": "increment",
32293                            "workflow_sequence": index + 2,
32294                            "payload_codec": DEFAULT_CODEC,
32295                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32296                                .expect("Avro signal envelope")
32297                        }
32298                    })
32299                }))
32300                .collect::<Vec<_>>();
32301                let (resume_id, resume_name, resume_arguments) = if finish {
32302                    history_events.push(json!({
32303                        "event_type": "SignalReceived",
32304                        "payload": {
32305                            "signal_id": "finish",
32306                            "signal_name": "finish",
32307                            "workflow_sequence": 4,
32308                            "payload_codec": DEFAULT_CODEC,
32309                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32310                                .expect("Avro finish signal envelope")
32311                        }
32312                    }));
32313                    (
32314                        "finish".to_string(),
32315                        "finish".to_string(),
32316                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
32317                            .expect("Avro finish resume signal"),
32318                    )
32319                } else {
32320                    let amount = amounts.last().expect("amount");
32321                    (
32322                        format!("increment-{amount}"),
32323                        "increment".to_string(),
32324                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32325                            .expect("Avro increment resume signal"),
32326                    )
32327                };
32328                let body = json!({
32329                    "task": {
32330                        "task_id": task_id,
32331                        "workflow_id": "snapshot-1",
32332                        "run_id": "snapshot-run-1",
32333                        "workflow_type": "snapshot",
32334                        "payload_codec": DEFAULT_CODEC,
32335                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32336                            .expect("Avro workflow arguments"),
32337                        "history_events": history_events,
32338                        "workflow_task_attempt": 1,
32339                        "workflow_signal_id": resume_id,
32340                        "signal_name": resume_name,
32341                        "signal_arguments": resume_arguments,
32342                        "lease_owner": "rust-snapshot-worker"
32343                    }
32344                })
32345                .to_string();
32346                write_mock_response(stream, "200 OK", &body);
32347                return;
32348            }
32349
32350            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
32351                let history_events = [3, 5]
32352                    .into_iter()
32353                    .enumerate()
32354                    .map(|(index, amount)| {
32355                        json!({
32356                            "event_type": "SignalReceived",
32357                            "payload": {
32358                                "signal_id": format!("increment-{amount}"),
32359                                "signal_name": "increment",
32360                                "workflow_sequence": index + 2,
32361                                "payload_codec": DEFAULT_CODEC,
32362                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
32363                                    .expect("Avro query signal envelope")
32364                            }
32365                        })
32366                    })
32367                    .collect::<Vec<_>>();
32368                let body = json!({
32369                    "task": {
32370                        "query_task_id": "snapshot-current",
32371                        "query_task_attempt": 1,
32372                        "lease_owner": "rust-snapshot-worker",
32373                        "workflow_id": "snapshot-1",
32374                        "run_id": "snapshot-run-1",
32375                        "workflow_type": "snapshot",
32376                        "query_name": "current",
32377                        "payload_codec": DEFAULT_CODEC,
32378                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32379                            .expect("Avro workflow arguments"),
32380                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
32381                            .expect("Avro query arguments"),
32382                        "history_events": history_events,
32383                        "run_status": "waiting"
32384                    }
32385                })
32386                .to_string();
32387                write_mock_response(stream, "200 OK", &body);
32388                return;
32389            }
32390
32391            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
32392                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
32393            {
32394                write_mock_response(
32395                    stream,
32396                    "200 OK",
32397                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
32398                );
32399                return;
32400            }
32401
32402            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
32403                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
32404                return;
32405            }
32406
32407            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
32408                write_mock_response(
32409                    stream,
32410                    "200 OK",
32411                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
32412                );
32413                return;
32414            }
32415
32416            if path == "/api/worker/query-tasks/snapshot-current/complete" {
32417                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
32418                return;
32419            }
32420        }
32421
32422        if matches!(
32423            path,
32424            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
32425        ) {
32426            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
32427                .expect("typed mock result");
32428            let body = json!({
32429                "result": typed_fidelity_probe().into_json().expect("result projection"),
32430                "result_envelope": result,
32431            })
32432            .to_string();
32433            write_mock_response(stream, "200 OK", &body);
32434            return;
32435        }
32436
32437        if path == "/api/workflows/typed-1" {
32438            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
32439                .expect("typed mock result");
32440            let body = json!({
32441                "workflow_id": "typed-1",
32442                "run_id": "run-typed-1",
32443                "workflow_type": "typed.echo",
32444                "status": "completed",
32445                "output": typed_fidelity_probe().into_json().expect("output projection"),
32446                "output_envelope": result,
32447            })
32448            .to_string();
32449            write_mock_response(stream, "200 OK", &body);
32450            return;
32451        }
32452
32453        let (status, body) = match path {
32454            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
32455            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
32456            "/api/workflows" => (
32457                "201 Created",
32458                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
32459            ),
32460            "/api/worker/register" if behavior.decline_registration => (
32461                "200 OK",
32462                r#"{"worker_id":"declined-worker","registered":false}"#,
32463            ),
32464            "/api/worker/register" if behavior.waiting_query_worker => (
32465                "200 OK",
32466                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
32467            ),
32468            "/api/worker/register" => (
32469                "200 OK",
32470                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
32471            ),
32472            "/api/worker/heartbeat" => ("200 OK", "{}"),
32473            "/api/worker/activity-tasks/poll"
32474                if behavior.cancelled_activity && request_number == 1 =>
32475            {
32476                (
32477                    "200 OK",
32478                    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"}}"#,
32479                )
32480            }
32481            "/api/worker/activity-tasks/poll"
32482                if behavior.long_poll_capacity_responses_per_path > 0
32483                    && request_number
32484                        == behavior
32485                            .long_poll_capacity_responses_per_path
32486                            .saturating_add(1) =>
32487            {
32488                (
32489                    "200 OK",
32490                    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"}}"#,
32491                )
32492            }
32493            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
32494                ("200 OK", r#"{"task":null}"#)
32495            }
32496            "/api/worker/query-tasks/poll"
32497                if behavior.reject_query_completion && request_number == 1 =>
32498            {
32499                (
32500                    "200 OK",
32501                    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"}}"#,
32502                )
32503            }
32504            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
32505            "/api/worker/query-tasks/query-capture/complete"
32506            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
32507            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
32508                "200 OK",
32509                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
32510            ),
32511            "/api/worker/activity-tasks/activity-cancel/complete" => (
32512                "409 Conflict",
32513                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
32514            ),
32515            "/api/worker/activity-tasks/activity-typed/complete"
32516            | "/api/worker/activity-tasks/activity-typed/fail"
32517            | "/api/worker/activity-tasks/capacity-activity/complete"
32518            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
32519            "/api/workflows/counter-1/query/current" => (
32520                "200 OK",
32521                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
32522            ),
32523            "/api/workflows/counter-1/query/missing" => (
32524                "404 Not Found",
32525                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
32526            ),
32527            "/api/workflows/wf-lifecycle/cancel" => (
32528                "200 OK",
32529                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
32530            ),
32531            "/api/workflows/wf-lifecycle/terminate" => (
32532                "200 OK",
32533                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
32534            ),
32535            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
32536                "200 OK",
32537                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
32538            ),
32539            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
32540                "200 OK",
32541                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
32542            ),
32543            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
32544                "202 Accepted",
32545                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
32546            ),
32547            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
32548                "200 OK",
32549                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}"#,
32550            ),
32551            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
32552                "409 Conflict",
32553                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
32554            ),
32555            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
32556            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
32557                "409 Conflict",
32558                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
32559            ),
32560            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
32561                "200 OK",
32562                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"}]}}"#,
32563            ),
32564            "/api/workflows/wf-cancelled" => (
32565                "200 OK",
32566                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
32567            ),
32568            "/api/workflows/wf-terminated" => (
32569                "200 OK",
32570                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
32571            ),
32572            "/api/workflows/wf-timed-out" => (
32573                "200 OK",
32574                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
32575            ),
32576            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
32577                "200 OK",
32578                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
32579            ),
32580            "/api/workflows/wf-selected" => (
32581                "200 OK",
32582                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
32583            ),
32584            "/api/workflows/wf-selected/runs/run-selected" => (
32585                "200 OK",
32586                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
32587            ),
32588            _ => ("404 Not Found", r#"{"message":"not found"}"#),
32589        };
32590        write_mock_response(stream, status, body);
32591    }
32592
32593    fn mock_request_is_complete(request: &[u8]) -> bool {
32594        let Some(header_end) = request
32595            .windows(4)
32596            .position(|window| window == b"\r\n\r\n")
32597            .map(|position| position + 4)
32598        else {
32599            return false;
32600        };
32601        let headers = String::from_utf8_lossy(&request[..header_end]);
32602        let content_length = headers.lines().find_map(|line| {
32603            let (name, value) = line.split_once(':')?;
32604            name.eq_ignore_ascii_case("content-length")
32605                .then(|| value.trim().parse::<usize>().ok())
32606                .flatten()
32607        });
32608
32609        request.len() >= header_end + content_length.unwrap_or(0)
32610    }
32611
32612    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
32613        let response = format!(
32614            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
32615            body.len()
32616        );
32617
32618        let _ = stream.write_all(response.as_bytes());
32619        let _ = stream.flush();
32620    }
32621
32622    fn typed_activity_failure_server(
32623        path: &str,
32624        _body: &str,
32625        request_number: usize,
32626    ) -> Option<(&'static str, String)> {
32627        match path {
32628            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
32629                "200 OK",
32630                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(),
32631            )),
32632            "/api/worker/activity-tasks/typed-failure/fail" => Some(("200 OK", "{}".into())),
32633            _ => None,
32634        }
32635    }
32636
32637    #[tokio::test]
32638    async fn managed_activity_reports_application_type_and_non_retryable_marker() {
32639        for non_retryable in [false, true] {
32640            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32641                request_override: Some(typed_activity_failure_server),
32642                ..MockWorkerBehavior::default()
32643            });
32644            let client = Client::builder(server.base_url()).build().unwrap();
32645            let mut worker = Worker::new(client, "typed-queue").worker_id("typed-worker");
32646            worker.register_activity("typed.failure", move |_, _| async move {
32647                Err(ActivityError::new("PaymentDeclined", "card declined")
32648                    .non_retryable(non_retryable)
32649                    .into())
32650            });
32651            assert_eq!(worker.run_once().await.unwrap(), 1);
32652            assert_eq!(
32653                server.request_body("/api/worker/activity-tasks/typed-failure/fail"),
32654                json!({
32655                    "activity_attempt_id": "typed-attempt",
32656                    "lease_owner": "typed-worker",
32657                    "failure": {"type": "PaymentDeclined", "message": "card declined",
32658                                "non_retryable": non_retryable}
32659                })
32660            );
32661        }
32662    }
32663
32664    fn activity_completion_backend_recovery(
32665        path: &str,
32666        _body: &str,
32667        request_number: usize,
32668    ) -> Option<(&'static str, String)> {
32669        match path {
32670            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
32671                "200 OK",
32672                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(),
32673            )),
32674            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
32675                "503 Service Unavailable",
32676                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(),
32677            )),
32678            "/api/worker/activity-tasks/recover-activity/complete" => Some((
32679                "200 OK",
32680                r#"{"outcome":"completed","recorded":true}"#.to_string(),
32681            )),
32682            _ => None,
32683        }
32684    }
32685
32686    fn workflow_completion_backend_recovery(
32687        path: &str,
32688        _body: &str,
32689        request_number: usize,
32690    ) -> Option<(&'static str, String)> {
32691        match path {
32692            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
32693                "200 OK",
32694                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
32695            )),
32696            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
32697                "503 Service Unavailable",
32698                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(),
32699            )),
32700            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
32701                "200 OK",
32702                r#"{"outcome":"completed","recorded":true}"#.to_string(),
32703            )),
32704            _ => None,
32705        }
32706    }
32707
32708    fn workflow_completion_lock_pressure(
32709        path: &str,
32710        body: &str,
32711        request_number: usize,
32712    ) -> Option<(&'static str, String)> {
32713        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number == 1 {
32714            return Some((
32715                "503 Service Unavailable",
32716                json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
32717                    "outcome":"deferred", "recorded":false, "retryable":true,
32718                    "retry_after_seconds":1, "task_id":"recover-workflow",
32719                    "lease_owner":"recover-worker", "workflow_task_attempt":3,
32720                    "backend":{"driver":"sqlite", "lock_pressure":true}})
32721                .to_string(),
32722            ));
32723        }
32724        workflow_completion_backend_recovery(path, body, request_number)
32725    }
32726
32727    fn workflow_completion_lock_pressure_forever(
32728        path: &str,
32729        body: &str,
32730        request_number: usize,
32731    ) -> Option<(&'static str, String)> {
32732        if path == "/api/worker/workflow-tasks/recover-workflow/complete" {
32733            return workflow_completion_lock_pressure(path, body, 1);
32734        }
32735        workflow_completion_lock_pressure(path, body, request_number)
32736    }
32737
32738    fn workflow_completion_lock_pressure_then_expired(
32739        path: &str,
32740        body: &str,
32741        request_number: usize,
32742    ) -> Option<(&'static str, String)> {
32743        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32744            return Some(("409 Conflict", json!({"reason":"lease_expired", "recorded":false,
32745                "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3}).to_string()));
32746        }
32747        workflow_completion_lock_pressure(path, body, request_number)
32748    }
32749
32750    fn workflow_completion_lock_pressure_then_slow(
32751        path: &str,
32752        body: &str,
32753        request_number: usize,
32754    ) -> Option<(&'static str, String)> {
32755        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32756            thread::sleep(Duration::from_secs(2));
32757        }
32758        workflow_completion_lock_pressure(path, body, request_number)
32759    }
32760
32761    fn workflow_completion_pressure_then_backend_loss(
32762        path: &str,
32763        body: &str,
32764        request_number: usize,
32765    ) -> Option<(&'static str, String)> {
32766        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
32767            return Some((
32768                "503 Service Unavailable",
32769                json!({"reason":"backend_unavailable", "operation":"complete_workflow_task",
32770                    "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
32771                    "retryable":true, "retry_after_seconds":3, "task_id":"recover-workflow",
32772                    "lease_owner":"recover-worker", "workflow_task_attempt":3})
32773                .to_string(),
32774            ));
32775        }
32776        workflow_completion_lock_pressure(path, body, request_number)
32777    }
32778
32779    fn completion_deferral_worker(server: &MockWorkerServer, calls: Arc<AtomicUsize>) -> Worker {
32780        let client = Client::builder(server.base_url())
32781            .timeout(Duration::from_secs(4))
32782            .build()
32783            .unwrap();
32784        let mut worker = Worker::new(client, "recover-queue")
32785            .worker_id("recover-worker")
32786            .poll_timeout(Duration::from_millis(10));
32787        worker.register_workflow("recover.workflow", move |_ctx, _args| {
32788            let calls = Arc::clone(&calls);
32789            async move {
32790                calls.fetch_add(1, Ordering::SeqCst);
32791                Ok(json!("done"))
32792            }
32793        });
32794        worker
32795    }
32796
32797    #[tokio::test]
32798    async fn workflow_completion_deferral_stops_at_original_cleanup_budget() {
32799        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32800            request_override: Some(workflow_completion_lock_pressure_forever),
32801            ..MockWorkerBehavior::default()
32802        });
32803        let calls = Arc::new(AtomicUsize::new(0));
32804        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32805            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32806        worker
32807            .client
32808            .worker_storage_admission
32809            .as_mut()
32810            .unwrap()
32811            .workflow_completion_retry_deadline =
32812            Some(tokio::time::Instant::now() + Duration::from_millis(250));
32813        let result = tokio::time::timeout(Duration::from_secs(2), worker.poll_workflow_once())
32814            .await
32815            .unwrap();
32816        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32817        assert_eq!(calls.load(Ordering::SeqCst), 1);
32818        assert_eq!(
32819            server
32820                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32821                .len(),
32822            1
32823        );
32824    }
32825
32826    #[tokio::test]
32827    async fn workflow_completion_deferral_bounds_the_inflight_retry() {
32828        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32829            request_override: Some(workflow_completion_lock_pressure_then_slow),
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        let start = tokio::time::Instant::now();
32836        worker
32837            .client
32838            .worker_storage_admission
32839            .as_mut()
32840            .unwrap()
32841            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
32842        assert!(matches!(
32843            worker.poll_workflow_once().await,
32844            Err(Error::Timeout)
32845        ));
32846        assert!(start.elapsed() < Duration::from_secs(2));
32847        assert_eq!(calls.load(Ordering::SeqCst), 1);
32848        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32849        assert_eq!(bodies.len(), 2);
32850        assert_eq!(bodies[0], bodies[1]);
32851    }
32852
32853    #[tokio::test]
32854    async fn workflow_completion_deferral_retains_deadline_when_backend_reason_changes() {
32855        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32856            request_override: Some(workflow_completion_pressure_then_backend_loss),
32857            ..MockWorkerBehavior::default()
32858        });
32859        let calls = Arc::new(AtomicUsize::new(0));
32860        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
32861            .with_storage_admission(Arc::new(AtomicBool::new(false)));
32862        let start = tokio::time::Instant::now();
32863        worker
32864            .client
32865            .worker_storage_admission
32866            .as_mut()
32867            .unwrap()
32868            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
32869        let result = worker.poll_workflow_once().await;
32870        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32871        assert!(start.elapsed() < Duration::from_secs(2));
32872        assert_eq!(calls.load(Ordering::SeqCst), 1);
32873        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32874        assert_eq!(bodies.len(), 2);
32875        assert_eq!(bodies[0], bodies[1]);
32876    }
32877
32878    #[tokio::test]
32879    async fn workflow_completion_deferral_shutdown_interrupts_prolonged_pressure() {
32880        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32881            request_override: Some(workflow_completion_lock_pressure_forever),
32882            ..MockWorkerBehavior::default()
32883        });
32884        let calls = Arc::new(AtomicUsize::new(0));
32885        let stop = Arc::new(AtomicBool::new(false));
32886        let worker = completion_deferral_worker(&server, Arc::clone(&calls))
32887            .with_storage_admission(Arc::clone(&stop));
32888        let shutdown = async {
32889            while server
32890                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32891                .is_empty()
32892            {
32893                tokio::time::sleep(Duration::from_millis(10)).await;
32894            }
32895            stop.store(true, Ordering::SeqCst);
32896        };
32897        let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
32898            tokio::join!(worker.poll_workflow_once(), shutdown)
32899        })
32900        .await
32901        .unwrap();
32902        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
32903        assert_eq!(calls.load(Ordering::SeqCst), 1);
32904        assert_eq!(
32905            server
32906                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
32907                .len(),
32908            1
32909        );
32910    }
32911
32912    #[tokio::test]
32913    async fn workflow_completion_deferral_preserves_later_expiry_refusal() {
32914        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32915            request_override: Some(workflow_completion_lock_pressure_then_expired),
32916            ..MockWorkerBehavior::default()
32917        });
32918        let calls = Arc::new(AtomicUsize::new(0));
32919        let worker = completion_deferral_worker(&server, Arc::clone(&calls));
32920        let result = worker.run_once().await;
32921        assert!(
32922            matches!(result, Err(Error::Http { status, ref body }) if status.as_u16() == 409 && body.contains("lease_expired"))
32923        );
32924        assert_eq!(calls.load(Ordering::SeqCst), 1);
32925        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32926        assert_eq!(bodies.len(), 2);
32927        assert_eq!(bodies[0], bodies[1]);
32928        assert!(server
32929            .request_bodies("/api/worker/workflow-tasks/recover-workflow/fail")
32930            .is_empty());
32931    }
32932
32933    #[tokio::test]
32934    async fn managed_workflow_completion_deferral_preserves_bytes_and_server_delay() {
32935        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32936            request_override: Some(workflow_completion_lock_pressure),
32937            ..MockWorkerBehavior::default()
32938        });
32939        let client = Client::builder(server.base_url())
32940            .timeout(Duration::from_secs(2))
32941            .build()
32942            .unwrap();
32943        let calls = Arc::new(AtomicUsize::new(0));
32944        let mut worker = Worker::new(client, "recover-queue")
32945            .worker_id("recover-worker")
32946            .recover_transient_outages(true)
32947            .poll_timeout(Duration::from_millis(10))
32948            .retry_policy(WorkerRetryPolicy {
32949                max_retries: 1,
32950                initial_backoff: Duration::from_millis(10),
32951                max_backoff: Duration::from_millis(10),
32952            });
32953        worker.register_workflow("recover.workflow", {
32954            let calls = Arc::clone(&calls);
32955            move |_ctx, _args| {
32956                let calls = Arc::clone(&calls);
32957                async move {
32958                    calls.fetch_add(1, Ordering::SeqCst);
32959                    Ok(json!("done"))
32960                }
32961            }
32962        });
32963        let start = tokio::time::Instant::now();
32964        assert_eq!(worker.run_once().await.unwrap(), 1);
32965        assert!(start.elapsed() >= Duration::from_secs(1));
32966        assert_eq!(calls.load(Ordering::SeqCst), 1);
32967        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
32968        assert_eq!(bodies.len(), 2);
32969        assert_eq!(bodies[0], bodies[1]);
32970    }
32971
32972    #[test]
32973    fn workflow_completion_deferral_requires_an_exact_unrecorded_fence() {
32974        let path = "/worker/workflow-tasks/recover-workflow/complete";
32975        let request = json!({"lease_owner":"recover-worker", "workflow_task_attempt":3});
32976        let response = json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
32977            "outcome":"deferred", "recorded":false, "retryable":true, "retry_after_seconds":1,
32978            "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3,
32979            "backend":{"driver":"sqlite", "lock_pressure":true}});
32980        let error = |body: Value| Error::Http {
32981            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
32982            body: body.to_string(),
32983        };
32984        assert_eq!(
32985            worker_deferred_workflow_completion_retry_after(
32986                &error(response.clone()),
32987                path,
32988                Some(&request)
32989            ),
32990            Some(Duration::from_secs(1))
32991        );
32992        for (field, value) in [
32993            ("reason", json!("backend_unavailable")),
32994            ("operation", json!("complete_activity_task")),
32995            ("task_id", json!("other-task")),
32996            ("lease_owner", json!("other-owner")),
32997            ("workflow_task_attempt", json!(4)),
32998            ("recorded", json!(true)),
32999            ("recorded", Value::Null),
33000            ("recorded", json!("false")),
33001            ("retryable", json!(false)),
33002            ("retry_after_seconds", json!(0)),
33003            ("retry_after_seconds", json!(-1)),
33004            ("retry_after_seconds", json!(1.0)),
33005            ("retry_after_seconds", json!("1")),
33006            ("retry_after_seconds", json!(6)),
33007            ("backend", json!({"lock_pressure":false})),
33008        ] {
33009            let mut invalid = response.clone();
33010            invalid[field] = value;
33011            assert_eq!(
33012                worker_deferred_workflow_completion_retry_after(
33013                    &error(invalid),
33014                    path,
33015                    Some(&request)
33016                ),
33017                None,
33018                "invalid {field}"
33019            );
33020        }
33021        for field in [
33022            "reason",
33023            "operation",
33024            "task_id",
33025            "lease_owner",
33026            "workflow_task_attempt",
33027            "recorded",
33028            "retryable",
33029            "retry_after_seconds",
33030            "backend",
33031        ] {
33032            let mut missing = response.clone();
33033            missing.as_object_mut().unwrap().remove(field);
33034            assert_eq!(
33035                worker_deferred_workflow_completion_retry_after(
33036                    &error(missing),
33037                    path,
33038                    Some(&request)
33039                ),
33040                None,
33041                "missing {field}"
33042            );
33043        }
33044        assert_eq!(
33045            worker_deferred_workflow_completion_retry_after(
33046                &error(response.clone()),
33047                "/worker/activity-tasks/recover-workflow/complete",
33048                Some(&request)
33049            ),
33050            None
33051        );
33052        assert_eq!(
33053            worker_deferred_workflow_completion_retry_after(&error(response.clone()), path, None),
33054            None
33055        );
33056        let wrong_status = Error::Http {
33057            status: reqwest::StatusCode::CONFLICT,
33058            body: response.to_string(),
33059        };
33060        assert_eq!(
33061            worker_deferred_workflow_completion_retry_after(&wrong_status, path, Some(&request)),
33062            None
33063        );
33064    }
33065
33066    fn activity_completion_stale_after_backend_recovery(
33067        path: &str,
33068        body: &str,
33069        request_number: usize,
33070    ) -> Option<(&'static str, String)> {
33071        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
33072            return Some((
33073                "409 Conflict",
33074                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(),
33075            ));
33076        }
33077        activity_completion_backend_recovery(path, body, request_number)
33078    }
33079
33080    fn activity_completion_remains_unavailable(
33081        path: &str,
33082        body: &str,
33083        request_number: usize,
33084    ) -> Option<(&'static str, String)> {
33085        if path == "/api/worker/activity-tasks/recover-activity/complete" {
33086            return activity_completion_backend_recovery(path, body, 1);
33087        }
33088        activity_completion_backend_recovery(path, body, request_number)
33089    }
33090
33091    #[tokio::test]
33092    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
33093        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33094            request_override: Some(activity_completion_backend_recovery),
33095            ..MockWorkerBehavior::default()
33096        });
33097        let client = Client::builder(server.base_url())
33098            .timeout(Duration::from_secs(2))
33099            .build()
33100            .expect("client");
33101        let handler_calls = Arc::new(AtomicUsize::new(0));
33102        let mut worker = Worker::new(client, "recover-queue")
33103            .worker_id("recover-worker")
33104            .poll_timeout(Duration::from_millis(10));
33105        worker.register_activity("recover.activity", {
33106            let handler_calls = Arc::clone(&handler_calls);
33107            move |_ctx, _args| {
33108                let handler_calls = Arc::clone(&handler_calls);
33109                async move {
33110                    handler_calls.fetch_add(1, Ordering::SeqCst);
33111                    Ok(json!("done"))
33112                }
33113            }
33114        });
33115
33116        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
33117        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33118        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
33119        assert_eq!(bodies.len(), 2);
33120        assert_eq!(bodies[0], bodies[1]);
33121    }
33122
33123    #[tokio::test]
33124    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
33125        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33126            request_override: Some(workflow_completion_backend_recovery),
33127            ..MockWorkerBehavior::default()
33128        });
33129        let client = Client::builder(server.base_url())
33130            .timeout(Duration::from_secs(2))
33131            .build()
33132            .expect("client");
33133        let handler_calls = Arc::new(AtomicUsize::new(0));
33134        let mut worker = Worker::new(client, "recover-queue")
33135            .worker_id("recover-worker")
33136            .poll_timeout(Duration::from_millis(10));
33137        worker.register_workflow("recover.workflow", {
33138            let handler_calls = Arc::clone(&handler_calls);
33139            move |_ctx, _args| {
33140                let handler_calls = Arc::clone(&handler_calls);
33141                async move {
33142                    handler_calls.fetch_add(1, Ordering::SeqCst);
33143                    Ok(json!("done"))
33144                }
33145            }
33146        });
33147
33148        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
33149        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33150        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
33151        assert_eq!(bodies.len(), 2);
33152        assert_eq!(bodies[0], bodies[1]);
33153    }
33154
33155    #[tokio::test]
33156    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
33157        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33158            request_override: Some(activity_completion_stale_after_backend_recovery),
33159            ..MockWorkerBehavior::default()
33160        });
33161        let client = Client::builder(server.base_url())
33162            .timeout(Duration::from_secs(2))
33163            .build()
33164            .expect("client");
33165        let handler_calls = Arc::new(AtomicUsize::new(0));
33166        let mut worker = Worker::new(client, "recover-queue")
33167            .worker_id("recover-worker")
33168            .poll_timeout(Duration::from_millis(10));
33169        worker.register_activity("recover.activity", {
33170            let handler_calls = Arc::clone(&handler_calls);
33171            move |_ctx, _args| {
33172                let handler_calls = Arc::clone(&handler_calls);
33173                async move {
33174                    handler_calls.fetch_add(1, Ordering::SeqCst);
33175                    Ok(json!("done"))
33176                }
33177            }
33178        });
33179
33180        assert_eq!(
33181            worker
33182                .run_once()
33183                .await
33184                .expect("authoritative stale outcome"),
33185            1
33186        );
33187        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
33188        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
33189        assert_eq!(bodies.len(), 2);
33190        assert_eq!(bodies[0], bodies[1]);
33191    }
33192
33193    #[test]
33194    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
33195        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
33196        let response = json!({
33197            "reason":"backend_unavailable", "operation":"complete_activity_task",
33198            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
33199            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
33200            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
33201        });
33202        let path = "/worker/activity-tasks/recover-activity/complete";
33203        let error = |body: Value| Error::Http {
33204            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33205            body: body.to_string(),
33206        };
33207        assert_eq!(
33208            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
33209            Some(Duration::from_secs(1))
33210        );
33211
33212        for (field, invalid) in [
33213            ("operation", json!("poll_activity_task")),
33214            ("outcome", json!("rejected")),
33215            ("worker_id", json!("another-worker")),
33216            ("task_queue", json!("recover-queue")),
33217            ("retryable", json!(false)),
33218            ("retry_after_seconds", json!(0)),
33219            ("task_id", json!("another-task")),
33220            ("lease_owner", json!("another-worker")),
33221            ("activity_attempt_id", json!("another-attempt")),
33222        ] {
33223            let mut invalid_response = response.clone();
33224            invalid_response[field] = invalid;
33225            assert_eq!(
33226                worker_fenced_completion_retry_after(
33227                    &error(invalid_response),
33228                    path,
33229                    Some(&request)
33230                ),
33231                None,
33232                "must not retry mismatched {field}"
33233            );
33234        }
33235        assert_eq!(
33236            worker_fenced_completion_retry_after(&error(response), path, None),
33237            None
33238        );
33239    }
33240
33241    #[tokio::test]
33242    async fn shutdown_interrupts_fenced_completion_backend_wait() {
33243        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33244            request_override: Some(activity_completion_remains_unavailable),
33245            ..MockWorkerBehavior::default()
33246        });
33247        let client = Client::builder(server.base_url())
33248            .timeout(Duration::from_secs(2))
33249            .build()
33250            .expect("client");
33251        let stop = Arc::new(AtomicBool::new(false));
33252        let worker = Worker::new(client, "recover-queue")
33253            .worker_id("recover-worker")
33254            .with_storage_admission(Arc::clone(&stop));
33255        let completion = tokio::spawn(async move {
33256            worker
33257                .client
33258                .complete_activity_task(
33259                    "recover-activity",
33260                    "recover-attempt",
33261                    "recover-worker",
33262                    json!("done"),
33263                    DEFAULT_CODEC,
33264                )
33265                .await
33266        });
33267        let path = "/api/worker/activity-tasks/recover-activity/complete";
33268        tokio::time::timeout(Duration::from_secs(2), async {
33269            while server.request_count(path) == 0 {
33270                tokio::time::sleep(Duration::from_millis(10)).await;
33271            }
33272        })
33273        .await
33274        .expect("first completion request");
33275        stop.store(true, Ordering::SeqCst);
33276        let error = tokio::time::timeout(Duration::from_secs(1), completion)
33277            .await
33278            .expect("shutdown must interrupt retry wait")
33279            .expect("completion task")
33280            .expect_err("backend is still unavailable");
33281        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
33282        assert_eq!(server.request_count(path), 1);
33283    }
33284}