Skip to content
Durable Workflowrust

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 failure_reporting;
14mod local_activity;
15pub mod metrics;
16mod nexus;
17pub mod pagination;
18mod query_authority;
19mod raw_request;
20mod replay_clock;
21mod run_activities;
22mod runtime_payloads;
23mod runtime_uploads;
24mod sticky_worker;
25mod sticky_workflow_cache;
26#[cfg(feature = "telemetry")]
27pub mod telemetry;
28pub mod testing;
29pub use pagination::{
30    PaginationError, WorkflowHistoryIterator, WorkflowHistoryOptions, WorkflowHistoryPage,
31    WorkflowIterator, WorkflowListOptions, WorkflowListPage, WorkflowSummary,
32};
33mod terminal_failure_detail;
34mod tls;
35mod update_outcome;
36mod worker_capacity;
37mod worker_session;
38mod workflow_hydration;
39mod workflow_logging;
40pub use workflow_logging::{WorkflowLogger, WorkflowReplayState};
41
42pub use activity_error::ActivityError;
43pub use activity_retry::{ActivityAttemptLimit, ActivityRetryInfo};
44pub use cancellation_context::{
45    CancellationCause, CancellationContext, CancellationLineage, ScopedCancellationContext,
46    ScopedCancellationLineage,
47};
48pub use cancellation_scope::CancellationScopeOpenReceipt;
49#[doc(hidden)]
50pub use cancellation_scope_history::{
51    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
52};
53#[doc(hidden)]
54pub use cancellation_scope_replay::CancellationScopeRequested;
55pub use failure_reporting::FailureReportError;
56pub use run_activities::{
57    WorkflowActivity, WorkflowActivityAttempt, WorkflowActivityList, WorkflowActivityMetadataError,
58};
59
60pub use cooperative_cancellation::{
61    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
62    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
63    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
64    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
65};
66
67use std::{
68    any::{type_name, Any, TypeId},
69    collections::{BTreeMap, BTreeSet, HashMap},
70    future::Future,
71    io::{self, Read},
72    pin::Pin,
73    sync::{
74        atomic::{AtomicBool, AtomicUsize, Ordering},
75        Arc, Mutex, OnceLock,
76    },
77    task::{Context as TaskContext, Poll},
78    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
79};
80
81use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
82use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
83use chrono::DateTime;
84use futures_util::{future::OptionFuture, task::noop_waker_ref};
85pub use local_activity::LocalActivityOptions;
86pub use raw_request::{
87    worker_protocol_compatible, HttpRefusal, RawMethod, RawRequest, RawResponse,
88};
89use serde::{
90    de::DeserializeOwned,
91    ser::{SerializeMap, SerializeSeq},
92    Deserialize, Deserializer, Serialize, Serializer,
93};
94pub use serde_json::{json, Value};
95use sha2::{Digest, Sha256};
96pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
97use thiserror::Error;
98pub use update_outcome::{UpdatePending, UpdateWaitStage};
99pub use uuid::Uuid;
100pub use worker_session::{WorkerSession, WorkerSessionOptions};
101
102pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
103pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
104
105/// Select the worker request protocol without enabling optional capabilities.
106#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
107#[non_exhaustive]
108pub enum WorkerProtocolVersion {
109    /// Compatibility with Servers that implement only worker protocol 1.19.
110    V119,
111    /// The default worker protocol.
112    #[default]
113    V120,
114}
115
116impl WorkerProtocolVersion {
117    fn as_str(self) -> &'static str {
118        match self {
119            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
120            Self::V120 => WORKER_PROTOCOL_VERSION,
121        }
122    }
123}
124const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
125/// First additive worker protocol that defines portable worker-affinity features.
126pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
127pub const CONTROL_PLANE_VERSION: &str = "2";
128pub const DEFAULT_CODEC: &str = "avro";
129pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
130/// Worker-registration capability for authored condition-wait occurrence identity.
131pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
132    "condition_wait_occurrence_identity";
133/// Worker-registration capability for portable memo upserts.
134pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
135/// Worker-registration capability for server-routed read-only queries.
136pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
137/// Worker-registration capability for canonical typed search attributes.
138pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
139/// Worker-registration capability for synchronous workflow updates.
140pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
141/// Worker-registration capability for durable named input streams.
142pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
143/// Worker-registration capability for persisted first-completion selection.
144pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
145pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
146pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
147pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
148pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
149pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
150/// First additive worker protocol that defines query-task transport.
151pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
152/// First additive worker protocol that defines typed search-attribute upserts.
153pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
154/// First additive worker protocol that defines portable memo upserts.
155pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
156/// First additive worker protocol that preserves declared search-attribute types.
157pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
158/// First additive worker protocol that defines external durable condition waits.
159pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
160/// First additive worker protocol that preserves authored condition-wait occurrences.
161pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
162/// First additive worker protocol that defines durable selection groups.
163pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
164
165pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
166    let Some((major, minor)) = version.split_once('.') else {
167        return false;
168    };
169    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
170}
171
172fn validate_user_signal_name(signal_name: &str) -> Result<()> {
173    if signal_name == MESSAGE_STREAM_SIGNAL {
174        return Err(Error::Codec(format!(
175            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
176        )));
177    }
178    Ok(())
179}
180
181const REQUEST_ID_CONFLICT_REASON: &str = "request_id_conflict";
182const MAX_REQUEST_ID_CHARACTERS: usize = 255;
183
184/// The caller command key is a case-sensitive body field of 1 to 255 Unicode characters.
185fn validate_request_id(request_id: &str) -> Result<()> {
186    if request_id.is_empty() || request_id.chars().count() > MAX_REQUEST_ID_CHARACTERS {
187        return Err(Error::Codec(format!(
188            "request_id must be 1 to {MAX_REQUEST_ID_CHARACTERS} Unicode characters"
189        )));
190    }
191    Ok(())
192}
193
194/// Encode one identifier as exactly one control-plane path segment.
195///
196/// The value is percent-encoded like [`RawRequest`] segments, so `/`, `?` or
197/// `#` in an id stays inside its segment. An empty, `.` or `..` value is
198/// refused before any request: it would address another route, such as
199/// `/workflows` instead of one workflow.
200fn path_segment(field: &'static str, value: &str) -> Result<String> {
201    if value.is_empty() || value == "." || value == ".." {
202        return Err(Error::InvalidPathSegment { field });
203    }
204    Ok(percent_encode_path_segment(value))
205}
206
207fn generated_request_id(command: &str) -> String {
208    format!("sdk-rust-{command}-{}", Uuid::new_v4().simple())
209}
210
211/// Guarantee the sent caller command key on a receipt from a Server that does not echo it.
212fn with_request_id(mut receipt: Value, request_id: &str) -> Value {
213    if receipt.is_null() {
214        return json!({ "request_id": request_id });
215    }
216    if let Some(receipt) = receipt.as_object_mut() {
217        receipt
218            .entry("request_id")
219            .or_insert_with(|| Value::String(request_id.to_string()));
220    }
221    receipt
222}
223
224const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
225const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
226    "Workflow task waiting for scheduled history.";
227const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
228const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
229const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
230const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
231const MAX_MEMO_ENTRIES: usize = 100;
232const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
233const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
234
235const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
236    "lease_expired",
237    "query_task_not_found",
238    "query_task_not_leased",
239    "query_task_timed_out",
240    "query_deadline_unavailable",
241    "lease_owner_mismatch",
242    "query_task_attempt_mismatch",
243];
244
245/// Manifest for the default service-worker profile.
246///
247/// Inline local execution is enabled separately by [`Worker::local_activities`].
248/// Local execution, sessions and caching require explicit Worker configuration.
249pub fn portable_worker_affinity_capability_manifest() -> Value {
250    json!({
251        "local_activities": {
252            "supported": false,
253            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
254            "reason": "rust_worker_does_not_execute_record_local_activity",
255        },
256        "worker_sessions": {
257            "supported": false,
258            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
259            "reason": "rust_worker_has_no_typed_session_lifecycle",
260        },
261        "sticky_execution": {
262            "supported": false,
263            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
264            "reason": "rust_worker_uses_complete_durable_history_replay",
265        },
266    })
267}
268
269/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
270pub const AVRO_VALUE_SCHEMA_JSON: &str =
271    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
272pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
273pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
274const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
275
276static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
277static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
278    OnceLock::new();
279
280#[derive(Clone, Copy)]
281enum RequestProtocol {
282    ControlPlane,
283    DefaultWorker,
284    Worker(&'static str),
285}
286
287pub type Result<T> = std::result::Result<T, Error>;
288
289pub use nexus::{
290    NexusOperationFailure, NexusOperationMode, NexusOperationResult, NexusServiceCall,
291    NexusServiceOptions, NexusWaitFor,
292};
293
294#[derive(Debug, Error)]
295#[non_exhaustive]
296pub enum Error {
297    #[error("replay time is unavailable without a supported authoritative consumed boundary")]
298    ReplayClockUnavailable,
299    #[error("transport error: {0}")]
300    Transport(#[from] reqwest::Error),
301    #[error(
302        "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"
303    )]
304    InvalidBaseUrl,
305    /// A supplied static credential failed validation before client construction.
306    #[error(
307        "invalid static credential option {option}: leading or trailing Unicode whitespace or control character"
308    )]
309    InvalidStaticCredential { option: &'static str },
310    #[error("invalid additional root certificates: {0}")]
311    InvalidRootCertificates(String),
312    #[error("invalid raw request: {0}")]
313    InvalidRawRequest(String),
314    /// An identifier placed in a request path was empty, `.` or `..`, so it
315    /// cannot stay one path segment. Nothing was sent.
316    #[error("invalid path segment for {field}: must not be empty, \".\" or \"..\"")]
317    InvalidPathSegment { field: &'static str },
318    #[error(transparent)]
319    FailureReporting(#[from] FailureReportError),
320    #[error(transparent)]
321    Testing(#[from] testing::TestingError),
322    #[error(transparent)]
323    Pagination(#[from] pagination::PaginationError),
324    #[error(transparent)]
325    WorkflowActivityMetadata(#[from] WorkflowActivityMetadataError),
326    #[error("json error: {0}")]
327    Json(#[from] serde_json::Error),
328    #[error("http {status}: {body}")]
329    Http {
330        status: reqwest::StatusCode,
331        body: String,
332    },
333    #[error("codec error: {0}")]
334    Codec(String),
335    #[error(transparent)]
336    QueryFailed(QueryFailure),
337    #[error(transparent)]
338    Protocol(ProtocolFailure),
339    /// The Server refused a workflow-task completion as larger than its
340    /// aggregate completion limit. Never retried; see
341    /// [`WorkflowTaskCompletionTooLarge`].
342    #[error(transparent)]
343    WorkflowTaskCompletionTooLarge(WorkflowTaskCompletionTooLarge),
344    #[error(transparent)]
345    NonDeterministicReplay(ReplayFailure),
346    #[error(transparent)]
347    ChildWorkflowFailed(ChildWorkflowFailure),
348    #[error(transparent)]
349    ActivityFailed(ActivityFailure),
350    #[error(transparent)]
351    ActivityError(#[from] ActivityError),
352    #[error(transparent)]
353    NexusOperationFailed(Box<NexusOperationFailure>),
354    #[error(transparent)]
355    ParallelFailed(ParallelFailure),
356    #[error(transparent)]
357    SagaCompensationFailed(SagaCompensationFailure),
358    #[error(transparent)]
359    InvalidParallelGroup(ParallelGroupError),
360    #[error(transparent)]
361    DurableOperationCancelled(DurableOperationCancelled),
362    #[error(transparent)]
363    WorkflowCancellationRequested(WorkflowCancellationRequested),
364    #[error(transparent)]
365    CooperativeCancellationRequested(CooperativeCancellationRequested),
366    #[error(transparent)]
367    CancellationScopeRequested(CancellationScopeRequested),
368    #[error(transparent)]
369    WorkflowCommandRejected(WorkflowCommandRejection),
370    #[error(transparent)]
371    WorkflowFailed(WorkflowTerminalOutcome),
372    #[error(transparent)]
373    WorkflowCancelled(WorkflowTerminalOutcome),
374    #[error(transparent)]
375    WorkflowTerminated(WorkflowTerminalOutcome),
376    #[error(transparent)]
377    WorkflowTimedOut(WorkflowTerminalOutcome),
378    #[error(transparent)]
379    ActivityTaskRejected(ActivityTaskRejection),
380    #[error("activity lease renewal unavailable: {0}")]
381    ActivityLeaseRenewalUnavailable(String),
382    #[error("workflow handler {0:?} is not registered")]
383    WorkflowNotRegistered(String),
384    #[error("activity handler {0:?} is not registered")]
385    ActivityNotRegistered(String),
386    #[error(
387        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
388    )]
389    HandlerType {
390        handler_kind: HandlerKind,
391        handler_name: String,
392        value_kind: HandlerValueKind,
393        rust_type: &'static str,
394        message: String,
395    },
396    #[error("workflow future yielded without emitting a durable command")]
397    WorkflowYieldedWithoutCommand,
398    #[error(
399        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
400    )]
401    MissingWorkflowCommandIdentity,
402    #[error("workflow state lock is poisoned")]
403    WorkflowStatePoisoned,
404    #[error("timer duration is too large for the worker protocol")]
405    TimerDurationOverflow,
406    #[error(transparent)]
407    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
408    #[error(transparent)]
409    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
410    #[error("operation timed out")]
411    Timeout,
412    #[error(
413        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
414    )]
415    MissingRoleCredentials {
416        role: &'static str,
417        opposite_role: &'static str,
418    },
419    #[error("worker loop error: {0}")]
420    WorkerLoop(String),
421    #[error(
422        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
423    )]
424    UnsupportedUpdateValidators { workflow_type: String },
425    #[error("{primary}; worker deregistration also failed: {deregistration}")]
426    WorkerShutdown {
427        primary: Box<Error>,
428        deregistration: Box<Error>,
429    },
430    #[error("invalid child workflow options: {0}")]
431    InvalidChildWorkflowOptions(String),
432    #[error("invalid workflow memo update: {0}")]
433    InvalidMemoUpdate(String),
434    #[error(
435        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
436    )]
437    WorkflowMemoUpdatesUnavailable,
438    /// An accepted update had not completed when the wait ended; it has no
439    /// result yet. See [`UpdatePending`].
440    #[error(transparent)]
441    UpdateStillPending(UpdatePending),
442    /// The connected Server does not advertise `update_outcome_reads`, so an
443    /// update outcome cannot be read by update id. Nothing was read or sent.
444    #[error(
445        "update_outcome_reads_unavailable: the connected Server does not advertise update_outcome_reads, so an update outcome cannot be read by update id; call update_workflow() again with the same request_id instead"
446    )]
447    UpdateOutcomeReadsUnavailable,
448    /// A successful update outcome read did not answer with a receipt for the
449    /// requested update: it lacked a matching `update_id` and `update_status`,
450    /// or claimed a finished outcome without being completed. No outcome is
451    /// returned for it.
452    #[error(
453        "update_outcome_unrecognized: the Server's answer is not an outcome receipt for update {update_id:?} on workflow {workflow_id:?}; no outcome was read"
454    )]
455    UnrecognizedUpdateOutcome {
456        workflow_id: String,
457        update_id: String,
458        receipt: Value,
459    },
460    #[error("cooperative cancellation is unavailable: {0}")]
461    CooperativeCancellationUnavailable(String),
462    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
463    CancellationScopeExecutionUnavailable,
464    #[error("invalid cooperative cancellation: {0}")]
465    InvalidCooperativeCancellation(String),
466    #[error("activity execution no longer owns its claim: {0}")]
467    ActivityExecutionAbandoned(String),
468    #[error(transparent)]
469    InvalidActivityOptions(ActivityOptionsError),
470    #[error(transparent)]
471    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
472    #[doc(hidden)]
473    #[error("workflow requested continue as new")]
474    ContinueAsNew(ContinueAsNewRequest),
475}
476
477impl Error {
478    /// The caller command key echoed by the Server in a refusal body.
479    ///
480    /// Signals and updates send their key as the `request_id` body field, and a
481    /// Server refusal can echo it. A `request_id_conflict` refusal always
482    /// carries it: when the Server does not echo it (native Server 3.9.0 does
483    /// not), the SDK adds the key it sent. Transport failures and other
484    /// refusals without an echoed key return `None`: keep the key you passed
485    /// to a `*_with_request_id` method, or obtained from
486    /// [`Client::generate_signal_request_id`] or
487    /// [`Client::generate_update_request_id`], to retry the same logical command
488    /// after an uncertain outcome.
489    pub fn request_id(&self) -> Option<String> {
490        self.refusal_body()?
491            .get("request_id")
492            .and_then(Value::as_str)
493            .filter(|request_id| !request_id.is_empty())
494            .map(str::to_string)
495    }
496
497    /// Whether the Server refused a signal or update because its caller command
498    /// key is retained for a command with a different intent
499    /// (HTTP 409, `reason: "request_id_conflict"`).
500    ///
501    /// The SDK never resends this refusal, and the caller should not retry it
502    /// unchanged: send the original input to recover the retained receipt, or
503    /// use a new key for new input.
504    pub fn is_request_id_conflict(&self) -> bool {
505        self.request_id_conflict().is_some()
506    }
507
508    /// The retained-command details of a `request_id_conflict` refusal.
509    pub fn request_id_conflict(&self) -> Option<RequestIdConflict> {
510        let status = match self {
511            Self::Http { status, .. } => status.as_u16(),
512            Self::WorkflowCommandRejected(rejection) => rejection.status,
513            _ => return None,
514        };
515        request_id_conflict(status, self.refusal_body()?)
516    }
517
518    /// Record the sent caller command key on a `request_id_conflict` refusal
519    /// whose body does not echo it, so [`Error::request_id`] and
520    /// [`RequestIdConflict::request_id`] name the key. Every other error, and a
521    /// body that already echoes a key, is returned unchanged.
522    fn with_sent_request_id(self, request_id: &str) -> Self {
523        let Self::Http { status, body } = self else {
524            return self;
525        };
526        let echoed = |map: &serde_json::Map<String, Value>| {
527            map.get("request_id")
528                .and_then(Value::as_str)
529                .is_some_and(|echoed| !echoed.is_empty())
530        };
531        match serde_json::from_str::<Value>(&body) {
532            Ok(Value::Object(mut map))
533                if map.get("reason").and_then(Value::as_str)
534                    == Some(REQUEST_ID_CONFLICT_REASON)
535                    && !echoed(&map) =>
536            {
537                map.insert(
538                    "request_id".to_string(),
539                    Value::String(request_id.to_string()),
540                );
541                Self::Http {
542                    status,
543                    body: Value::Object(map).to_string(),
544                }
545            }
546            _ => Self::Http { status, body },
547        }
548    }
549
550    /// Whether an update outcome read found no retained update with that id
551    /// for the workflow (HTTP 404, `reason: "update_not_found"`).
552    ///
553    /// That includes an update pruned with its run, so it does not prove the
554    /// update was never admitted.
555    pub fn is_update_not_found(&self) -> bool {
556        matches!(self, Self::Http { status, .. } if status.as_u16() == 404)
557            && self
558                .refusal_body()
559                .and_then(|body| {
560                    body.get("reason")
561                        .and_then(Value::as_str)
562                        .map(str::to_string)
563                })
564                .as_deref()
565                == Some("update_not_found")
566    }
567
568    fn refusal_body(&self) -> Option<Value> {
569        match self {
570            Self::Http { body, .. } => serde_json::from_str(body).ok(),
571            Self::WorkflowCommandRejected(rejection) => Some(rejection.body.clone()),
572            _ => None,
573        }
574    }
575}
576
577/// A refused signal or update whose caller command key is already retained for
578/// a command with a different intent.
579///
580/// Nothing was admitted or recorded, and the key stays bound to the retained
581/// command. Send a new key for a different command, or repeat the retained
582/// command's exact intent to receive its receipt. `conflict` lists the
583/// mismatched intent parts: `name`, `arguments` or `target_or_arguments`
584/// (native Server 3.9.0). `retained_command_id` names the retained command.
585/// `request_id` is the key that was sent. `retained_command_type` is `None`
586/// when the Server does not report it, as native Server 3.9.0 does not; the
587/// full answer, including `outcome: "rejected_request_id_conflict"`, is in
588/// `body`.
589///
590/// A Server that advertises `capabilities.command_request_keys` in
591/// [`Client::cluster_info`] compares every keyed signal and update this way.
592/// Older Servers (PHP Server 2.x and native up to 3.8) do not: a repeated
593/// signal key can record a second signal there, and an update retried with
594/// changed arguments returns the original receipt.
595#[derive(Clone, Debug, PartialEq)]
596#[non_exhaustive]
597pub struct RequestIdConflict {
598    pub status: u16,
599    pub request_id: String,
600    pub message: String,
601    pub retained_command_id: Option<String>,
602    pub retained_command_type: Option<String>,
603    pub retained_outcome: Option<String>,
604    pub conflict: Vec<String>,
605    pub body: Value,
606}
607
608fn request_id_conflict(status: u16, body: Value) -> Option<RequestIdConflict> {
609    if body.get("reason").and_then(Value::as_str) != Some(REQUEST_ID_CONFLICT_REASON) {
610        return None;
611    }
612    let string = |name: &str| body.get(name).and_then(Value::as_str).map(str::to_string);
613    Some(RequestIdConflict {
614        status,
615        request_id: string("request_id").unwrap_or_default(),
616        message: string("message")
617            .or_else(|| string("error"))
618            .unwrap_or_else(|| "request id is retained for a different command intent".to_string()),
619        retained_command_id: string("retained_command_id"),
620        retained_command_type: string("retained_command_type"),
621        retained_outcome: string("retained_outcome"),
622        conflict: body
623            .get("conflict")
624            .and_then(Value::as_array)
625            .map(|parts| {
626                parts
627                    .iter()
628                    .filter_map(Value::as_str)
629                    .map(str::to_string)
630                    .collect()
631            })
632            .unwrap_or_default(),
633        body,
634    })
635}
636
637/// Handler namespaces checked independently within a Worker.
638#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
639pub enum RegistrationKind {
640    Workflow,
641    Activity,
642    Query,
643    Update,
644}
645
646impl std::fmt::Display for RegistrationKind {
647    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
648        formatter.write_str(match self {
649            Self::Workflow => "workflow",
650            Self::Activity => "activity",
651            Self::Query => "query",
652            Self::Update => "update",
653        })
654    }
655}
656
657/// The authoring adapter and source location of a handler registration.
658#[derive(Clone, Debug, PartialEq, Eq)]
659pub struct HandlerRegistration {
660    pub method: &'static str,
661    pub handler_type: &'static str,
662    pub file: &'static str,
663    pub line: u32,
664    pub column: u32,
665}
666
667impl std::fmt::Display for HandlerRegistration {
668    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
669        write!(
670            formatter,
671            "{} at {}:{}:{} ({})",
672            self.method, self.file, self.line, self.column, self.handler_type
673        )
674    }
675}
676
677/// Ambiguous local configuration, rejected before contacting Server.
678#[derive(Clone, Debug, Error, PartialEq, Eq)]
679#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
680pub struct DuplicateRegistrationError {
681    pub handler_kind: RegistrationKind,
682    pub handler_name: String,
683    /// Query/update registrations are scoped to their owning workflow type.
684    pub workflow_type: Option<String>,
685    pub first_definition: HandlerRegistration,
686    pub second_definition: HandlerRegistration,
687}
688
689impl From<DuplicateRegistrationError> for Error {
690    fn from(error: DuplicateRegistrationError) -> Self {
691        Self::WorkerLoop(error.to_string())
692    }
693}
694
695/// Validation failure for a durable condition-wait definition.
696#[derive(Clone, Debug, Error, PartialEq, Eq)]
697pub enum ConditionWaitOptionsError {
698    #[error("condition_key must be non-empty")]
699    EmptyKey,
700    #[error("condition_definition_fingerprint must be non-empty")]
701    EmptyPredicateIdentity,
702    #[error("condition timeout is too large for the worker protocol")]
703    TimeoutOverflow,
704}
705
706/// Stable identity and optional durable timeout for a condition wait.
707///
708/// `predicate_identity` is recorded as the worker protocol's
709/// `condition_definition_fingerprint` and must change whenever predicate
710/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
711/// is written inline; it derives this identity from the predicate tokens.
712#[derive(Clone, Debug, PartialEq, Eq)]
713pub struct ConditionWaitOptions {
714    condition_key: String,
715    predicate_identity: String,
716    timeout: Option<Duration>,
717}
718
719impl ConditionWaitOptions {
720    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
721        Self {
722            condition_key: condition_key.into(),
723            predicate_identity: predicate_identity.into(),
724            timeout: None,
725        }
726    }
727
728    pub fn timeout(mut self, timeout: Duration) -> Self {
729        self.timeout = Some(timeout);
730        self
731    }
732
733    fn validate(
734        &self,
735    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
736        let condition_key = self.condition_key.trim();
737        if condition_key.is_empty() {
738            return Err(ConditionWaitOptionsError::EmptyKey);
739        }
740        let predicate_identity = self.predicate_identity.trim();
741        if predicate_identity.is_empty() {
742            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
743        }
744        let timeout_seconds = self
745            .timeout
746            .map(|timeout| {
747                timeout
748                    .as_secs()
749                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
750                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
751            })
752            .transpose()?;
753
754        Ok(ValidatedConditionWaitOptions {
755            condition_key: condition_key.to_string(),
756            predicate_identity: predicate_identity.to_string(),
757            timeout_seconds,
758        })
759    }
760}
761
762#[derive(Clone, Debug, PartialEq, Eq)]
763struct ValidatedConditionWaitOptions {
764    condition_key: String,
765    predicate_identity: String,
766    timeout_seconds: Option<u64>,
767}
768
769const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
770
771/// Unambiguous terminal result of a durable condition wait.
772#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
773#[serde(rename_all = "snake_case")]
774pub enum ConditionWaitResult {
775    Satisfied,
776    TimedOut,
777}
778
779impl ConditionWaitResult {
780    pub fn is_satisfied(self) -> bool {
781        self == Self::Satisfied
782    }
783
784    pub fn is_timed_out(self) -> bool {
785        self == Self::TimedOut
786    }
787}
788
789/// Build the stable condition definition identity used by [`wait_condition!`].
790#[doc(hidden)]
791pub fn __condition_definition_fingerprint(source: &str) -> String {
792    let mut digest = Sha256::new();
793    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
794    digest.update(source.as_bytes());
795    format!("sha256:{:x}", digest.finalize())
796}
797
798/// Create a durable condition wait whose predicate definition is fingerprinted
799/// from its inline Rust tokens.
800///
801/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
802/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
803///
804/// The identity includes the call site's [`module_path!`] and the predicate's
805/// [`stringify!`] output. Moving or renaming the workflow module changes it,
806/// even when the predicate behaves the same. Compiler upgrades can also change
807/// token stringification. Keep those identities stable while waits are open,
808/// or drain the affected runs before changing them.
809///
810/// Use [`ConditionWaitOptions::new`] with an explicit stable predicate identity
811/// when module moves or compiler changes must not affect it. Choose that
812/// identity before starting runs; replacing an existing macro fingerprint with
813/// a new label does not migrate histories. Change an explicit identity whenever
814/// the predicate's behavior changes.
815#[macro_export]
816macro_rules! wait_condition {
817    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
818        $ctx.wait_condition(
819            $crate::ConditionWaitOptions::new(
820                $key,
821                $crate::__condition_definition_fingerprint(concat!(
822                    module_path!(),
823                    "\0",
824                    stringify!($predicate)
825                )),
826            )
827            .timeout($timeout),
828            $predicate,
829        )
830    }};
831    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
832        $ctx.wait_condition(
833            $crate::ConditionWaitOptions::new(
834                $key,
835                $crate::__condition_definition_fingerprint(concat!(
836                    module_path!(),
837                    "\0",
838                    stringify!($predicate)
839                )),
840            ),
841            $predicate,
842        )
843    }};
844}
845
846const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
847const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
848const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
849const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
850const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
851
852/// Validation failure for a typed workflow search-attribute update.
853#[derive(Clone, Debug, Error, PartialEq, Eq)]
854pub enum SearchAttributeUpdateError {
855    #[error("search-attribute update requires at least one attribute")]
856    Empty,
857    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
858    InvalidKey(String),
859    #[error("search-attribute update exceeds the limit of 100 attributes")]
860    TooManyAttributes,
861    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
862    ValueTooLong {
863        key: String,
864        kind: &'static str,
865        limit: usize,
866    },
867    #[error(
868        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
869    )]
870    EmptyString(String),
871    #[error("search attribute {0:?} has a non-finite float value")]
872    NonFiniteFloat(String),
873    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
874    InvalidDateTime(String),
875    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
876    PayloadTooLarge,
877}
878
879/// One public typed search-attribute value.
880#[derive(Clone, Debug, PartialEq)]
881pub enum SearchAttributeValue {
882    String(String),
883    Keyword(String),
884    KeywordList(Vec<String>),
885    Int(i64),
886    Float(f64),
887    Bool(bool),
888    DateTime(String),
889    Delete,
890}
891
892impl SearchAttributeValue {
893    fn type_name(&self) -> Option<&'static str> {
894        match self {
895            Self::String(_) => Some("string"),
896            Self::Keyword(_) => Some("keyword"),
897            Self::KeywordList(_) => Some("keyword_list"),
898            Self::Int(_) => Some("int"),
899            Self::Float(_) => Some("float"),
900            Self::Bool(_) => Some("bool"),
901            Self::DateTime(_) => Some("datetime"),
902            Self::Delete => None,
903        }
904    }
905
906    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
907        let normalize_string = |value: String, kind: &'static str, limit: usize| {
908            let value = value.trim().to_string();
909            if value.is_empty() {
910                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
911            }
912            if value.len() > limit {
913                return Err(SearchAttributeUpdateError::ValueTooLong {
914                    key: key.to_string(),
915                    kind,
916                    limit,
917                });
918            }
919            Ok(value)
920        };
921
922        match self {
923            Self::String(value) => Ok(Self::String(normalize_string(
924                value,
925                "string",
926                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
927            )?)),
928            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
929                value,
930                "keyword",
931                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
932            )?)),
933            Self::KeywordList(values) => {
934                let values = values
935                    .into_iter()
936                    .map(|value| {
937                        let value = value.trim().to_string();
938                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
939                            return Err(SearchAttributeUpdateError::ValueTooLong {
940                                key: key.to_string(),
941                                kind: "keyword-list entry",
942                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
943                            });
944                        }
945                        Ok(value)
946                    })
947                    .collect::<std::result::Result<Vec<_>, _>>()?;
948                Ok(Self::KeywordList(values))
949            }
950            Self::Float(value) if !value.is_finite() => {
951                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
952            }
953            Self::DateTime(value) => {
954                let value =
955                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
956                if DateTime::parse_from_rfc3339(&value).is_err() {
957                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
958                }
959                Ok(Self::DateTime(value))
960            }
961            value => Ok(value),
962        }
963    }
964
965    fn into_json(self) -> Value {
966        match self {
967            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
968                Value::String(value)
969            }
970            Self::KeywordList(values) => {
971                Value::Array(values.into_iter().map(Value::String).collect())
972            }
973            Self::Int(value) => json!(value),
974            Self::Float(value) => json!(value),
975            Self::Bool(value) => json!(value),
976            Self::Delete => Value::Null,
977        }
978    }
979}
980
981/// Validated typed workflow-side search-attribute mutation.
982#[derive(Clone, Debug, Default, PartialEq)]
983pub struct SearchAttributeUpdate {
984    attributes: BTreeMap<String, SearchAttributeValue>,
985}
986
987impl SearchAttributeUpdate {
988    pub fn new() -> Self {
989        Self::default()
990    }
991
992    pub fn set(
993        mut self,
994        key: impl Into<String>,
995        value: SearchAttributeValue,
996    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
997        let key = key.into();
998        validate_search_attribute_key(&key)?;
999        if !self.attributes.contains_key(&key)
1000            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
1001        {
1002            return Err(SearchAttributeUpdateError::TooManyAttributes);
1003        }
1004        self.attributes.insert(key.clone(), value.normalized(&key)?);
1005        self.validate_size()?;
1006        Ok(self)
1007    }
1008
1009    pub fn string(
1010        self,
1011        key: impl Into<String>,
1012        value: impl Into<String>,
1013    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1014        self.set(key, SearchAttributeValue::String(value.into()))
1015    }
1016
1017    pub fn keyword(
1018        self,
1019        key: impl Into<String>,
1020        value: impl Into<String>,
1021    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1022        self.set(key, SearchAttributeValue::Keyword(value.into()))
1023    }
1024
1025    pub fn keyword_list<I, V>(
1026        self,
1027        key: impl Into<String>,
1028        values: I,
1029    ) -> std::result::Result<Self, SearchAttributeUpdateError>
1030    where
1031        I: IntoIterator<Item = V>,
1032        V: Into<String>,
1033    {
1034        self.set(
1035            key,
1036            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
1037        )
1038    }
1039
1040    pub fn int(
1041        self,
1042        key: impl Into<String>,
1043        value: i64,
1044    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1045        self.set(key, SearchAttributeValue::Int(value))
1046    }
1047
1048    pub fn float(
1049        self,
1050        key: impl Into<String>,
1051        value: f64,
1052    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1053        self.set(key, SearchAttributeValue::Float(value))
1054    }
1055
1056    pub fn bool(
1057        self,
1058        key: impl Into<String>,
1059        value: bool,
1060    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1061        self.set(key, SearchAttributeValue::Bool(value))
1062    }
1063
1064    pub fn datetime(
1065        self,
1066        key: impl Into<String>,
1067        value: impl Into<String>,
1068    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1069        self.set(key, SearchAttributeValue::DateTime(value.into()))
1070    }
1071
1072    pub fn delete(
1073        self,
1074        key: impl Into<String>,
1075    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1076        self.set(key, SearchAttributeValue::Delete)
1077    }
1078
1079    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
1080        let (attributes, _) = self.clone().into_wire_parts();
1081        if serde_json::to_vec(&attributes)
1082            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
1083            .unwrap_or(true)
1084        {
1085            return Err(SearchAttributeUpdateError::PayloadTooLarge);
1086        }
1087        Ok(())
1088    }
1089
1090    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
1091        let mut attributes = serde_json::Map::new();
1092        let mut attribute_types = BTreeMap::new();
1093        for (key, value) in self.attributes {
1094            if let Some(type_name) = value.type_name() {
1095                attribute_types.insert(key.clone(), type_name.to_string());
1096            }
1097            attributes.insert(key, value.into_json());
1098        }
1099        (Value::Object(attributes), attribute_types)
1100    }
1101
1102    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
1103        if self.attributes.is_empty() {
1104            return Err(SearchAttributeUpdateError::Empty);
1105        }
1106        self.validate_size()
1107    }
1108}
1109
1110fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
1111    let valid = !key.is_empty()
1112        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
1113        && key
1114            .bytes()
1115            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
1116    if valid {
1117        Ok(())
1118    } else {
1119        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
1120    }
1121}
1122
1123/// The registered handler family reported by [`Error::HandlerType`].
1124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1125pub enum HandlerKind {
1126    Workflow,
1127    Activity,
1128}
1129
1130impl std::fmt::Display for HandlerKind {
1131    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1132        formatter.write_str(match self {
1133            Self::Workflow => "workflow",
1134            Self::Activity => "activity",
1135        })
1136    }
1137}
1138
1139/// Whether a typed handler failed to adapt its input or result.
1140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1141pub enum HandlerValueKind {
1142    Input,
1143    Result,
1144}
1145
1146impl std::fmt::Display for HandlerValueKind {
1147    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1148        formatter.write_str(match self {
1149            Self::Input => "input",
1150            Self::Result => "result",
1151        })
1152    }
1153}
1154
1155/// The lifecycle command sent to a workflow execution.
1156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1157pub enum WorkflowCommandKind {
1158    Cancel,
1159    Terminate,
1160}
1161
1162impl WorkflowCommandKind {
1163    fn as_str(self) -> &'static str {
1164        match self {
1165            Self::Cancel => "cancel",
1166            Self::Terminate => "terminate",
1167        }
1168    }
1169}
1170
1171/// Optional structured fields for a cancellation or termination request.
1172#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
1173pub struct WorkflowCommandOptions {
1174    #[serde(skip_serializing_if = "Option::is_none")]
1175    pub reason: Option<String>,
1176    #[serde(skip_serializing_if = "Option::is_none")]
1177    pub request_id: Option<String>,
1178}
1179
1180/// Server-enforced timeout policy for a workflow start.
1181///
1182/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
1183/// only bounds how long the caller waits. A server deadline produces a terminal
1184/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
1185/// `run_timeout`.
1186#[derive(Clone, Debug, PartialEq, Eq)]
1187pub struct WorkflowStartOptions {
1188    pub execution_timeout_seconds: u64,
1189    pub run_timeout_seconds: u64,
1190}
1191
1192impl Default for WorkflowStartOptions {
1193    fn default() -> Self {
1194        Self {
1195            execution_timeout_seconds: 3600,
1196            run_timeout_seconds: 600,
1197        }
1198    }
1199}
1200
1201impl WorkflowStartOptions {
1202    pub fn new() -> Self {
1203        Self::default()
1204    }
1205
1206    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1207        self.execution_timeout_seconds = seconds;
1208        self
1209    }
1210
1211    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1212        self.run_timeout_seconds = seconds;
1213        self
1214    }
1215
1216    fn validate(&self) -> Result<()> {
1217        if self.execution_timeout_seconds == 0 {
1218            return Err(Error::Codec(
1219                "execution_timeout_seconds must be at least 1".to_string(),
1220            ));
1221        }
1222        if self.run_timeout_seconds == 0 {
1223            return Err(Error::Codec(
1224                "run_timeout_seconds must be at least 1".to_string(),
1225            ));
1226        }
1227        if self.run_timeout_seconds > self.execution_timeout_seconds {
1228            return Err(Error::Codec(
1229                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
1230            ));
1231        }
1232
1233        Ok(())
1234    }
1235}
1236
1237/// Optional routing overrides for a continue-as-new transition.
1238///
1239/// Omitted values retain the current workflow type and task queue. Server-owned
1240/// instance metadata is not accepted here and is carried by the server.
1241#[derive(Clone, Debug, Default, PartialEq, Eq)]
1242pub struct ContinueAsNewOptions {
1243    pub workflow_type: Option<String>,
1244    pub task_queue: Option<String>,
1245}
1246
1247impl ContinueAsNewOptions {
1248    pub fn new() -> Self {
1249        Self::default()
1250    }
1251
1252    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
1253        self.workflow_type = Some(workflow_type.into());
1254        self
1255    }
1256
1257    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1258        self.task_queue = Some(task_queue.into());
1259        self
1260    }
1261
1262    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
1263        for (field, value) in [
1264            ("workflow_type", self.workflow_type.as_deref()),
1265            ("task_queue", self.task_queue.as_deref()),
1266        ] {
1267            if value.is_some_and(|value| value.trim().is_empty()) {
1268                return Err(ContinueAsNewOptionsError {
1269                    field,
1270                    message: format!("{field} must not be empty"),
1271                });
1272            }
1273        }
1274        Ok(())
1275    }
1276}
1277
1278/// A stable validation error raised before a continue-as-new command is emitted.
1279#[derive(Clone, Debug, Error, PartialEq, Eq)]
1280#[error("invalid continue-as-new option {field}: {message}")]
1281pub struct ContinueAsNewOptionsError {
1282    pub field: &'static str,
1283    pub message: String,
1284}
1285
1286/// Public history-budget information attached to the current workflow task.
1287#[derive(Clone, Debug, Default, PartialEq, Eq)]
1288pub struct WorkflowHistoryBudget {
1289    pub event_count: u64,
1290    pub size_bytes: Option<u64>,
1291    pub continue_as_new_recommended: bool,
1292    pub pressure: Option<String>,
1293}
1294
1295#[doc(hidden)]
1296#[derive(Clone, Debug)]
1297pub struct ContinueAsNewRequest {
1298    arguments: AvroValue,
1299    options: ContinueAsNewOptions,
1300}
1301
1302impl WorkflowCommandOptions {
1303    pub fn new() -> Self {
1304        Self::default()
1305    }
1306
1307    pub fn reason(mut self, reason: impl Into<String>) -> Self {
1308        self.reason = Some(reason.into());
1309        self
1310    }
1311
1312    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
1313        self.request_id = Some(request_id.into());
1314        self
1315    }
1316}
1317
1318/// The accepted, machine-readable result of a lifecycle command.
1319#[derive(Clone, Debug, PartialEq)]
1320pub struct WorkflowCommandResult {
1321    pub command: WorkflowCommandKind,
1322    pub workflow_id: String,
1323    pub run_id: Option<String>,
1324    pub outcome: Option<String>,
1325    pub reason: Option<String>,
1326    pub command_status: Option<String>,
1327    pub raw: Value,
1328}
1329
1330/// A new run continuing a failed run from its recorded activity boundary.
1331#[derive(Clone, Debug, PartialEq)]
1332pub struct WorkflowRedriveResult {
1333    pub workflow_id: String,
1334    pub source_run_id: String,
1335    pub run_id: String,
1336    pub resume_step_sequence: u64,
1337    pub raw: Value,
1338}
1339
1340/// A stable rejection returned by instance- or selected-run lifecycle commands.
1341#[derive(Clone, Debug, Error)]
1342#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1343pub struct WorkflowCommandRejection {
1344    pub command: WorkflowCommandKind,
1345    pub status: u16,
1346    pub reason: String,
1347    pub message: String,
1348    pub workflow_id: String,
1349    pub run_id: Option<String>,
1350    pub target_scope: Option<String>,
1351    pub body: Value,
1352}
1353
1354/// Stable terminal categories returned by [`WorkflowHandle::result`].
1355#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1356pub enum WorkflowTerminalKind {
1357    Failed,
1358    Cancelled,
1359    Terminated,
1360    TimedOut,
1361}
1362
1363/// A typed terminal workflow outcome with durable identity and failure metadata.
1364///
1365/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1366/// of parsing its display representation. Fields remain `None` when an older
1367/// server did not publish that metadata.
1368#[derive(Clone, Debug, Error)]
1369#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1370pub struct WorkflowTerminalOutcome {
1371    pub kind: WorkflowTerminalKind,
1372    pub workflow_id: String,
1373    pub run_id: Option<String>,
1374    pub reason: String,
1375    pub failure_category: Option<String>,
1376    pub failure_id: Option<String>,
1377    pub exception_type: Option<String>,
1378    pub exception_class: Option<String>,
1379    pub non_retryable: Option<bool>,
1380    pub message: Option<String>,
1381    pub exception: Option<Value>,
1382    pub raw: Value,
1383}
1384
1385/// A worker-side activity settlement or heartbeat rejected by durable state.
1386#[derive(Clone, Debug, Error)]
1387#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1388pub struct ActivityTaskRejection {
1389    pub operation: String,
1390    pub status: u16,
1391    pub reason: String,
1392    pub task_id: String,
1393    pub activity_attempt_id: String,
1394    pub cancel_requested: bool,
1395    pub can_continue: Option<bool>,
1396    pub run_closed_reason: Option<String>,
1397    pub body: Value,
1398}
1399
1400/// Stable validation categories for [`ActivityOptions`].
1401#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1402pub enum ActivityOptionsErrorKind {
1403    EmptyTaskQueue,
1404    EmptyRetryPolicy,
1405    InvalidMaxAttempts,
1406    BackoffWithoutRetryBudget,
1407    TooManyBackoffIntervals,
1408    InvalidBackoffCoefficient,
1409    BackoffGenerationTooLarge,
1410    BackoffOverflow,
1411    EmptyNonRetryableErrorType,
1412    TimeoutNotPositive,
1413    MissingTotalTimeout,
1414    TimeoutOverflow,
1415    TimeoutOrder,
1416}
1417
1418/// A machine-readable activity-options validation failure.
1419#[derive(Clone, Debug, Error, PartialEq, Eq)]
1420#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1421pub struct ActivityOptionsError {
1422    pub kind: ActivityOptionsErrorKind,
1423    pub field: Option<&'static str>,
1424    pub message: String,
1425}
1426
1427impl ActivityOptionsError {
1428    fn new(
1429        kind: ActivityOptionsErrorKind,
1430        field: Option<&'static str>,
1431        message: impl Into<String>,
1432    ) -> Self {
1433        Self {
1434            kind,
1435            field,
1436            message: message.into(),
1437        }
1438    }
1439}
1440
1441/// Stable terminal categories returned when an awaited activity does not succeed.
1442#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1443pub enum ActivityFailureKind {
1444    Failed,
1445    Cancelled,
1446    TimedOut,
1447}
1448
1449/// A stable, machine-readable terminal activity failure.
1450///
1451/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1452/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1453#[derive(Clone, Debug, Error, PartialEq)]
1454#[error("activity failed ({reason}): {message}")]
1455pub struct ActivityFailure {
1456    pub kind: ActivityFailureKind,
1457    pub reason: String,
1458    pub message: String,
1459    pub activity_execution_id: Option<String>,
1460    pub activity_attempt_id: Option<String>,
1461    pub activity_type: Option<String>,
1462    pub activity_class: Option<String>,
1463    pub attempt_number: Option<u64>,
1464    pub failure_id: Option<String>,
1465    pub failure_category: Option<String>,
1466    pub timeout_kind: Option<String>,
1467    pub non_retryable: bool,
1468    pub exception_type: Option<String>,
1469    pub exception_class: Option<String>,
1470    pub code: Option<Value>,
1471    pub exception: Option<Value>,
1472}
1473
1474/// Stable terminal categories returned when an awaited child does not succeed.
1475#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1476pub enum ChildWorkflowFailureKind {
1477    Failed,
1478    Cancelled,
1479    Terminated,
1480}
1481
1482/// A stable, machine-readable child workflow failure delivered to its parent.
1483///
1484/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1485/// of parsing the display message. Child and parent identifiers retain the
1486/// relationship recorded in durable history across worker restarts.
1487#[derive(Clone, Debug, Error)]
1488#[error("child workflow failed ({reason}): {message}")]
1489pub struct ChildWorkflowFailure {
1490    pub kind: ChildWorkflowFailureKind,
1491    pub reason: String,
1492    pub message: String,
1493    pub parent_workflow_id: Option<String>,
1494    pub parent_workflow_run_id: Option<String>,
1495    pub child_workflow_id: Option<String>,
1496    pub child_workflow_run_id: Option<String>,
1497    pub child_workflow_type: Option<String>,
1498    pub failure_id: Option<String>,
1499    pub failure_category: Option<String>,
1500    pub exception_type: Option<String>,
1501    pub exception_class: Option<String>,
1502    pub non_retryable: bool,
1503    pub code: Option<Value>,
1504    pub exception: Option<Value>,
1505}
1506
1507/// The identity of one durable workflow execution.
1508#[derive(Clone, Debug, PartialEq, Eq)]
1509pub struct WorkflowIdentity {
1510    pub workflow_id: Option<String>,
1511    pub run_id: Option<String>,
1512}
1513
1514/// A successful child result together with its durable parent-child identity.
1515#[derive(Clone, Debug, PartialEq)]
1516pub struct ChildWorkflowResult {
1517    pub parent: WorkflowIdentity,
1518    pub child: WorkflowIdentity,
1519    pub child_workflow_type: Option<String>,
1520    pub result: Value,
1521}
1522
1523/// Lossless successful child result for fixed Avro Value workflows.
1524#[derive(Clone, Debug, PartialEq)]
1525pub struct ChildWorkflowAvroResult {
1526    pub parent: WorkflowIdentity,
1527    pub child: WorkflowIdentity,
1528    pub child_workflow_type: Option<String>,
1529    pub result: AvroValue,
1530}
1531
1532/// Stable user-facing identity for one member of a durable selection group.
1533#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1534#[serde(untagged)]
1535pub enum SelectionKey {
1536    Index(usize),
1537    Name(String),
1538}
1539
1540impl From<usize> for SelectionKey {
1541    fn from(value: usize) -> Self {
1542        Self::Index(value)
1543    }
1544}
1545
1546impl From<String> for SelectionKey {
1547    fn from(value: String) -> Self {
1548        Self::Name(value)
1549    }
1550}
1551
1552impl From<&str> for SelectionKey {
1553    fn from(value: &str) -> Self {
1554        Self::Name(value.to_string())
1555    }
1556}
1557
1558/// Typed result of explicitly awaiting a cancelled non-winning operation.
1559#[derive(Clone, Debug, Error, PartialEq, Eq)]
1560#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1561pub struct DurableOperationCancelled {
1562    pub selection_group_id: String,
1563    pub member_key: SelectionKey,
1564    pub member_index: usize,
1565    pub operation_kind: String,
1566    pub operation_identity: String,
1567}
1568
1569/// Stable identity for one enclosing deterministic parallel group.
1570///
1571/// The same fields are attached to every ordinary activity, timer, or child
1572/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1573/// no Rust-specific wire command is introduced.
1574#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1575pub struct ParallelGroupMetadata {
1576    pub parallel_group_id: String,
1577    pub parallel_group_kind: String,
1578    pub parallel_group_base_sequence: u64,
1579    pub parallel_group_size: usize,
1580    pub parallel_group_index: usize,
1581    #[serde(default, skip_serializing_if = "Option::is_none")]
1582    pub parallel_group_mode: Option<String>,
1583    #[serde(default, skip_serializing_if = "Option::is_none")]
1584    pub selection_member_key: Option<SelectionKey>,
1585    #[serde(default, skip_serializing_if = "Option::is_none")]
1586    pub selection_member_index: Option<usize>,
1587    #[serde(default, skip_serializing_if = "Option::is_none")]
1588    pub selection_member_base_sequence: Option<u64>,
1589    #[serde(default, skip_serializing_if = "Option::is_none")]
1590    pub selection_member_size: Option<usize>,
1591    #[serde(default, skip_serializing_if = "Option::is_none")]
1592    pub selection_member_kind: Option<String>,
1593}
1594
1595/// One input-ordered result returned by [`WorkflowContext::parallel`].
1596#[derive(Clone, Debug, PartialEq)]
1597pub enum ParallelResult {
1598    Activity(Value),
1599    ChildWorkflow(ChildWorkflowResult),
1600    Timer,
1601    Signal(Vec<Value>),
1602    Condition(ConditionWaitResult),
1603    Group(Vec<ParallelResult>),
1604}
1605
1606/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1607#[derive(Clone, Debug, PartialEq)]
1608pub enum ParallelAvroResult {
1609    Activity(AvroValue),
1610    ChildWorkflow(ChildWorkflowAvroResult),
1611    Timer,
1612    Signal(Vec<AvroValue>),
1613    Condition(ConditionWaitResult),
1614    Group(Vec<ParallelAvroResult>),
1615}
1616
1617impl ParallelAvroResult {
1618    fn into_json_result(self) -> Result<ParallelResult> {
1619        match self {
1620            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1621            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1622                parent: result.parent,
1623                child: result.child,
1624                child_workflow_type: result.child_workflow_type,
1625                result: result.result.into_json()?,
1626            })),
1627            Self::Timer => Ok(ParallelResult::Timer),
1628            Self::Signal(values) => Ok(ParallelResult::Signal(
1629                values
1630                    .into_iter()
1631                    .map(AvroValue::into_json)
1632                    .collect::<Result<Vec<_>>>()?,
1633            )),
1634            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1635            Self::Group(results) => Ok(ParallelResult::Group(
1636                results
1637                    .into_iter()
1638                    .map(Self::into_json_result)
1639                    .collect::<Result<Vec<_>>>()?,
1640            )),
1641        }
1642    }
1643}
1644
1645/// One successful leaf retained when another parallel member failed.
1646#[derive(Clone, Debug, PartialEq)]
1647pub struct ParallelCompletion {
1648    pub member_path: Vec<usize>,
1649    pub result: ParallelResult,
1650}
1651
1652/// A deterministic join failed after some siblings had already completed.
1653///
1654/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1655/// error. `completed` is declaration ordered and contains only durable
1656/// successes observed in the same replay. Late sibling completions can add
1657/// entries on a later replay without changing `member_path` or the selected
1658/// positional failure.
1659#[derive(Debug, Error)]
1660#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1661pub struct ParallelFailure {
1662    pub group_id: String,
1663    pub member_path: Vec<usize>,
1664    pub group_path: Vec<ParallelGroupMetadata>,
1665    pub completed: Vec<ParallelCompletion>,
1666    #[source]
1667    pub cause: Box<Error>,
1668}
1669
1670/// Stable validation error returned before an invalid group emits commands.
1671#[derive(Clone, Debug, Error, PartialEq, Eq)]
1672#[error("invalid deterministic parallel group ({reason}): {message}")]
1673pub struct ParallelGroupError {
1674    pub reason: &'static str,
1675    pub member_path: Vec<usize>,
1676    pub message: String,
1677}
1678
1679/// Cooperative workflow cancellation observed at an author-controlled point.
1680#[derive(Clone, Debug, Error, PartialEq, Eq)]
1681#[error("workflow cancellation was requested")]
1682pub struct WorkflowCancellationRequested;
1683
1684/// A forward saga failure followed by a terminal compensation failure.
1685#[derive(Debug, Error)]
1686#[error(
1687    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1688)]
1689pub struct SagaCompensationFailure {
1690    pub initiating_failure: Box<Error>,
1691    pub compensation_failure: Box<Error>,
1692    pub compensation_activity_type: String,
1693    pub compensation_registration_order: usize,
1694}
1695
1696/// Server behavior when a parent closes while its child is still open.
1697#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1698pub enum ParentClosePolicy {
1699    #[default]
1700    Abandon,
1701    /// Legacy terminal cancellation without cooperative cleanup.
1702    RequestCancel,
1703    /// Request cooperative cleanup with the original lineage and deadline.
1704    RequestCancellation,
1705    Terminate,
1706}
1707
1708impl ParentClosePolicy {
1709    fn as_str(self) -> &'static str {
1710        match self {
1711            Self::Abandon => "abandon",
1712            Self::RequestCancel => "request_cancel",
1713            Self::RequestCancellation => "request_cancellation",
1714            Self::Terminate => "terminate",
1715        }
1716    }
1717}
1718
1719/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1720#[non_exhaustive]
1721#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1722pub enum CancellationPolicy {
1723    /// Request cancellation and continue without waiting. Historical Activity default.
1724    TryCancel,
1725    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1726    WaitCancellationCompleted,
1727    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1728    #[default]
1729    Abandon,
1730}
1731
1732impl CancellationPolicy {
1733    fn as_str(self) -> &'static str {
1734        match self {
1735            Self::TryCancel => "try_cancel",
1736            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1737            Self::Abandon => "abandon",
1738        }
1739    }
1740}
1741
1742/// Durable retry policy for one child workflow invocation.
1743#[derive(Clone, Debug, Default, PartialEq, Eq)]
1744pub struct ChildWorkflowRetryPolicy {
1745    pub max_attempts: Option<u32>,
1746    pub backoff_seconds: Vec<u64>,
1747    pub non_retryable_error_types: Vec<String>,
1748}
1749
1750/// Options recorded with a child-workflow command.
1751///
1752/// The task queue is mandatory so routing is explicit and replay-stable.
1753#[derive(Clone, Debug, PartialEq, Eq)]
1754pub struct ChildWorkflowOptions {
1755    pub task_queue: String,
1756    pub parent_close_policy: ParentClosePolicy,
1757    pub cancellation_policy: CancellationPolicy,
1758    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1759    pub execution_timeout_seconds: Option<u64>,
1760    pub run_timeout_seconds: Option<u64>,
1761}
1762
1763impl ChildWorkflowOptions {
1764    pub fn new(task_queue: impl Into<String>) -> Self {
1765        Self {
1766            task_queue: task_queue.into(),
1767            parent_close_policy: ParentClosePolicy::Abandon,
1768            cancellation_policy: CancellationPolicy::Abandon,
1769            retry_policy: None,
1770            execution_timeout_seconds: None,
1771            run_timeout_seconds: None,
1772        }
1773    }
1774
1775    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1776        self.parent_close_policy = policy;
1777        self
1778    }
1779
1780    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1781        self.cancellation_policy = policy;
1782        self
1783    }
1784
1785    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1786        self.retry_policy = Some(policy);
1787        self
1788    }
1789
1790    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1791        self.execution_timeout_seconds = Some(seconds);
1792        self
1793    }
1794
1795    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1796        self.run_timeout_seconds = Some(seconds);
1797        self
1798    }
1799}
1800
1801/// Backoff intervals for one durable activity retry policy.
1802#[derive(Clone, Debug, PartialEq, Eq)]
1803pub enum ActivityBackoff {
1804    /// Use these intervals between attempts. The server repeats the final
1805    /// interval if the retry budget contains more attempts than entries.
1806    /// All entries are retained, including those beyond the retry budget.
1807    Explicit(Vec<Duration>),
1808    /// Generate one interval for every retry using integer exponential growth.
1809    Exponential {
1810        initial_interval: Duration,
1811        coefficient: u32,
1812        maximum_interval: Option<Duration>,
1813    },
1814}
1815
1816/// Durable server-side retry policy for one activity execution.
1817#[derive(Clone, Debug, Default, PartialEq, Eq)]
1818pub struct ActivityRetryPolicy {
1819    pub max_attempts: Option<u32>,
1820    pub backoff: Option<ActivityBackoff>,
1821    pub non_retryable_error_types: Vec<String>,
1822}
1823
1824impl ActivityRetryPolicy {
1825    /// Start a policy with a finite attempt budget, including the first attempt.
1826    pub fn new(max_attempts: u32) -> Self {
1827        Self {
1828            max_attempts: Some(max_attempts),
1829            ..Self::default()
1830        }
1831    }
1832
1833    /// Preserve the complete explicit list independently of the attempt budget.
1834    /// Unused entries remain part of the policy compared during replay.
1835    /// Set explicit durable retry intervals. Each positive fractional second
1836    /// is rounded up when encoded: `Duration::from_millis(100)` becomes one
1837    /// second. Zero stays zero. Queue latency can delay the next attempt further.
1838    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
1839        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
1840        self
1841    }
1842
1843    /// Generate durable retry intervals from `initial_interval` and `coefficient`.
1844    /// Each interval is capped by `maximum_interval`, when present, then rounded
1845    /// up to whole seconds. A 100 ms interval or cap therefore encodes one second.
1846    /// Zero stays zero. This policy is separate from HTTP transport retries.
1847    pub fn exponential_backoff(
1848        mut self,
1849        initial_interval: Duration,
1850        coefficient: u32,
1851        maximum_interval: Option<Duration>,
1852    ) -> Self {
1853        self.backoff = Some(ActivityBackoff::Exponential {
1854            initial_interval,
1855            coefficient,
1856            maximum_interval,
1857        });
1858        self
1859    }
1860
1861    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
1862        self.non_retryable_error_types.push(error_type.into());
1863        self
1864    }
1865
1866    pub fn non_retryable_error_types(
1867        mut self,
1868        error_types: impl IntoIterator<Item = impl Into<String>>,
1869    ) -> Self {
1870        self.non_retryable_error_types
1871            .extend(error_types.into_iter().map(Into::into));
1872        self
1873    }
1874}
1875
1876/// Options recorded atomically on one deterministic `schedule_activity` command.
1877///
1878/// Durations are rounded up to whole seconds when encoded, so the server never
1879/// receives a shorter timeout or backoff than the caller requested.
1880#[derive(Clone, Debug, Default, PartialEq, Eq)]
1881pub struct ActivityOptions {
1882    pub task_queue: Option<String>,
1883    pub retry_policy: Option<ActivityRetryPolicy>,
1884    pub start_to_close_timeout: Option<Duration>,
1885    pub schedule_to_start_timeout: Option<Duration>,
1886    pub schedule_to_close_timeout: Option<Duration>,
1887    pub heartbeat_timeout: Option<Duration>,
1888    pub cancellation_policy: Option<CancellationPolicy>,
1889}
1890
1891impl ActivityOptions {
1892    pub fn new() -> Self {
1893        Self::default()
1894    }
1895
1896    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1897        self.task_queue = Some(task_queue.into());
1898        self
1899    }
1900
1901    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
1902        self.retry_policy = Some(policy);
1903        self
1904    }
1905
1906    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
1907        self.start_to_close_timeout = Some(timeout);
1908        self
1909    }
1910
1911    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
1912        self.schedule_to_start_timeout = Some(timeout);
1913        self
1914    }
1915
1916    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
1917        self.schedule_to_close_timeout = Some(timeout);
1918        self
1919    }
1920
1921    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
1922        self.heartbeat_timeout = Some(timeout);
1923        self
1924    }
1925
1926    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1927        self.cancellation_policy = Some(policy);
1928        self
1929    }
1930
1931    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
1932        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
1933            && self.schedule_to_close_timeout.is_none()
1934        {
1935            return Err(ActivityOptionsError::new(
1936                ActivityOptionsErrorKind::MissingTotalTimeout,
1937                Some("schedule_to_close_timeout"),
1938                "remote Activity Abandon requires a finite positive total timeout",
1939            ));
1940        }
1941        if self
1942            .task_queue
1943            .as_deref()
1944            .is_some_and(|queue| queue.trim().is_empty())
1945        {
1946            return Err(ActivityOptionsError::new(
1947                ActivityOptionsErrorKind::EmptyTaskQueue,
1948                Some("task_queue"),
1949                "task_queue must not be empty",
1950            ));
1951        }
1952
1953        for (field, value) in [
1954            ("start_to_close_timeout", self.start_to_close_timeout),
1955            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
1956            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
1957            ("heartbeat_timeout", self.heartbeat_timeout),
1958        ] {
1959            if value.is_some_and(|value| value.is_zero()) {
1960                return Err(ActivityOptionsError::new(
1961                    ActivityOptionsErrorKind::TimeoutNotPositive,
1962                    Some(field),
1963                    format!("{field} must be positive"),
1964                ));
1965            }
1966        }
1967
1968        validate_timeout_order(
1969            "heartbeat_timeout",
1970            self.heartbeat_timeout,
1971            "start_to_close_timeout",
1972            self.start_to_close_timeout,
1973        )?;
1974        validate_timeout_order(
1975            "start_to_close_timeout",
1976            self.start_to_close_timeout,
1977            "schedule_to_close_timeout",
1978            self.schedule_to_close_timeout,
1979        )?;
1980        validate_timeout_order(
1981            "schedule_to_start_timeout",
1982            self.schedule_to_start_timeout,
1983            "schedule_to_close_timeout",
1984            self.schedule_to_close_timeout,
1985        )?;
1986
1987        Ok(ValidatedActivityOptions {
1988            task_queue: self.task_queue.clone(),
1989            retry_policy: self
1990                .retry_policy
1991                .as_ref()
1992                .map(validate_activity_retry_policy)
1993                .transpose()?,
1994            start_to_close_timeout: timeout_seconds(
1995                "start_to_close_timeout",
1996                self.start_to_close_timeout,
1997            )?,
1998            schedule_to_start_timeout: timeout_seconds(
1999                "schedule_to_start_timeout",
2000                self.schedule_to_start_timeout,
2001            )?,
2002            schedule_to_close_timeout: timeout_seconds(
2003                "schedule_to_close_timeout",
2004                self.schedule_to_close_timeout,
2005            )?,
2006            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
2007            cancellation_policy: self.cancellation_policy,
2008        })
2009    }
2010}
2011
2012/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
2013///
2014/// Constructors capture arguments but perform no I/O. The join validates the
2015/// complete tree, attaches the existing parallel-group metadata to every
2016/// ordinary command, schedules all leaves, and then suspends.
2017pub enum ParallelOperation {
2018    Activity {
2019        activity_type: String,
2020        options: ActivityOptions,
2021        arguments: Result<AvroValue>,
2022    },
2023    ChildWorkflow {
2024        workflow_type: String,
2025        options: ChildWorkflowOptions,
2026        arguments: Result<AvroValue>,
2027    },
2028    Timer(Duration),
2029    Signal(String),
2030    Condition {
2031        options: ConditionWaitOptions,
2032        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
2033    },
2034    Group(Vec<ParallelOperation>),
2035}
2036
2037impl ParallelOperation {
2038    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
2039        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
2040    }
2041
2042    pub fn activity_with_options<T: Serialize>(
2043        activity_type: impl Into<String>,
2044        options: ActivityOptions,
2045        args: T,
2046    ) -> Self {
2047        Self::Activity {
2048            activity_type: activity_type.into(),
2049            options,
2050            arguments: AvroValue::from_serialize(&args),
2051        }
2052    }
2053
2054    pub fn child_workflow<T: Serialize>(
2055        workflow_type: impl Into<String>,
2056        options: ChildWorkflowOptions,
2057        args: T,
2058    ) -> Self {
2059        Self::ChildWorkflow {
2060            workflow_type: workflow_type.into(),
2061            options,
2062            arguments: AvroValue::from_serialize(&args),
2063        }
2064    }
2065
2066    pub fn timer(duration: Duration) -> Self {
2067        Self::Timer(duration)
2068    }
2069
2070    pub fn signal(signal_name: impl Into<String>) -> Self {
2071        Self::Signal(signal_name.into())
2072    }
2073
2074    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
2075    where
2076        F: Fn() -> Result<bool> + Send + 'static,
2077    {
2078        Self::Condition {
2079            options,
2080            predicate: Box::new(predicate),
2081        }
2082    }
2083
2084    pub fn group(operations: Vec<ParallelOperation>) -> Self {
2085        Self::Group(operations)
2086    }
2087}
2088
2089#[derive(Clone, Debug)]
2090struct ValidatedActivityOptions {
2091    task_queue: Option<String>,
2092    retry_policy: Option<Value>,
2093    start_to_close_timeout: Option<u64>,
2094    schedule_to_start_timeout: Option<u64>,
2095    schedule_to_close_timeout: Option<u64>,
2096    heartbeat_timeout: Option<u64>,
2097    cancellation_policy: Option<CancellationPolicy>,
2098}
2099
2100fn validate_timeout_order(
2101    smaller_name: &'static str,
2102    smaller: Option<Duration>,
2103    larger_name: &'static str,
2104    larger: Option<Duration>,
2105) -> std::result::Result<(), ActivityOptionsError> {
2106    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
2107        return Err(ActivityOptionsError::new(
2108            ActivityOptionsErrorKind::TimeoutOrder,
2109            Some(smaller_name),
2110            format!("{smaller_name} must be <= {larger_name}"),
2111        ));
2112    }
2113    Ok(())
2114}
2115
2116fn timeout_seconds(
2117    field: &'static str,
2118    value: Option<Duration>,
2119) -> std::result::Result<Option<u64>, ActivityOptionsError> {
2120    value
2121        .map(|value| {
2122            activity_protocol_seconds(value).ok_or_else(|| {
2123                ActivityOptionsError::new(
2124                    ActivityOptionsErrorKind::TimeoutOverflow,
2125                    Some(field),
2126                    format!("{field} is too large for the worker protocol"),
2127                )
2128            })
2129        })
2130        .transpose()
2131}
2132
2133fn duration_seconds_ceil(value: Duration) -> Option<u64> {
2134    value
2135        .as_secs()
2136        .checked_add(u64::from(value.subsec_nanos() > 0))
2137}
2138
2139fn activity_protocol_seconds(value: Duration) -> Option<u64> {
2140    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
2141}
2142
2143fn validate_activity_retry_policy(
2144    policy: &ActivityRetryPolicy,
2145) -> std::result::Result<Value, ActivityOptionsError> {
2146    if policy.max_attempts.is_none()
2147        && policy.backoff.is_none()
2148        && policy.non_retryable_error_types.is_empty()
2149    {
2150        return Err(ActivityOptionsError::new(
2151            ActivityOptionsErrorKind::EmptyRetryPolicy,
2152            Some("retry_policy"),
2153            "retry_policy must configure at least one field",
2154        ));
2155    }
2156    if policy.max_attempts == Some(0) {
2157        return Err(ActivityOptionsError::new(
2158            ActivityOptionsErrorKind::InvalidMaxAttempts,
2159            Some("retry_policy.max_attempts"),
2160            "max_attempts must be >= 1",
2161        ));
2162    }
2163    if policy
2164        .non_retryable_error_types
2165        .iter()
2166        .any(|error_type| error_type.trim().is_empty())
2167    {
2168        return Err(ActivityOptionsError::new(
2169            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
2170            Some("retry_policy.non_retryable_error_types"),
2171            "non_retryable_error_types must not contain empty values",
2172        ));
2173    }
2174
2175    let backoff_seconds = match &policy.backoff {
2176        None => None,
2177        Some(backoff) => {
2178            let max_attempts = policy.max_attempts.ok_or_else(|| {
2179                ActivityOptionsError::new(
2180                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
2181                    Some("retry_policy.backoff"),
2182                    "backoff requires max_attempts",
2183                )
2184            })?;
2185            let retry_count = max_attempts.saturating_sub(1) as usize;
2186            let intervals = match backoff {
2187                ActivityBackoff::Explicit(intervals) => intervals.clone(),
2188                ActivityBackoff::Exponential {
2189                    initial_interval,
2190                    coefficient,
2191                    maximum_interval,
2192                } => {
2193                    if *coefficient < 1 {
2194                        return Err(ActivityOptionsError::new(
2195                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
2196                            Some("retry_policy.backoff.coefficient"),
2197                            "backoff coefficient must be >= 1",
2198                        ));
2199                    }
2200                    if retry_count > 10_000 {
2201                        return Err(ActivityOptionsError::new(
2202                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
2203                            Some("retry_policy.max_attempts"),
2204                            "generated backoff supports at most 10000 retry intervals",
2205                        ));
2206                    }
2207                    let mut current = *initial_interval;
2208                    let mut intervals = Vec::with_capacity(retry_count);
2209                    for _ in 0..retry_count {
2210                        let interval = maximum_interval
2211                            .map(|maximum| current.min(maximum))
2212                            .unwrap_or(current);
2213                        intervals.push(interval);
2214                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
2215                            break;
2216                        }
2217                        current = current.checked_mul(*coefficient).ok_or_else(|| {
2218                            ActivityOptionsError::new(
2219                                ActivityOptionsErrorKind::BackoffOverflow,
2220                                Some("retry_policy.backoff"),
2221                                "generated backoff interval overflowed",
2222                            )
2223                        })?;
2224                    }
2225                    intervals
2226                }
2227            };
2228            Some(
2229                intervals
2230                    .into_iter()
2231                    .map(|interval| {
2232                        activity_protocol_seconds(interval).ok_or_else(|| {
2233                            ActivityOptionsError::new(
2234                                ActivityOptionsErrorKind::BackoffOverflow,
2235                                Some("retry_policy.backoff"),
2236                                "backoff interval is too large for the worker protocol",
2237                            )
2238                        })
2239                    })
2240                    .collect::<std::result::Result<Vec<_>, _>>()?,
2241            )
2242        }
2243    };
2244
2245    let mut encoded = serde_json::Map::new();
2246    if let Some(max_attempts) = policy.max_attempts {
2247        encoded.insert("max_attempts".to_string(), json!(max_attempts));
2248    }
2249    if let Some(backoff_seconds) = backoff_seconds {
2250        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
2251    }
2252    if !policy.non_retryable_error_types.is_empty() {
2253        let mut canonical_error_types = Vec::new();
2254        for error_type in policy
2255            .non_retryable_error_types
2256            .iter()
2257            .map(|error_type| error_type.trim())
2258        {
2259            if !canonical_error_types.contains(&error_type) {
2260                canonical_error_types.push(error_type);
2261            }
2262        }
2263        encoded.insert(
2264            "non_retryable_error_types".to_string(),
2265            json!(canonical_error_types),
2266        );
2267    }
2268    Ok(Value::Object(encoded))
2269}
2270
2271/// A stable, machine-readable failure raised when workflow code no longer
2272/// reconstructs the durable command stream recorded in history.
2273#[derive(Clone, Debug, Error)]
2274#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
2275pub struct ReplayFailure {
2276    pub reason: String,
2277    pub sequence: Option<u64>,
2278    pub expected: Option<String>,
2279    pub actual: Option<String>,
2280    pub message: String,
2281}
2282
2283impl ReplayFailure {
2284    fn new(
2285        reason: impl Into<String>,
2286        sequence: Option<u64>,
2287        expected: Option<String>,
2288        actual: Option<String>,
2289        message: impl Into<String>,
2290    ) -> Self {
2291        Self {
2292            reason: reason.into(),
2293            sequence,
2294            expected,
2295            actual,
2296            message: message.into(),
2297        }
2298    }
2299}
2300
2301/// A stable, machine-readable workflow query or query-task settlement failure.
2302#[derive(Clone, Debug, Error)]
2303#[error("query failed ({reason}, HTTP {status}): {message}")]
2304pub struct QueryFailure {
2305    pub status: u16,
2306    pub reason: String,
2307    pub message: String,
2308    pub body: Value,
2309}
2310
2311/// A stable failure returned when a server rejects an SDK protocol version.
2312#[derive(Clone, Debug, Error)]
2313#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
2314pub struct ProtocolFailure {
2315    pub status: u16,
2316    pub reason: String,
2317    pub message: String,
2318    pub supported_version: Option<String>,
2319    pub requested_version: Option<String>,
2320    pub body: Value,
2321}
2322
2323/// The `limit_kind` a native Server (3.6.0 or later) reports when it refuses a
2324/// workflow-task completion body as too large.
2325pub const WORKFLOW_TASK_COMPLETION_BYTES_LIMIT_KIND: &str = "workflow_task_completion_bytes";
2326
2327/// A workflow-task completion the Server refused as larger than its aggregate
2328/// completion limit (HTTP 413, `reason: "payload_too_large"`,
2329/// `limit_kind: "workflow_task_completion_bytes"`).
2330///
2331/// Native Server 3.6.0 accepts a completion with commands up to 16 times the
2332/// per-payload limit (32 MiB by default); each command's arguments must still
2333/// meet the per-payload limit. The refusal is deterministic: running the same
2334/// workflow task again produces the same completion, so the SDK never resends it. `limit`
2335/// is the Server's limit in bytes when it reports one, and `size` is the
2336/// encoded request body the SDK sent. A [`Worker`] answers the refusal by
2337/// completing the same task once with a non-retryable `fail_workflow` command
2338/// whose message starts with `Structural limit exceeded:`, so the run fails
2339/// with failure category `structural_limit` instead of retrying the task or
2340/// parking the run. Split the fan-out into smaller batches, move work into child
2341/// workflows, or continue as new; offload large payloads with external payload
2342/// storage.
2343#[derive(Clone, Debug, Error)]
2344pub struct WorkflowTaskCompletionTooLarge {
2345    pub status: u16,
2346    pub limit_kind: String,
2347    pub limit: Option<u64>,
2348    pub size: u64,
2349    pub message: String,
2350    pub body: Value,
2351}
2352
2353impl std::fmt::Display for WorkflowTaskCompletionTooLarge {
2354    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2355        write!(
2356            formatter,
2357            "Structural limit exceeded: {}: the workflow task completion is {} bytes, over the server limit",
2358            self.limit_kind, self.size
2359        )?;
2360        if let Some(limit) = self.limit {
2361            write!(formatter, " of {limit} bytes")?;
2362        }
2363        formatter.write_str(
2364            ". Split the fan-out into smaller batches, move work into child workflows, or continue-as-new; offload large payloads with external payload storage.",
2365        )
2366    }
2367}
2368
2369#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2370pub struct PayloadEnvelope {
2371    pub codec: String,
2372    pub blob: String,
2373}
2374
2375impl PayloadEnvelope {
2376    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2377        encode_payload(value, DEFAULT_CODEC)
2378    }
2379
2380    /// Encode an explicit typed value, including the bytes branch that JSON
2381    /// serialization cannot represent.
2382    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2383        encode_avro_value(value)
2384    }
2385}
2386
2387/// Native adapter for the fixed language-neutral Avro Value schema.
2388#[derive(Clone, Debug)]
2389pub enum AvroValue {
2390    Null,
2391    Boolean(bool),
2392    Long(i64),
2393    Double(f64),
2394    Bytes(Vec<u8>),
2395    String(String),
2396    Array(Vec<AvroValue>),
2397    Map(BTreeMap<String, AvroValue>),
2398}
2399
2400impl PartialEq for AvroValue {
2401    fn eq(&self, other: &Self) -> bool {
2402        match (self, other) {
2403            (Self::Null, Self::Null) => true,
2404            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2405            (Self::Long(left), Self::Long(right)) => left == right,
2406            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2407            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2408            (Self::String(left), Self::String(right)) => left == right,
2409            (Self::Array(left), Self::Array(right)) => left == right,
2410            (Self::Map(left), Self::Map(right)) => left == right,
2411            _ => false,
2412        }
2413    }
2414}
2415
2416impl AvroValue {
2417    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2418        Self::from_serde_value(
2419            serde_value::to_value(value).map_err(|error| {
2420                Error::Codec(format!("could not adapt value for Avro: {error}"))
2421            })?,
2422        )
2423    }
2424
2425    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2426        use serde_value::Value as SerdeValue;
2427
2428        match value {
2429            SerdeValue::Unit => Ok(Self::Null),
2430            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2431            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2432            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2433            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2434            SerdeValue::I64(value) => Ok(Self::Long(value)),
2435            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2436            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2437            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2438            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2439                Error::Codec(
2440                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2441                        .to_string(),
2442                )
2443            }),
2444            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2445            SerdeValue::F64(value) => Self::finite_double(value),
2446            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2447            SerdeValue::String(value) => Ok(Self::String(value)),
2448            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2449            SerdeValue::Option(None) => Ok(Self::Null),
2450            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2451                Self::from_serde_value(*value)
2452            }
2453            SerdeValue::Seq(values) => values
2454                .into_iter()
2455                .map(Self::from_serde_value)
2456                .collect::<Result<Vec<_>>>()
2457                .map(Self::Array),
2458            SerdeValue::Map(values) => values
2459                .into_iter()
2460                .map(|(key, value)| {
2461                    let SerdeValue::String(key) = key else {
2462                        return Err(Error::Codec(
2463                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2464                        ));
2465                    };
2466
2467                    Ok((key, Self::from_serde_value(value)?))
2468                })
2469                .collect::<Result<BTreeMap<_, _>>>()
2470                .map(Self::Map),
2471        }
2472    }
2473
2474    fn finite_double(value: f64) -> Result<Self> {
2475        if !value.is_finite() {
2476            return Err(Error::Codec(
2477                "non_finite_float: Avro Value doubles must be finite".to_string(),
2478            ));
2479        }
2480
2481        Ok(Self::Double(value))
2482    }
2483
2484    fn into_json(self) -> Result<Value> {
2485        match self {
2486            Self::Null => Ok(Value::Null),
2487            Self::Boolean(value) => Ok(Value::Bool(value)),
2488            Self::Long(value) => Ok(Value::Number(value.into())),
2489            Self::Double(value) => serde_json::Number::from_f64(value)
2490                .map(Value::Number)
2491                .ok_or_else(|| {
2492                    Error::Codec(
2493                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2494                    )
2495                }),
2496            Self::Bytes(value) => Ok(json!({
2497                "$type": "bytes",
2498                "base64": BASE64.encode(value),
2499            })),
2500            Self::String(value) => Ok(Value::String(value)),
2501            Self::Array(values) => values
2502                .into_iter()
2503                .map(Self::into_json)
2504                .collect::<Result<Vec<_>>>()
2505                .map(Value::Array),
2506            Self::Map(values) => values
2507                .into_iter()
2508                .map(|(key, value)| Ok((key, value.into_json()?)))
2509                .collect::<Result<serde_json::Map<_, _>>>()
2510                .map(Value::Object),
2511        }
2512    }
2513
2514    fn into_serde_value(self) -> serde_value::Value {
2515        use serde_value::Value as SerdeValue;
2516
2517        match self {
2518            Self::Null => SerdeValue::Unit,
2519            Self::Boolean(value) => SerdeValue::Bool(value),
2520            Self::Long(value) => SerdeValue::I64(value),
2521            Self::Double(value) => SerdeValue::F64(value),
2522            Self::Bytes(value) => SerdeValue::Bytes(value),
2523            Self::String(value) => SerdeValue::String(value),
2524            Self::Array(values) => {
2525                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2526            }
2527            Self::Map(values) => SerdeValue::Map(
2528                values
2529                    .into_iter()
2530                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2531                    .collect(),
2532            ),
2533        }
2534    }
2535
2536    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2537        self.into_serde_value().deserialize_into().map_err(|error| {
2538            Error::Codec(format!(
2539                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2540            ))
2541        })
2542    }
2543}
2544
2545impl Serialize for AvroValue {
2546    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2547    where
2548        S: Serializer,
2549    {
2550        match self {
2551            Self::Null => serializer.serialize_unit(),
2552            Self::Boolean(value) => serializer.serialize_bool(*value),
2553            Self::Long(value) => serializer.serialize_i64(*value),
2554            Self::Double(value) => serializer.serialize_f64(*value),
2555            Self::Bytes(value) => serializer.serialize_bytes(value),
2556            Self::String(value) => serializer.serialize_str(value),
2557            Self::Array(values) => {
2558                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2559                for value in values {
2560                    sequence.serialize_element(value)?;
2561                }
2562                sequence.end()
2563            }
2564            Self::Map(values) => {
2565                let mut map = serializer.serialize_map(Some(values.len()))?;
2566                for (key, value) in values {
2567                    map.serialize_entry(key, value)?;
2568                }
2569                map.end()
2570            }
2571        }
2572    }
2573}
2574
2575pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2576    let datum = avro_value_to_datum(value)?;
2577    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2578        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2579    let mut bytes = Vec::with_capacity(datum.len() + 10);
2580    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2581    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2582    bytes.extend_from_slice(&datum);
2583    Ok(PayloadEnvelope {
2584        codec: DEFAULT_CODEC.to_string(),
2585        blob: BASE64.encode(bytes),
2586    })
2587}
2588
2589pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2590    if envelope.codec != DEFAULT_CODEC {
2591        return Err(unsupported_payload_codec(&envelope.codec));
2592    }
2593    decode_avro_value_blob(&envelope.blob)
2594}
2595
2596pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2597    let blob = match codec {
2598        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2599        other => return Err(unsupported_payload_codec(other)),
2600    };
2601
2602    Ok(PayloadEnvelope {
2603        codec: codec.to_string(),
2604        blob,
2605    })
2606}
2607
2608pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2609    match envelope.codec.as_str() {
2610        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2611        other => Err(unsupported_payload_codec(other)),
2612    }
2613}
2614
2615fn handler_type_error<T>(
2616    handler_kind: HandlerKind,
2617    handler_name: &str,
2618    value_kind: HandlerValueKind,
2619    message: impl Into<String>,
2620) -> Error {
2621    Error::HandlerType {
2622        handler_kind,
2623        handler_name: handler_name.to_string(),
2624        value_kind,
2625        rust_type: type_name::<T>(),
2626        message: message.into(),
2627    }
2628}
2629
2630fn decode_handler_input<T: DeserializeOwned>(
2631    arguments: AvroValue,
2632    handler_kind: HandlerKind,
2633    handler_name: &str,
2634) -> Result<T> {
2635    let argument = match arguments {
2636        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2637            arguments.pop().expect("one typed handler argument")
2638        }
2639        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2640        AvroValue::Array(arguments) => {
2641            return Err(handler_type_error::<T>(
2642                handler_kind,
2643                handler_name,
2644                HandlerValueKind::Input,
2645                format!(
2646                    "typed handlers accept one request value, but the task carried {} arguments",
2647                    arguments.len()
2648                ),
2649            ));
2650        }
2651        argument => argument,
2652    };
2653
2654    argument.deserialize().map_err(|error| {
2655        handler_type_error::<T>(
2656            handler_kind,
2657            handler_name,
2658            HandlerValueKind::Input,
2659            error.to_string(),
2660        )
2661    })
2662}
2663
2664fn decode_workflow_entry<T: DeserializeOwned>(
2665    arguments: AvroValue,
2666    workflow_type: &str,
2667) -> Result<T> {
2668    decode_handler_input(arguments, HandlerKind::Workflow, workflow_type).map_err(|_| {
2669        // Serde errors may contain recorded values. The entry refusal exposes
2670        // only the registered workflow and expected Rust type.
2671        handler_type_error::<T>(
2672            HandlerKind::Workflow,
2673            workflow_type,
2674            HandlerValueKind::Input,
2675            "workflow_entry_arguments_mismatch: restore compatible entry code before retrying the original task",
2676        )
2677    })
2678}
2679
2680fn encode_handler_result<T: Serialize>(
2681    result: &T,
2682    handler_kind: HandlerKind,
2683    handler_name: &str,
2684) -> Result<AvroValue> {
2685    AvroValue::from_serialize(result).map_err(|error| {
2686        handler_type_error::<T>(
2687            handler_kind,
2688            handler_name,
2689            HandlerValueKind::Result,
2690            error.to_string(),
2691        )
2692    })
2693}
2694
2695fn decode_handler_result<T: DeserializeOwned>(
2696    result: AvroValue,
2697    handler_kind: HandlerKind,
2698    handler_name: &str,
2699) -> Result<T> {
2700    result.deserialize().map_err(|error| {
2701        handler_type_error::<T>(
2702            handler_kind,
2703            handler_name,
2704            HandlerValueKind::Result,
2705            error.to_string(),
2706        )
2707    })
2708}
2709
2710#[cfg(test)]
2711fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2712    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2713}
2714
2715fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2716    validate_payload_codec(fallback_codec)?;
2717
2718    if value.is_null() {
2719        return Ok(Value::Null);
2720    }
2721
2722    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2723        return decode_blob(blob, codec);
2724    }
2725
2726    if let Some(blob) = value.as_str() {
2727        return decode_blob(blob, fallback_codec);
2728    }
2729
2730    Err(untagged_payload_value())
2731}
2732
2733fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
2734    let envelope = match codec {
2735        DEFAULT_CODEC => encode_avro_value(value)?,
2736        other => return Err(unsupported_payload_codec(other)),
2737    };
2738    Ok(serde_json::to_value(envelope)?)
2739}
2740
2741fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
2742    validate_payload_codec(fallback_codec)?;
2743
2744    if value.is_null() {
2745        return Ok(AvroValue::Null);
2746    }
2747
2748    if let Some((codec, blob)) = payload_envelope_parts(value)? {
2749        validate_payload_codec(codec)?;
2750        return decode_avro_value_blob(blob);
2751    }
2752
2753    if let Some(blob) = value.as_str() {
2754        return match fallback_codec {
2755            DEFAULT_CODEC => decode_avro_value_blob(blob),
2756            other => Err(unsupported_payload_codec(other)),
2757        };
2758    }
2759
2760    Err(untagged_payload_value())
2761}
2762
2763fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
2764    match value {
2765        AvroValue::Null => AvroValue::Array(Vec::new()),
2766        AvroValue::Array(_) => value,
2767        other => AvroValue::Array(vec![other]),
2768    }
2769}
2770
2771fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
2772    match codec {
2773        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
2774        other => Err(unsupported_payload_codec(other)),
2775    }
2776}
2777
2778fn validate_payload_codec(codec: &str) -> Result<()> {
2779    match codec {
2780        DEFAULT_CODEC => Ok(()),
2781        MISSING_TASK_PAYLOAD_CODEC => {
2782            Err(invalid_task_payload_codec("task payload_codec is missing"))
2783        }
2784        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
2785        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
2786            "task payload_codec must be a string",
2787        )),
2788        other => Err(unsupported_payload_codec(other)),
2789    }
2790}
2791
2792fn invalid_task_payload_codec(reason: &str) -> Error {
2793    Error::Codec(format!(
2794        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
2795    ))
2796}
2797
2798fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
2799    let Some(object) = value.as_object() else {
2800        return Ok(None);
2801    };
2802    if !object.contains_key("codec") && !object.contains_key("blob") {
2803        return Ok(None);
2804    }
2805
2806    let codec = object
2807        .get("codec")
2808        .and_then(Value::as_str)
2809        .ok_or_else(invalid_payload_envelope)?;
2810    validate_payload_codec(codec)?;
2811    let blob = object
2812        .get("blob")
2813        .and_then(Value::as_str)
2814        .ok_or_else(invalid_payload_envelope)?;
2815    Ok(Some((codec, blob)))
2816}
2817
2818fn invalid_payload_envelope() -> Error {
2819    Error::Codec(
2820        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
2821            .to_string(),
2822    )
2823}
2824
2825fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
2826    for command in commands {
2827        let Some(command) = command.as_object() else {
2828            continue;
2829        };
2830        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
2831            continue;
2832        };
2833        let Some(payload_field) = workflow_command_payload_field(command_type) else {
2834            continue;
2835        };
2836
2837        if let Some(codec) = command.get("payload_codec") {
2838            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
2839            validate_payload_codec(codec)?;
2840        }
2841
2842        let payload = command
2843            .get(payload_field)
2844            .ok_or_else(invalid_payload_envelope)?;
2845        if runtime_payloads::Reference::parse(payload)?.is_none() {
2846            validate_outbound_payload_envelope(payload)?;
2847        }
2848    }
2849    Ok(())
2850}
2851
2852fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
2853    if commands.iter().any(|command| {
2854        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
2855            && command
2856                .get("condition_wait_occurrence_id")
2857                .and_then(Value::as_str)
2858                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
2859    }) {
2860        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
2861    } else if commands.iter().any(|command| {
2862        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2863            && command.get("attribute_types").is_some()
2864    }) {
2865        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
2866    } else if commands
2867        .iter()
2868        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
2869    {
2870        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
2871    } else if commands
2872        .iter()
2873        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
2874    {
2875        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
2876    } else if commands.iter().any(|command| {
2877        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
2878    }) {
2879        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
2880    } else {
2881        MINIMUM_WORKER_PROTOCOL_VERSION
2882    }
2883}
2884
2885fn workflow_completion_protocol_version_with_message_streams(
2886    commands: &[Value],
2887    has_message_stream_metadata: bool,
2888) -> &'static str {
2889    let command_protocol = workflow_completion_protocol_version(commands);
2890    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
2891        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
2892    } else {
2893        command_protocol
2894    }
2895}
2896
2897fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
2898    match command_type {
2899        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
2900        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
2901        "start_service_operation" => Some("request_payload"),
2902        "upsert_memo" => Some("entries"),
2903        _ => None,
2904    }
2905}
2906
2907fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
2908    let Some((codec, blob)) = payload_envelope_parts(value)? else {
2909        return Err(untagged_payload_value());
2910    };
2911    validate_payload_codec(codec)?;
2912    decode_avro_value_blob(blob)?;
2913    Ok(())
2914}
2915
2916fn unsupported_payload_codec(codec: &str) -> Error {
2917    Error::Codec(format!(
2918        "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"
2919    ))
2920}
2921
2922fn untagged_payload_value() -> Error {
2923    Error::Codec(
2924        "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"
2925            .to_string(),
2926    )
2927}
2928
2929fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
2930    let bytes = BASE64.decode(blob).map_err(|err| {
2931        Error::Codec(format!(
2932            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
2933        ))
2934    })?;
2935
2936    if serde_json::from_slice::<Value>(&bytes).is_ok() {
2937        return Err(unsupported_payload_codec("json"));
2938    }
2939
2940    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
2941        return Err(Error::Codec(
2942            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
2943        ));
2944    }
2945
2946    let fingerprint: [u8; 8] = bytes[2..10]
2947        .try_into()
2948        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
2949    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
2950        return Err(Error::Codec(format!(
2951            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
2952            fingerprint
2953                .iter()
2954                .map(|byte| format!("{byte:02x}"))
2955                .collect::<String>()
2956        )));
2957    }
2958
2959    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
2960    // The current fingerprint selects the current immutable schema, so reader
2961    // resolution would only re-walk the same recursive union. Future retained
2962    // writer fingerprints supply a distinct reader schema in this branch.
2963    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
2964    if datum_reader.truncated {
2965        return Err(Error::Codec(
2966            "invalid_payload_framing: truncated Avro Value datum".to_string(),
2967        ));
2968    }
2969    let datum = datum.map_err(|err| {
2970        Error::Codec(format!(
2971            "invalid_payload_framing: malformed Avro Value datum: {err}"
2972        ))
2973    })?;
2974    if datum_reader.remaining() != 0 {
2975        return Err(Error::Codec(format!(
2976            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
2977            datum_reader.remaining()
2978        )));
2979    }
2980    avro_value_from_datum(datum)
2981}
2982
2983struct StrictAvroDatumReader<'a> {
2984    bytes: &'a [u8],
2985    offset: usize,
2986    truncated: bool,
2987}
2988
2989impl<'a> StrictAvroDatumReader<'a> {
2990    fn new(bytes: &'a [u8]) -> Self {
2991        Self {
2992            bytes,
2993            offset: 0,
2994            truncated: false,
2995        }
2996    }
2997
2998    fn remaining(&self) -> usize {
2999        self.bytes.len() - self.offset
3000    }
3001}
3002
3003impl Read for StrictAvroDatumReader<'_> {
3004    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
3005        let count = buffer.len().min(self.remaining());
3006        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
3007        self.offset += count;
3008        if count < buffer.len() {
3009            self.truncated = true;
3010        }
3011
3012        Ok(count)
3013    }
3014}
3015
3016fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
3017    let branch = match value {
3018        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
3019        AvroValue::Boolean(value) => AvroDatum::Union(
3020            1,
3021            Box::new(AvroDatum::Record(vec![(
3022                "boolean".to_string(),
3023                AvroDatum::Boolean(*value),
3024            )])),
3025        ),
3026        AvroValue::Long(value) => AvroDatum::Union(
3027            2,
3028            Box::new(AvroDatum::Record(vec![(
3029                "long".to_string(),
3030                AvroDatum::Long(*value),
3031            )])),
3032        ),
3033        AvroValue::Double(value) => {
3034            if !value.is_finite() {
3035                return Err(Error::Codec(
3036                    "non_finite_float: Avro Value doubles must be finite".to_string(),
3037                ));
3038            }
3039            AvroDatum::Union(
3040                3,
3041                Box::new(AvroDatum::Record(vec![(
3042                    "double".to_string(),
3043                    AvroDatum::Double(*value),
3044                )])),
3045            )
3046        }
3047        AvroValue::Bytes(value) => AvroDatum::Union(
3048            4,
3049            Box::new(AvroDatum::Record(vec![(
3050                "bytes".to_string(),
3051                AvroDatum::Bytes(value.clone()),
3052            )])),
3053        ),
3054        AvroValue::String(value) => AvroDatum::Union(
3055            5,
3056            Box::new(AvroDatum::Record(vec![(
3057                "string".to_string(),
3058                AvroDatum::String(value.clone()),
3059            )])),
3060        ),
3061        AvroValue::Array(values) => AvroDatum::Union(
3062            6,
3063            Box::new(AvroDatum::Record(vec![(
3064                "items".to_string(),
3065                AvroDatum::Array(
3066                    values
3067                        .iter()
3068                        .map(avro_value_to_datum)
3069                        .collect::<Result<Vec<_>>>()?,
3070                ),
3071            )])),
3072        ),
3073        AvroValue::Map(values) => AvroDatum::Union(
3074            7,
3075            Box::new(AvroDatum::Record(vec![(
3076                "entries".to_string(),
3077                AvroDatum::Array(
3078                    values
3079                        .iter()
3080                        .map(|(key, value)| {
3081                            Ok(AvroDatum::Record(vec![
3082                                ("key".to_string(), AvroDatum::String(key.clone())),
3083                                ("value".to_string(), avro_value_to_datum(value)?),
3084                            ]))
3085                        })
3086                        .collect::<Result<Vec<_>>>()?,
3087                ),
3088            )])),
3089        ),
3090    };
3091    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
3092}
3093
3094fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
3095    let AvroDatum::Record(mut outer) = datum else {
3096        return Err(Error::Codec(
3097            "invalid_payload_framing: datum is not a Value record".to_string(),
3098        ));
3099    };
3100    let (_, branch) = outer
3101        .pop()
3102        .filter(|(name, _)| name == "value")
3103        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
3104    let AvroDatum::Union(_, branch) = branch else {
3105        return Err(Error::Codec(
3106            "invalid_payload_framing: invalid Value union".to_string(),
3107        ));
3108    };
3109    match *branch {
3110        AvroDatum::Null => Ok(AvroValue::Null),
3111        AvroDatum::Record(mut fields) => {
3112            let (name, value) = fields.pop().ok_or_else(|| {
3113                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
3114            })?;
3115            match (name.as_str(), value) {
3116                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
3117                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
3118                ("double", AvroDatum::Double(value)) if value.is_finite() => {
3119                    Ok(AvroValue::Double(value))
3120                }
3121                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
3122                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
3123                ("items", AvroDatum::Array(values)) => values
3124                    .into_iter()
3125                    .map(avro_value_from_datum)
3126                    .collect::<Result<Vec<_>>>()
3127                    .map(AvroValue::Array),
3128                ("entries", AvroDatum::Map(values)) => values
3129                    .into_iter()
3130                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
3131                    .collect::<Result<BTreeMap<_, _>>>()
3132                    .map(AvroValue::Map),
3133                _ => Err(Error::Codec(
3134                    "invalid_payload_framing: unknown Value branch".to_string(),
3135                )),
3136            }
3137        }
3138        _ => Err(Error::Codec(
3139            "invalid_payload_framing: invalid Value branch".to_string(),
3140        )),
3141    }
3142}
3143
3144fn avro_value_schema() -> Result<&'static Schema> {
3145    match AVRO_VALUE_SCHEMA.get_or_init(|| {
3146        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
3147            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
3148    }) {
3149        Ok(schema) => Ok(schema),
3150        Err(message) => Err(Error::Codec(message.clone())),
3151    }
3152}
3153
3154fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
3155    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
3156        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
3157        // have the same block representation when each ordered array record
3158        // contains the map key followed by its value, so this encoding-only
3159        // adaptation lets the official encoder retain BTreeMap wire order.
3160        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
3161            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
3162        let entries_schema = schema
3163            .pointer_mut("/fields/0/type/7/fields/0/type")
3164            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
3165        if *entries_schema != json!({"type": "map", "values": "Value"}) {
3166            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
3167        }
3168        *entries_schema = json!({
3169            "type": "array",
3170            "items": {
3171                "type": "record",
3172                "name": "MapEntry",
3173                "fields": [
3174                    {"name": "key", "type": "string"},
3175                    {"name": "value", "type": "Value"}
3176                ]
3177            }
3178        });
3179        Schema::parse_str(&schema.to_string())
3180            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
3181    }) {
3182        Ok(schema) => Ok(schema),
3183        Err(message) => Err(Error::Codec(message.clone())),
3184    }
3185}
3186
3187#[derive(Clone, Debug)]
3188pub struct Client {
3189    metrics: metrics::Metrics,
3190    // Managed-worker dispatch recording is separate from client HTTP recording.
3191    worker_dispatch_metrics: metrics::Metrics,
3192    http: reqwest::Client,
3193    hydration_timeout: Duration,
3194    base_url: String,
3195    token: Option<String>,
3196    control_token: Option<String>,
3197    worker_token: Option<String>,
3198    namespace: String,
3199    max_external_payload_bytes: usize,
3200    worker_storage_admission: Option<WorkerStorageAdmission>,
3201    worker_task_slot: Option<Arc<worker_capacity::TaskSlotMarker>>,
3202    cooperative_worker_protocol: bool,
3203    worker_protocol_version: WorkerProtocolVersion,
3204    local_activities_enabled: bool,
3205    worker_sessions_enabled: bool,
3206    max_concurrent_worker_sessions: usize,
3207    worker_build_id: Option<String>,
3208    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
3209    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
3210    failure_request_limit: Arc<AtomicUsize>,
3211    activity_lease_renewal_supported: Arc<AtomicBool>,
3212    /// Server #1017: the Server sends sticky hits only the history after the cached sequence.
3213    sticky_history_suffix_supported: Arc<AtomicBool>,
3214    /// Server #1131: the Server advertised `update_outcome_reads`.
3215    update_outcome_reads_supported: Arc<AtomicBool>,
3216    activity_lease_discovery: Arc<activity_lease::Discovery>,
3217    activity_lease_authority: Option<Arc<activity_lease::authority::Authority>>,
3218    #[cfg(feature = "telemetry")]
3219    execution_telemetry: Option<telemetry::ExecutionTelemetry>,
3220    #[cfg(feature = "telemetry")]
3221    observability_context_supported: Arc<AtomicBool>,
3222}
3223
3224impl Client {
3225    /// Configure optional propagation. Actual cluster discovery must advertise
3226    /// the exact supported capability before any command carries context.
3227    #[cfg(feature = "telemetry")]
3228    pub fn with_telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
3229        self.execution_telemetry = Some(telemetry);
3230        self
3231    }
3232
3233    #[cfg(feature = "telemetry")]
3234    fn with_observability_context(&self, mut body: Value) -> Value {
3235        if self.observability_context_supported.load(Ordering::SeqCst) {
3236            if let Some(context) = self
3237                .execution_telemetry
3238                .as_ref()
3239                .and_then(|telemetry| telemetry.capture())
3240            {
3241                body["observability_context"] = context;
3242            }
3243        }
3244        body
3245    }
3246
3247    #[cfg(not(feature = "telemetry"))]
3248    fn with_observability_context(&self, body: Value) -> Value {
3249        body
3250    }
3251
3252    pub fn new(base_url: impl Into<String>) -> Result<Self> {
3253        Self::builder(base_url).build()
3254    }
3255
3256    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
3257        ClientBuilder {
3258            base_url: base_url.into(),
3259            token: None,
3260            control_token: None,
3261            worker_token: None,
3262            namespace: "default".to_string(),
3263            timeout: Duration::from_secs(60),
3264            max_external_payload_bytes: 64 * 1024 * 1024,
3265            worker_protocol_version: WorkerProtocolVersion::default(),
3266            additional_root_certificates: Vec::new(),
3267            danger_accept_invalid_certs: false,
3268            metrics: metrics::Metrics::default(),
3269        }
3270    }
3271
3272    pub async fn health(&self) -> Result<Value> {
3273        self.request_json(
3274            reqwest::Method::GET,
3275            "/health",
3276            RequestProtocol::ControlPlane,
3277            Option::<&Value>::None,
3278        )
3279        .await
3280    }
3281
3282    pub async fn cluster_info(&self) -> Result<Value> {
3283        let discovery: Value = self
3284            .request_json(
3285                reqwest::Method::GET,
3286                "/cluster/info",
3287                RequestProtocol::ControlPlane,
3288                Option::<&Value>::None,
3289            )
3290            .await?;
3291        self.observe_activity_lease_capabilities(
3292            &discovery["worker_protocol"]["server_capabilities"],
3293        );
3294        self.observe_failure_request_limit(&discovery);
3295        Ok(discovery)
3296    }
3297
3298    pub async fn start_workflow<T: Serialize>(
3299        &self,
3300        workflow_type: &str,
3301        task_queue: &str,
3302        workflow_id: &str,
3303        input: T,
3304    ) -> Result<WorkflowHandle> {
3305        self.start_workflow_with_options(
3306            workflow_type,
3307            task_queue,
3308            workflow_id,
3309            WorkflowStartOptions::default(),
3310            input,
3311        )
3312        .await
3313    }
3314
3315    /// Start a workflow with explicit server-enforced execution and run
3316    /// deadlines.
3317    pub async fn start_workflow_with_options<T: Serialize>(
3318        &self,
3319        workflow_type: &str,
3320        task_queue: &str,
3321        workflow_id: &str,
3322        options: WorkflowStartOptions,
3323        input: T,
3324    ) -> Result<WorkflowHandle> {
3325        options.validate()?;
3326        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3327        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3328        let body = self.with_observability_context(json!({
3329            "workflow_id": workflow_id,
3330            "workflow_type": workflow_type,
3331            "task_queue": task_queue,
3332            "input": input_envelope,
3333            "execution_timeout_seconds": options.execution_timeout_seconds,
3334            "run_timeout_seconds": options.run_timeout_seconds
3335        }));
3336
3337        let data: Value = self
3338            .request_json(
3339                reqwest::Method::POST,
3340                "/workflows",
3341                RequestProtocol::ControlPlane,
3342                Some(&body),
3343            )
3344            .await?;
3345
3346        Ok(WorkflowHandle {
3347            client: self.clone(),
3348            workflow_id: data
3349                .get("workflow_id")
3350                .and_then(Value::as_str)
3351                .unwrap_or(workflow_id)
3352                .to_string(),
3353            run_id: data
3354                .get("run_id")
3355                .and_then(Value::as_str)
3356                .map(str::to_string),
3357            workflow_type: data
3358                .get("workflow_type")
3359                .and_then(Value::as_str)
3360                .unwrap_or(workflow_type)
3361                .to_string(),
3362        })
3363    }
3364
3365    /// Send a signal with an SDK-generated caller command key.
3366    ///
3367    /// The key is sent as the `request_id` body field and is present in the
3368    /// returned receipt's `request_id`. A Server that already retains the key
3369    /// for the same signal intent returns the original receipt with
3370    /// `retained: true`; a different intent is refused with
3371    /// [`Error::is_request_id_conflict`]. Choose the key yourself with
3372    /// [`Client::signal_workflow_with_request_id`] when the application must be
3373    /// able to retry the same logical signal after a transport failure.
3374    pub async fn signal_workflow<T: Serialize>(
3375        &self,
3376        workflow_id: &str,
3377        signal_name: &str,
3378        input: T,
3379    ) -> Result<Value> {
3380        let request_id = Self::generate_signal_request_id();
3381        self.signal_workflow_target(workflow_id, None, signal_name, input, &request_id)
3382            .await
3383    }
3384
3385    /// Send a signal with an explicit caller command key (1 to 255 Unicode characters).
3386    ///
3387    /// Resend the identical signal with the same key after an uncertain
3388    /// outcome: the Server returns the retained receipt instead of admitting a
3389    /// second signal, for as long as the retained run's details are kept.
3390    pub async fn signal_workflow_with_request_id<T: Serialize>(
3391        &self,
3392        workflow_id: &str,
3393        signal_name: &str,
3394        input: T,
3395        request_id: &str,
3396    ) -> Result<Value> {
3397        self.signal_workflow_target(workflow_id, None, signal_name, input, request_id)
3398            .await
3399    }
3400
3401    /// A fresh caller command key for one logical signal (`sdk-rust-signal-<uuid>`).
3402    ///
3403    /// Methods without an explicit key generate one of these per call. Obtain it
3404    /// up front and pass it to [`Client::signal_workflow_with_request_id`] so a
3405    /// transport failure does not lose the key needed for a safe retry.
3406    pub fn generate_signal_request_id() -> String {
3407        generated_request_id("signal")
3408    }
3409
3410    /// A fresh caller command key for one logical update (`sdk-rust-update-<uuid>`).
3411    ///
3412    /// [`Client::update_workflow`] generates one of these when `request_id` is
3413    /// `None`. Obtain it up front and pass it explicitly so a transport failure
3414    /// does not lose the key needed for a safe retry.
3415    pub fn generate_update_request_id() -> String {
3416        generated_request_id("update")
3417    }
3418
3419    /// Append one idempotently identified item to an instance-scoped input stream.
3420    pub async fn append_message_stream<T: Serialize>(
3421        &self,
3422        workflow_id: &str,
3423        stream_name: &str,
3424        message_id: &str,
3425        input: T,
3426    ) -> Result<Value> {
3427        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3428        let body = json!({
3429            "message_id": message_id,
3430            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
3431        });
3432        self.request_json(
3433            reqwest::Method::POST,
3434            &format!(
3435                "/workflows/{}/message-streams/{}/messages",
3436                path_segment("workflow_id", workflow_id)?,
3437                path_segment("stream_name", stream_name)?,
3438            ),
3439            RequestProtocol::ControlPlane,
3440            Some(&body),
3441        )
3442        .await
3443    }
3444
3445    /// Signal only if `run_id` is still the current run for this instance,
3446    /// with an SDK-generated caller command key.
3447    pub async fn signal_workflow_run<T: Serialize>(
3448        &self,
3449        workflow_id: &str,
3450        run_id: &str,
3451        signal_name: &str,
3452        input: T,
3453    ) -> Result<Value> {
3454        let request_id = Self::generate_signal_request_id();
3455        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, &request_id)
3456            .await
3457    }
3458
3459    /// Signal only if `run_id` is still the current run for this instance,
3460    /// with an explicit caller command key (1 to 255 Unicode characters).
3461    ///
3462    /// The selected run is part of the signal's intent: retrying with the same
3463    /// key and a different run target is a `request_id_conflict` refusal.
3464    pub async fn signal_workflow_run_with_request_id<T: Serialize>(
3465        &self,
3466        workflow_id: &str,
3467        run_id: &str,
3468        signal_name: &str,
3469        input: T,
3470        request_id: &str,
3471    ) -> Result<Value> {
3472        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, request_id)
3473            .await
3474    }
3475
3476    async fn signal_workflow_target<T: Serialize>(
3477        &self,
3478        workflow_id: &str,
3479        run_id: Option<&str>,
3480        signal_name: &str,
3481        input: T,
3482        request_id: &str,
3483    ) -> Result<Value> {
3484        validate_user_signal_name(signal_name)?;
3485        validate_request_id(request_id)?;
3486        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3487        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3488        let body = self.with_observability_context(json!({
3489            "input": input_envelope,
3490            "request_id": request_id,
3491        }));
3492        let path = match run_id {
3493            Some(run_id) => {
3494                format!(
3495                    "/workflows/{}/runs/{}/signal/{}",
3496                    path_segment("workflow_id", workflow_id)?,
3497                    path_segment("run_id", run_id)?,
3498                    path_segment("signal_name", signal_name)?,
3499                )
3500            }
3501            None => format!(
3502                "/workflows/{}/signal/{}",
3503                path_segment("workflow_id", workflow_id)?,
3504                path_segment("signal_name", signal_name)?,
3505            ),
3506        };
3507        let receipt = self
3508            .request_json(
3509                reqwest::Method::POST,
3510                &path,
3511                RequestProtocol::ControlPlane,
3512                Some(&body),
3513            )
3514            .await
3515            .map_err(|error| error.with_sent_request_id(request_id))?;
3516        Ok(with_request_id(receipt, request_id))
3517    }
3518
3519    /// Close the current run as cancelled immediately.
3520    ///
3521    /// Server revokes open tasks and timers without resuming workflow code for
3522    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3523    /// request on a supporting runtime and opted-in worker.
3524    pub async fn cancel_workflow(
3525        &self,
3526        workflow_id: &str,
3527        options: WorkflowCommandOptions,
3528    ) -> Result<WorkflowCommandResult> {
3529        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3530            .await
3531    }
3532
3533    /// Close the selected run as cancelled, only if `run_id` is still current.
3534    pub async fn cancel_workflow_run(
3535        &self,
3536        workflow_id: &str,
3537        run_id: &str,
3538        options: WorkflowCommandOptions,
3539    ) -> Result<WorkflowCommandResult> {
3540        self.workflow_command(
3541            workflow_id,
3542            Some(run_id),
3543            WorkflowCommandKind::Cancel,
3544            options,
3545        )
3546        .await
3547    }
3548
3549    /// Forcefully terminate the current run for an instance.
3550    pub async fn terminate_workflow(
3551        &self,
3552        workflow_id: &str,
3553        options: WorkflowCommandOptions,
3554    ) -> Result<WorkflowCommandResult> {
3555        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3556            .await
3557    }
3558
3559    /// Forcefully terminate only if `run_id` is still current.
3560    pub async fn terminate_workflow_run(
3561        &self,
3562        workflow_id: &str,
3563        run_id: &str,
3564        options: WorkflowCommandOptions,
3565    ) -> Result<WorkflowCommandResult> {
3566        self.workflow_command(
3567            workflow_id,
3568            Some(run_id),
3569            WorkflowCommandKind::Terminate,
3570            options,
3571        )
3572        .await
3573    }
3574
3575    /// Continue a failed run from its recorded activity failure boundary.
3576    pub async fn redrive_workflow_run(
3577        &self,
3578        workflow_id: &str,
3579        failed_run_id: &str,
3580        request_id: Option<&str>,
3581    ) -> Result<WorkflowRedriveResult> {
3582        let body = request_id
3583            .map(|id| json!({"request_id": id}))
3584            .unwrap_or_else(|| json!({}));
3585        let data: Value = self
3586            .request_json(
3587                reqwest::Method::POST,
3588                &format!(
3589                    "/workflows/{}/runs/{}/redrive",
3590                    path_segment("workflow_id", workflow_id)?,
3591                    path_segment("run_id", failed_run_id)?,
3592                ),
3593                RequestProtocol::ControlPlane,
3594                Some(&body),
3595            )
3596            .await?;
3597        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3598            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3599        {
3600            return Err(Error::Codec(
3601                "redrive response was not accepted".to_string(),
3602            ));
3603        }
3604        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3605            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3606        {
3607            return Err(Error::Codec(
3608                "redrive response does not match the requested source run".to_string(),
3609            ));
3610        }
3611        let run_id = data
3612            .get("run_id")
3613            .and_then(Value::as_str)
3614            .filter(|id| !id.is_empty() && *id != failed_run_id)
3615            .ok_or_else(|| {
3616                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3617            })?;
3618        let resume_step_sequence = data
3619            .get("resume_step_sequence")
3620            .and_then(Value::as_u64)
3621            .filter(|sequence| *sequence > 0)
3622            .ok_or_else(|| {
3623                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3624            })?;
3625        Ok(WorkflowRedriveResult {
3626            workflow_id: workflow_id.to_string(),
3627            source_run_id: failed_run_id.to_string(),
3628            run_id: run_id.to_string(),
3629            resume_step_sequence,
3630            raw: data,
3631        })
3632    }
3633
3634    async fn workflow_command(
3635        &self,
3636        workflow_id: &str,
3637        run_id: Option<&str>,
3638        command: WorkflowCommandKind,
3639        options: WorkflowCommandOptions,
3640    ) -> Result<WorkflowCommandResult> {
3641        #[cfg(feature = "telemetry")]
3642        let body = if command == WorkflowCommandKind::Cancel {
3643            self.with_observability_context(serde_json::to_value(&options)?)
3644        } else {
3645            serde_json::to_value(&options)?
3646        };
3647        #[cfg(not(feature = "telemetry"))]
3648        let body = &options;
3649        let path = match run_id {
3650            Some(run_id) => format!(
3651                "/workflows/{}/runs/{}/{}",
3652                path_segment("workflow_id", workflow_id)?,
3653                path_segment("run_id", run_id)?,
3654                command.as_str()
3655            ),
3656            None => format!(
3657                "/workflows/{}/{}",
3658                path_segment("workflow_id", workflow_id)?,
3659                command.as_str(),
3660            ),
3661        };
3662        let data = match self
3663            .request_json(
3664                reqwest::Method::POST,
3665                &path,
3666                RequestProtocol::ControlPlane,
3667                Some(&body),
3668            )
3669            .await
3670        {
3671            Ok(data) => data,
3672            Err(Error::Http { status, body }) => {
3673                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
3674                    command,
3675                    status,
3676                    body,
3677                    workflow_id,
3678                    run_id,
3679                )));
3680            }
3681            Err(error) => return Err(error),
3682        };
3683
3684        Ok(workflow_command_result(command, data, workflow_id, run_id))
3685    }
3686
3687    /// Execute a named, read-only query against a running or completed workflow.
3688    ///
3689    /// Arguments and results use the platform payload envelope. Server and
3690    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
3691    /// reason, HTTP status, and original response body.
3692    pub async fn query_workflow<T: Serialize>(
3693        &self,
3694        workflow_id: &str,
3695        query_name: &str,
3696        input: T,
3697    ) -> Result<Value> {
3698        self.query_workflow_target(workflow_id, None, query_name, input)
3699            .await
3700    }
3701
3702    /// Query only if `run_id` is still current, preventing accidental retargeting.
3703    pub async fn query_workflow_run<T: Serialize>(
3704        &self,
3705        workflow_id: &str,
3706        run_id: &str,
3707        query_name: &str,
3708        input: T,
3709    ) -> Result<Value> {
3710        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
3711            .await
3712    }
3713
3714    /// Query a workflow and return the lossless fixed Avro Value result.
3715    pub async fn query_workflow_avro_value<T: Serialize>(
3716        &self,
3717        workflow_id: &str,
3718        query_name: &str,
3719        input: T,
3720    ) -> Result<AvroValue> {
3721        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
3722            .await
3723    }
3724
3725    /// Query a selected run and return the lossless fixed Avro Value result.
3726    pub async fn query_workflow_run_avro_value<T: Serialize>(
3727        &self,
3728        workflow_id: &str,
3729        run_id: &str,
3730        query_name: &str,
3731        input: T,
3732    ) -> Result<AvroValue> {
3733        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
3734            .await
3735    }
3736
3737    async fn query_workflow_avro_value_target<T: Serialize>(
3738        &self,
3739        workflow_id: &str,
3740        run_id: Option<&str>,
3741        query_name: &str,
3742        input: T,
3743    ) -> Result<AvroValue> {
3744        let response = self
3745            .query_workflow_response(workflow_id, run_id, query_name, input)
3746            .await?;
3747        let envelope = response
3748            .get("result_envelope")
3749            .filter(|envelope| !envelope.is_null())
3750            .ok_or_else(|| {
3751                Error::Codec(
3752                    "missing_payload_envelope: typed query result requires result_envelope"
3753                        .to_string(),
3754                )
3755            })?;
3756        decode_wire_avro_value(envelope, DEFAULT_CODEC)
3757    }
3758
3759    async fn query_workflow_target<T: Serialize>(
3760        &self,
3761        workflow_id: &str,
3762        run_id: Option<&str>,
3763        query_name: &str,
3764        input: T,
3765    ) -> Result<Value> {
3766        let response = self
3767            .query_workflow_response(workflow_id, run_id, query_name, input)
3768            .await?;
3769        if let Some(envelope) = response
3770            .get("result_envelope")
3771            .filter(|envelope| !envelope.is_null())
3772        {
3773            return decode_wire_value(envelope, DEFAULT_CODEC);
3774        }
3775
3776        Ok(response.get("result").cloned().unwrap_or(Value::Null))
3777    }
3778
3779    // Typed and JSON readers share route validation and HTTP refusal handling.
3780    async fn query_workflow_response<T: Serialize>(
3781        &self,
3782        workflow_id: &str,
3783        run_id: Option<&str>,
3784        query_name: &str,
3785        input: T,
3786    ) -> Result<Value> {
3787        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3788        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
3789        let path = match run_id {
3790            Some(run_id) => {
3791                format!(
3792                    "/workflows/{}/runs/{}/query/{}",
3793                    path_segment("workflow_id", workflow_id)?,
3794                    path_segment("run_id", run_id)?,
3795                    path_segment("query_name", query_name)?,
3796                )
3797            }
3798            None => format!(
3799                "/workflows/{}/query/{}",
3800                path_segment("workflow_id", workflow_id)?,
3801                path_segment("query_name", query_name)?,
3802            ),
3803        };
3804        let response: Value = match self
3805            .request_json(
3806                reqwest::Method::POST,
3807                &path,
3808                RequestProtocol::ControlPlane,
3809                Some(&body),
3810            )
3811            .await
3812        {
3813            Ok(response) => response,
3814            Err(Error::Http { status, body }) => {
3815                return Err(Error::QueryFailed(query_failure(status, body)));
3816            }
3817            Err(error) => return Err(error),
3818        };
3819        Ok(response)
3820    }
3821
3822    /// Send a synchronous update using fixed Avro Value arguments.
3823    ///
3824    /// `request_id` is the caller command key (1 to 255 Unicode characters), sent as the
3825    /// `request_id` body field; `None` generates one with
3826    /// [`Client::generate_update_request_id`]. A Server that already retains the
3827    /// key for the same update intent returns the original update's receipt and
3828    /// result instead of admitting a second update; a different intent is
3829    /// refused with [`Error::is_request_id_conflict`].
3830    ///
3831    /// The Server waits for the update to complete. When its wait ends first,
3832    /// this returns [`Error::UpdateStillPending`], never `Null`: read the
3833    /// outcome later with [`Client::update_outcome`] and the pending update's
3834    /// id, or send the update again with the same `request_id`. A handler that
3835    /// returned null is `Ok(Value::Null)`.
3836    pub async fn update_workflow<T: Serialize>(
3837        &self,
3838        workflow_id: &str,
3839        update_name: &str,
3840        input: T,
3841        request_id: Option<&str>,
3842    ) -> Result<Value> {
3843        let response = self
3844            .update_workflow_response(workflow_id, update_name, input, request_id)
3845            .await?;
3846        Self::submitted_update_value(workflow_id, response)
3847    }
3848
3849    /// Send a synchronous update and retain a bytes-capable Avro result.
3850    pub async fn update_workflow_avro_value<T: Serialize>(
3851        &self,
3852        workflow_id: &str,
3853        update_name: &str,
3854        input: T,
3855        request_id: Option<&str>,
3856    ) -> Result<AvroValue> {
3857        let response = self
3858            .update_workflow_response(workflow_id, update_name, input, request_id)
3859            .await?;
3860        Self::submitted_update_avro_value(workflow_id, response)
3861    }
3862
3863    async fn update_workflow_response<T: Serialize>(
3864        &self,
3865        workflow_id: &str,
3866        update_name: &str,
3867        input: T,
3868        request_id: Option<&str>,
3869    ) -> Result<Value> {
3870        let path = format!(
3871            "/workflows/{}/update/{}",
3872            path_segment("workflow_id", workflow_id)?,
3873            path_segment("update_name", update_name)?
3874        );
3875        let request_id = match request_id {
3876            Some(request_id) => {
3877                validate_request_id(request_id)?;
3878                request_id.to_string()
3879            }
3880            None => Self::generate_update_request_id(),
3881        };
3882        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3883        let body = self.with_observability_context(json!({
3884            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
3885            "wait_for": "completed",
3886            "request_id": request_id,
3887        }));
3888        let receipt = self
3889            .request_json(
3890                reqwest::Method::POST,
3891                &path,
3892                RequestProtocol::ControlPlane,
3893                Some(&body),
3894            )
3895            .await
3896            .map_err(|error| error.with_sent_request_id(&request_id))?;
3897        Ok(with_request_id(receipt, &request_id))
3898    }
3899
3900    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
3901        let path = format!("/workflows/{}", path_segment("workflow_id", workflow_id)?);
3902        let mut data: WorkflowDescription = self
3903            .request_json(
3904                reqwest::Method::GET,
3905                &path,
3906                RequestProtocol::ControlPlane,
3907                Option::<&Value>::None,
3908            )
3909            .await?;
3910        data.decode_payloads()?;
3911        Ok(data)
3912    }
3913
3914    /// Describe one selected run, including historical terminal runs.
3915    pub async fn describe_workflow_run(
3916        &self,
3917        workflow_id: &str,
3918        run_id: &str,
3919    ) -> Result<WorkflowDescription> {
3920        let path = format!(
3921            "/workflows/{}/runs/{}",
3922            path_segment("workflow_id", workflow_id)?,
3923            path_segment("run_id", run_id)?,
3924        );
3925        let mut data: WorkflowDescription = self
3926            .request_json(
3927                reqwest::Method::GET,
3928                &path,
3929                RequestProtocol::ControlPlane,
3930                Option::<&Value>::None,
3931            )
3932            .await?;
3933        data.decode_payloads()?;
3934        Ok(data)
3935    }
3936
3937    fn workflow_stream_path(
3938        workflow_id: &str,
3939        run_id: &str,
3940        stream_name: Option<&str>,
3941    ) -> Result<String> {
3942        let mut path = format!(
3943            "/workflows/{}/runs/{}/streams",
3944            path_segment("workflow_id", workflow_id)?,
3945            path_segment("run_id", run_id)?,
3946        );
3947        if let Some(stream_name) = stream_name {
3948            path.push('/');
3949            path.push_str(&path_segment("stream_name", stream_name)?);
3950        }
3951        Ok(path)
3952    }
3953
3954    /// List the run-scoped output streams already opened by a workflow.
3955    pub async fn list_workflow_streams(
3956        &self,
3957        workflow_id: &str,
3958        run_id: &str,
3959    ) -> Result<Vec<WorkflowStreamDescription>> {
3960        let response: WorkflowStreamListResponse = self
3961            .request_json(
3962                reqwest::Method::GET,
3963                &Self::workflow_stream_path(workflow_id, run_id, None)?,
3964                RequestProtocol::ControlPlane,
3965                Option::<&Value>::None,
3966            )
3967            .await?;
3968        Ok(response.streams)
3969    }
3970
3971    /// Describe stream lifecycle, offsets, pending count, and terminal error.
3972    pub async fn describe_workflow_stream(
3973        &self,
3974        workflow_id: &str,
3975        run_id: &str,
3976        stream_name: &str,
3977    ) -> Result<WorkflowStreamDescription> {
3978        let response: WorkflowStreamDescriptionResponse = self
3979            .request_json(
3980                reqwest::Method::GET,
3981                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name))?,
3982                RequestProtocol::ControlPlane,
3983                Option::<&Value>::None,
3984            )
3985            .await?;
3986        Ok(response.stream)
3987    }
3988
3989    /// Read one bounded page beginning at a zero-based offset.
3990    ///
3991    /// Delivery is at least once: persist `next_offset` only after processing
3992    /// the page. The future is cancellation-safe; dropping it cancels the
3993    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
3994    /// service contract.
3995    pub async fn subscribe_workflow_stream(
3996        &self,
3997        workflow_id: &str,
3998        run_id: &str,
3999        stream_name: &str,
4000        from_offset: u64,
4001        max_items: usize,
4002        wait: Duration,
4003    ) -> Result<WorkflowStreamPage> {
4004        let max_items = max_items.clamp(1, 500);
4005        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
4006        let path = format!(
4007            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
4008            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name))?,
4009        );
4010        let response: WorkflowStreamPageResponse = self
4011            .request_json_with_timeout(
4012                reqwest::Method::GET,
4013                &path,
4014                RequestProtocol::ControlPlane,
4015                Option::<&Value>::None,
4016                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
4017            )
4018            .await?;
4019
4020        let items = response
4021            .items
4022            .into_iter()
4023            .map(|raw| {
4024                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
4025                let envelope = raw.get("payload").cloned();
4026                let payload = envelope
4027                    .as_ref()
4028                    .filter(|value| value.get("blob").is_some())
4029                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
4030                    .transpose()?
4031                    .map(AvroValue::into_json)
4032                    .transpose()?;
4033                Ok(WorkflowStreamItem {
4034                    offset,
4035                    payload,
4036                    payload_envelope: envelope,
4037                    payload_reference: raw
4038                        .get("payload_reference")
4039                        .and_then(Value::as_str)
4040                        .map(str::to_string),
4041                    payload_codec: raw
4042                        .get("payload_codec")
4043                        .and_then(Value::as_str)
4044                        .map(str::to_string),
4045                    idempotency_key: raw
4046                        .get("idempotency_key")
4047                        .and_then(Value::as_str)
4048                        .map(str::to_string),
4049                    item_type: raw
4050                        .get("item_type")
4051                        .and_then(Value::as_str)
4052                        .map(str::to_string),
4053                    content_type: raw
4054                        .get("content_type")
4055                        .and_then(Value::as_str)
4056                        .map(str::to_string),
4057                    origin: raw
4058                        .get("origin")
4059                        .and_then(Value::as_str)
4060                        .map(str::to_string),
4061                    origin_reference: raw
4062                        .get("origin_reference")
4063                        .and_then(Value::as_str)
4064                        .map(str::to_string),
4065                    emitted_at: raw
4066                        .get("emitted_at")
4067                        .and_then(Value::as_str)
4068                        .map(str::to_string),
4069                    raw,
4070                })
4071            })
4072            .collect::<Result<Vec<_>>>()?;
4073        Ok(WorkflowStreamPage {
4074            stream: response.stream,
4075            items,
4076            next_offset: response.next_offset,
4077            terminal: response.terminal,
4078        })
4079    }
4080
4081    /// Append inline Avro envelopes or opaque external payload references.
4082    pub async fn append_workflow_stream(
4083        &self,
4084        workflow_id: &str,
4085        run_id: &str,
4086        stream_name: &str,
4087        items: &[WorkflowStreamAppendItem],
4088        max_pending_items: Option<u64>,
4089    ) -> Result<WorkflowStreamAppendResult> {
4090        if items.is_empty() {
4091            return Err(Error::Codec(
4092                "workflow_stream_items_empty: append requires at least one item".to_string(),
4093            ));
4094        }
4095        let mut body = json!({
4096            "items": items
4097                .iter()
4098                .map(|item| item.wire_value(None))
4099                .collect::<Vec<_>>(),
4100        });
4101        if let Some(max_pending_items) = max_pending_items {
4102            if max_pending_items == 0 {
4103                return Err(Error::Codec(
4104                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
4105                        .to_string(),
4106                ));
4107            }
4108            body["max_pending_items"] = json!(max_pending_items);
4109        }
4110        let response: WorkflowStreamAppendResponse = self
4111            .request_json(
4112                reqwest::Method::POST,
4113                &format!(
4114                    "{}/items",
4115                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name))?,
4116                ),
4117                RequestProtocol::ControlPlane,
4118                Some(&body),
4119            )
4120            .await?;
4121        Ok(WorkflowStreamAppendResult {
4122            stream: response.stream,
4123            accepted_offsets: response.accepted_offsets,
4124            accepted: response.accepted,
4125            deduped: response.deduped,
4126        })
4127    }
4128
4129    /// Close a stream, or mark it errored when `error_reason` is supplied.
4130    pub async fn close_workflow_stream(
4131        &self,
4132        workflow_id: &str,
4133        run_id: &str,
4134        stream_name: &str,
4135        error_reason: Option<&str>,
4136        retention_seconds: Option<u64>,
4137    ) -> Result<WorkflowStreamDescription> {
4138        let mut body = json!({});
4139        if let Some(error_reason) = error_reason {
4140            body["error_reason"] = json!(error_reason);
4141        }
4142        if let Some(retention_seconds) = retention_seconds {
4143            if retention_seconds == 0 {
4144                return Err(Error::Codec(
4145                    "workflow_stream_retention_invalid: retention_seconds must be positive"
4146                        .to_string(),
4147                ));
4148            }
4149            body["retention_seconds"] = json!(retention_seconds);
4150        }
4151        let response: WorkflowStreamDescriptionResponse = self
4152            .request_json(
4153                reqwest::Method::POST,
4154                &format!(
4155                    "{}/close",
4156                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name))?,
4157                ),
4158                RequestProtocol::ControlPlane,
4159                Some(&body),
4160            )
4161            .await?;
4162        Ok(response.stream)
4163    }
4164
4165    pub async fn register_worker(
4166        &self,
4167        worker_id: &str,
4168        task_queue: &str,
4169        supported_workflow_types: Vec<String>,
4170        supported_activity_types: Vec<String>,
4171        max_concurrent_workflow_tasks: usize,
4172        max_concurrent_activity_tasks: usize,
4173    ) -> Result<RegisterWorkerResponse> {
4174        self.register_worker_with_capabilities(
4175            worker_id,
4176            task_queue,
4177            supported_workflow_types,
4178            supported_activity_types,
4179            max_concurrent_workflow_tasks,
4180            max_concurrent_activity_tasks,
4181            Vec::new(),
4182        )
4183        .await
4184    }
4185
4186    /// Register a worker and explicitly advertise additive worker capabilities.
4187    pub async fn register_worker_with_capabilities(
4188        &self,
4189        worker_id: &str,
4190        task_queue: &str,
4191        supported_workflow_types: Vec<String>,
4192        supported_activity_types: Vec<String>,
4193        max_concurrent_workflow_tasks: usize,
4194        max_concurrent_activity_tasks: usize,
4195        capabilities: Vec<String>,
4196    ) -> Result<RegisterWorkerResponse> {
4197        self.register_worker_with_command_contracts(
4198            worker_id,
4199            task_queue,
4200            supported_workflow_types,
4201            supported_activity_types,
4202            max_concurrent_workflow_tasks,
4203            max_concurrent_activity_tasks,
4204            capabilities,
4205            Value::Object(serde_json::Map::new()),
4206        )
4207        .await
4208    }
4209
4210    /// Register a worker and advertise its named query and update handlers.
4211    ///
4212    /// This Rust SDK cannot execute synchronous pre-accept update validation,
4213    /// so a workflow contract with a non-empty or malformed
4214    /// `update_validators` declaration returns
4215    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
4216    #[allow(clippy::too_many_arguments)]
4217    pub async fn register_worker_with_command_contracts(
4218        &self,
4219        worker_id: &str,
4220        task_queue: &str,
4221        supported_workflow_types: Vec<String>,
4222        supported_activity_types: Vec<String>,
4223        max_concurrent_workflow_tasks: usize,
4224        max_concurrent_activity_tasks: usize,
4225        capabilities: Vec<String>,
4226        workflow_command_contracts: Value,
4227    ) -> Result<RegisterWorkerResponse> {
4228        self.register_worker_with_definition_fingerprints(
4229            worker_id,
4230            task_queue,
4231            supported_workflow_types,
4232            supported_activity_types,
4233            max_concurrent_workflow_tasks,
4234            max_concurrent_activity_tasks,
4235            capabilities,
4236            workflow_command_contracts,
4237            None,
4238        )
4239        .await
4240    }
4241
4242    #[allow(clippy::too_many_arguments)]
4243    async fn register_worker_with_definition_fingerprints(
4244        &self,
4245        worker_id: &str,
4246        task_queue: &str,
4247        supported_workflow_types: Vec<String>,
4248        supported_activity_types: Vec<String>,
4249        max_concurrent_workflow_tasks: usize,
4250        max_concurrent_activity_tasks: usize,
4251        capabilities: Vec<String>,
4252        workflow_command_contracts: Value,
4253        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
4254    ) -> Result<RegisterWorkerResponse> {
4255        if let Some(contracts) = workflow_command_contracts.as_object() {
4256            for (workflow_type, contract) in contracts {
4257                let Some(update_validators) = contract.get("update_validators") else {
4258                    continue;
4259                };
4260                if !update_validators
4261                    .as_array()
4262                    .is_some_and(|validators| validators.is_empty())
4263                {
4264                    return Err(Error::UnsupportedUpdateValidators {
4265                        workflow_type: workflow_type.clone(),
4266                    });
4267                }
4268            }
4269        }
4270
4271        let mut body = json!({
4272            "worker_id": worker_id,
4273            "task_queue": task_queue,
4274            "runtime": "rust",
4275            "sdk_version": SDK_VERSION,
4276            "supported_workflow_types": supported_workflow_types,
4277            "supported_activity_types": supported_activity_types,
4278            "capabilities": capabilities,
4279            "capability_manifest": portable_worker_affinity_capability_manifest(),
4280            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
4281            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
4282        });
4283        if capabilities
4284            .iter()
4285            .any(|capability| capability == "nexus_cooperative_cancellation")
4286        {
4287            body["capability_manifest"]["nexus_cooperative_cancellation"] = json!({
4288                "supported":true, "minimum_protocol_version":"1.20",
4289                "implementation":"owned_workflow_run_canonical_delivery", "binding_kinds":["workflow_run"],
4290            });
4291        }
4292        if let Some(build_id) = &self.worker_build_id {
4293            if build_id.is_empty() || build_id.len() > 255 {
4294                return Err(Error::WorkerLoop(
4295                    "worker build ID must contain 1 to 255 bytes".into(),
4296                ));
4297            }
4298            body["build_id"] = json!(build_id);
4299        }
4300        if self.sticky_cache.is_some() {
4301            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
4302                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
4303                "implementation":"bounded_durable_history_cache"});
4304            body["capability_manifest"]["sticky_history_suffix"] = json!({"supported":true,
4305                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
4306                "version":1});
4307        }
4308        if self.local_activities_enabled {
4309            body["capability_manifest"]["local_activities"] = json!({"supported":true,
4310                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4311        }
4312        if self.worker_sessions_enabled {
4313            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
4314                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4315            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
4316        }
4317        if workflow_command_contracts
4318            .as_object()
4319            .is_some_and(|contracts| !contracts.is_empty())
4320        {
4321            body["workflow_command_contracts"] = workflow_command_contracts;
4322        }
4323        if let Some(fingerprints) = workflow_definition_fingerprints {
4324            body["workflow_definition_fingerprints"] = json!(fingerprints);
4325        }
4326
4327        let response: Value = self
4328            .request_json(
4329                reqwest::Method::POST,
4330                "/worker/register",
4331                RequestProtocol::DefaultWorker,
4332                Some(&body),
4333            )
4334            .await?;
4335        if response["registered"] == true && response["worker_id"].as_str() == Some(worker_id) {
4336            self.observe_worker_activity_lease_capabilities(&response["server_capabilities"]);
4337        }
4338        if self.sticky_cache.is_some() {
4339            self.confirm_sticky_registration(&response, worker_id, task_queue)
4340                .await?;
4341        }
4342        if self.local_activities_enabled || self.worker_sessions_enabled {
4343            let compatible = response["registered"].as_bool() == Some(true)
4344                && response["worker_id"].as_str() == Some(worker_id)
4345                && response["namespace"].as_str() == Some(self.namespace.as_str())
4346                && response["task_queue"].as_str() == Some(task_queue)
4347                && response["protocol_version"]
4348                    .as_str()
4349                    .and_then(|version| version.strip_prefix("1."))
4350                    .and_then(|minor| minor.parse::<u64>().ok())
4351                    .is_some_and(|minor| minor >= 18)
4352                && (!self.local_activities_enabled
4353                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
4354                        == Some(true))
4355                && (!self.worker_sessions_enabled
4356                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
4357                        == Some(true)
4358                        && response["capabilities"].as_array().is_some_and(|accepted| {
4359                            capabilities.iter().all(|capability| {
4360                                accepted
4361                                    .iter()
4362                                    .any(|value| value.as_str() == Some(capability.as_str()))
4363                            })
4364                        })));
4365            if !compatible {
4366                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
4367                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
4368                } else {
4369                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
4370                });
4371                if response["registered"] == true
4372                    && response["worker_id"].as_str() == Some(worker_id)
4373                {
4374                    if let Err(deregistration) =
4375                        self.deregister_worker_registration(worker_id).await
4376                    {
4377                        return Err(Error::WorkerShutdown {
4378                            primary: Box::new(error),
4379                            deregistration: Box::new(deregistration),
4380                        });
4381                    }
4382                }
4383                return Err(error);
4384            }
4385        }
4386        if self.cooperative_worker_protocol {
4387            let compatible = response["registered"].as_bool() == Some(true)
4388                && response["worker_id"].as_str() == Some(worker_id)
4389                && response["namespace"].as_str() == Some(self.namespace.as_str())
4390                && response["task_queue"].as_str() == Some(task_queue)
4391                && response["protocol_version"]
4392                    .as_str()
4393                    .is_some_and(cooperative_cancellation::supports_protocol)
4394                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
4395                    == Some(true)
4396                && (!capabilities
4397                    .iter()
4398                    .any(|capability| capability == "nexus_cooperative_cancellation")
4399                    || nexus::installed_cooperation(&response["server_capabilities"]))
4400                && response["capabilities"].as_array().is_some_and(|accepted| {
4401                    capabilities.iter().all(|capability| {
4402                        accepted
4403                            .iter()
4404                            .any(|value| value.as_str() == Some(capability.as_str()))
4405                    })
4406                });
4407            if !compatible {
4408                let error = Error::CooperativeCancellationUnavailable(
4409                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
4410                );
4411                if response["registered"].as_bool() == Some(true)
4412                    && response["worker_id"].as_str() == Some(worker_id)
4413                {
4414                    if let Err(deregistration) =
4415                        self.deregister_worker_registration(worker_id).await
4416                    {
4417                        return Err(Error::WorkerShutdown {
4418                            primary: Box::new(error),
4419                            deregistration: Box::new(deregistration),
4420                        });
4421                    }
4422                }
4423                return Err(error);
4424            }
4425        }
4426        Ok(serde_json::from_value(response)?)
4427    }
4428
4429    /// Gracefully remove one worker's registration through the worker plane.
4430    ///
4431    /// This operation is separate from operator-facing worker management. It
4432    /// uses worker-protocol authentication and returns the server's lease
4433    /// recovery result.
4434    pub async fn deregister_worker_registration(
4435        &self,
4436        worker_id: &str,
4437    ) -> Result<WorkerDeregistrationEnvelope> {
4438        let path = format!(
4439            "/worker/registrations/{}",
4440            percent_encode_path_segment(worker_id)
4441        );
4442        self.request_json(
4443            reqwest::Method::DELETE,
4444            &path,
4445            RequestProtocol::DefaultWorker,
4446            Option::<&Value>::None,
4447        )
4448        .await
4449    }
4450
4451    /// Long-poll for an ephemeral, read-only workflow query task.
4452    pub async fn poll_query_task(
4453        &self,
4454        worker_id: &str,
4455        task_queue: &str,
4456        timeout: Duration,
4457    ) -> Result<Option<QueryTask>> {
4458        Ok(self
4459            .poll_query_task_response(worker_id, task_queue, timeout)
4460            .await?
4461            .task)
4462    }
4463
4464    /// Poll a query task while preserving server stop and drain metadata.
4465    pub async fn poll_query_task_response(
4466        &self,
4467        worker_id: &str,
4468        task_queue: &str,
4469        timeout: Duration,
4470    ) -> Result<PollQueryTaskResponse> {
4471        let poll_request_id = unique_request_id("rust-query-poll");
4472        self.poll_query_task_response_with_request_id(
4473            worker_id,
4474            task_queue,
4475            timeout,
4476            &poll_request_id,
4477            1,
4478        )
4479        .await
4480    }
4481
4482    async fn poll_query_task_response_with_request_id(
4483        &self,
4484        worker_id: &str,
4485        task_queue: &str,
4486        timeout: Duration,
4487        poll_request_id: &str,
4488        transport_retries: usize,
4489    ) -> Result<PollQueryTaskResponse> {
4490        let timeout_seconds = long_poll_timeout_seconds(timeout);
4491        let body = json!({
4492            "worker_id": worker_id,
4493            "task_queue": task_queue,
4494            "poll_request_id": poll_request_id,
4495            "timeout_seconds": timeout_seconds,
4496        });
4497        self.poll_request_json(
4498            "/worker/query-tasks/poll",
4499            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4500            &body,
4501            timeout + Duration::from_secs(5),
4502            transport_retries,
4503        )
4504        .await
4505    }
4506
4507    /// Complete a query task without appending workflow history.
4508    pub async fn complete_query_task<T: Serialize>(
4509        &self,
4510        query_task_id: &str,
4511        lease_owner: &str,
4512        query_task_attempt: u64,
4513        result: T,
4514        codec: &str,
4515    ) -> Result<Value> {
4516        let typed_result = AvroValue::from_serialize(&result)?;
4517        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
4518        self.complete_query_task_with_envelope(
4519            query_task_id,
4520            lease_owner,
4521            query_task_attempt,
4522            typed_result.into_json()?,
4523            result_envelope,
4524        )
4525        .await
4526    }
4527
4528    async fn complete_query_task_with_envelope(
4529        &self,
4530        query_task_id: &str,
4531        lease_owner: &str,
4532        query_task_attempt: u64,
4533        result: Value,
4534        result_envelope: Value,
4535    ) -> Result<Value> {
4536        let body = json!({
4537            "lease_owner": lease_owner,
4538            "query_task_attempt": query_task_attempt,
4539            "result": result,
4540            "result_envelope": result_envelope,
4541        });
4542        let path = format!("/worker/query-tasks/{query_task_id}/complete");
4543        let response = self
4544            .request_json(
4545                reqwest::Method::POST,
4546                &path,
4547                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4548                Some(&body),
4549            )
4550            .await;
4551        query_task_response(response)
4552    }
4553
4554    /// Report a stable machine-readable query-task failure.
4555    pub async fn fail_query_task(
4556        &self,
4557        query_task_id: &str,
4558        lease_owner: &str,
4559        query_task_attempt: u64,
4560        message: impl Into<String>,
4561        reason: impl Into<String>,
4562        failure_type: impl Into<String>,
4563    ) -> Result<Value> {
4564        let body = json!({
4565            "lease_owner": lease_owner,
4566            "query_task_attempt": query_task_attempt,
4567            "failure": {
4568                "message": message.into(),
4569                "reason": reason.into(),
4570                "type": failure_type.into(),
4571            }
4572        });
4573        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4574        let response = self
4575            .request_json(
4576                reqwest::Method::POST,
4577                &path,
4578                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4579                Some(&body),
4580            )
4581            .await;
4582        query_task_response(response)
4583    }
4584
4585    pub async fn heartbeat_worker(
4586        &self,
4587        worker_id: &str,
4588        workflow_available: usize,
4589        activity_available: usize,
4590    ) -> Result<Value> {
4591        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4592            .await
4593    }
4594
4595    async fn heartbeat_worker_with_sessions(
4596        &self,
4597        worker_id: &str,
4598        workflow_available: usize,
4599        activity_available: usize,
4600        session_available: Option<usize>,
4601    ) -> Result<Value> {
4602        let mut body = json!({
4603            "worker_id": worker_id,
4604            "task_slots": {
4605                "workflow_available": workflow_available,
4606                "activity_available": activity_available
4607            },
4608            "process_metrics": {
4609                "process_id": std::process::id(),
4610                "process_uptime_seconds": 0
4611            }
4612        });
4613
4614        if let Some(available) = session_available {
4615            body["task_slots"]["session_available"] = json!(available);
4616        }
4617
4618        self.request_json(
4619            reqwest::Method::POST,
4620            "/worker/heartbeat",
4621            RequestProtocol::DefaultWorker,
4622            Some(&body),
4623        )
4624        .await
4625    }
4626
4627    pub async fn poll_workflow_task(
4628        &self,
4629        worker_id: &str,
4630        task_queue: &str,
4631        timeout: Duration,
4632    ) -> Result<Option<WorkflowTask>> {
4633        Ok(self
4634            .poll_workflow_task_response(worker_id, task_queue, timeout)
4635            .await?
4636            .task)
4637    }
4638
4639    pub async fn poll_workflow_task_response(
4640        &self,
4641        worker_id: &str,
4642        task_queue: &str,
4643        timeout: Duration,
4644    ) -> Result<PollWorkflowTaskResponse> {
4645        let poll_request_id = unique_request_id("rust-workflow-poll");
4646        self.poll_workflow_task_response_with_request_id(
4647            worker_id,
4648            task_queue,
4649            timeout,
4650            &poll_request_id,
4651            1,
4652        )
4653        .await
4654    }
4655
4656    async fn poll_workflow_task_response_with_request_id(
4657        &self,
4658        worker_id: &str,
4659        task_queue: &str,
4660        timeout: Duration,
4661        poll_request_id: &str,
4662        transport_retries: usize,
4663    ) -> Result<PollWorkflowTaskResponse> {
4664        let body = json!({
4665            "worker_id": worker_id,
4666            "task_queue": task_queue,
4667            "poll_request_id": poll_request_id,
4668            "timeout_seconds": long_poll_timeout_seconds(timeout),
4669            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
4670        });
4671        let mut wire: Value = self
4672            .poll_request_json_unresolved(
4673                "/worker/workflow-tasks/poll",
4674                RequestProtocol::DefaultWorker,
4675                &body,
4676                timeout + Duration::from_secs(5),
4677                transport_retries,
4678            )
4679            .await?;
4680        let ready_age = metrics::ready_age_from_poll(&wire);
4681        let claim =
4682            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
4683        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
4684            self.resolve_runtime_payloads(
4685                &mut wire,
4686                "/worker/workflow-tasks/poll",
4687                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
4688            )
4689            .await?;
4690            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
4691            if let Some(task) = data.task.as_mut() {
4692                self.fetch_remaining_workflow_history(worker_id, task)
4693                    .await?;
4694            }
4695            Ok(data)
4696        })
4697        .await?;
4698        if data.task.is_some() {
4699            self.worker_dispatch_metrics
4700                .ready_age("workflow", task_queue, ready_age);
4701        }
4702        Ok(data)
4703    }
4704
4705    async fn fetch_remaining_workflow_history(
4706        &self,
4707        worker_id: &str,
4708        task: &mut WorkflowTask,
4709    ) -> Result<()> {
4710        let mut next_token = task.next_history_page_token.clone();
4711        let mut seen = BTreeSet::new();
4712
4713        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
4714            if seen.len() >= 128 || !seen.insert(token.clone()) {
4715                return Err(Error::Codec(
4716                    "workflow history pagination exceeded its page bound or repeated a token"
4717                        .into(),
4718                ));
4719            }
4720            let lease_owner = task
4721                .lease_owner
4722                .clone()
4723                .unwrap_or_else(|| worker_id.to_string());
4724            let page = self
4725                .workflow_task_history_page(
4726                    &task.task_id,
4727                    &lease_owner,
4728                    task.workflow_task_attempt,
4729                    &token,
4730                )
4731                .await?;
4732
4733            task.append_history_page(page);
4734
4735            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
4736                return Err(Error::Codec(
4737                    "workflow history pagination returned the same page token".to_string(),
4738                ));
4739            }
4740
4741            next_token = task.next_history_page_token.clone();
4742        }
4743
4744        Ok(())
4745    }
4746
4747    async fn workflow_task_history_page(
4748        &self,
4749        task_id: &str,
4750        lease_owner: &str,
4751        workflow_task_attempt: u64,
4752        next_history_page_token: &str,
4753    ) -> Result<WorkflowTaskHistoryPage> {
4754        let body = json!({
4755            "lease_owner": lease_owner,
4756            "workflow_task_attempt": workflow_task_attempt,
4757            "next_history_page_token": next_history_page_token
4758        });
4759        let path = format!("/worker/workflow-tasks/{task_id}/history");
4760
4761        self.request_json(
4762            reqwest::Method::POST,
4763            &path,
4764            RequestProtocol::DefaultWorker,
4765            Some(&body),
4766        )
4767        .await
4768    }
4769
4770    pub async fn complete_workflow_task(
4771        &self,
4772        task_id: &str,
4773        lease_owner: &str,
4774        workflow_task_attempt: u64,
4775        commands: Vec<Value>,
4776    ) -> Result<Value> {
4777        self.complete_workflow_task_with_message_streams(
4778            task_id,
4779            lease_owner,
4780            workflow_task_attempt,
4781            commands,
4782            Vec::new(),
4783            Vec::new(),
4784            None,
4785        )
4786        .await
4787    }
4788
4789    #[allow(clippy::too_many_arguments)]
4790    async fn complete_workflow_task_with_message_streams(
4791        &self,
4792        task_id: &str,
4793        lease_owner: &str,
4794        workflow_task_attempt: u64,
4795        commands: Vec<Value>,
4796        message_stream_cursors: Vec<Value>,
4797        message_stream_waits: Vec<Value>,
4798        sticky_cache: Option<Value>,
4799    ) -> Result<Value> {
4800        validate_workflow_task_commands(&commands)?;
4801        let has_message_stream_metadata =
4802            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
4803        if has_message_stream_metadata
4804            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
4805        {
4806            return Err(Error::Codec(
4807                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
4808                    .to_string(),
4809            ));
4810        }
4811        let protocol_version = workflow_completion_protocol_version_with_message_streams(
4812            &commands,
4813            has_message_stream_metadata,
4814        );
4815        let protocol_version = if sticky_cache.is_some()
4816            && protocol_version
4817                .strip_prefix("1.")
4818                .and_then(|minor| minor.parse::<u64>().ok())
4819                .is_some_and(|minor| minor < 18)
4820        {
4821            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
4822        } else {
4823            protocol_version
4824        };
4825        let mut body = json!({
4826            "lease_owner": lease_owner,
4827            "workflow_task_attempt": workflow_task_attempt,
4828            "commands": commands
4829        });
4830        #[cfg(feature = "telemetry")]
4831        if self.observability_context_supported.load(Ordering::SeqCst)
4832            && opentelemetry::Context::current()
4833                .get::<telemetry::ExecutionFields>()
4834                .is_some()
4835        {
4836            if let Some(commands) = body["commands"].as_array_mut() {
4837                for command in commands {
4838                    if command.get("observability_context").is_none()
4839                        && matches!(
4840                            command["type"].as_str(),
4841                            Some("start_child_workflow" | "continue_as_new")
4842                        )
4843                    {
4844                        *command = self.with_observability_context(command.take());
4845                    }
4846                }
4847            }
4848        }
4849        if !message_stream_cursors.is_empty() {
4850            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
4851        }
4852        if !message_stream_waits.is_empty() {
4853            body["message_stream_waits"] = Value::Array(message_stream_waits);
4854        }
4855        if let Some(claim) = sticky_cache {
4856            body["sticky_cache"] = claim;
4857        }
4858        let path = format!("/worker/workflow-tasks/{task_id}/complete");
4859        self.request_json(
4860            reqwest::Method::POST,
4861            &path,
4862            RequestProtocol::Worker(protocol_version),
4863            Some(&body),
4864        )
4865        .await
4866    }
4867
4868    pub async fn fail_workflow_task(
4869        &self,
4870        task_id: &str,
4871        lease_owner: &str,
4872        workflow_task_attempt: u64,
4873        message: impl Into<String>,
4874    ) -> Result<Value> {
4875        self.fail_workflow_task_with_type(
4876            task_id,
4877            lease_owner,
4878            workflow_task_attempt,
4879            message,
4880            "RustWorkflowTaskFailure",
4881        )
4882        .await
4883    }
4884
4885    async fn fail_workflow_task_with_type(
4886        &self,
4887        task_id: &str,
4888        lease_owner: &str,
4889        workflow_task_attempt: u64,
4890        message: impl Into<String>,
4891        failure_type: &str,
4892    ) -> Result<Value> {
4893        self.fail_workflow_task_with_failure(
4894            task_id,
4895            lease_owner,
4896            workflow_task_attempt,
4897            json!({"message": message.into(), "type": failure_type}),
4898        )
4899        .await
4900    }
4901
4902    /// Report a workflow-task failure using the existing Server failure schema.
4903    /// The published schema supports `message`, `type`, `reason`, `sequence`
4904    /// and `stack_trace`. Oversized data is bounded before transport; original
4905    /// sizes and omissions are marked in the existing message field.
4906    pub async fn fail_workflow_task_with_failure(
4907        &self,
4908        task_id: &str,
4909        lease_owner: &str,
4910        workflow_task_attempt: u64,
4911        failure: Value,
4912    ) -> Result<Value> {
4913        let body = json!({
4914            "lease_owner": lease_owner,
4915            "workflow_task_attempt": workflow_task_attempt,
4916            "failure": failure,
4917        });
4918        let path = format!("/worker/workflow-tasks/{task_id}/fail");
4919        self.request_json(
4920            reqwest::Method::POST,
4921            &path,
4922            RequestProtocol::DefaultWorker,
4923            Some(&body),
4924        )
4925        .await
4926    }
4927
4928    pub async fn poll_activity_task(
4929        &self,
4930        worker_id: &str,
4931        task_queue: &str,
4932        timeout: Duration,
4933    ) -> Result<Option<ActivityTask>> {
4934        Ok(self
4935            .poll_activity_task_response(worker_id, task_queue, timeout)
4936            .await?
4937            .task)
4938    }
4939
4940    /// Poll an activity task while preserving server stop and drain metadata.
4941    pub async fn poll_activity_task_response(
4942        &self,
4943        worker_id: &str,
4944        task_queue: &str,
4945        timeout: Duration,
4946    ) -> Result<PollActivityTaskResponse> {
4947        let poll_request_id = unique_request_id("rust-activity-poll");
4948        self.poll_activity_task_response_with_request_id(
4949            worker_id,
4950            task_queue,
4951            timeout,
4952            &poll_request_id,
4953            1,
4954        )
4955        .await
4956        .map(worker_session::SessionPollResponse::ordinary)
4957    }
4958
4959    async fn poll_activity_task_response_with_request_id(
4960        &self,
4961        worker_id: &str,
4962        task_queue: &str,
4963        timeout: Duration,
4964        poll_request_id: &str,
4965        transport_retries: usize,
4966    ) -> Result<worker_session::SessionPollResponse> {
4967        let body = json!({
4968            "worker_id": worker_id,
4969            "task_queue": task_queue,
4970            "poll_request_id": poll_request_id,
4971            "timeout_seconds": long_poll_timeout_seconds(timeout),
4972        });
4973        let mut wire: Value = self
4974            .poll_request_json_unresolved(
4975                "/worker/activity-tasks/poll",
4976                RequestProtocol::DefaultWorker,
4977                &body,
4978                timeout + Duration::from_secs(5),
4979                transport_retries,
4980            )
4981            .await?;
4982        let ready_age = metrics::ready_age_from_poll(&wire);
4983        let lease =
4984            activity_lease::authority::Lease::confirm(self, &wire, worker_id, task_queue).await?;
4985        let observed = self.with_activity_lease_authority(
4986            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
4987        );
4988        let claim = if lease.is_none() {
4989            activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?
4990        } else {
4991            None
4992        };
4993        let loading = async {
4994            observed
4995                .resolve_runtime_payloads(
4996                    &mut wire,
4997                    "/worker/activity-tasks/poll",
4998                    RequestProtocol::DefaultWorker,
4999                )
5000                .await?;
5001            if let Some(lease) = &lease {
5002                lease
5003                    .authority
5004                    .refresh_delivery_session(&mut wire["task"])?;
5005            }
5006            Ok(serde_json::from_value(wire)?)
5007        };
5008        let mut data: worker_session::SessionPollResponse = match lease.as_ref() {
5009            Some(lease) => lease.authority.protect(loading).await?,
5010            None => {
5011                activity_hydration::HydrationClaim::protect(claim.as_ref(), self, loading).await?
5012            }
5013        };
5014        if let Some(task) = data.task.as_mut() {
5015            task.hydration_claim = claim;
5016            task.activity_lease = lease;
5017            self.worker_dispatch_metrics
5018                .ready_age("activity", task_queue, ready_age);
5019        }
5020        Ok(data)
5021    }
5022
5023    pub async fn complete_activity_task<T: Serialize>(
5024        &self,
5025        task_id: &str,
5026        activity_attempt_id: &str,
5027        lease_owner: &str,
5028        result: T,
5029        codec: &str,
5030    ) -> Result<Value> {
5031        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
5032        let body = json!({
5033            "activity_attempt_id": activity_attempt_id,
5034            "lease_owner": lease_owner,
5035            "result": result
5036        });
5037        let path = format!("/worker/activity-tasks/{task_id}/complete");
5038        activity_task_response(
5039            self.request_json(
5040                reqwest::Method::POST,
5041                &path,
5042                RequestProtocol::DefaultWorker,
5043                Some(&body),
5044            )
5045            .await,
5046            "complete",
5047            task_id,
5048            activity_attempt_id,
5049        )
5050    }
5051
5052    pub async fn fail_activity_task(
5053        &self,
5054        task_id: &str,
5055        activity_attempt_id: &str,
5056        lease_owner: &str,
5057        message: impl Into<String>,
5058        non_retryable: bool,
5059    ) -> Result<Value> {
5060        self.fail_activity_task_with_error(
5061            task_id,
5062            activity_attempt_id,
5063            lease_owner,
5064            &ActivityError::new("RustActivityFailure", message).non_retryable(non_retryable),
5065        )
5066        .await
5067    }
5068
5069    /// Report an activity's application-defined failure type and retry marker.
5070    pub async fn fail_activity_task_with_error(
5071        &self,
5072        task_id: &str,
5073        activity_attempt_id: &str,
5074        lease_owner: &str,
5075        error: &ActivityError,
5076    ) -> Result<Value> {
5077        let error = error.validated();
5078        self.fail_activity_task_with_failure(task_id,activity_attempt_id,lease_owner,json!({
5079            "message":error.message,"type":error.exception_type,"non_retryable":error.non_retryable
5080        })).await
5081    }
5082
5083    /// Report a structured activity failure using existing Server fields such as
5084    /// `message`, `type`, `stack_trace`, `non_retryable` and Avro `details`.
5085    /// The final encoded report is bounded without changing claim identity or
5086    /// retry flags. Invalid or unfit required data is a reporting error.
5087    pub async fn fail_activity_task_with_failure(
5088        &self,
5089        task_id: &str,
5090        activity_attempt_id: &str,
5091        lease_owner: &str,
5092        failure: Value,
5093    ) -> Result<Value> {
5094        let body = json!({
5095            "activity_attempt_id":activity_attempt_id,"lease_owner":lease_owner,"failure":failure
5096        });
5097        let path = format!("/worker/activity-tasks/{task_id}/fail");
5098        activity_task_response(
5099            self.request_json(
5100                reqwest::Method::POST,
5101                &path,
5102                RequestProtocol::DefaultWorker,
5103                Some(&body),
5104            )
5105            .await,
5106            "fail",
5107            task_id,
5108            activity_attempt_id,
5109        )
5110    }
5111
5112    /// Record a flat map of scalar/null activity progress metadata.
5113    ///
5114    /// Heartbeat details use the Server's bounded JSON progress contract.
5115    /// They are not workflow payload envelopes.
5116    pub async fn heartbeat_activity_task<T: Serialize>(
5117        &self,
5118        task_id: &str,
5119        activity_attempt_id: &str,
5120        lease_owner: &str,
5121        details: T,
5122    ) -> Result<ActivityHeartbeatResponse> {
5123        serde_json::from_value(
5124            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
5125                .await?,
5126        )
5127        .map_err(Error::from)
5128    }
5129
5130    async fn heartbeat_activity_task_value<T: Serialize>(
5131        &self,
5132        task_id: &str,
5133        activity_attempt_id: &str,
5134        lease_owner: &str,
5135        details: T,
5136    ) -> Result<Value> {
5137        let details = AvroValue::from_serialize(&details)?.into_json()?;
5138        let body = json!({
5139            "activity_attempt_id": activity_attempt_id,
5140            "lease_owner": lease_owner,
5141            "details": details
5142        });
5143        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
5144        let started = tokio::time::Instant::now();
5145        let response = activity_task_response(
5146            self.request_json(
5147                reqwest::Method::POST,
5148                &path,
5149                RequestProtocol::DefaultWorker,
5150                Some(&body),
5151            )
5152            .await,
5153            "heartbeat",
5154            task_id,
5155            activity_attempt_id,
5156        )?;
5157        if let Some(authority) = &self.activity_lease_authority {
5158            authority.progress(&response, started)?;
5159        }
5160        Ok(response)
5161    }
5162
5163    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
5164        &self,
5165        method: reqwest::Method,
5166        path: &str,
5167        protocol: RequestProtocol,
5168        body: Option<&B>,
5169    ) -> Result<T> {
5170        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
5171            .await
5172    }
5173
5174    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
5175        &self,
5176        method: reqwest::Method,
5177        path: &str,
5178        protocol: RequestProtocol,
5179        body: Option<&B>,
5180        timeout: Duration,
5181    ) -> Result<T> {
5182        self.metrics_request(method, path, protocol, body, timeout, true)
5183            .await
5184    }
5185
5186    fn worker_request_protocol(&self, protocol: RequestProtocol) -> Result<RequestProtocol> {
5187        Ok(match protocol {
5188            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
5189                let selected = self.worker_protocol_version.as_str();
5190                if self.cooperative_worker_protocol
5191                    && !cooperative_cancellation::supports_protocol(selected)
5192                {
5193                    return Err(Error::CooperativeCancellationUnavailable(
5194                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
5195                    ));
5196                }
5197                if let RequestProtocol::Worker(minimum) = protocol {
5198                    let supported = minimum
5199                        .strip_prefix("1.")
5200                        .and_then(|minor| minor.parse::<u64>().ok())
5201                        .zip(
5202                            selected
5203                                .strip_prefix("1.")
5204                                .and_then(|minor| minor.parse::<u64>().ok()),
5205                        )
5206                        .is_some_and(|(minimum, selected)| selected >= minimum);
5207                    if !supported {
5208                        return Err(Error::WorkerLoop(format!(
5209                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
5210                        )));
5211                    }
5212                }
5213                RequestProtocol::Worker(selected)
5214            }
5215            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
5216        })
5217    }
5218
5219    fn check_activity_lease_request(&self, path: &str, body: Option<&Value>) -> Result<()> {
5220        match &self.activity_lease_authority {
5221            Some(authority) => authority.check(path, body),
5222            None => Ok(()),
5223        }
5224    }
5225
5226    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
5227        &self,
5228        method: reqwest::Method,
5229        path: &str,
5230        protocol: RequestProtocol,
5231        body: Option<&B>,
5232        timeout: Duration,
5233    ) -> Result<T> {
5234        self.metrics_request(method, path, protocol, body, timeout, false)
5235            .await
5236    }
5237
5238    async fn send_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
5239        &self,
5240        method: reqwest::Method,
5241        path: &str,
5242        protocol: RequestProtocol,
5243        body: Option<&B>,
5244        timeout: Duration,
5245        observation: &metrics::ClientObservation,
5246    ) -> Result<T> {
5247        #[cfg(feature = "telemetry")]
5248        self.begin_observability_discovery(&method, path);
5249        let protocol = self.worker_request_protocol(protocol)?;
5250        let auth_token = self.auth_token(protocol)?;
5251        let mut request = self
5252            .http
5253            .request(method.clone(), format!("{}/api{}", self.base_url, path))
5254            .timeout(timeout)
5255            .header(reqwest::header::ACCEPT, "application/json")
5256            .header(reqwest::header::CONTENT_TYPE, "application/json")
5257            .header("X-Namespace", &self.namespace);
5258
5259        match protocol {
5260            RequestProtocol::DefaultWorker => {
5261                request = request.header(
5262                    "X-Durable-Workflow-Protocol-Version",
5263                    self.worker_protocol_version.as_str(),
5264                );
5265            }
5266            RequestProtocol::Worker(version) => {
5267                request = request.header("X-Durable-Workflow-Protocol-Version", version);
5268            }
5269            RequestProtocol::ControlPlane => {
5270                request = request.header(
5271                    "X-Durable-Workflow-Control-Plane-Version",
5272                    CONTROL_PLANE_VERSION,
5273                );
5274            }
5275        }
5276
5277        if let Some(token) = auth_token {
5278            request = request.bearer_auth(token);
5279        }
5280
5281        if let Some(body) = body {
5282            let mut body = serde_json::to_value(body)?;
5283            self.check_activity_lease_request(path, Some(&body))?;
5284            let mut report = failure_reporting::Prepared::new(
5285                &mut body,
5286                path,
5287                failure_reporting::REQUEST_BYTES,
5288            )?;
5289            if let Some(report) = report.as_mut().filter(|report| report.can_reduce()) {
5290                let limit = self
5291                    .discover_failure_request_limit(&body, path, protocol)
5292                    .await?;
5293                report.encode(&mut body, limit)?;
5294            }
5295            if matches!(
5296                method,
5297                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
5298            ) {
5299                self.check_activity_lease_request(path, Some(&body))?;
5300                self.externalize_runtime_payloads(&mut body, path, protocol)
5301                    .await?;
5302                self.check_activity_lease_request(path, Some(&body))?;
5303            }
5304            if let Some(mut report) = report {
5305                let limit = self.known_failure_request_limit(protocol)?;
5306                request = request.body(report.encode(&mut body, limit)?);
5307            } else {
5308                request = request.json(&body);
5309            }
5310        }
5311
5312        let request = request.build()?;
5313        let request_body = request
5314            .body()
5315            .and_then(reqwest::Body::as_bytes)
5316            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
5317        let poll_request_id = path.ends_with("/poll").then(|| {
5318            request_body
5319                .as_ref()
5320                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
5321                .unwrap_or_default()
5322        });
5323        let request_bytes = request
5324            .body()
5325            .and_then(reqwest::Body::as_bytes)
5326            .map_or(0, |body| body.len() as u64);
5327        let mut storage_retries = 0_usize;
5328        let mut deferred_workflow_completion = false;
5329
5330        loop {
5331            // Keep the serialized body and lease/poll identity across admission pauses.
5332            self.check_activity_lease_request(path, request_body.as_ref())?;
5333            let receive = async {
5334                let response = self
5335                    .http
5336                    .execute(request.try_clone().ok_or_else(|| {
5337                        Error::WorkerLoop("worker request body cannot be retried".to_string())
5338                    })?)
5339                    .await?;
5340                let status = response.status();
5341                observation.status(status);
5342                Ok::<_, Error>((status, response.bytes().await?))
5343            };
5344            let retry_deadline = self
5345                .worker_storage_admission
5346                .as_ref()
5347                .and_then(|admission| admission.workflow_completion_retry_deadline);
5348            if deferred_workflow_completion
5349                && retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
5350            {
5351                return Err(Error::Timeout);
5352            }
5353            let received = async {
5354                match retry_deadline.filter(|_| deferred_workflow_completion) {
5355                    Some(deadline) => tokio::time::timeout_at(deadline, receive)
5356                        .await
5357                        .map_err(|_| Error::Timeout)?,
5358                    None => receive.await,
5359                }
5360            };
5361            let (status, bytes) = match self
5362                .activity_lease_authority
5363                .as_ref()
5364                .filter(|authority| authority.governs(path))
5365            {
5366                Some(authority) => authority.protect(received).await?,
5367                None => received.await?,
5368            };
5369
5370            if !status.is_success() {
5371                let body = String::from_utf8_lossy(&bytes).to_string();
5372                if let Some(protocol) = protocol_failure(status, &body) {
5373                    return Err(Error::Protocol(protocol));
5374                }
5375                // A typed oversized completion is deterministic: never resend it.
5376                if let Some(refusal) =
5377                    workflow_task_completion_too_large(status, &body, request_bytes)
5378                {
5379                    return Err(Error::WorkflowTaskCompletionTooLarge(refusal));
5380                }
5381                let error = Error::Http { status, body };
5382                deferred_workflow_completion |= worker_deferred_workflow_completion_retry_after(
5383                    &error,
5384                    path,
5385                    request_body.as_ref(),
5386                )
5387                .is_some();
5388                if self
5389                    .wait_for_storage_admission(
5390                        &error,
5391                        protocol,
5392                        Some(path),
5393                        poll_request_id.as_deref(),
5394                        request_body.as_ref(),
5395                        &mut storage_retries,
5396                    )
5397                    .await
5398                {
5399                    continue;
5400                }
5401                return Err(error);
5402            }
5403
5404            if bytes.is_empty() {
5405                return Ok(serde_json::from_value(Value::Null)?);
5406            }
5407
5408            #[cfg(feature = "telemetry")]
5409            return self.decode_observability_response(
5410                &method,
5411                path,
5412                request_body.as_ref(),
5413                &bytes,
5414            );
5415
5416            #[cfg(not(feature = "telemetry"))]
5417            return Ok(serde_json::from_slice(&bytes)?);
5418        }
5419    }
5420
5421    #[cfg(feature = "telemetry")]
5422    fn begin_observability_discovery(&self, method: &reqwest::Method, path: &str) {
5423        if *method == reqwest::Method::GET && path == "/cluster/info" {
5424            self.observability_context_supported
5425                .store(false, Ordering::SeqCst);
5426        }
5427    }
5428
5429    #[cfg(feature = "telemetry")]
5430    fn decode_observability_response<T: DeserializeOwned>(
5431        &self,
5432        method: &reqwest::Method,
5433        path: &str,
5434        request_body: Option<&Value>,
5435        bytes: &[u8],
5436    ) -> Result<T> {
5437        if *method == reqwest::Method::POST
5438            && self.execution_telemetry.is_some()
5439            && matches!(
5440                path,
5441                "/worker/workflow-tasks/poll"
5442                    | "/worker/activity-tasks/poll"
5443                    | "/worker/query-tasks/poll"
5444            )
5445        {
5446            let mut wire: Value = serde_json::from_slice(bytes)?;
5447            telemetry::carrier::retain_poll_observations(
5448                &mut wire,
5449                request_body.unwrap_or(&Value::Null),
5450                path,
5451                &self.namespace,
5452            );
5453            return Ok(serde_json::from_value(wire)?);
5454        }
5455        if *method == reqwest::Method::GET && path == "/cluster/info" {
5456            let info: Value = serde_json::from_slice(bytes)?;
5457            self.observability_context_supported
5458                .store(telemetry::carrier::supported(&info), Ordering::SeqCst);
5459            return Ok(serde_json::from_value(info)?);
5460        }
5461        Ok(serde_json::from_slice(bytes)?)
5462    }
5463
5464    async fn wait_for_storage_admission(
5465        &self,
5466        error: &Error,
5467        protocol: RequestProtocol,
5468        path: Option<&str>,
5469        poll_request_id: Option<&str>,
5470        request_body: Option<&Value>,
5471        retries: &mut usize,
5472    ) -> bool {
5473        let Some(admission) = self
5474            .worker_storage_admission
5475            .as_ref()
5476            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
5477        else {
5478            return false;
5479        };
5480        let completion_deferred = path.and_then(|path| {
5481            worker_deferred_workflow_completion_retry_after(error, path, request_body)
5482        });
5483        let Some(advertised_delay) = completion_deferred
5484            .or_else(|| worker_storage_admission_retry_after(error, poll_request_id))
5485            .or_else(|| {
5486                path.and_then(|path| {
5487                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
5488                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
5489                })
5490            })
5491        else {
5492            return false;
5493        };
5494        *retries = retries.saturating_add(1);
5495        let delay = worker_retry_delay(admission.policy, *retries)
5496            .max(advertised_delay)
5497            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
5498        let delay = if completion_deferred.is_some() {
5499            delay.max(advertised_delay)
5500        } else {
5501            delay
5502        };
5503        let wait_deadline = tokio::time::Instant::now() + delay;
5504        loop {
5505            if admission.stop.load(Ordering::SeqCst) {
5506                return false;
5507            }
5508            let now = tokio::time::Instant::now();
5509            if admission
5510                .workflow_completion_retry_deadline
5511                .is_some_and(|deadline| now >= deadline)
5512            {
5513                return false;
5514            }
5515            let remaining = wait_deadline.saturating_duration_since(now);
5516            if remaining.is_zero() {
5517                return true;
5518            }
5519            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
5520        }
5521    }
5522
5523    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
5524        &self,
5525        path: &str,
5526        protocol: RequestProtocol,
5527        body: &B,
5528        timeout: Duration,
5529        max_retries: usize,
5530    ) -> Result<T> {
5531        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
5532            .await
5533    }
5534
5535    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
5536        &self,
5537        path: &str,
5538        protocol: RequestProtocol,
5539        body: &B,
5540        timeout: Duration,
5541        max_retries: usize,
5542    ) -> Result<T> {
5543        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
5544            .await
5545    }
5546
5547    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
5548        &self,
5549        path: &str,
5550        protocol: RequestProtocol,
5551        body: &B,
5552        timeout: Duration,
5553        max_retries: usize,
5554        resolve: bool,
5555    ) -> Result<T> {
5556        self.metrics_poll_request(path, protocol, body, timeout, max_retries, resolve)
5557            .await
5558    }
5559
5560    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
5561        match protocol {
5562            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
5563                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
5564                    return Ok(Some(token));
5565                }
5566                if self.control_token.is_some() {
5567                    return Err(Error::MissingRoleCredentials {
5568                        role: "worker",
5569                        opposite_role: "control",
5570                    });
5571                }
5572                Ok(None)
5573            }
5574            RequestProtocol::ControlPlane => {
5575                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
5576                    return Ok(Some(token));
5577                }
5578                if self.worker_token.is_some() {
5579                    return Err(Error::MissingRoleCredentials {
5580                        role: "control",
5581                        opposite_role: "worker",
5582                    });
5583                }
5584                Ok(None)
5585            }
5586        }
5587    }
5588}
5589
5590fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
5591    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
5592    let reason = body
5593        .get("reason")
5594        .and_then(Value::as_str)
5595        .unwrap_or("query_rejected")
5596        .to_string();
5597    let message = body
5598        .get("message")
5599        .or_else(|| body.get("error"))
5600        .and_then(Value::as_str)
5601        .unwrap_or("workflow query was rejected")
5602        .to_string();
5603
5604    QueryFailure {
5605        status: status.as_u16(),
5606        reason,
5607        message,
5608        body,
5609    }
5610}
5611
5612fn workflow_command_result(
5613    command: WorkflowCommandKind,
5614    data: Value,
5615    workflow_id: &str,
5616    run_id: Option<&str>,
5617) -> WorkflowCommandResult {
5618    WorkflowCommandResult {
5619        command,
5620        workflow_id: data
5621            .get("workflow_id")
5622            .and_then(Value::as_str)
5623            .unwrap_or(workflow_id)
5624            .to_string(),
5625        run_id: data
5626            .get("run_id")
5627            .and_then(Value::as_str)
5628            .or(run_id)
5629            .map(str::to_string),
5630        outcome: data
5631            .get("outcome")
5632            .and_then(Value::as_str)
5633            .map(str::to_string),
5634        reason: data
5635            .get("reason")
5636            .and_then(Value::as_str)
5637            .map(str::to_string),
5638        command_status: data
5639            .get("command_status")
5640            .and_then(Value::as_str)
5641            .map(str::to_string),
5642        raw: data,
5643    }
5644}
5645
5646fn workflow_command_rejection(
5647    command: WorkflowCommandKind,
5648    status: reqwest::StatusCode,
5649    raw_body: String,
5650    workflow_id: &str,
5651    run_id: Option<&str>,
5652) -> WorkflowCommandRejection {
5653    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
5654    WorkflowCommandRejection {
5655        command,
5656        status: status.as_u16(),
5657        reason: body
5658            .get("reason")
5659            .and_then(Value::as_str)
5660            .unwrap_or("workflow_command_rejected")
5661            .to_string(),
5662        message: body
5663            .get("message")
5664            .or_else(|| body.get("error"))
5665            .and_then(Value::as_str)
5666            .unwrap_or("workflow lifecycle command was rejected")
5667            .to_string(),
5668        workflow_id: body
5669            .get("workflow_id")
5670            .and_then(Value::as_str)
5671            .unwrap_or(workflow_id)
5672            .to_string(),
5673        run_id: body
5674            .get("run_id")
5675            .and_then(Value::as_str)
5676            .or(run_id)
5677            .map(str::to_string),
5678        target_scope: body
5679            .get("target_scope")
5680            .and_then(Value::as_str)
5681            .map(str::to_string),
5682        body,
5683    }
5684}
5685
5686fn query_task_response(response: Result<Value>) -> Result<Value> {
5687    match response {
5688        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
5689        response => response,
5690    }
5691}
5692
5693fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
5694    match response {
5695        Err(Error::Http { status, body })
5696            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
5697        {
5698            Ok(serde_json::from_str(&body)?)
5699        }
5700        response => response,
5701    }
5702}
5703
5704fn worker_poll_body_is_stop(body: &str) -> bool {
5705    serde_json::from_str::<Value>(body)
5706        .ok()
5707        .is_some_and(|body| {
5708            worker_poll_is_stop(
5709                body.get("poll_status").and_then(Value::as_str),
5710                body.get("reason").and_then(Value::as_str),
5711            )
5712        })
5713}
5714
5715fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
5716    matches!(poll_status, Some("draining" | "stopped"))
5717        || matches!(reason, Some("worker_draining" | "worker_stopped"))
5718}
5719
5720fn query_task_rejection_is_final(error: &Error) -> bool {
5721    matches!(
5722        error,
5723        Error::QueryFailed(failure)
5724            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
5725    )
5726}
5727
5728fn activity_task_response<T>(
5729    response: Result<T>,
5730    operation: &str,
5731    task_id: &str,
5732    activity_attempt_id: &str,
5733) -> Result<T> {
5734    match response {
5735        Err(Error::Http { status, body }) => {
5736            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
5737            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
5738                operation: operation.to_string(),
5739                status: status.as_u16(),
5740                reason: body
5741                    .get("reason")
5742                    .and_then(Value::as_str)
5743                    .unwrap_or("activity_task_rejected")
5744                    .to_string(),
5745                task_id: body
5746                    .get("task_id")
5747                    .and_then(Value::as_str)
5748                    .unwrap_or(task_id)
5749                    .to_string(),
5750                activity_attempt_id: body
5751                    .get("activity_attempt_id")
5752                    .and_then(Value::as_str)
5753                    .unwrap_or(activity_attempt_id)
5754                    .to_string(),
5755                cancel_requested: body
5756                    .get("cancel_requested")
5757                    .and_then(Value::as_bool)
5758                    .unwrap_or(false),
5759                can_continue: body.get("can_continue").and_then(Value::as_bool),
5760                run_closed_reason: body
5761                    .get("run_closed_reason")
5762                    .and_then(Value::as_str)
5763                    .map(str::to_string),
5764                body,
5765            }))
5766        }
5767        response => response,
5768    }
5769}
5770
5771fn activity_task_rejection_is_final(error: &Error) -> bool {
5772    matches!(
5773        error,
5774        Error::ActivityTaskRejected(rejection)
5775            if matches!(
5776                rejection.reason.as_str(),
5777                "run_cancelled"
5778                    | "run_terminated"
5779                    | "attempt_closed"
5780                    | "stale_attempt"
5781                    | "activity_cancelled"
5782                    | "task_cancelled"
5783                    | "run_closed"
5784                    | "activity_not_running"
5785                    | "attempt_not_found"
5786            )
5787    )
5788}
5789
5790/// A workflow-task report the server answered with a non-recorded receipt
5791/// for exactly this task, attempt and run, which settles the managed tick:
5792/// the run's terminal timeout (`run_timed_out` with `run_status=failed`), a
5793/// task this worker no longer holds (`task_not_leased`, for example after the
5794/// run was cancelled or the task was reclaimed), or a run already closed by
5795/// another path (`run_closed` with the terminal state it implies). Nothing was
5796/// recorded, and the server owns any redelivery.
5797fn workflow_task_report_is_settled(
5798    error: &Error,
5799    task_id: &str,
5800    workflow_task_attempt: u64,
5801    run_id: Option<&str>,
5802) -> bool {
5803    let Error::Http { status, body } = error else {
5804        return false;
5805    };
5806    if *status != reqwest::StatusCode::CONFLICT {
5807        return false;
5808    }
5809
5810    let Some(run_id) = run_id else {
5811        return false;
5812    };
5813    let Ok(body) = serde_json::from_str::<Value>(body) else {
5814        return false;
5815    };
5816
5817    let settled = match body.get("reason").and_then(Value::as_str) {
5818        Some("run_timed_out") => body.get("run_status").and_then(Value::as_str) == Some("failed"),
5819        Some("task_not_leased") => true,
5820        Some("run_closed") => run_closed_receipt_is_terminal(&body),
5821        _ => false,
5822    };
5823    settled
5824        && body.get("recorded").and_then(Value::as_bool) == Some(false)
5825        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
5826        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
5827        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
5828}
5829
5830/// A `run_closed` refusal settles only with the closed run's own state: a
5831/// terminal `run_status`, the `stop_reason` that status implies, and
5832/// `can_continue=false`. Absent or inconsistent state is never inferred.
5833fn run_closed_receipt_is_terminal(body: &Value) -> bool {
5834    let stop_reason = match body.get("run_status").and_then(Value::as_str) {
5835        Some("completed") => "run_completed",
5836        Some("failed") => "run_failed",
5837        Some("cancelled") => "run_cancelled",
5838        Some("terminated") => "run_terminated",
5839        _ => return false,
5840    };
5841    body.get("stop_reason").and_then(Value::as_str) == Some(stop_reason)
5842        && body.get("can_continue").and_then(Value::as_bool) == Some(false)
5843}
5844
5845fn workflow_task_completion_too_large(
5846    status: reqwest::StatusCode,
5847    raw_body: &str,
5848    size: u64,
5849) -> Option<WorkflowTaskCompletionTooLarge> {
5850    if status != reqwest::StatusCode::PAYLOAD_TOO_LARGE {
5851        return None;
5852    }
5853    let body: Value = serde_json::from_str(raw_body).ok()?;
5854    if body.get("reason").and_then(Value::as_str) != Some("payload_too_large")
5855        || body.get("limit_kind").and_then(Value::as_str)
5856            != Some(WORKFLOW_TASK_COMPLETION_BYTES_LIMIT_KIND)
5857    {
5858        return None;
5859    }
5860    Some(WorkflowTaskCompletionTooLarge {
5861        status: status.as_u16(),
5862        limit_kind: WORKFLOW_TASK_COMPLETION_BYTES_LIMIT_KIND.to_string(),
5863        limit: body.get("limit").and_then(Value::as_u64),
5864        size,
5865        message: body
5866            .get("message")
5867            .and_then(Value::as_str)
5868            .unwrap_or_default()
5869            .to_string(),
5870        body,
5871    })
5872}
5873
5874fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
5875    let body: Value = serde_json::from_str(raw_body).ok()?;
5876    let reason = body.get("reason")?.as_str()?;
5877    if !matches!(
5878        reason,
5879        "missing_protocol_version"
5880            | "unsupported_protocol_version"
5881            | "missing_control_plane_version"
5882            | "unsupported_control_plane_version"
5883    ) {
5884        return None;
5885    }
5886
5887    Some(ProtocolFailure {
5888        status: status.as_u16(),
5889        reason: reason.to_string(),
5890        message: body
5891            .get("message")
5892            .or_else(|| body.get("error"))
5893            .and_then(Value::as_str)
5894            .unwrap_or("protocol version rejected")
5895            .to_string(),
5896        supported_version: body
5897            .get("supported_version")
5898            .and_then(Value::as_str)
5899            .map(str::to_string),
5900        requested_version: body
5901            .get("requested_version")
5902            .and_then(Value::as_str)
5903            .map(str::to_string),
5904        body,
5905    })
5906}
5907
5908fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
5909    timeout
5910        .as_secs()
5911        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
5912        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
5913}
5914
5915fn worker_operation_is_retryable(error: &Error) -> bool {
5916    if worker_poll_capacity_retry_after(error).is_some()
5917        || worker_storage_admission_body(error).is_some()
5918        || worker_backend_unavailable_body(error).is_some()
5919        || worker_operation_is_explicitly_non_retryable(error)
5920    {
5921        return false;
5922    }
5923
5924    match error {
5925        Error::Transport(error) => {
5926            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
5927        }
5928        Error::Http { status, .. } => {
5929            matches!(
5930                *status,
5931                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
5932            ) || status.is_server_error()
5933        }
5934        _ => false,
5935    }
5936}
5937
5938fn worker_storage_admission_body(error: &Error) -> Option<Value> {
5939    let body: Value = match error {
5940        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
5941        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
5942        _ => return None,
5943    };
5944    matches!(
5945        body.get("reason").and_then(Value::as_str),
5946        Some("storage_pressure" | "storage_admission_unavailable")
5947    )
5948    .then_some(body)
5949}
5950
5951fn worker_storage_admission_retry_after(
5952    error: &Error,
5953    poll_request_id: Option<&str>,
5954) -> Option<Duration> {
5955    let Error::Http { status, .. } = error else {
5956        return None;
5957    };
5958    let body = worker_storage_admission_body(error)?;
5959    let delay = body.get("retry_after_seconds")?.as_u64()?;
5960    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
5961        || delay == 0
5962        || body.get("retryable") != Some(&Value::Bool(true))
5963        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
5964        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
5965        || body
5966            .get("request_admitted")
5967            .is_some_and(|admitted| admitted != &Value::Bool(false))
5968    {
5969        return None;
5970    }
5971    match poll_request_id {
5972        Some(id) => {
5973            if id.is_empty()
5974                || body.get("task") != Some(&Value::Null)
5975                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
5976                || body.get("poll_status") != body.get("reason")
5977                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
5978                || body.get("claim_admitted") != Some(&Value::Bool(false))
5979            {
5980                return None;
5981            }
5982        }
5983        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
5984        None => {}
5985    }
5986    Some(Duration::from_secs(delay))
5987}
5988
5989fn worker_backend_unavailable_retry_after(
5990    error: &Error,
5991    path: &str,
5992    poll_request_id: Option<&str>,
5993) -> Option<Duration> {
5994    let operation = match path {
5995        "/worker/register" => "register_worker",
5996        "/worker/heartbeat" => "heartbeat_worker",
5997        "/worker/workflow-tasks/poll" => "poll_workflow_task",
5998        "/worker/activity-tasks/poll" => "poll_activity_task",
5999        "/worker/query-tasks/poll" => "poll_query_task",
6000        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
6001        _ => return None,
6002    };
6003    let body = worker_backend_unavailable_body(error)?;
6004    let delay = body.get("retry_after_seconds")?.as_u64()?;
6005    if delay == 0
6006        || body.get("operation")?.as_str()? != operation
6007        || body.get("outcome")?.as_str()? != "unknown"
6008        || body.get("retryable") != Some(&Value::Bool(true))
6009        || body.get("worker_id")?.as_str()?.is_empty()
6010    {
6011        return None;
6012    }
6013    if let Some(id) = poll_request_id {
6014        if id.is_empty()
6015            || body.get("task") != Some(&Value::Null)
6016            || body.get("poll_status")?.as_str()? != "backend_unavailable"
6017            || body.get("poll_request_id")?.as_str()? != id
6018            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
6019        {
6020            return None;
6021        }
6022    } else if path.ends_with("/poll") {
6023        return None;
6024    }
6025    Some(Duration::from_secs(delay))
6026}
6027
6028fn worker_fenced_completion_retry_after(
6029    error: &Error,
6030    path: &str,
6031    request_body: Option<&Value>,
6032) -> Option<Duration> {
6033    let (operation, task_id, attempt_field) = if let Some(task_id) = path
6034        .strip_prefix("/worker/workflow-tasks/")
6035        .and_then(|tail| tail.strip_suffix("/complete"))
6036    {
6037        ("complete_workflow_task", task_id, "workflow_task_attempt")
6038    } else if let Some(task_id) = path
6039        .strip_prefix("/worker/activity-tasks/")
6040        .and_then(|tail| tail.strip_suffix("/complete"))
6041    {
6042        ("complete_activity_task", task_id, "activity_attempt_id")
6043    } else {
6044        return None;
6045    };
6046    if task_id.is_empty() || task_id.contains('/') {
6047        return None;
6048    }
6049
6050    let request = request_body?.as_object()?;
6051    let lease_owner = request.get("lease_owner")?.as_str()?;
6052    if lease_owner.is_empty() {
6053        return None;
6054    }
6055    let attempt = request.get(attempt_field)?;
6056    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
6057        || (attempt_field == "activity_attempt_id"
6058            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
6059    {
6060        return None;
6061    }
6062
6063    let body = worker_backend_unavailable_body(error)?;
6064    let delay = body.get("retry_after_seconds")?.as_u64()?;
6065    if delay == 0
6066        || body.get("operation")?.as_str()? != operation
6067        || body.get("outcome")?.as_str()? != "unknown"
6068        || body.get("retryable") != Some(&Value::Bool(true))
6069        || body.get("worker_id")?.as_str()? != lease_owner
6070        || body.get("task_queue") != Some(&Value::Null)
6071        || body.get("task_id")?.as_str()? != task_id
6072        || body.get("lease_owner")?.as_str()? != lease_owner
6073        || body.get(attempt_field) != Some(attempt)
6074    {
6075        return None;
6076    }
6077
6078    Some(Duration::from_secs(delay))
6079}
6080
6081fn worker_deferred_workflow_completion_retry_after(
6082    error: &Error,
6083    path: &str,
6084    request_body: Option<&Value>,
6085) -> Option<Duration> {
6086    let task_id = path
6087        .strip_prefix("/worker/workflow-tasks/")?
6088        .strip_suffix("/complete")?;
6089    if task_id.is_empty() || task_id.contains('/') {
6090        return None;
6091    }
6092    let request = request_body?.as_object()?;
6093    let owner = request.get("lease_owner")?.as_str()?;
6094    let attempt = request.get("workflow_task_attempt")?;
6095    if owner.trim().is_empty() || attempt.as_u64().filter(|attempt| *attempt > 0).is_none() {
6096        return None;
6097    }
6098    let Error::Http { status, body } = error else {
6099        return None;
6100    };
6101    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
6102        return None;
6103    }
6104    let body: Value = serde_json::from_str(body).ok()?;
6105    let delay = body.get("retry_after_seconds")?.as_u64()?;
6106    if !(1..=5).contains(&delay)
6107        || body.get("reason")?.as_str()? != "backend_lock_pressure"
6108        || body.get("operation")?.as_str()? != "complete_workflow_task"
6109        || body.get("outcome")?.as_str()? != "deferred"
6110        || body.get("recorded") != Some(&Value::Bool(false))
6111        || body.get("retryable") != Some(&Value::Bool(true))
6112        || body.get("task_id")?.as_str()? != task_id
6113        || body.get("lease_owner")?.as_str()? != owner
6114        || body.get("workflow_task_attempt") != Some(attempt)
6115        || body.get("backend")?.get("lock_pressure") != Some(&Value::Bool(true))
6116    {
6117        return None;
6118    }
6119    Some(Duration::from_secs(delay))
6120}
6121
6122fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
6123    let Error::Http { status, body } = error else {
6124        return None;
6125    };
6126    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
6127        return None;
6128    }
6129    let body: Value = serde_json::from_str(body).ok()?;
6130    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
6131}
6132
6133fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
6134    let Error::Http { body, .. } = error else {
6135        return false;
6136    };
6137
6138    serde_json::from_str::<Value>(body)
6139        .ok()
6140        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
6141        == Some(false)
6142}
6143
6144fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
6145    let Error::Http { status, body } = error else {
6146        return None;
6147    };
6148    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
6149        return None;
6150    }
6151
6152    let body = serde_json::from_str::<Value>(body).ok()?;
6153    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
6154        == Some("long_poll_capacity_exhausted")
6155        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
6156    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
6157        return None;
6158    }
6159
6160    Some(Duration::from_secs(
6161        body.get("retry_after_seconds")
6162            .and_then(Value::as_u64)
6163            .unwrap_or_default(),
6164    ))
6165}
6166
6167fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
6168    let exponent = retry.saturating_sub(1).min(31) as u32;
6169    policy
6170        .initial_backoff
6171        .saturating_mul(1_u32 << exponent)
6172        .min(policy.max_backoff)
6173}
6174
6175#[derive(Debug)]
6176pub struct ClientBuilder {
6177    metrics: metrics::Metrics,
6178    base_url: String,
6179    token: Option<String>,
6180    control_token: Option<String>,
6181    worker_token: Option<String>,
6182    namespace: String,
6183    timeout: Duration,
6184    max_external_payload_bytes: usize,
6185    worker_protocol_version: WorkerProtocolVersion,
6186    additional_root_certificates: Vec<reqwest::Certificate>,
6187    danger_accept_invalid_certs: bool,
6188}
6189
6190fn validate_static_credential(option: &'static str, value: Option<&str>) -> Result<()> {
6191    let Some(value) = value else {
6192        return Ok(());
6193    };
6194    // The cross-SDK policy fixes Unicode White_Space at the edges and Cc
6195    // anywhere. Do not normalize, trim, or broaden the accepted token alphabet.
6196    let edge_whitespace = |character| {
6197        matches!(
6198            character,
6199            '\u{0009}'..='\u{000d}'
6200                | '\u{0020}'
6201                | '\u{0085}'
6202                | '\u{00a0}'
6203                | '\u{1680}'
6204                | '\u{2000}'..='\u{200a}'
6205                | '\u{2028}'
6206                | '\u{2029}'
6207                | '\u{202f}'
6208                | '\u{205f}'
6209                | '\u{3000}'
6210        )
6211    };
6212    if value.chars().next().is_some_and(edge_whitespace)
6213        || value.chars().next_back().is_some_and(edge_whitespace)
6214        || value
6215            .chars()
6216            .any(|character| matches!(character, '\u{0000}'..='\u{001f}' | '\u{007f}'..='\u{009f}'))
6217    {
6218        return Err(Error::InvalidStaticCredential { option });
6219    }
6220    Ok(())
6221}
6222
6223impl ClientBuilder {
6224    /// Configure stable request metrics. Newly constructed workers inherit this recorder.
6225    pub fn metrics_recorder(mut self, recorder: Arc<dyn metrics::MetricsRecorder>) -> Self {
6226        self.metrics = metrics::Metrics::new(recorder);
6227        self
6228    }
6229    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
6230    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
6231        self.worker_protocol_version = version;
6232        self
6233    }
6234
6235    /// Set the shared static token. Build validates every supplied token without
6236    /// trimming it. `None` is absent; `Some("")` remains a supplied empty token.
6237    pub fn token(mut self, token: Option<String>) -> Self {
6238        self.token = token;
6239        self
6240    }
6241
6242    /// Set the control-plane token, which takes precedence over the shared token
6243    /// even when empty. Build also validates tokens for unused roles.
6244    pub fn control_token(mut self, token: Option<String>) -> Self {
6245        self.control_token = token;
6246        self
6247    }
6248
6249    /// Set the worker-plane token, which takes precedence over the shared token
6250    /// even when empty. Build also validates tokens for unused roles.
6251    pub fn worker_token(mut self, token: Option<String>) -> Self {
6252        self.worker_token = token;
6253        self
6254    }
6255
6256    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
6257        self.namespace = namespace.into();
6258        self
6259    }
6260
6261    pub fn timeout(mut self, timeout: Duration) -> Self {
6262        self.timeout = timeout;
6263        self
6264    }
6265
6266    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
6267    /// References are fetched only from this client's authenticated runtime.
6268    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
6269        self.max_external_payload_bytes = bytes;
6270        self
6271    }
6272
6273    pub fn build(self) -> Result<Client> {
6274        validate_static_credential("token", self.token.as_deref())?;
6275        validate_static_credential("control_token", self.control_token.as_deref())?;
6276        validate_static_credential("worker_token", self.worker_token.as_deref())?;
6277        let base_url = self.base_url.trim_end_matches('/').to_string();
6278        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
6279            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
6280            .unwrap_or_else(|_| base_url.ends_with("/api"));
6281
6282        if has_sdk_api_suffix {
6283            return Err(Error::InvalidBaseUrl);
6284        }
6285
6286        let mut http = reqwest::Client::builder()
6287            .timeout(self.timeout)
6288            .redirect(reqwest::redirect::Policy::none());
6289        for certificate in self.additional_root_certificates {
6290            http = http.add_root_certificate(certificate);
6291        }
6292        if self.danger_accept_invalid_certs {
6293            tracing::warn!(
6294                target: "durable_workflow::tls",
6295                endpoint = %tls_warning_endpoint(&base_url),
6296                "TLS certificate and hostname verification is disabled for this client"
6297            );
6298            http = http.danger_accept_invalid_certs(true);
6299        }
6300        Ok(Client {
6301            metrics: self.metrics,
6302            worker_dispatch_metrics: metrics::Metrics::default(),
6303            http: http.build()?,
6304            hydration_timeout: self.timeout,
6305            base_url,
6306            token: self.token,
6307            control_token: self.control_token,
6308            worker_token: self.worker_token,
6309            namespace: self.namespace,
6310            max_external_payload_bytes: self.max_external_payload_bytes,
6311            worker_storage_admission: None,
6312            worker_task_slot: None,
6313            cooperative_worker_protocol: false,
6314            worker_protocol_version: self.worker_protocol_version,
6315            local_activities_enabled: false,
6316            worker_sessions_enabled: false,
6317            max_concurrent_worker_sessions: 10,
6318            worker_build_id: None,
6319            sticky_cache: None,
6320            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
6321            failure_request_limit: Arc::new(AtomicUsize::new(failure_reporting::REQUEST_BYTES)),
6322            activity_lease_renewal_supported: Arc::new(AtomicBool::new(false)),
6323            sticky_history_suffix_supported: Arc::new(AtomicBool::new(false)),
6324            update_outcome_reads_supported: Arc::new(AtomicBool::new(false)),
6325            activity_lease_discovery: Arc::new(activity_lease::Discovery::default()),
6326            activity_lease_authority: None,
6327            #[cfg(feature = "telemetry")]
6328            execution_telemetry: None,
6329            #[cfg(feature = "telemetry")]
6330            observability_context_supported: Arc::new(AtomicBool::new(false)),
6331        })
6332    }
6333}
6334
6335#[derive(Clone, Debug)]
6336pub struct WorkflowHandle {
6337    client: Client,
6338    pub workflow_id: String,
6339    pub run_id: Option<String>,
6340    pub workflow_type: String,
6341}
6342
6343impl WorkflowHandle {
6344    /// Describe whichever run is current for this stable workflow instance.
6345    pub async fn describe(&self) -> Result<WorkflowDescription> {
6346        self.client.describe_workflow(&self.workflow_id).await
6347    }
6348
6349    /// Describe the run identity originally selected by this handle.
6350    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
6351        let run_id = self.run_id.as_deref().ok_or_else(|| {
6352            Error::Codec("run_id is required for selected-run description".to_string())
6353        })?;
6354        self.client
6355            .describe_workflow_run(&self.workflow_id, run_id)
6356            .await
6357    }
6358
6359    /// Signal this workflow with an SDK-generated caller command key.
6360    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
6361        self.client
6362            .signal_workflow(&self.workflow_id, signal_name, input)
6363            .await
6364    }
6365
6366    /// Signal this workflow with an explicit caller command key (1 to 255 Unicode characters).
6367    pub async fn signal_with_request_id<T: Serialize>(
6368        &self,
6369        signal_name: &str,
6370        input: T,
6371        request_id: &str,
6372    ) -> Result<Value> {
6373        self.client
6374            .signal_workflow_with_request_id(&self.workflow_id, signal_name, input, request_id)
6375            .await
6376    }
6377
6378    pub async fn append_message<T: Serialize>(
6379        &self,
6380        stream_name: &str,
6381        message_id: &str,
6382        input: T,
6383    ) -> Result<Value> {
6384        self.client
6385            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
6386            .await
6387    }
6388
6389    /// Signal only if this handle's selected run is still current, with an
6390    /// SDK-generated caller command key.
6391    pub async fn signal_selected_run<T: Serialize>(
6392        &self,
6393        signal_name: &str,
6394        input: T,
6395    ) -> Result<Value> {
6396        let run_id = self.run_id.as_deref().ok_or_else(|| {
6397            Error::Codec("run_id is required for selected-run signaling".to_string())
6398        })?;
6399        self.client
6400            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
6401            .await
6402    }
6403
6404    /// Signal only if this handle's selected run is still current, with an
6405    /// explicit caller command key (1 to 255 Unicode characters).
6406    pub async fn signal_selected_run_with_request_id<T: Serialize>(
6407        &self,
6408        signal_name: &str,
6409        input: T,
6410        request_id: &str,
6411    ) -> Result<Value> {
6412        let run_id = self.run_id.as_deref().ok_or_else(|| {
6413            Error::Codec("run_id is required for selected-run signaling".to_string())
6414        })?;
6415        self.client
6416            .signal_workflow_run_with_request_id(
6417                &self.workflow_id,
6418                run_id,
6419                signal_name,
6420                input,
6421                request_id,
6422            )
6423            .await
6424    }
6425
6426    /// Close whichever run is current as cancelled, without workflow cleanup.
6427    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
6428        self.client
6429            .cancel_workflow(&self.workflow_id, options)
6430            .await
6431    }
6432
6433    /// Request cancellation only if this handle's selected run is still current.
6434    pub async fn cancel_selected_run(
6435        &self,
6436        options: WorkflowCommandOptions,
6437    ) -> Result<WorkflowCommandResult> {
6438        let run_id = self.run_id.as_deref().ok_or_else(|| {
6439            Error::Codec("run_id is required for selected-run cancellation".to_string())
6440        })?;
6441        self.client
6442            .cancel_workflow_run(&self.workflow_id, run_id, options)
6443            .await
6444    }
6445
6446    /// Forcefully terminate whichever run is current.
6447    pub async fn terminate(
6448        &self,
6449        options: WorkflowCommandOptions,
6450    ) -> Result<WorkflowCommandResult> {
6451        self.client
6452            .terminate_workflow(&self.workflow_id, options)
6453            .await
6454    }
6455
6456    /// Terminate only if this handle's selected run is still current.
6457    pub async fn terminate_selected_run(
6458        &self,
6459        options: WorkflowCommandOptions,
6460    ) -> Result<WorkflowCommandResult> {
6461        let run_id = self.run_id.as_deref().ok_or_else(|| {
6462            Error::Codec("run_id is required for selected-run termination".to_string())
6463        })?;
6464        self.client
6465            .terminate_workflow_run(&self.workflow_id, run_id, options)
6466            .await
6467    }
6468
6469    /// Continue this handle's failed run without repeating completed activities.
6470    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
6471        let run_id = self
6472            .run_id
6473            .as_deref()
6474            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
6475        self.client
6476            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
6477            .await
6478    }
6479
6480    /// Execute a named, read-only query against this workflow.
6481    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
6482        self.client
6483            .query_workflow(&self.workflow_id, query_name, input)
6484            .await
6485    }
6486
6487    pub async fn query_avro_value<T: Serialize>(
6488        &self,
6489        query_name: &str,
6490        input: T,
6491    ) -> Result<AvroValue> {
6492        self.client
6493            .query_workflow_avro_value(&self.workflow_id, query_name, input)
6494            .await
6495    }
6496
6497    pub async fn update<T: Serialize>(
6498        &self,
6499        update_name: &str,
6500        input: T,
6501        request_id: Option<&str>,
6502    ) -> Result<Value> {
6503        self.client
6504            .update_workflow(&self.workflow_id, update_name, input, request_id)
6505            .await
6506    }
6507
6508    pub async fn update_avro_value<T: Serialize>(
6509        &self,
6510        update_name: &str,
6511        input: T,
6512        request_id: Option<&str>,
6513    ) -> Result<AvroValue> {
6514        self.client
6515            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
6516            .await
6517    }
6518
6519    /// Query only if this handle's selected run is still current.
6520    pub async fn query_selected_run<T: Serialize>(
6521        &self,
6522        query_name: &str,
6523        input: T,
6524    ) -> Result<Value> {
6525        let run_id = self
6526            .run_id
6527            .as_deref()
6528            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
6529        self.client
6530            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
6531            .await
6532    }
6533
6534    /// Await the final terminal outcome of the current continue-as-new chain.
6535    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
6536        self.result_target(options, None).await
6537    }
6538
6539    /// Await the final result without projecting Avro bytes through JSON.
6540    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
6541        self.result_avro_value_target(options, None).await
6542    }
6543
6544    /// Await the final result and decode it into a Serde application type.
6545    pub async fn result_typed<T: DeserializeOwned>(
6546        &self,
6547        options: WorkflowResultOptions,
6548    ) -> Result<T> {
6549        let result = self.result_avro_value(options).await?;
6550        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
6551    }
6552
6553    /// Await only the run identity originally selected by this handle.
6554    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
6555        let run_id = self.run_id.as_deref().ok_or_else(|| {
6556            Error::Codec("run_id is required for selected-run result".to_string())
6557        })?;
6558        self.result_target(options, Some(run_id)).await
6559    }
6560
6561    /// Await the selected run's result on the lossless Avro Value surface.
6562    pub async fn result_selected_run_avro_value(
6563        &self,
6564        options: WorkflowResultOptions,
6565    ) -> Result<AvroValue> {
6566        let run_id = self.run_id.as_deref().ok_or_else(|| {
6567            Error::Codec("run_id is required for selected-run result".to_string())
6568        })?;
6569        self.result_avro_value_target(options, Some(run_id)).await
6570    }
6571
6572    /// Await the selected run and decode its result into a Serde type.
6573    pub async fn result_selected_run_typed<T: DeserializeOwned>(
6574        &self,
6575        options: WorkflowResultOptions,
6576    ) -> Result<T> {
6577        let result = self.result_selected_run_avro_value(options).await?;
6578        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
6579    }
6580
6581    async fn result_avro_value_target(
6582        &self,
6583        options: WorkflowResultOptions,
6584        selected_run_id: Option<&str>,
6585    ) -> Result<AvroValue> {
6586        let started = Instant::now();
6587
6588        loop {
6589            let description = match selected_run_id {
6590                Some(run_id) => {
6591                    self.client
6592                        .describe_workflow_run(&self.workflow_id, run_id)
6593                        .await?
6594                }
6595                None => self.describe().await?,
6596            };
6597            if description.is_completed() {
6598                return description.output_avro_value.ok_or_else(|| {
6599                    Error::Codec(
6600                        "missing_payload_envelope: typed workflow result requires output_envelope"
6601                            .to_string(),
6602                    )
6603                });
6604            }
6605            if description.is_terminal() {
6606                let description = self
6607                    .client
6608                    .with_terminal_failure_detail(description, &self.workflow_id, selected_run_id)
6609                    .await;
6610                let outcome =
6611                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
6612                return Err(match outcome.kind {
6613                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
6614                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
6615                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
6616                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
6617                });
6618            }
6619            if started.elapsed() >= options.timeout {
6620                return Err(Error::Timeout);
6621            }
6622            tokio::time::sleep(options.poll_interval).await;
6623        }
6624    }
6625
6626    async fn result_target(
6627        &self,
6628        options: WorkflowResultOptions,
6629        selected_run_id: Option<&str>,
6630    ) -> Result<Value> {
6631        let started = Instant::now();
6632
6633        loop {
6634            let description = match selected_run_id {
6635                Some(run_id) => {
6636                    self.client
6637                        .describe_workflow_run(&self.workflow_id, run_id)
6638                        .await?
6639                }
6640                None => self.describe().await?,
6641            };
6642            if description.is_completed() {
6643                return Ok(description.output.unwrap_or(Value::Null));
6644            }
6645
6646            if description.is_terminal() {
6647                let description = self
6648                    .client
6649                    .with_terminal_failure_detail(description, &self.workflow_id, selected_run_id)
6650                    .await;
6651                let outcome =
6652                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
6653                return Err(match outcome.kind {
6654                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
6655                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
6656                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
6657                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
6658                });
6659            }
6660
6661            if started.elapsed() >= options.timeout {
6662                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
6663                    kind: WorkflowTerminalKind::TimedOut,
6664                    workflow_id: description
6665                        .workflow_id
6666                        .clone()
6667                        .unwrap_or_else(|| self.workflow_id.clone()),
6668                    run_id: description
6669                        .run_id
6670                        .clone()
6671                        .or_else(|| selected_run_id.map(str::to_string)),
6672                    reason: "result_wait_timeout".to_string(),
6673                    failure_category: Some("client_timeout".to_string()),
6674                    failure_id: None,
6675                    exception_type: None,
6676                    exception_class: None,
6677                    non_retryable: None,
6678                    message: Some(format!(
6679                        "workflow result was not terminal within {:?}",
6680                        options.timeout
6681                    )),
6682                    exception: None,
6683                    raw: description.raw_value(),
6684                }));
6685            }
6686
6687            tokio::time::sleep(options.poll_interval).await;
6688        }
6689    }
6690}
6691
6692#[derive(Clone, Copy, Debug)]
6693pub struct WorkflowResultOptions {
6694    pub poll_interval: Duration,
6695    pub timeout: Duration,
6696}
6697
6698impl Default for WorkflowResultOptions {
6699    fn default() -> Self {
6700        Self {
6701            poll_interval: Duration::from_millis(500),
6702            timeout: Duration::from_secs(30),
6703        }
6704    }
6705}
6706
6707#[derive(Clone, Debug, Deserialize)]
6708pub struct WorkflowDescription {
6709    pub workflow_id: Option<String>,
6710    pub run_id: Option<String>,
6711    pub workflow_type: Option<String>,
6712    pub status: Option<String>,
6713    #[serde(default)]
6714    pub closed_reason: Option<String>,
6715    #[serde(default)]
6716    pub error: Option<String>,
6717    #[serde(default)]
6718    pub failure: Option<Value>,
6719    #[serde(default)]
6720    pub exception: Option<Value>,
6721    #[serde(default)]
6722    pub failures: Vec<Value>,
6723    #[serde(default)]
6724    pub output: Option<Value>,
6725    #[serde(default)]
6726    pub output_envelope: Option<Value>,
6727    #[serde(skip)]
6728    pub output_avro_value: Option<AvroValue>,
6729    #[serde(flatten)]
6730    pub raw: HashMap<String, Value>,
6731}
6732
6733/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
6734#[derive(Clone, Debug, Deserialize)]
6735pub struct WorkflowStreamDescription {
6736    pub stream_name: String,
6737    pub status: String,
6738    pub last_offset: i64,
6739    pub total_items: u64,
6740    pub pending_items: u64,
6741    #[serde(default)]
6742    pub opened_at: Option<String>,
6743    #[serde(default)]
6744    pub last_appended_at: Option<String>,
6745    #[serde(default)]
6746    pub closed_at: Option<String>,
6747    #[serde(default)]
6748    pub error_reason: Option<String>,
6749    #[serde(default)]
6750    pub retention_seconds: Option<u64>,
6751    #[serde(flatten)]
6752    pub raw: HashMap<String, Value>,
6753}
6754
6755impl WorkflowStreamDescription {
6756    pub fn is_terminal(&self) -> bool {
6757        matches!(self.status.as_str(), "closed" | "errored")
6758    }
6759}
6760
6761/// One item for direct or replay-safe append.
6762#[derive(Clone, Debug, Default)]
6763pub struct WorkflowStreamAppendItem {
6764    pub payload_envelope: Option<Value>,
6765    pub payload_reference: Option<String>,
6766    pub item_type: Option<String>,
6767    pub content_type: Option<String>,
6768    pub idempotency_key: Option<String>,
6769}
6770
6771impl WorkflowStreamAppendItem {
6772    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
6773    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
6774        let value = AvroValue::from_serialize(&payload)?;
6775        Ok(Self {
6776            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
6777            ..Self::default()
6778        })
6779    }
6780
6781    /// Preserve an external payload URI as an opaque service-contract reference.
6782    pub fn from_reference(reference: impl Into<String>) -> Self {
6783        Self {
6784            payload_reference: Some(reference.into()),
6785            ..Self::default()
6786        }
6787    }
6788
6789    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
6790        self.item_type = Some(item_type.into());
6791        self
6792    }
6793
6794    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
6795        self.content_type = Some(content_type.into());
6796        self
6797    }
6798
6799    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
6800        self.idempotency_key = Some(idempotency_key.into());
6801        self
6802    }
6803
6804    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
6805        let mut item = serde_json::Map::new();
6806        if let Some(payload) = &self.payload_envelope {
6807            item.insert("payload".to_string(), payload.clone());
6808            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
6809        }
6810        if let Some(reference) = &self.payload_reference {
6811            item.insert("payload_reference".to_string(), json!(reference));
6812        }
6813        if let Some(item_type) = &self.item_type {
6814            item.insert("item_type".to_string(), json!(item_type));
6815        }
6816        if let Some(content_type) = &self.content_type {
6817            item.insert("content_type".to_string(), json!(content_type));
6818        }
6819        if let Some(key) = derived_idempotency_key
6820            .as_ref()
6821            .or(self.idempotency_key.as_ref())
6822        {
6823            item.insert("idempotency_key".to_string(), json!(key));
6824        }
6825        Value::Object(item)
6826    }
6827}
6828
6829/// One durable item at its stable zero-based offset.
6830#[derive(Clone, Debug)]
6831pub struct WorkflowStreamItem {
6832    pub offset: u64,
6833    pub payload: Option<Value>,
6834    pub payload_envelope: Option<Value>,
6835    pub payload_reference: Option<String>,
6836    pub payload_codec: Option<String>,
6837    pub idempotency_key: Option<String>,
6838    pub item_type: Option<String>,
6839    pub content_type: Option<String>,
6840    pub origin: Option<String>,
6841    pub origin_reference: Option<String>,
6842    pub emitted_at: Option<String>,
6843    pub raw: Value,
6844}
6845
6846/// One bounded at-least-once subscription page.
6847#[derive(Clone, Debug)]
6848pub struct WorkflowStreamPage {
6849    pub stream: WorkflowStreamDescription,
6850    pub items: Vec<WorkflowStreamItem>,
6851    pub next_offset: u64,
6852    pub terminal: bool,
6853}
6854
6855/// Durable acceptance and deduplication outcome for an append request.
6856#[derive(Clone, Debug)]
6857pub struct WorkflowStreamAppendResult {
6858    pub stream: WorkflowStreamDescription,
6859    pub accepted_offsets: Vec<u64>,
6860    pub accepted: u64,
6861    pub deduped: u64,
6862}
6863
6864#[derive(Deserialize)]
6865struct WorkflowStreamListResponse {
6866    #[serde(default)]
6867    streams: Vec<WorkflowStreamDescription>,
6868}
6869
6870#[derive(Deserialize)]
6871struct WorkflowStreamDescriptionResponse {
6872    stream: WorkflowStreamDescription,
6873}
6874
6875#[derive(Deserialize)]
6876struct WorkflowStreamPageResponse {
6877    stream: WorkflowStreamDescription,
6878    #[serde(default)]
6879    items: Vec<Value>,
6880    next_offset: u64,
6881    terminal: bool,
6882}
6883
6884#[derive(Deserialize)]
6885struct WorkflowStreamAppendResponse {
6886    stream: WorkflowStreamDescription,
6887    #[serde(default)]
6888    accepted_offsets: Vec<u64>,
6889    accepted: u64,
6890    deduped: u64,
6891}
6892
6893impl WorkflowDescription {
6894    pub fn is_completed(&self) -> bool {
6895        matches!(self.status.as_deref(), Some("completed" | "Completed"))
6896    }
6897
6898    pub fn is_terminal(&self) -> bool {
6899        matches!(
6900            self.status.as_deref(),
6901            Some(
6902                "completed"
6903                    | "Completed"
6904                    | "failed"
6905                    | "Failed"
6906                    | "cancelled"
6907                    | "Cancelled"
6908                    | "terminated"
6909                    | "Terminated"
6910                    | "timed_out"
6911                    | "TimedOut",
6912            )
6913        )
6914    }
6915
6916    fn decode_payloads(&mut self) -> Result<()> {
6917        if let Some(envelope) = &self.output_envelope {
6918            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
6919            self.output = Some(value.clone().into_json()?);
6920            self.output_avro_value = Some(value);
6921        }
6922
6923        Ok(())
6924    }
6925
6926    fn raw_value(&self) -> Value {
6927        let mut data = self.raw.clone();
6928        data.insert(
6929            "workflow_id".to_string(),
6930            self.workflow_id
6931                .clone()
6932                .map(Value::String)
6933                .unwrap_or(Value::Null),
6934        );
6935        data.insert(
6936            "run_id".to_string(),
6937            self.run_id
6938                .clone()
6939                .map(Value::String)
6940                .unwrap_or(Value::Null),
6941        );
6942        data.insert(
6943            "workflow_type".to_string(),
6944            self.workflow_type
6945                .clone()
6946                .map(Value::String)
6947                .unwrap_or(Value::Null),
6948        );
6949        data.insert(
6950            "status".to_string(),
6951            self.status
6952                .clone()
6953                .map(Value::String)
6954                .unwrap_or(Value::Null),
6955        );
6956        data.insert(
6957            "closed_reason".to_string(),
6958            self.closed_reason
6959                .clone()
6960                .map(Value::String)
6961                .unwrap_or(Value::Null),
6962        );
6963        if let Some(failure) = &self.failure {
6964            data.insert("failure".to_string(), failure.clone());
6965        }
6966        if let Some(exception) = &self.exception {
6967            data.insert("exception".to_string(), exception.clone());
6968        }
6969        Value::Object(data.into_iter().collect())
6970    }
6971}
6972
6973fn workflow_terminal_outcome(
6974    description: &WorkflowDescription,
6975    workflow_id: &str,
6976    run_id: Option<&str>,
6977) -> WorkflowTerminalOutcome {
6978    let terminal_kind = description
6979        .closed_reason
6980        .as_deref()
6981        .or(description.status.as_deref())
6982        .unwrap_or("failed")
6983        .to_ascii_lowercase();
6984    let kind = match terminal_kind.as_str() {
6985        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
6986        "terminated" => WorkflowTerminalKind::Terminated,
6987        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
6988        _ => WorkflowTerminalKind::Failed,
6989    };
6990    let default_reason = match kind {
6991        WorkflowTerminalKind::Failed => "workflow_failed",
6992        WorkflowTerminalKind::Cancelled => "cancelled",
6993        WorkflowTerminalKind::Terminated => "terminated",
6994        WorkflowTerminalKind::TimedOut => "timed_out",
6995    };
6996    let failure = description
6997        .failure
6998        .as_ref()
6999        .filter(|value| value.is_object());
7000    let nested_failure = failure
7001        .and_then(|value| value.get("failures"))
7002        .and_then(Value::as_array)
7003        .and_then(|failures| failures.last())
7004        .or_else(|| description.failures.last());
7005    let exception = description
7006        .exception
7007        .clone()
7008        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
7009        .or_else(|| {
7010            nested_failure
7011                .and_then(|value| value.get("exception_payload"))
7012                .cloned()
7013        });
7014    let string_field = |name: &str| {
7015        failure
7016            .and_then(|value| value.get(name))
7017            .and_then(Value::as_str)
7018            .or_else(|| {
7019                nested_failure
7020                    .and_then(|value| value.get(name))
7021                    .and_then(Value::as_str)
7022            })
7023            .map(str::to_string)
7024    };
7025    let exception_field = |name: &str| {
7026        exception
7027            .as_ref()
7028            .and_then(|value| value.get(name))
7029            .and_then(Value::as_str)
7030            .map(str::to_string)
7031    };
7032    let message = description
7033        .error
7034        .clone()
7035        .or_else(|| string_field("message"))
7036        .or_else(|| exception_field("message"));
7037    let reason = description
7038        .raw
7039        .get("reason")
7040        .and_then(Value::as_str)
7041        .map(str::to_string)
7042        .or_else(|| {
7043            failure
7044                .and_then(|value| value.get("reason"))
7045                .and_then(Value::as_str)
7046                .map(str::to_string)
7047        })
7048        .or_else(|| description.closed_reason.clone())
7049        .unwrap_or_else(|| default_reason.to_string());
7050    let failure_id = string_field("failure_id").or_else(|| {
7051        nested_failure
7052            .and_then(|value| value.get("id"))
7053            .and_then(Value::as_str)
7054            .map(str::to_string)
7055    });
7056
7057    WorkflowTerminalOutcome {
7058        kind,
7059        workflow_id: description
7060            .workflow_id
7061            .clone()
7062            .unwrap_or_else(|| workflow_id.to_string()),
7063        run_id: description
7064            .run_id
7065            .clone()
7066            .or_else(|| run_id.map(str::to_string)),
7067        reason,
7068        failure_category: string_field("failure_category")
7069            .or_else(|| Some(default_reason.to_string())),
7070        failure_id,
7071        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
7072        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
7073        non_retryable: failure
7074            .and_then(|value| value.get("non_retryable"))
7075            .and_then(Value::as_bool)
7076            .or_else(|| {
7077                nested_failure
7078                    .and_then(|value| value.get("non_retryable"))
7079                    .and_then(Value::as_bool)
7080            }),
7081        message,
7082        exception,
7083        raw: description.raw_value(),
7084    }
7085}
7086
7087#[derive(Clone, Debug, Deserialize)]
7088pub struct RegisterWorkerResponse {
7089    pub worker_id: String,
7090    pub registered: bool,
7091    #[serde(default)]
7092    pub heartbeat_interval_seconds: Option<u64>,
7093    #[serde(default)]
7094    pub protocol_version: Option<String>,
7095    #[serde(default)]
7096    pub server_capabilities: Option<Value>,
7097}
7098
7099/// Result of gracefully removing a worker-plane registration.
7100#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
7101pub struct WorkerDeregistrationEnvelope {
7102    pub worker_id: String,
7103    pub outcome: String,
7104    pub recovered_workflow_task_count: u64,
7105}
7106
7107#[derive(Clone, Debug, Deserialize)]
7108pub struct PollWorkflowTaskResponse {
7109    #[serde(default)]
7110    pub task: Option<WorkflowTask>,
7111    #[serde(default)]
7112    pub poll_status: Option<String>,
7113    #[serde(default)]
7114    pub reason: Option<String>,
7115    #[serde(default)]
7116    pub protocol_version: Option<String>,
7117    #[serde(default)]
7118    pub server_capabilities: Option<Value>,
7119}
7120
7121impl PollWorkflowTaskResponse {
7122    /// Classify this response without parsing server display text.
7123    pub fn outcome(&self) -> WorkerPollOutcome {
7124        worker_poll_outcome(
7125            self.task.is_some(),
7126            self.poll_status.as_deref(),
7127            self.reason.as_deref(),
7128        )
7129    }
7130}
7131
7132fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
7133    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
7134        return false;
7135    };
7136    let supported = capabilities
7137        .get("workflow_memo_updates")
7138        .and_then(Value::as_object)
7139        .and_then(|memo| memo.get("supported"))
7140        .and_then(Value::as_bool)
7141        == Some(true);
7142    let command_advertised = capabilities
7143        .get("supported_workflow_task_commands")
7144        .and_then(Value::as_array)
7145        .is_some_and(|commands| {
7146            commands
7147                .iter()
7148                .any(|command| command.as_str() == Some("upsert_memo"))
7149        });
7150    supported && command_advertised
7151}
7152
7153fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
7154    commands
7155        .iter()
7156        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
7157}
7158
7159#[derive(Clone, Debug, Deserialize)]
7160pub struct PollActivityTaskResponse {
7161    #[serde(default)]
7162    pub task: Option<ActivityTask>,
7163    #[serde(default)]
7164    pub poll_status: Option<String>,
7165    #[serde(default)]
7166    pub reason: Option<String>,
7167}
7168
7169impl PollActivityTaskResponse {
7170    /// Classify this response without parsing server display text.
7171    pub fn outcome(&self) -> WorkerPollOutcome {
7172        worker_poll_outcome(
7173            self.task.is_some(),
7174            self.poll_status.as_deref(),
7175            self.reason.as_deref(),
7176        )
7177    }
7178}
7179
7180#[derive(Clone, Debug, Deserialize)]
7181pub struct PollQueryTaskResponse {
7182    #[serde(default)]
7183    pub task: Option<QueryTask>,
7184    #[serde(default)]
7185    pub poll_status: Option<String>,
7186    #[serde(default)]
7187    pub reason: Option<String>,
7188}
7189
7190impl PollQueryTaskResponse {
7191    /// Classify this response without parsing server display text.
7192    pub fn outcome(&self) -> WorkerPollOutcome {
7193        worker_poll_outcome(
7194            self.task.is_some(),
7195            self.poll_status.as_deref(),
7196            self.reason.as_deref(),
7197        )
7198    }
7199}
7200
7201/// Stable classification for worker poll responses.
7202#[derive(Clone, Debug, PartialEq, Eq)]
7203pub enum WorkerPollOutcome {
7204    /// A task was leased and is available on the response.
7205    Task,
7206    /// No task was leased, but the worker should continue polling.
7207    Idle {
7208        poll_status: Option<String>,
7209        reason: Option<String>,
7210    },
7211    /// The server asked this worker to stop claiming new work.
7212    Stop {
7213        poll_status: Option<String>,
7214        reason: Option<String>,
7215    },
7216}
7217
7218impl WorkerPollOutcome {
7219    pub fn should_stop(&self) -> bool {
7220        matches!(self, Self::Stop { .. })
7221    }
7222}
7223
7224fn worker_poll_outcome(
7225    has_task: bool,
7226    poll_status: Option<&str>,
7227    reason: Option<&str>,
7228) -> WorkerPollOutcome {
7229    if worker_poll_is_stop(poll_status, reason) {
7230        return WorkerPollOutcome::Stop {
7231            poll_status: poll_status.map(str::to_string),
7232            reason: reason.map(str::to_string),
7233        };
7234    }
7235
7236    if has_task {
7237        WorkerPollOutcome::Task
7238    } else {
7239        WorkerPollOutcome::Idle {
7240            poll_status: poll_status.map(str::to_string),
7241            reason: reason.map(str::to_string),
7242        }
7243    }
7244}
7245
7246/// An ephemeral server-routed query task.
7247#[derive(Clone, Debug, Deserialize)]
7248pub struct QueryTask {
7249    pub query_task_id: String,
7250    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
7251    #[serde(default)]
7252    pub observability_context: Option<Value>,
7253    #[serde(default)]
7254    pub dispatch_observability_context: Option<Value>,
7255    #[serde(default)]
7256    pub observability_links: Option<Value>,
7257    #[serde(default = "default_workflow_task_attempt")]
7258    pub query_task_attempt: u64,
7259    #[serde(default)]
7260    pub lease_owner: Option<String>,
7261    #[serde(default)]
7262    pub workflow_id: Option<String>,
7263    #[serde(default)]
7264    pub run_id: Option<String>,
7265    pub workflow_type: String,
7266    pub query_name: String,
7267    #[serde(
7268        default = "missing_task_payload_codec",
7269        deserialize_with = "deserialize_task_payload_codec"
7270    )]
7271    pub payload_codec: String,
7272    #[serde(default)]
7273    pub workflow_arguments: Option<Value>,
7274    #[serde(default)]
7275    pub query_arguments: Option<Value>,
7276    #[serde(default)]
7277    pub history_events: Vec<HistoryEvent>,
7278    #[serde(default)]
7279    pub history_export: Option<Value>,
7280    #[serde(default)]
7281    pub run_status: Option<String>,
7282}
7283
7284#[derive(Clone, Debug, Deserialize)]
7285pub struct WorkflowTask {
7286    pub task_id: String,
7287    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
7288    #[serde(default)]
7289    pub observability_context: Option<Value>,
7290    #[serde(default)]
7291    pub dispatch_observability_context: Option<Value>,
7292    #[serde(default)]
7293    pub observability_links: Option<Value>,
7294    #[serde(default)]
7295    pub workflow_command_id: Option<String>,
7296    #[serde(default)]
7297    pub workflow_id: Option<String>,
7298    #[serde(default)]
7299    pub run_id: Option<String>,
7300    pub workflow_type: String,
7301    #[serde(default)]
7302    pub cancel_requested: bool,
7303    #[serde(
7304        default = "missing_task_payload_codec",
7305        deserialize_with = "deserialize_task_payload_codec"
7306    )]
7307    pub payload_codec: String,
7308    #[serde(default)]
7309    pub arguments: Option<Value>,
7310    #[serde(default)]
7311    pub history_events: Vec<HistoryEvent>,
7312    #[serde(default)]
7313    pub total_history_events: Option<u64>,
7314    #[serde(default)]
7315    pub history_size_bytes: Option<u64>,
7316    #[serde(default)]
7317    pub continue_as_new_recommended: Option<bool>,
7318    #[serde(default)]
7319    pub history_budget_pressure: Option<String>,
7320    #[serde(default)]
7321    pub next_history_page_token: Option<String>,
7322    #[serde(default = "default_workflow_task_attempt")]
7323    pub workflow_task_attempt: u64,
7324    #[serde(default)]
7325    pub workflow_signal_id: Option<String>,
7326    #[serde(default)]
7327    pub signal_name: Option<String>,
7328    #[serde(default)]
7329    pub signal_arguments: Option<Value>,
7330    #[serde(default)]
7331    pub workflow_update_id: Option<String>,
7332    #[serde(default)]
7333    pub update_name: Option<String>,
7334    #[serde(default)]
7335    pub lease_owner: Option<String>,
7336}
7337
7338impl WorkflowTask {
7339    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
7340        self.history_events.extend(page.history_events);
7341
7342        if page.total_history_events.is_some() {
7343            self.total_history_events = page.total_history_events;
7344        }
7345
7346        self.next_history_page_token = page
7347            .next_history_page_token
7348            .filter(|token| !token.is_empty());
7349    }
7350}
7351
7352#[derive(Clone, Debug, Deserialize)]
7353struct WorkflowTaskHistoryPage {
7354    #[serde(default)]
7355    history_events: Vec<HistoryEvent>,
7356    #[serde(default)]
7357    total_history_events: Option<u64>,
7358    #[serde(default)]
7359    next_history_page_token: Option<String>,
7360}
7361
7362#[derive(Clone, Debug, Deserialize)]
7363pub struct ActivityTask {
7364    pub task_id: String,
7365    #[serde(default)]
7366    pub workflow_id: Option<String>,
7367    #[serde(default)]
7368    pub run_id: Option<String>,
7369    #[serde(default)]
7370    pub activity_execution_id: Option<String>,
7371    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
7372    #[serde(default)]
7373    pub observability_context: Option<Value>,
7374    #[serde(default)]
7375    pub dispatch_observability_context: Option<Value>,
7376    #[serde(default)]
7377    pub observability_links: Option<Value>,
7378    #[serde(default)]
7379    pub activity_attempt_id: Option<String>,
7380    #[serde(default)]
7381    pub attempt_id: Option<String>,
7382    pub activity_type: String,
7383    #[serde(
7384        default = "missing_task_payload_codec",
7385        deserialize_with = "deserialize_task_payload_codec"
7386    )]
7387    pub payload_codec: String,
7388    #[serde(default)]
7389    pub arguments: Option<Value>,
7390    #[serde(default = "default_attempt_number")]
7391    pub attempt_number: u64,
7392    #[serde(default)]
7393    pub lease_owner: Option<String>,
7394}
7395
7396#[derive(Clone, Debug, Serialize, Deserialize)]
7397pub struct HistoryEvent {
7398    #[serde(alias = "type")]
7399    pub event_type: String,
7400    #[serde(default)]
7401    pub payload: Value,
7402    #[serde(flatten)]
7403    pub raw: HashMap<String, Value>,
7404}
7405
7406/// One decoded signal in the committed workflow-history snapshot.
7407#[derive(Clone, Debug, PartialEq)]
7408pub struct QuerySignal {
7409    pub id: Option<String>,
7410    pub name: String,
7411    pub arguments: Vec<Value>,
7412    avro_arguments: Vec<AvroValue>,
7413    pub workflow_sequence: Option<u64>,
7414}
7415
7416impl QuerySignal {
7417    /// Lossless fixed Avro Value arguments for this committed signal.
7418    pub fn arguments_avro_value(&self) -> &[AvroValue] {
7419        &self.avro_arguments
7420    }
7421}
7422
7423/// Immutable state supplied to a registered query handler.
7424///
7425/// This context intentionally exposes no activity, signal-wait, or command
7426/// APIs. Query handlers inspect committed history and return a value; query
7427/// completion does not append an event or advance deterministic execution.
7428#[derive(Clone, Debug)]
7429pub struct QueryContext {
7430    pub workflow_id: Option<String>,
7431    pub run_id: Option<String>,
7432    pub workflow_type: String,
7433    pub run_status: Option<String>,
7434    workflow_input: Value,
7435    workflow_input_avro_value: AvroValue,
7436    history_events: Arc<Vec<HistoryEvent>>,
7437    signal_events: Arc<Vec<QuerySignal>>,
7438    replay_time: Option<DateTime<chrono::Utc>>,
7439}
7440
7441impl QueryContext {
7442    /// The normalized argument list used to start the workflow.
7443    pub fn workflow_input(&self) -> &Value {
7444        &self.workflow_input
7445    }
7446
7447    /// The lossless fixed Avro Value argument list used to start the workflow.
7448    pub fn workflow_input_avro_value(&self) -> &AvroValue {
7449        &self.workflow_input_avro_value
7450    }
7451
7452    /// The immutable committed history used for this query snapshot.
7453    pub fn history_events(&self) -> &[HistoryEvent] {
7454        self.history_events.as_slice()
7455    }
7456
7457    /// All decoded signals in committed workflow order.
7458    pub fn signal_events(&self) -> &[QuerySignal] {
7459        self.signal_events.as_slice()
7460    }
7461
7462    /// Decoded argument lists for each committed signal with `signal_name`.
7463    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
7464        self.signal_events
7465            .iter()
7466            .filter(|signal| signal.name == signal_name)
7467            .map(|signal| signal.arguments.clone())
7468            .collect()
7469    }
7470
7471    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
7472    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
7473        self.signal_events
7474            .iter()
7475            .filter(|signal| signal.name == signal_name)
7476            .map(|signal| signal.avro_arguments.clone())
7477            .collect()
7478    }
7479}
7480
7481#[derive(Clone, Debug, Deserialize)]
7482pub struct ActivityHeartbeatResponse {
7483    #[serde(default)]
7484    pub cancel_requested: bool,
7485    #[serde(default)]
7486    pub heartbeat_recorded: bool,
7487    #[serde(default)]
7488    pub can_continue: Option<bool>,
7489    #[serde(default)]
7490    pub reason: Option<String>,
7491    #[serde(default)]
7492    pub run_closed_reason: Option<String>,
7493    #[serde(default)]
7494    pub run_closed_at: Option<String>,
7495    #[serde(default)]
7496    pub lease_expires_at: Option<String>,
7497    #[serde(default)]
7498    pub last_heartbeat_at: Option<String>,
7499}
7500
7501impl ActivityHeartbeatResponse {
7502    /// Whether the activity should stop instead of attempting completion.
7503    pub fn should_stop(&self) -> bool {
7504        self.cancel_requested || self.can_continue == Some(false)
7505    }
7506}
7507
7508fn missing_task_payload_codec() -> String {
7509    MISSING_TASK_PAYLOAD_CODEC.to_string()
7510}
7511
7512fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
7513where
7514    D: Deserializer<'de>,
7515{
7516    Ok(match Value::deserialize(deserializer)? {
7517        Value::String(codec) => codec,
7518        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
7519        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
7520    })
7521}
7522
7523fn default_workflow_task_attempt() -> u64 {
7524    1
7525}
7526
7527fn default_attempt_number() -> u64 {
7528    1
7529}
7530
7531type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7532type WorkflowHandler =
7533    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<WorkflowFuture> + Send + Sync>;
7534type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
7535type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
7536type ReplayedWorkflowHandler =
7537    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<ReplayedWorkflowInvocation> + Send + Sync>;
7538type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7539type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
7540type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
7541type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
7542type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
7543type ReplayedQueryHandler = Arc<
7544    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
7545        + Send
7546        + Sync,
7547>;
7548type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
7549
7550struct ReplayedWorkflowInvocation {
7551    future: WorkflowFuture,
7552    snapshot: WorkflowStateSnapshot,
7553}
7554
7555#[derive(Clone)]
7556struct RegisteredWorkflow {
7557    execute: WorkflowHandler,
7558    replay: Option<ReplayedWorkflowHandler>,
7559    state_type: Option<TypeId>,
7560    definition_fingerprint: Option<String>,
7561}
7562
7563fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
7564    names
7565        .iter()
7566        .map(|name| {
7567            json!({
7568                "name": name,
7569                "parameters": [{
7570                    "name": "args",
7571                    "position": 0,
7572                    "required": false,
7573                    "variadic": true,
7574                    "type": null,
7575                    "allows_null": true,
7576                    "default_available": false,
7577                    "default": null,
7578                }],
7579            })
7580        })
7581        .collect()
7582}
7583
7584#[derive(Debug)]
7585struct WorkflowTaskDecision {
7586    commands: Vec<Value>,
7587    message_stream_cursors: Vec<Value>,
7588    message_stream_waits: Vec<Value>,
7589    cancellation_delivery: Option<CancellationDelivery>,
7590    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
7591    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
7592}
7593
7594enum PreparedWorkflowTask {
7595    Decision(WorkflowTaskDecision),
7596    Execution {
7597        task: WorkflowTask,
7598        context: WorkflowContext,
7599        future: WorkflowFuture,
7600    },
7601}
7602
7603impl WorkflowTaskDecision {
7604    fn without_message_streams(commands: Vec<Value>) -> Self {
7605        Self {
7606            commands,
7607            message_stream_cursors: Vec::new(),
7608            message_stream_waits: Vec::new(),
7609            cancellation_delivery: None,
7610            cancellation_scope_opening: None,
7611            cancellation_scope_delivery: None,
7612        }
7613    }
7614}
7615
7616#[derive(Clone)]
7617enum RegisteredQuery {
7618    Snapshot(QueryHandler),
7619    Replayed {
7620        state_type: TypeId,
7621        handler: ReplayedQueryHandler,
7622    },
7623}
7624
7625#[derive(Clone, Debug)]
7626pub struct WorkerHeartbeatObservation {
7627    pub worker_id: String,
7628    pub task_queue: String,
7629    pub acknowledged_at_unix_millis: u64,
7630    pub acknowledgement: Value,
7631}
7632
7633/// Bounded retry policy for worker poll acquisition and worker heartbeats.
7634///
7635/// Expected empty long polls and explicit Server capacity backpressure are
7636/// normal worker states. Capacity backpressure honors the advertised retry
7637/// delay without consuming this retry budget. Other transport failures,
7638/// retryable HTTP 408/429 responses, and server errors are retried with capped
7639/// exponential backoff. Authentication, protocol, codec, and handler failures
7640/// are never retried by the worker.
7641/// Explicit storage admission pauses also preserve the already-serialized worker
7642/// request without consuming this budget or rerunning its handler. The delay is
7643/// capped by `max_backoff`, except an explicit completion deferral must honor
7644/// the Server's minimum delay. Shutdown interrupts storage waits; cooperative
7645/// completion retries remain bounded by the original cleanup deadline.
7646/// [`Worker::recover_transient_outages`] can keep a long-running worker retrying
7647/// poll acquisition and heartbeats beyond this budget. `run_once` stays bounded,
7648/// and `max_retries = 0` disables ordinary retries in either mode.
7649#[derive(Clone, Copy, Debug)]
7650pub struct WorkerRetryPolicy {
7651    /// Number of retries after the initial request fails.
7652    pub max_retries: usize,
7653    /// Delay before the first retry.
7654    pub initial_backoff: Duration,
7655    /// Maximum delay between retries.
7656    pub max_backoff: Duration,
7657}
7658
7659impl Default for WorkerRetryPolicy {
7660    fn default() -> Self {
7661        Self {
7662            max_retries: 5,
7663            initial_backoff: Duration::from_millis(100),
7664            max_backoff: Duration::from_secs(5),
7665        }
7666    }
7667}
7668
7669#[derive(Clone, Debug)]
7670struct WorkerStorageAdmission {
7671    policy: WorkerRetryPolicy,
7672    stop: Arc<AtomicBool>,
7673    workflow_completion_retry_deadline: Option<tokio::time::Instant>,
7674}
7675
7676struct StopWorkerOnDrop(Arc<AtomicBool>);
7677
7678impl Drop for StopWorkerOnDrop {
7679    fn drop(&mut self) {
7680        self.0.store(true, Ordering::SeqCst);
7681    }
7682}
7683
7684async fn wait_for_worker_stop(stop: &AtomicBool) {
7685    while !stop.load(Ordering::SeqCst) {
7686        tokio::time::sleep(Duration::from_millis(100)).await;
7687    }
7688}
7689
7690#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7691enum ManagedPollOutcome {
7692    Idle,
7693    Handled,
7694    Stop,
7695}
7696
7697#[derive(Clone)]
7698pub struct Worker {
7699    metrics: metrics::Metrics,
7700    #[cfg(feature = "telemetry")]
7701    telemetry: Option<telemetry::ExecutionTelemetry>,
7702    client: Client,
7703    worker_id: String,
7704    task_queue: String,
7705    workflows: HashMap<String, RegisteredWorkflow>,
7706    activities: HashMap<String, ActivityHandler>,
7707    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
7708    signals: HashMap<String, Vec<String>>,
7709    updates: HashMap<String, HashMap<String, UpdateHandler>>,
7710    registration_definitions:
7711        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
7712    registration_error: Option<DuplicateRegistrationError>,
7713    max_concurrent_workflow_tasks: usize,
7714    max_concurrent_activity_tasks: usize,
7715    workflow_capacity: Arc<worker_capacity::TaskCapacity>,
7716    activity_capacity: Arc<worker_capacity::TaskCapacity>,
7717    poll_timeout: Duration,
7718    heartbeat_interval: Duration,
7719    retry_policy: WorkerRetryPolicy,
7720    recover_transient_outages: bool,
7721    run_stop: Option<Arc<AtomicBool>>,
7722    heartbeat_observer: Option<WorkerHeartbeatObserver>,
7723    cooperative_cancellation_enabled: bool,
7724    nexus_cooperative_cancellation_enabled: bool,
7725    allow_cancellation_scope_authoring: bool,
7726    allow_cancellation_scope_delivery: bool,
7727    cooperative_registration_confirmed: Arc<AtomicBool>,
7728    nexus_registration_confirmed: Arc<AtomicBool>,
7729    local_registration_confirmed: Arc<AtomicBool>,
7730    session_registration_confirmed: Arc<AtomicBool>,
7731    sticky_registration_confirmed: Arc<AtomicBool>,
7732    require_query_task_authority: bool,
7733    query_authority_confirmed: Arc<AtomicBool>,
7734    resource_capabilities: Vec<String>,
7735    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
7736}
7737
7738impl Worker {
7739    /// Override worker poll/task metrics; client request metrics retain their client's recorder.
7740    pub fn metrics_recorder(mut self, recorder: Arc<dyn metrics::MetricsRecorder>) -> Self {
7741        self.metrics = metrics::Metrics::new(recorder);
7742        self.client.worker_dispatch_metrics = self.metrics.clone();
7743        self
7744    }
7745    pub fn new(mut client: Client, task_queue: impl Into<String>) -> Self {
7746        client.worker_dispatch_metrics = client.metrics.clone();
7747        Self {
7748            metrics: client.metrics.clone(),
7749            #[cfg(feature = "telemetry")]
7750            telemetry: None,
7751            client,
7752            worker_id: default_worker_id(),
7753            task_queue: task_queue.into(),
7754            workflows: HashMap::new(),
7755            activities: HashMap::new(),
7756            queries: HashMap::new(),
7757            signals: HashMap::new(),
7758            updates: HashMap::new(),
7759            registration_definitions: HashMap::new(),
7760            registration_error: None,
7761            max_concurrent_workflow_tasks: 10,
7762            max_concurrent_activity_tasks: 10,
7763            workflow_capacity: worker_capacity::TaskCapacity::new(10),
7764            activity_capacity: worker_capacity::TaskCapacity::new(10),
7765            poll_timeout: Duration::from_secs(30),
7766            heartbeat_interval: Duration::from_secs(60),
7767            retry_policy: WorkerRetryPolicy::default(),
7768            recover_transient_outages: false,
7769            run_stop: None,
7770            heartbeat_observer: None,
7771            cooperative_cancellation_enabled: false,
7772            nexus_cooperative_cancellation_enabled: false,
7773            allow_cancellation_scope_authoring: false,
7774            allow_cancellation_scope_delivery: false,
7775            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
7776            nexus_registration_confirmed: Arc::new(AtomicBool::new(false)),
7777            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
7778            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
7779            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
7780            require_query_task_authority: false,
7781            query_authority_confirmed: Arc::new(AtomicBool::new(false)),
7782            resource_capabilities: Vec::new(),
7783            sessions: Arc::new(Mutex::new(HashMap::new())),
7784        }
7785    }
7786
7787    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
7788        self.worker_id = worker_id.into();
7789        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
7790        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7791        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
7792        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
7793        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
7794        self.query_authority_confirmed = Arc::new(AtomicBool::new(false));
7795        self.client.reset_sticky_cache();
7796        self.sessions = Arc::new(Mutex::new(HashMap::new()));
7797        self
7798    }
7799
7800    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
7801        self.poll_timeout = timeout;
7802        self
7803    }
7804
7805    /// Opt in to execution spans using application-owned OpenTelemetry providers.
7806    /// No exporter, logging bridge, global provider or Server carrier is installed.
7807    #[cfg(feature = "telemetry")]
7808    pub fn telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
7809        self.client.execution_telemetry = Some(telemetry.clone());
7810        self.telemetry = Some(telemetry);
7811        self
7812    }
7813
7814    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
7815        self.heartbeat_interval = interval;
7816        self
7817    }
7818
7819    /// Require original query timing and non-renewing runtime observation.
7820    ///
7821    /// Registration refuses before creating a Worker unless protocol 1.20 and
7822    /// the runtime's `query_task_authority` capability are available. By default,
7823    /// older Servers retain their weaker, disclosed local-timing behavior.
7824    pub fn require_query_task_authority(mut self, required: bool) -> Self {
7825        self.require_query_task_authority = required;
7826        self
7827    }
7828
7829    /// Explicitly enable inline local activities in this workflow worker.
7830    ///
7831    /// The worker advertises the capability to Server only when enabled.
7832    /// These callbacks must yield to Tokio and have idempotent side effects.
7833    /// Cooperative prepared local supervision is a separate capability.
7834    pub fn local_activities(mut self, enabled: bool) -> Self {
7835        self.client.local_activities_enabled = enabled;
7836        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
7837        self
7838    }
7839
7840    /// Opt in to separate cooperative workflow cancellation requests.
7841    ///
7842    /// Registration requires the Server to acknowledge this exact worker,
7843    /// namespace, queue and capabilities with compatible protocol 1.20. Task
7844    /// processing uses canonical delivery and activity ownership fences.
7845    /// Existing terminal cancel and terminate operations remain terminal.
7846    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
7847    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
7848    /// and [`Worker::run_until`] register automatically.
7849    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
7850        self.cooperative_cancellation_enabled = enabled;
7851        self.client.cooperative_worker_protocol = enabled;
7852        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
7853        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7854        if !enabled {
7855            self.nexus_cooperative_cancellation_enabled = false;
7856        }
7857        self
7858    }
7859
7860    /// Opt in to cooperative Nexus completion waits on an installed workflow binding.
7861    ///
7862    /// This also enables ordinary cooperative cancellation. Registration checks
7863    /// protocol 1.20 and Server's installed `workflow_run` bridge before advertising.
7864    pub fn nexus_cooperative_cancellation(self, enabled: bool) -> Self {
7865        let mut worker = if enabled {
7866            self.cooperative_cancellation(true)
7867        } else {
7868            self
7869        };
7870        worker.nexus_cooperative_cancellation_enabled = enabled;
7871        worker.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
7872        worker
7873    }
7874
7875    /// Enable candidate scope authoring without advertising scoped execution.
7876    #[doc(hidden)]
7877    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
7878        self.allow_cancellation_scope_authoring = enabled;
7879        self
7880    }
7881
7882    /// Enable the candidate scoped call consumer with canonical authoring.
7883    #[doc(hidden)]
7884    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
7885        self.allow_cancellation_scope_delivery = enabled;
7886        self
7887    }
7888
7889    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
7890    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
7891        self.retry_policy = policy;
7892        self
7893    }
7894
7895    /// Keep `run` and `run_until` alive during retryable poll and heartbeat outages.
7896    ///
7897    /// Retries preserve the poll request identity and use capped exponential
7898    /// backoff from [`WorkerRetryPolicy`]. Shutdown interrupts a retry wait.
7899    /// An in-flight poll is allowed to finish so leased work is not discarded.
7900    /// Authentication, protocol, codec, handler and task settlement failures
7901    /// remain errors. Registration and deregistration are not retried here.
7902    ///
7903    /// The default is disabled, preserving the bounded retry contract.
7904    /// `run_once` always remains bounded. `max_retries = 0` disables retries,
7905    /// even when this option is enabled.
7906    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
7907        self.recover_transient_outages = enabled;
7908        self
7909    }
7910
7911    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
7912    where
7913        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
7914    {
7915        self.heartbeat_observer = Some(Arc::new(observer));
7916        self
7917    }
7918
7919    /// Bound simultaneous claimed workflow tasks, including loading and settlement.
7920    /// Defaults to 10. Use 1 for serial workflow-task execution.
7921    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
7922        self.max_concurrent_workflow_tasks = count.clamp(1, tokio::sync::Semaphore::MAX_PERMITS);
7923        self.workflow_capacity =
7924            worker_capacity::TaskCapacity::new(self.max_concurrent_workflow_tasks);
7925        self
7926    }
7927
7928    /// Bound simultaneous remote activity tasks, including loading and settlement.
7929    /// Defaults to 10. Use 1 for serial activity-task execution.
7930    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
7931        self.max_concurrent_activity_tasks = count.clamp(1, tokio::sync::Semaphore::MAX_PERMITS);
7932        self.activity_capacity =
7933            worker_capacity::TaskCapacity::new(self.max_concurrent_activity_tasks);
7934        self
7935    }
7936
7937    /// Validate local handler admission without making a Server request.
7938    ///
7939    /// Registration methods retain their existing signatures. A duplicate keeps
7940    /// the original handler and makes this Worker invalid, including its clones.
7941    /// `register`, `run`, `run_until` and `run_once` enforce this check before
7942    /// any network request. Build a new Worker to correct an invalid configuration.
7943    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
7944        match &self.registration_error {
7945            Some(error) => Err(error.clone()),
7946            None => Ok(()),
7947        }
7948    }
7949
7950    #[track_caller]
7951    fn admit_registration<F>(
7952        &mut self,
7953        handler_kind: RegistrationKind,
7954        workflow_type: Option<&str>,
7955        handler_name: &str,
7956        method: &'static str,
7957    ) -> bool {
7958        let location = std::panic::Location::caller();
7959        let definition = HandlerRegistration {
7960            method,
7961            handler_type: type_name::<F>(),
7962            file: location.file(),
7963            line: location.line(),
7964            column: location.column(),
7965        };
7966        let key = (
7967            handler_kind,
7968            workflow_type.map(str::to_owned),
7969            handler_name.to_owned(),
7970        );
7971        if let Some(first_definition) = self.registration_definitions.get(&key) {
7972            if self.registration_error.is_none() {
7973                self.registration_error = Some(DuplicateRegistrationError {
7974                    handler_kind,
7975                    workflow_type: key.1.clone(),
7976                    handler_name: key.2.clone(),
7977                    first_definition: first_definition.clone(),
7978                    second_definition: definition,
7979                });
7980            }
7981            return false;
7982        }
7983        self.registration_definitions.insert(key, definition);
7984        true
7985    }
7986
7987    /// Register a workflow handler.
7988    ///
7989    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
7990    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
7991    /// while acquiring or decoding a worker task remain worker-operation
7992    /// failures and do not get converted into workflow outcomes.
7993    #[track_caller]
7994    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
7995    where
7996        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
7997        Fut: Future<Output = Result<Value>> + Send + 'static,
7998    {
7999        let workflow_type = workflow_type.into();
8000        if !self.admit_registration::<F>(
8001            RegistrationKind::Workflow,
8002            None,
8003            &workflow_type,
8004            "register_workflow",
8005        ) {
8006            return;
8007        }
8008        let handler = Arc::new(handler);
8009        self.workflows.insert(
8010            workflow_type,
8011            RegisteredWorkflow {
8012                execute: Arc::new(move |ctx, input| {
8013                    let handler = Arc::clone(&handler);
8014                    Ok(Box::pin(async move {
8015                        let result = handler(ctx, input.into_json()?).await?;
8016                        AvroValue::from_serialize(&result)
8017                    }))
8018                }),
8019                replay: None,
8020                state_type: None,
8021                definition_fingerprint: None,
8022            },
8023        );
8024    }
8025
8026    /// Register a workflow with one Serde request value and a Serde result.
8027    ///
8028    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
8029    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
8030    /// workflow-specific schema. A task must contain zero arguments for a unit
8031    /// request or exactly one argument for every other request type.
8032    ///
8033    /// See the runnable
8034    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
8035    /// for typed workflow and activity contracts with retry and timeout policy.
8036    #[track_caller]
8037    pub fn register_typed_workflow<I, O, F, Fut>(
8038        &mut self,
8039        workflow_type: impl Into<String>,
8040        handler: F,
8041    ) where
8042        I: DeserializeOwned + Send + 'static,
8043        O: Serialize + Send + 'static,
8044        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
8045        Fut: Future<Output = Result<O>> + Send + 'static,
8046    {
8047        let workflow_type = workflow_type.into();
8048        if !self.admit_registration::<F>(
8049            RegistrationKind::Workflow,
8050            None,
8051            &workflow_type,
8052            "register_typed_workflow",
8053        ) {
8054            return;
8055        }
8056        let handler_name = workflow_type.clone();
8057        let handler = Arc::new(handler);
8058        self.workflows.insert(
8059            workflow_type,
8060            RegisteredWorkflow {
8061                execute: Arc::new(move |ctx, input| {
8062                    let input = decode_workflow_entry::<I>(input, &handler_name)?;
8063                    let handler = Arc::clone(&handler);
8064                    let handler_name = handler_name.clone();
8065                    Ok(Box::pin(async move {
8066                        let result = handler(ctx, input).await?;
8067                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
8068                    }))
8069                }),
8070                replay: None,
8071                state_type: None,
8072                definition_fingerprint: None,
8073            },
8074        );
8075    }
8076
8077    /// Register a workflow on the lossless fixed Avro Value surface.
8078    #[track_caller]
8079    pub fn register_workflow_avro_value<F, Fut>(
8080        &mut self,
8081        workflow_type: impl Into<String>,
8082        handler: F,
8083    ) where
8084        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
8085        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8086    {
8087        let workflow_type = workflow_type.into();
8088        if !self.admit_registration::<F>(
8089            RegistrationKind::Workflow,
8090            None,
8091            &workflow_type,
8092            "register_workflow_avro_value",
8093        ) {
8094            return;
8095        }
8096        self.workflows.insert(
8097            workflow_type,
8098            RegisteredWorkflow {
8099                execute: Arc::new(move |ctx, input| Ok(Box::pin(handler(ctx, input)))),
8100                replay: None,
8101                state_type: None,
8102                definition_fingerprint: None,
8103            },
8104        );
8105    }
8106
8107    /// Register a workflow whose typed instance state can be reconstructed for queries.
8108    ///
8109    /// `state_factory` creates a fresh instance for every normal workflow task and
8110    /// query replay. The workflow handler is the single source of truth for state
8111    /// transitions: it updates [`WorkflowInstance`] after activities and signals
8112    /// resolve. Query replay runs this same handler over committed history and
8113    /// discards any commands it would emit.
8114    #[track_caller]
8115    pub fn register_replayed_workflow<S, Factory, F, Fut>(
8116        &mut self,
8117        workflow_type: impl Into<String>,
8118        state_factory: Factory,
8119        handler: F,
8120    ) where
8121        S: Clone + Send + Sync + 'static,
8122        Factory: Fn() -> S + Send + Sync + 'static,
8123        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
8124        Fut: Future<Output = Result<Value>> + Send + 'static,
8125    {
8126        let workflow_type = workflow_type.into();
8127        if !self.admit_registration::<F>(
8128            RegistrationKind::Workflow,
8129            None,
8130            &workflow_type,
8131            "register_replayed_workflow",
8132        ) {
8133            return;
8134        }
8135        let state_factory = Arc::new(state_factory);
8136        let handler = Arc::new(handler);
8137
8138        let execute_factory = Arc::clone(&state_factory);
8139        let execute_handler = Arc::clone(&handler);
8140        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
8141            let state = WorkflowInstance::new(execute_factory());
8142            let handler = Arc::clone(&execute_handler);
8143            Ok(Box::pin(async move {
8144                let result = handler(ctx, input.into_json()?, state).await?;
8145                AvroValue::from_serialize(&result)
8146            }) as WorkflowFuture)
8147        });
8148
8149        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
8150            let state = WorkflowInstance::new(state_factory());
8151            let snapshot_state = state.clone();
8152            let snapshot: WorkflowStateSnapshot =
8153                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
8154            let replay_handler = Arc::clone(&handler);
8155            let future = async move {
8156                let result = replay_handler(ctx, input.into_json()?, state).await?;
8157                AvroValue::from_serialize(&result)
8158            };
8159            Ok(ReplayedWorkflowInvocation {
8160                future: Box::pin(future),
8161                snapshot,
8162            })
8163        });
8164
8165        self.workflows.insert(
8166            workflow_type,
8167            RegisteredWorkflow {
8168                execute,
8169                replay: Some(replay),
8170                state_type: Some(TypeId::of::<S>()),
8171                definition_fingerprint: None,
8172            },
8173        );
8174    }
8175
8176    /// Register a replayable workflow with one Serde request value and result.
8177    ///
8178    /// Normal task execution and instance-state query replay both decode and
8179    /// encode through the fixed Avro Value codec. The state factory and handler
8180    /// otherwise follow [`Worker::register_replayed_workflow`].
8181    #[track_caller]
8182    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
8183        &mut self,
8184        workflow_type: impl Into<String>,
8185        state_factory: Factory,
8186        handler: F,
8187    ) where
8188        I: DeserializeOwned + Send + 'static,
8189        O: Serialize + Send + 'static,
8190        S: Clone + Send + Sync + 'static,
8191        Factory: Fn() -> S + Send + Sync + 'static,
8192        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
8193        Fut: Future<Output = Result<O>> + Send + 'static,
8194    {
8195        let workflow_type = workflow_type.into();
8196        if !self.admit_registration::<F>(
8197            RegistrationKind::Workflow,
8198            None,
8199            &workflow_type,
8200            "register_typed_replayed_workflow",
8201        ) {
8202            return;
8203        }
8204        let state_factory = Arc::new(state_factory);
8205        let handler = Arc::new(handler);
8206
8207        let execute_name = workflow_type.clone();
8208        let execute_factory = Arc::clone(&state_factory);
8209        let execute_handler = Arc::clone(&handler);
8210        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
8211            let input = decode_workflow_entry::<I>(input, &execute_name)?;
8212            let state = WorkflowInstance::new(execute_factory());
8213            let handler = Arc::clone(&execute_handler);
8214            let handler_name = execute_name.clone();
8215            Ok(Box::pin(async move {
8216                let result = handler(ctx, input, state).await?;
8217                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
8218            }) as WorkflowFuture)
8219        });
8220
8221        let replay_name = workflow_type.clone();
8222        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
8223            let input = decode_workflow_entry::<I>(input, &replay_name)?;
8224            let state = WorkflowInstance::new(state_factory());
8225            let snapshot_state = state.clone();
8226            let snapshot: WorkflowStateSnapshot =
8227                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
8228            let handler = Arc::clone(&handler);
8229            let handler_name = replay_name.clone();
8230            let future = async move {
8231                let result = handler(ctx, input, state).await?;
8232                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
8233            };
8234            Ok(ReplayedWorkflowInvocation {
8235                future: Box::pin(future),
8236                snapshot,
8237            })
8238        });
8239
8240        self.workflows.insert(
8241            workflow_type,
8242            RegisteredWorkflow {
8243                execute,
8244                replay: Some(replay),
8245                state_type: Some(TypeId::of::<S>()),
8246                definition_fingerprint: None,
8247            },
8248        );
8249    }
8250
8251    /// Declare the signal names consumed by a registered workflow.
8252    ///
8253    /// Call this after registering the workflow and before starting the worker.
8254    /// Names read through `wait_signal` or `signals` need a declaration for
8255    /// Server command admission. Arguments remain arbitrary positional values,
8256    /// including lossless Avro values. This replaces the previous declaration;
8257    /// an empty slice declares no signals. Names are sorted and deduplicated.
8258    /// Existing runs retain the declarations captured when they started.
8259    pub fn declare_workflow_signals(
8260        &mut self,
8261        workflow_type: &str,
8262        signal_names: &[&str],
8263    ) -> Result<()> {
8264        if !self.workflows.contains_key(workflow_type) {
8265            return Err(Error::Codec(format!(
8266                "workflow type {workflow_type:?} is not registered"
8267            )));
8268        }
8269        if signal_names
8270            .iter()
8271            .any(|name| name.is_empty() || *name != name.trim())
8272        {
8273            return Err(Error::Codec(
8274                "signal names must be non-empty and have no surrounding whitespace".into(),
8275            ));
8276        }
8277        let mut names = signal_names
8278            .iter()
8279            .map(|name| (*name).to_string())
8280            .collect::<Vec<_>>();
8281        names.sort();
8282        names.dedup();
8283        self.signals.insert(workflow_type.to_string(), names);
8284        Ok(())
8285    }
8286
8287    /// Bind a registered workflow to compile-time embedded source for safe redrive.
8288    ///
8289    /// Supply `include_str!` values for the workflow body and every helper whose
8290    /// behavior can affect replay. Register the workflow once, then set its
8291    /// identity before starting the worker. Duplicate registrations are invalid. The server
8292    /// rejects reusing a worker ID when its prior fingerprint disappears.
8293    /// Workflows without source identity remain runnable but cannot be safely redriven.
8294    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
8295    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
8296    pub fn set_workflow_definition_sources(
8297        &mut self,
8298        workflow_type: &str,
8299        sources: &[&str],
8300    ) -> Result<()> {
8301        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
8302            return Err(Error::Codec(
8303                "workflow definition sources must be non-empty".to_string(),
8304            ));
8305        }
8306        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
8307            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
8308        })?;
8309        let mut hasher = Sha256::new();
8310        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
8311        hasher.update((workflow_type.len() as u64).to_be_bytes());
8312        hasher.update(workflow_type.as_bytes());
8313        for source in sources {
8314            hasher.update((source.len() as u64).to_be_bytes());
8315            hasher.update(source.as_bytes());
8316        }
8317        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
8318        Ok(())
8319    }
8320
8321    /// Register a replayable workflow on the lossless fixed Avro Value surface.
8322    #[track_caller]
8323    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
8324        &mut self,
8325        workflow_type: impl Into<String>,
8326        state_factory: Factory,
8327        handler: F,
8328    ) where
8329        S: Clone + Send + Sync + 'static,
8330        Factory: Fn() -> S + Send + Sync + 'static,
8331        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
8332        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8333    {
8334        let workflow_type = workflow_type.into();
8335        if !self.admit_registration::<F>(
8336            RegistrationKind::Workflow,
8337            None,
8338            &workflow_type,
8339            "register_replayed_workflow_avro_value",
8340        ) {
8341            return;
8342        }
8343        let state_factory = Arc::new(state_factory);
8344        let handler = Arc::new(handler);
8345
8346        let execute_factory = Arc::clone(&state_factory);
8347        let execute_handler = Arc::clone(&handler);
8348        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
8349            let state = WorkflowInstance::new(execute_factory());
8350            Ok(Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture)
8351        });
8352
8353        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
8354            let state = WorkflowInstance::new(state_factory());
8355            let snapshot_state = state.clone();
8356            let snapshot: WorkflowStateSnapshot =
8357                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
8358            Ok(ReplayedWorkflowInvocation {
8359                future: Box::pin(handler(ctx, input, state)),
8360                snapshot,
8361            })
8362        });
8363
8364        self.workflows.insert(
8365            workflow_type,
8366            RegisteredWorkflow {
8367                execute,
8368                replay: Some(replay),
8369                state_type: Some(TypeId::of::<S>()),
8370                definition_fingerprint: None,
8371            },
8372        );
8373    }
8374
8375    #[track_caller]
8376    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
8377    where
8378        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
8379        Fut: Future<Output = Result<Value>> + Send + 'static,
8380    {
8381        let activity_type = activity_type.into();
8382        if !self.admit_registration::<F>(
8383            RegistrationKind::Activity,
8384            None,
8385            &activity_type,
8386            "register_activity",
8387        ) {
8388            return;
8389        }
8390        let handler = Arc::new(handler);
8391        self.activities.insert(
8392            activity_type,
8393            Arc::new(move |ctx, args| {
8394                let handler = Arc::clone(&handler);
8395                Box::pin(async move {
8396                    let result = handler(ctx, args.into_json()?).await?;
8397                    AvroValue::from_serialize(&result)
8398                })
8399            }),
8400        );
8401    }
8402
8403    /// Register an activity with one Serde request value and a Serde result.
8404    ///
8405    /// Inputs and results use the platform's fixed Avro Value schema. Shape
8406    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
8407    /// with the activity name and Rust type.
8408    #[track_caller]
8409    pub fn register_typed_activity<I, O, F, Fut>(
8410        &mut self,
8411        activity_type: impl Into<String>,
8412        handler: F,
8413    ) where
8414        I: DeserializeOwned + Send + 'static,
8415        O: Serialize + Send + 'static,
8416        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
8417        Fut: Future<Output = Result<O>> + Send + 'static,
8418    {
8419        let activity_type = activity_type.into();
8420        if !self.admit_registration::<F>(
8421            RegistrationKind::Activity,
8422            None,
8423            &activity_type,
8424            "register_typed_activity",
8425        ) {
8426            return;
8427        }
8428        let handler_name = activity_type.clone();
8429        let handler = Arc::new(handler);
8430        self.activities.insert(
8431            activity_type,
8432            Arc::new(move |ctx, input| {
8433                let handler = Arc::clone(&handler);
8434                let handler_name = handler_name.clone();
8435                Box::pin(async move {
8436                    let input =
8437                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
8438                    let result = handler(ctx, input).await?;
8439                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
8440                })
8441            }),
8442        );
8443    }
8444
8445    /// Register an activity on the lossless fixed Avro Value surface.
8446    #[track_caller]
8447    pub fn register_activity_avro_value<F, Fut>(
8448        &mut self,
8449        activity_type: impl Into<String>,
8450        handler: F,
8451    ) where
8452        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
8453        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8454    {
8455        let activity_type = activity_type.into();
8456        if !self.admit_registration::<F>(
8457            RegistrationKind::Activity,
8458            None,
8459            &activity_type,
8460            "register_activity_avro_value",
8461        ) {
8462            return;
8463        }
8464        self.activities.insert(
8465            activity_type,
8466            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
8467        );
8468    }
8469
8470    /// Register a named, read-only query handler for a workflow type.
8471    ///
8472    /// The workflow type must also be registered with [`Worker::register_workflow`]
8473    /// before the worker runs. The handler receives only an immutable committed
8474    /// state snapshot and normalized query arguments.
8475    #[track_caller]
8476    pub fn register_query<F, Fut>(
8477        &mut self,
8478        workflow_type: impl Into<String>,
8479        query_name: impl Into<String>,
8480        handler: F,
8481    ) where
8482        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
8483        Fut: Future<Output = Result<Value>> + Send + 'static,
8484    {
8485        let workflow_type = workflow_type.into();
8486        let query_name = query_name.into();
8487        if !self.admit_registration::<F>(
8488            RegistrationKind::Query,
8489            Some(&workflow_type),
8490            &query_name,
8491            "register_query",
8492        ) {
8493            return;
8494        }
8495        let handler = Arc::new(handler);
8496        self.queries.entry(workflow_type).or_default().insert(
8497            query_name,
8498            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
8499                let handler = Arc::clone(&handler);
8500                Box::pin(async move {
8501                    let result = handler(ctx, args.into_json()?).await?;
8502                    AvroValue::from_serialize(&result)
8503                })
8504            })),
8505        );
8506    }
8507
8508    /// Register a query handler on the lossless fixed Avro Value surface.
8509    #[track_caller]
8510    pub fn register_query_avro_value<F, Fut>(
8511        &mut self,
8512        workflow_type: impl Into<String>,
8513        query_name: impl Into<String>,
8514        handler: F,
8515    ) where
8516        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
8517        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8518    {
8519        let workflow_type = workflow_type.into();
8520        let query_name = query_name.into();
8521        if !self.admit_registration::<F>(
8522            RegistrationKind::Query,
8523            Some(&workflow_type),
8524            &query_name,
8525            "register_query_avro_value",
8526        ) {
8527            return;
8528        }
8529        self.queries.entry(workflow_type).or_default().insert(
8530            query_name,
8531            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
8532        );
8533    }
8534
8535    /// Register a named query against deterministically replayed instance state.
8536    ///
8537    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
8538    /// same state type `S`. The handler receives an immutable, detached state
8539    /// clone, so successful and failed queries cannot affect workflow execution
8540    /// or the state reconstructed by a later query.
8541    #[track_caller]
8542    pub fn register_replayed_query<S, F, Fut>(
8543        &mut self,
8544        workflow_type: impl Into<String>,
8545        query_name: impl Into<String>,
8546        handler: F,
8547    ) where
8548        S: Clone + Send + Sync + 'static,
8549        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
8550        Fut: Future<Output = Result<Value>> + Send + 'static,
8551    {
8552        let workflow_type = workflow_type.into();
8553        let query_name = query_name.into();
8554        if !self.admit_registration::<F>(
8555            RegistrationKind::Query,
8556            Some(&workflow_type),
8557            &query_name,
8558            "register_replayed_query",
8559        ) {
8560            return;
8561        }
8562        let handler = Arc::new(handler);
8563        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
8564            let state = state.downcast::<S>().map_err(|_| {
8565                "registered query state type does not match the replayed workflow state".to_string()
8566            })?;
8567            let handler = Arc::clone(&handler);
8568            Ok(Box::pin(async move {
8569                let result = handler(ctx, state, args.into_json()?).await?;
8570                AvroValue::from_serialize(&result)
8571            }))
8572        });
8573
8574        self.queries.entry(workflow_type).or_default().insert(
8575            query_name,
8576            RegisteredQuery::Replayed {
8577                state_type: TypeId::of::<S>(),
8578                handler: erased_handler,
8579            },
8580        );
8581    }
8582
8583    /// Register a replayed-state query on the lossless fixed Avro Value surface.
8584    #[track_caller]
8585    pub fn register_replayed_query_avro_value<S, F, Fut>(
8586        &mut self,
8587        workflow_type: impl Into<String>,
8588        query_name: impl Into<String>,
8589        handler: F,
8590    ) where
8591        S: Clone + Send + Sync + 'static,
8592        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
8593        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8594    {
8595        let workflow_type = workflow_type.into();
8596        let query_name = query_name.into();
8597        if !self.admit_registration::<F>(
8598            RegistrationKind::Query,
8599            Some(&workflow_type),
8600            &query_name,
8601            "register_replayed_query_avro_value",
8602        ) {
8603            return;
8604        }
8605        let handler = Arc::new(handler);
8606        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
8607            let state = state.downcast::<S>().map_err(|_| {
8608                "registered query state type does not match the replayed workflow state".to_string()
8609            })?;
8610            Ok(Box::pin(handler(ctx, state, args)))
8611        });
8612
8613        self.queries.entry(workflow_type).or_default().insert(
8614            query_name,
8615            RegisteredQuery::Replayed {
8616                state_type: TypeId::of::<S>(),
8617                handler: erased_handler,
8618            },
8619        );
8620    }
8621
8622    /// Register a synchronous workflow update handler.
8623    #[track_caller]
8624    pub fn register_update<F, Fut>(
8625        &mut self,
8626        workflow_type: impl Into<String>,
8627        update_name: impl Into<String>,
8628        handler: F,
8629    ) where
8630        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
8631        Fut: Future<Output = Result<Value>> + Send + 'static,
8632    {
8633        let workflow_type = workflow_type.into();
8634        let update_name = update_name.into();
8635        if !self.admit_registration::<F>(
8636            RegistrationKind::Update,
8637            Some(&workflow_type),
8638            &update_name,
8639            "register_update",
8640        ) {
8641            return;
8642        }
8643        let handler = Arc::new(handler);
8644        self.updates.entry(workflow_type).or_default().insert(
8645            update_name,
8646            Arc::new(move |ctx, args| {
8647                let handler = Arc::clone(&handler);
8648                Box::pin(async move {
8649                    let result = handler(ctx, args.into_json()?).await?;
8650                    AvroValue::from_serialize(&result)
8651                })
8652            }),
8653        );
8654    }
8655
8656    /// Register an update handler on the lossless fixed Avro Value surface.
8657    #[track_caller]
8658    pub fn register_update_avro_value<F, Fut>(
8659        &mut self,
8660        workflow_type: impl Into<String>,
8661        update_name: impl Into<String>,
8662        handler: F,
8663    ) where
8664        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
8665        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8666    {
8667        let workflow_type = workflow_type.into();
8668        let update_name = update_name.into();
8669        if !self.admit_registration::<F>(
8670            RegistrationKind::Update,
8671            Some(&workflow_type),
8672            &update_name,
8673            "register_update_avro_value",
8674        ) {
8675            return;
8676        }
8677        self.updates.entry(workflow_type).or_default().insert(
8678            update_name,
8679            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
8680        );
8681    }
8682
8683    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
8684        self.validate_registration()?;
8685        self.nexus_registration_confirmed
8686            .store(false, Ordering::SeqCst);
8687        self.query_authority_confirmed
8688            .store(false, Ordering::SeqCst);
8689        if self.nexus_cooperative_cancellation_enabled {
8690            let info: Value = self
8691                .client
8692                .request_json(
8693                    reqwest::Method::GET,
8694                    "/cluster/info",
8695                    RequestProtocol::Worker("1.20"),
8696                    Option::<&Value>::None,
8697                )
8698                .await?;
8699            if !nexus::installed_cooperation(&info["worker_protocol"]["server_capabilities"]) {
8700                return Err(Error::CooperativeCancellationUnavailable(
8701                    "nexus_cooperative_cancellation_not_supported: Server must advertise the installed workflow_run bridge".into(),
8702                ));
8703            }
8704        }
8705        if self.require_query_task_authority {
8706            if self.client.worker_protocol_version != WorkerProtocolVersion::V120 {
8707                return Err(Error::WorkerLoop(
8708                    "query authority requires worker protocol 1.20".into(),
8709                ));
8710            }
8711            // Discovery uses the Worker credential, including worker-only Clients.
8712            let discovery: Value = self
8713                .client
8714                .request_json_unresolved_with_timeout::<Value, Value>(
8715                    reqwest::Method::GET,
8716                    "/cluster/info",
8717                    RequestProtocol::Worker("1.20"),
8718                    None,
8719                    Duration::from_secs(5),
8720                )
8721                .await?;
8722            if discovery["worker_protocol"]["server_capabilities"]["query_task_authority"] != true {
8723                return Err(Error::WorkerLoop(
8724                    "runtime does not advertise query_task_authority".into(),
8725                ));
8726            }
8727        }
8728        self.sticky_registration_confirmed
8729            .store(false, Ordering::SeqCst);
8730        self.session_registration_confirmed
8731            .store(false, Ordering::SeqCst);
8732        for capability in &self.resource_capabilities {
8733            worker_session::validate_resource_capability(capability)?;
8734        }
8735        self.local_registration_confirmed
8736            .store(false, Ordering::SeqCst);
8737        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
8738            return Err(Error::CooperativeCancellationUnavailable(
8739                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
8740            ));
8741        }
8742        let mut command_contracts = serde_json::Map::new();
8743        for workflow_type in self.workflows.keys() {
8744            let mut queries = self
8745                .queries
8746                .get(workflow_type)
8747                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
8748                .unwrap_or_default();
8749            queries.sort();
8750            let mut updates = self
8751                .updates
8752                .get(workflow_type)
8753                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
8754                .unwrap_or_default();
8755            updates.sort();
8756            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
8757            command_contracts.insert(
8758                workflow_type.clone(),
8759                json!({
8760                    "queries": queries,
8761                    "query_contracts": argument_vector_contracts(&queries),
8762                    "signals": signals,
8763                    "signal_contracts": argument_vector_contracts(&signals),
8764                    "updates": updates,
8765                    "update_contracts": argument_vector_contracts(&updates),
8766                    "update_validators": [],
8767                }),
8768            );
8769        }
8770
8771        self.cooperative_registration_confirmed
8772            .store(false, Ordering::SeqCst);
8773        #[cfg(feature = "telemetry")]
8774        if self
8775            .telemetry
8776            .as_ref()
8777            .is_some_and(telemetry::ExecutionTelemetry::is_enabled)
8778            && !self
8779                .client
8780                .observability_context_supported
8781                .load(Ordering::SeqCst)
8782        {
8783            // Optional startup discovery is bounded and cached. Its failure
8784            // cannot refuse registration or add retries to a business command.
8785            let _ = self
8786                .client
8787                .request_json_unresolved_with_timeout::<Value, Value>(
8788                    reqwest::Method::GET,
8789                    "/cluster/info",
8790                    RequestProtocol::DefaultWorker,
8791                    None,
8792                    Duration::from_secs(5),
8793                )
8794                .await;
8795        }
8796        let response = self
8797            .client
8798            .register_worker_with_definition_fingerprints(
8799                &self.worker_id,
8800                &self.task_queue,
8801                self.workflows.keys().cloned().collect(),
8802                self.activities.keys().cloned().collect(),
8803                self.max_concurrent_workflow_tasks,
8804                self.max_concurrent_activity_tasks,
8805                [
8806                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
8807                    Some("workflow_entry_arguments_validation".to_string()),
8808                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
8809                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
8810                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
8811                    self.client
8812                        .local_activities_enabled
8813                        .then(|| "local_activities".to_string()),
8814                    self.client
8815                        .worker_sessions_enabled
8816                        .then(|| "worker_sessions".to_string()),
8817                    self.client
8818                        .sticky_cache
8819                        .is_some()
8820                        .then(|| "sticky_execution".to_string()),
8821                    self.client
8822                        .sticky_cache
8823                        .is_some()
8824                        .then(|| "sticky_history_suffix".to_string()),
8825                    self.cooperative_cancellation_enabled
8826                        .then(|| "cooperative_cancellation".to_string()),
8827                    self.nexus_cooperative_cancellation_enabled
8828                        .then(|| "nexus_cooperative_cancellation".to_string()),
8829                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
8830                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
8831                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
8832                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
8833                ]
8834                .into_iter()
8835                .flatten()
8836                .chain(self.resource_capabilities.iter().cloned())
8837                .collect(),
8838                Value::Object(command_contracts),
8839                Some(
8840                    self.workflows
8841                        .iter()
8842                        .filter_map(|(workflow_type, workflow)| {
8843                            workflow
8844                                .definition_fingerprint
8845                                .as_ref()
8846                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
8847                        })
8848                        .collect(),
8849                ),
8850            )
8851            .await?;
8852        if self.cooperative_cancellation_enabled && response.registered {
8853            self.cooperative_registration_confirmed
8854                .store(true, Ordering::SeqCst);
8855        }
8856        if self.nexus_cooperative_cancellation_enabled && response.registered {
8857            self.nexus_registration_confirmed
8858                .store(true, Ordering::SeqCst);
8859        }
8860        if self.client.local_activities_enabled && response.registered {
8861            self.local_registration_confirmed
8862                .store(true, Ordering::SeqCst);
8863        }
8864        if self.client.worker_sessions_enabled && response.registered {
8865            self.session_registration_confirmed
8866                .store(true, Ordering::SeqCst);
8867        }
8868        if self.client.sticky_cache.is_some() && response.registered {
8869            self.sticky_registration_confirmed
8870                .store(true, Ordering::SeqCst);
8871        }
8872        self.query_authority_confirmed.store(
8873            response.registered
8874                && self.client.worker_protocol_version == WorkerProtocolVersion::V120
8875                && response
8876                    .server_capabilities
8877                    .as_ref()
8878                    .is_some_and(|capabilities| capabilities["query_task_authority"] == true),
8879            Ordering::SeqCst,
8880        );
8881        Ok(response)
8882    }
8883
8884    /// Run until shutdown or a terminal worker error occurs.
8885    ///
8886    /// Empty long-poll expirations do not stop the worker. Retryable poll and
8887    /// heartbeat failures use [`WorkerRetryPolicy`] independently, while
8888    /// authentication, protocol, and other non-retryable failures are returned.
8889    /// Enable [`Worker::recover_transient_outages`] to keep retrying transient
8890    /// poll and heartbeat outages beyond the ordinary retry budget.
8891    pub async fn run(&self) -> Result<()> {
8892        self.run_until(std::future::pending::<()>()).await
8893    }
8894
8895    /// Run until `shutdown` resolves or a terminal worker error occurs.
8896    ///
8897    /// This has the same liveness and terminal-error contract as [`Worker::run`].
8898    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
8899    where
8900        F: Future<Output = ()>,
8901    {
8902        let _clear_cache_on_drop =
8903            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
8904        let stop = Arc::new(AtomicBool::new(false));
8905        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
8906        let mut worker = self.with_storage_admission(Arc::clone(&stop));
8907        worker.run_stop = Some(Arc::clone(&stop));
8908        let run = worker.run_with_storage_admission(Arc::clone(&stop));
8909        tokio::pin!(run);
8910        tokio::pin!(shutdown);
8911        tokio::select! {
8912            result = &mut run => result,
8913            _ = &mut shutdown => {
8914                stop.store(true, Ordering::SeqCst);
8915                run.await
8916            }
8917        }
8918    }
8919
8920    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
8921        let mut worker = self.clone();
8922        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
8923            policy: self.retry_policy,
8924            stop,
8925            workflow_completion_retry_deadline: None,
8926        });
8927        worker
8928    }
8929
8930    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
8931        let registration = self.register().await?;
8932        if !registration.registered {
8933            return Err(Error::WorkerLoop(format!(
8934                "worker registration for {:?} was not accepted",
8935                self.worker_id
8936            )));
8937        }
8938        let registered_worker_id = registration.worker_id.clone();
8939        let primary = self.run_registered_until(stop, registration).await;
8940        let primary = match (primary, self.close_worker_sessions().await) {
8941            (Ok(()), result) => result,
8942            (Err(error), Ok(())) => Err(error),
8943            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
8944                primary: Box::new(primary),
8945                deregistration: Box::new(close),
8946            }),
8947        };
8948        self.session_registration_confirmed
8949            .store(false, Ordering::SeqCst);
8950        self.cooperative_registration_confirmed
8951            .store(false, Ordering::SeqCst);
8952        self.local_registration_confirmed
8953            .store(false, Ordering::SeqCst);
8954        let deregistration = self
8955            .client
8956            .deregister_worker_registration(&registered_worker_id)
8957            .await;
8958        self.sticky_registration_confirmed
8959            .store(false, Ordering::SeqCst);
8960        self.client.clear_sticky_cache()?;
8961
8962        match (primary, deregistration) {
8963            (Ok(()), Ok(_)) => Ok(()),
8964            (Ok(()), Err(deregistration)) => Err(deregistration),
8965            (Err(primary), Ok(_)) => Err(primary),
8966            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
8967                primary: Box::new(primary),
8968                deregistration: Box::new(deregistration),
8969            }),
8970        }
8971    }
8972
8973    async fn run_registered_until(
8974        &self,
8975        stop: Arc<AtomicBool>,
8976        registration: RegisterWorkerResponse,
8977    ) -> Result<()> {
8978        if self.require_query_task_authority
8979            && !self.query_authority_confirmed.load(Ordering::SeqCst)
8980        {
8981            return Err(Error::WorkerLoop(
8982                "registration did not confirm query_task_authority".into(),
8983            ));
8984        }
8985        let heartbeat_interval = Duration::from_secs(
8986            registration
8987                .heartbeat_interval_seconds
8988                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
8989        );
8990        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
8991        // from the completion of the preceding attempt, including its bounded
8992        // retries. A fixed-epoch interval can leave an already-due tick queued
8993        // while an acknowledgement is slow, producing a catch-up heartbeat as
8994        // soon as that request completes.
8995        let heartbeat = tokio::time::sleep(Duration::ZERO);
8996        tokio::pin!(heartbeat);
8997        // Poll responses may already have leased server-side work by the time
8998        // they become ready, so each poller owns its responses through
8999        // completion or failure instead of racing raw polls in this select.
9000        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
9001            let worker = self.clone();
9002            let stop = Arc::clone(&stop);
9003            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
9004        });
9005        let mut activity_poller = (!self.activities.is_empty()).then(|| {
9006            let worker = self.clone();
9007            let stop = Arc::clone(&stop);
9008            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
9009        });
9010        let mut query_poller = (!self.queries.is_empty()).then(|| {
9011            let worker = self.clone();
9012            let stop = Arc::clone(&stop);
9013            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
9014        });
9015
9016        loop {
9017            tokio::select! {
9018                _ = wait_for_worker_stop(&stop) => {
9019                    stop.store(true, Ordering::SeqCst);
9020                    break;
9021                }
9022                _ = &mut heartbeat => {
9023                    let result = self.retry_worker_operation(|| {
9024                        self.client.heartbeat_worker_with_sessions(
9025                            &self.worker_id,
9026                            self.workflow_capacity.available(),
9027                            self.activity_capacity.available(),
9028                            self.client.worker_sessions_enabled.then(|| self.session_available()),
9029                        )
9030                    }).await;
9031                    heartbeat
9032                        .as_mut()
9033                        .reset(tokio::time::Instant::now() + heartbeat_interval);
9034                    match result {
9035                        Ok(Some(acknowledgement)) => {
9036                            if let Some(observer) = &self.heartbeat_observer {
9037                                observer(&WorkerHeartbeatObservation {
9038                                    worker_id: self.worker_id.clone(),
9039                                    task_queue: self.task_queue.clone(),
9040                                    acknowledged_at_unix_millis: SystemTime::now()
9041                                        .duration_since(UNIX_EPOCH)
9042                                        .unwrap_or_default()
9043                                        .as_millis()
9044                                        .min(u64::MAX as u128)
9045                                        as u64,
9046                                    acknowledgement,
9047                                });
9048                            }
9049                        }
9050                        Ok(None) => break,
9051                        Err(error) => {
9052                            stop.store(true, Ordering::SeqCst);
9053                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
9054                            return Err(error);
9055                        }
9056                    }
9057                }
9058                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
9059                    workflow_poller = None;
9060                    let stopped_by_server = stop.load(Ordering::SeqCst);
9061                    stop.store(true, Ordering::SeqCst);
9062                    let poller_result = optional_poller_result("workflow", result);
9063                    let join_result =
9064                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
9065                    poller_result?;
9066                    join_result?;
9067                    if stopped_by_server {
9068                        return Ok(());
9069                    }
9070                    return Err(Error::WorkerLoop(
9071                        "workflow poller stopped unexpectedly".to_string(),
9072                    ));
9073                }
9074                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
9075                    activity_poller = None;
9076                    let stopped_by_server = stop.load(Ordering::SeqCst);
9077                    stop.store(true, Ordering::SeqCst);
9078                    let poller_result = optional_poller_result("activity", result);
9079                    let join_result =
9080                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
9081                    poller_result?;
9082                    join_result?;
9083                    if stopped_by_server {
9084                        return Ok(());
9085                    }
9086                    return Err(Error::WorkerLoop(
9087                        "activity poller stopped unexpectedly".to_string(),
9088                    ));
9089                }
9090                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
9091                    query_poller = None;
9092                    let stopped_by_server = stop.load(Ordering::SeqCst);
9093                    stop.store(true, Ordering::SeqCst);
9094                    let poller_result = optional_poller_result("query", result);
9095                    let join_result =
9096                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
9097                    poller_result?;
9098                    join_result?;
9099                    if stopped_by_server {
9100                        return Ok(());
9101                    }
9102                    return Err(Error::WorkerLoop(
9103                        "query poller stopped unexpectedly".to_string(),
9104                    ));
9105                }
9106            }
9107        }
9108
9109        join_pollers(
9110            workflow_poller.take(),
9111            activity_poller.take(),
9112            query_poller.take(),
9113        )
9114        .await
9115    }
9116
9117    /// Poll and settle at most one task from each enabled task family.
9118    ///
9119    /// A workflow may reach its server-enforced run deadline while this worker
9120    /// holds a task. When a completion or workflow-task failure endpoint rejects that
9121    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
9122    /// terminal `run_status=failed`, the workflow tick is considered settled:
9123    /// the late command was not recorded and cannot replace the terminal run.
9124    /// A `recorded=false`, `reason=task_not_leased` receipt for the same task,
9125    /// attempt and run settles the tick the same way: this worker no longer
9126    /// holds the task, and the server owns any redelivery.
9127    /// A `recorded=false`, `reason=run_closed` receipt for the same task,
9128    /// attempt and run also settles the tick when it carries the closed run's
9129    /// terminal `run_status`, the matching `stop_reason` and
9130    /// `can_continue=false`, for example after the run was cancelled while the
9131    /// report was in flight.
9132    /// Every other rejection remains an error. This worker-level
9133    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
9134    /// only bounds how long a client waits for a result.
9135    ///
9136    /// Direct callers of [`Client::complete_workflow_task`] and
9137    /// [`Client::fail_workflow_task`] continue to receive the original
9138    /// [`Error::Http`] status and response body.
9139    ///
9140    /// A completion the Server refuses as larger than its aggregate completion
9141    /// limit (native Server 3.6.0: HTTP 413 with
9142    /// `limit_kind: "workflow_task_completion_bytes"`) is never resent. The
9143    /// worker completes the same task once with a non-retryable `fail_workflow`
9144    /// command whose message starts with `Structural limit exceeded:`, so the
9145    /// run fails with failure category `structural_limit`. Direct callers of
9146    /// [`Client::complete_workflow_task`] receive
9147    /// [`Error::WorkflowTaskCompletionTooLarge`] for that refusal.
9148    pub async fn run_once(&self) -> Result<usize> {
9149        self.validate_registration()?;
9150        if self.client.worker_sessions_enabled {
9151            self.require_session_registration()?;
9152        }
9153        if self.cooperative_cancellation_enabled
9154            && !self
9155                .cooperative_registration_confirmed
9156                .load(Ordering::SeqCst)
9157        {
9158            return Err(Error::CooperativeCancellationUnavailable(
9159                "register this cooperative worker before polling tasks".into(),
9160            ));
9161        }
9162        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
9163        let mut handled = 0;
9164        // Keep optional telemetry/cooperative poller state off the caller's
9165        // stack, including callers that await several run_once turns.
9166        match Box::pin(worker.poll_workflow_once()).await? {
9167            ManagedPollOutcome::Handled => handled += 1,
9168            ManagedPollOutcome::Stop => return Ok(handled),
9169            ManagedPollOutcome::Idle => {}
9170        }
9171        match Box::pin(worker.poll_activity_once()).await? {
9172            ManagedPollOutcome::Handled => handled += 1,
9173            ManagedPollOutcome::Stop => return Ok(handled),
9174            ManagedPollOutcome::Idle => {}
9175        }
9176        if !self.queries.is_empty() {
9177            match Box::pin(worker.poll_query_once()).await? {
9178                ManagedPollOutcome::Handled => handled += 1,
9179                ManagedPollOutcome::Stop => return Ok(handled),
9180                ManagedPollOutcome::Idle => {}
9181            }
9182        }
9183        Ok(handled)
9184    }
9185
9186    async fn poll_workflow_once_reserved(&self) -> Result<ManagedPollOutcome> {
9187        if self.client.sticky_cache.is_some()
9188            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
9189        {
9190            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
9191        }
9192        if self.client.local_activities_enabled
9193            && !self.local_registration_confirmed.load(Ordering::SeqCst)
9194        {
9195            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
9196        }
9197        if self.cooperative_cancellation_enabled {
9198            return self.poll_cooperative_workflow_once().await;
9199        }
9200        let mut poll_metrics = self.metrics.worker(false, "workflow", &self.task_queue);
9201        let poll_request_id = unique_request_id("rust-workflow-poll");
9202        let response = self
9203            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
9204            .await;
9205        poll_metrics.poll(&response, |value| value.0.outcome());
9206        drop(poll_metrics);
9207        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
9208            return Ok(ManagedPollOutcome::Idle);
9209        };
9210        if response.outcome().should_stop() {
9211            return Ok(ManagedPollOutcome::Stop);
9212        }
9213        let memo_updates_supported =
9214            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
9215        let Some(task) = response.task else {
9216            return Ok(ManagedPollOutcome::Idle);
9217        };
9218
9219        self.client.release_worker_poll();
9220
9221        let mut task_metrics = self.metrics.worker(true, "workflow", &self.task_queue);
9222        task_metrics.outcome("failed");
9223        let task_id = task.task_id.clone();
9224        let attempt = task.workflow_task_attempt;
9225        let run_id = task.run_id.clone();
9226        let lease_owner = task
9227            .lease_owner
9228            .clone()
9229            .unwrap_or_else(|| self.worker_id.clone());
9230
9231        let decision = match self.execute_workflow_with_local_activities(task).await {
9232            Ok(Some(decision)) => Ok(decision),
9233            Ok(None) => {
9234                task_metrics.outcome("expired");
9235                return Ok(ManagedPollOutcome::Handled);
9236            }
9237            Err(error) => Err(error),
9238        };
9239        let task_outcome = metrics::workflow_task_outcome(decision.as_ref().ok());
9240        let settled = self
9241            .settle_workflow_task_decision(
9242                &task_id,
9243                &lease_owner,
9244                attempt,
9245                run_id.as_deref(),
9246                decision,
9247                memo_updates_supported,
9248                snapshot,
9249            )
9250            .await;
9251        if settled.is_ok() {
9252            task_metrics.outcome(task_outcome);
9253        }
9254        settled
9255    }
9256
9257    /// Answer a typed oversized-completion refusal (Server 3.6.0
9258    /// `workflow_task_completion_bytes`) without resending the completion:
9259    /// complete the same task once with a non-retryable structural-limit
9260    /// `fail_workflow` command. A failed task would be retried into the same
9261    /// refusal, or park the run. If this small completion is not recorded
9262    /// either, the original refusal is returned (or the report's settled
9263    /// receipt), and nothing is resent.
9264    async fn fail_oversized_workflow_task(
9265        &self,
9266        task_id: &str,
9267        lease_owner: &str,
9268        attempt: u64,
9269        run_id: Option<&str>,
9270        refusal: WorkflowTaskCompletionTooLarge,
9271    ) -> Result<Value> {
9272        let error = Error::WorkflowTaskCompletionTooLarge(refusal);
9273        tracing::warn!(
9274            target: "durable_workflow::worker",
9275            task_id,
9276            workflow_task_attempt = attempt,
9277            run_id,
9278            error = %error,
9279            "the Server refused the workflow task completion as too large; failing the run with a structural-limit failure"
9280        );
9281        let command = workflow_failure_command(&error, None);
9282        match self
9283            .client
9284            .complete_workflow_task(task_id, lease_owner, attempt, vec![command])
9285            .await
9286        {
9287            Ok(receipt) => Ok(receipt),
9288            Err(report) if workflow_task_report_is_settled(&report, task_id, attempt, run_id) => {
9289                Err(report)
9290            }
9291            Err(report) => {
9292                tracing::warn!(
9293                    target: "durable_workflow::worker",
9294                    task_id,
9295                    workflow_task_attempt = attempt,
9296                    run_id,
9297                    error = %report,
9298                    "the structural-limit workflow failure was not recorded"
9299                );
9300                Err(error)
9301            }
9302        }
9303    }
9304
9305    #[allow(clippy::too_many_arguments)]
9306    async fn settle_workflow_task_decision(
9307        &self,
9308        task_id: &str,
9309        lease_owner: &str,
9310        attempt: u64,
9311        run_id: Option<&str>,
9312        decision: Result<WorkflowTaskDecision>,
9313        memo_updates_supported: bool,
9314        snapshot: Option<sticky_worker::StickySnapshot>,
9315    ) -> Result<ManagedPollOutcome> {
9316        let reported = match decision {
9317            Ok(decision)
9318                if decision.cancellation_delivery.is_some()
9319                    || decision.cancellation_scope_delivery.is_some()
9320                    || decision.cancellation_scope_opening.is_some() =>
9321            {
9322                return Err(Error::CooperativeCancellationUnavailable(
9323                    "worker cancellation delivery has not been negotiated".into(),
9324                ));
9325            }
9326            Ok(decision)
9327                if commands_use_workflow_memo_updates(&decision.commands)
9328                    && !memo_updates_supported =>
9329            {
9330                self.client
9331                    .fail_workflow_task(
9332                        task_id,
9333                        lease_owner,
9334                        attempt,
9335                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
9336                    )
9337                    .await
9338            }
9339            Ok(decision) if decision.commands.is_empty() => {
9340                // A replay can consume a recorded pending durable command
9341                // without producing a new command. The standalone protocol
9342                // acknowledges that state through the typed waiting outcome;
9343                // an empty completion is rejected by servers that require at
9344                // least one executable command.
9345                self.client
9346                    .fail_workflow_task_with_type(
9347                        task_id,
9348                        lease_owner,
9349                        attempt,
9350                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
9351                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
9352                    )
9353                    .await
9354            }
9355            Ok(decision) => {
9356                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
9357                match self
9358                    .client
9359                    .complete_workflow_task_with_message_streams(
9360                        task_id,
9361                        lease_owner,
9362                        attempt,
9363                        decision.commands,
9364                        decision.message_stream_cursors,
9365                        decision.message_stream_waits,
9366                        sticky_claim,
9367                    )
9368                    .await
9369                {
9370                    Err(Error::WorkflowTaskCompletionTooLarge(refusal)) => {
9371                        // The refused commands were never recorded.
9372                        self.discard_sticky_snapshot(snapshot.as_ref())?;
9373                        self.fail_oversized_workflow_task(
9374                            task_id,
9375                            lease_owner,
9376                            attempt,
9377                            run_id,
9378                            refusal,
9379                        )
9380                        .await
9381                    }
9382                    reported => reported,
9383                }
9384            }
9385            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
9386            Err(error @ Error::FailureReporting(_)) => {
9387                self.discard_sticky_snapshot(snapshot.as_ref())?;
9388                return Err(error);
9389            }
9390            Err(error) => {
9391                self.discard_sticky_snapshot(snapshot.as_ref())?;
9392                if matches!(
9393                    error,
9394                    Error::HandlerType {
9395                        handler_kind: HandlerKind::Workflow,
9396                        value_kind: HandlerValueKind::Input,
9397                        ..
9398                    }
9399                ) {
9400                    self.client
9401                        .fail_workflow_task_with_failure(
9402                            task_id,
9403                            lease_owner,
9404                            attempt,
9405                            json!({
9406                                "message": error.to_string(),
9407                                "type": "WorkflowEntryArgumentsMismatch",
9408                                "reason": "workflow_entry_arguments_mismatch",
9409                            }),
9410                        )
9411                        .await
9412                } else {
9413                    self.client
9414                        .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
9415                        .await
9416                }
9417            }
9418        };
9419
9420        // A run may expire or close, or the task may be reclaimed, while a
9421        // completion or failure report is in flight. Settle only the matching
9422        // task's non-recorded receipt.
9423        if let Err(error) = reported {
9424            self.discard_sticky_snapshot(snapshot.as_ref())?;
9425            if !workflow_task_report_is_settled(&error, task_id, attempt, run_id) {
9426                return Err(error);
9427            }
9428            #[cfg(feature = "telemetry")]
9429            tracing::debug!(
9430                task_id,
9431                workflow_task_attempt = attempt,
9432                run_id,
9433                error = %error,
9434                "settled a non-recorded workflow-task receipt"
9435            );
9436        }
9437
9438        Ok(ManagedPollOutcome::Handled)
9439    }
9440
9441    async fn poll_activity_once_reserved(&self) -> Result<ManagedPollOutcome> {
9442        if self.client.worker_sessions_enabled {
9443            self.require_session_registration()?;
9444        }
9445        let mut poll_metrics = self.metrics.worker(false, "activity", &self.task_queue);
9446        let poll_request_id = unique_request_id("rust-activity-poll");
9447        let response = self
9448            .retry_worker_operation(|| {
9449                self.client.poll_activity_task_response_with_request_id(
9450                    &self.worker_id,
9451                    &self.task_queue,
9452                    self.poll_timeout,
9453                    &poll_request_id,
9454                    0,
9455                )
9456            })
9457            .await;
9458        poll_metrics.poll(&response, |value| value.outcome());
9459        drop(poll_metrics);
9460        let response = match response {
9461            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
9462            response => response,
9463        };
9464        let Some(response) = self.settle_worker_poll_response(response).await? else {
9465            return Ok(ManagedPollOutcome::Idle);
9466        };
9467        if response.outcome().should_stop() {
9468            return Ok(ManagedPollOutcome::Stop);
9469        }
9470        let Some(task) = response.task else {
9471            return Ok(ManagedPollOutcome::Idle);
9472        };
9473
9474        self.client.release_worker_poll();
9475        self.settle_polled_activity(task).await
9476    }
9477
9478    async fn settle_polled_activity(
9479        &self,
9480        task: worker_session::SessionActivityTask,
9481    ) -> Result<ManagedPollOutcome> {
9482        let mut task_metrics = self.metrics.worker(true, "activity", &self.task_queue);
9483        task_metrics.outcome("failed");
9484        let lease = task.activity_lease.clone();
9485        let mut worker = self.clone();
9486        worker.client = self.client.with_activity_lease_authority(
9487            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
9488        );
9489        let operation = worker.execute_polled_activity(task, &mut task_metrics);
9490        let result = match lease.as_ref() {
9491            Some(lease) => lease.authority.protect(operation).await,
9492            None => operation.await,
9493        };
9494        match result {
9495            Err(Error::ActivityExecutionAbandoned(_)) => {
9496                task_metrics.outcome("expired");
9497                Ok(ManagedPollOutcome::Handled)
9498            }
9499            result => result,
9500        }
9501    }
9502
9503    async fn execute_polled_activity(
9504        &self,
9505        task: worker_session::SessionActivityTask,
9506        task_metrics: &mut metrics::WorkerObservation,
9507    ) -> Result<ManagedPollOutcome> {
9508        if self.cooperative_cancellation_enabled {
9509            return self.settle_cooperative_activity(task, task_metrics).await;
9510        }
9511        let session = self.track_session_task(task.worker_session.as_ref())?;
9512        let invocation = task.invocation(session);
9513        let task = task.task;
9514
9515        let task_id = task.task_id.clone();
9516        let attempt_id = task
9517            .activity_attempt_id
9518            .clone()
9519            .or(task.attempt_id.clone())
9520            .unwrap_or_default();
9521        let lease_owner = task
9522            .lease_owner
9523            .clone()
9524            .unwrap_or_else(|| self.worker_id.clone());
9525        let codec = task.payload_codec.clone();
9526        let result = self.execute_session_activity_task(task, invocation).await;
9527        let task_outcome = if result.is_ok() {
9528            "completed"
9529        } else if matches!(result, Err(Error::ActivityExecutionAbandoned(_))) {
9530            "expired"
9531        } else {
9532            "failed"
9533        };
9534        match result {
9535            Err(Error::ActivityExecutionAbandoned(_)) => {}
9536            Err(error) if activity_hydration::stopped(&error) => {}
9537            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
9538            Ok(value) => {
9539                let completion = self
9540                    .client
9541                    .complete_activity_task(&task_id, &attempt_id, &lease_owner, value, &codec)
9542                    .await;
9543                if let Err(error) = completion {
9544                    if !activity_task_rejection_is_final(&error) {
9545                        return Err(error);
9546                    }
9547                }
9548            }
9549            Err(error) => {
9550                let failure = self
9551                    .client
9552                    .fail_activity_task_with_error(
9553                        &task_id,
9554                        &attempt_id,
9555                        &lease_owner,
9556                        &ActivityError::from_error(&error, "RustActivityFailure"),
9557                    )
9558                    .await;
9559                if let Err(error) = failure {
9560                    if !activity_task_rejection_is_final(&error) {
9561                        return Err(error);
9562                    }
9563                }
9564            }
9565        }
9566
9567        task_metrics.outcome(task_outcome);
9568        Ok(ManagedPollOutcome::Handled)
9569    }
9570
9571    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
9572        let mut poll_metrics = self.metrics.worker(false, "query", &self.task_queue);
9573        let poll_request_id = unique_request_id("rust-query-poll");
9574        let response = self
9575            .retry_worker_operation(|| {
9576                let body = json!({"worker_id":self.worker_id,"task_queue":self.task_queue,
9577                    "poll_request_id":poll_request_id,
9578                    "timeout_seconds":long_poll_timeout_seconds(self.poll_timeout)});
9579                async move {
9580                    self.client
9581                        .poll_request_json_unresolved::<Value, Value>(
9582                            "/worker/query-tasks/poll",
9583                            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
9584                            &body,
9585                            self.poll_timeout + Duration::from_secs(5),
9586                            0,
9587                        )
9588                        .await
9589                }
9590            })
9591            .await;
9592        poll_metrics.poll(&response, |value| {
9593            worker_poll_outcome(
9594                value.get("task").is_some_and(|task| !task.is_null()),
9595                value.get("poll_status").and_then(Value::as_str),
9596                value.get("reason").and_then(Value::as_str),
9597            )
9598        });
9599        drop(poll_metrics);
9600        let Some(mut wire) = self.settle_worker_poll_response(response).await? else {
9601            return Ok(ManagedPollOutcome::Idle);
9602        };
9603        let authority = if wire.get("task").is_some_and(|task| !task.is_null()) {
9604            match query_authority::Authority::capture(&wire["task"], self) {
9605                Ok(authority) => authority,
9606                Err(_) => return Ok(ManagedPollOutcome::Handled),
9607            }
9608        } else {
9609            None
9610        };
9611        let loading = self.client.resolve_runtime_payloads(
9612            &mut wire,
9613            "/worker/query-tasks/poll",
9614            RequestProtocol::Worker(self.client.worker_protocol_version.as_str()),
9615        );
9616        match query_authority::Authority::protect(authority.as_ref(), self, loading).await {
9617            Err(_) => return Ok(ManagedPollOutcome::Handled),
9618            Ok(result) => result?,
9619        }
9620        let response: PollQueryTaskResponse = serde_json::from_value(wire)?;
9621        if response.outcome().should_stop() {
9622            return Ok(ManagedPollOutcome::Stop);
9623        }
9624        let Some(task) = response.task else {
9625            return Ok(ManagedPollOutcome::Idle);
9626        };
9627
9628        let mut task_metrics = self.metrics.worker(true, "query", &self.task_queue);
9629        task_metrics.outcome("failed");
9630        let query_task_id = task.query_task_id.clone();
9631        let attempt = task.query_task_attempt;
9632        let lease_owner = task
9633            .lease_owner
9634            .clone()
9635            .unwrap_or_else(|| self.worker_id.clone());
9636        let codec = task.payload_codec.clone();
9637
9638        let execution = query_authority::Authority::protect(
9639            authority.as_ref(),
9640            self,
9641            self.execute_query_task_with_authority(task, authority.as_ref()),
9642        )
9643        .await;
9644        let execution = match execution {
9645            Err(_) => return Ok(ManagedPollOutcome::Handled),
9646            Ok(Err(failure)) if failure.reason == "query_authority_lost" => {
9647                return Ok(ManagedPollOutcome::Handled)
9648            }
9649            Ok(result) => result,
9650        };
9651        let task_outcome = if execution.is_ok() {
9652            "completed"
9653        } else {
9654            "failed"
9655        };
9656        match execution {
9657            Ok(value) => {
9658                let result_envelope = match encode_typed_envelope(&value, &codec) {
9659                    Ok(result_envelope) => result_envelope,
9660                    Err(error) => {
9661                        let failure = query_authority::Authority::protect(
9662                            authority.as_ref(),
9663                            self,
9664                            self.client.fail_query_task(
9665                                &query_task_id,
9666                                &lease_owner,
9667                                attempt,
9668                                error.to_string(),
9669                                "query_result_encode_failed",
9670                                "QueryResultEncodeFailed",
9671                            ),
9672                        )
9673                        .await;
9674                        let Ok(failure) = failure else {
9675                            return Ok(ManagedPollOutcome::Handled);
9676                        };
9677                        if let Err(error) = failure {
9678                            if !query_task_rejection_is_final(&error) {
9679                                return Err(error);
9680                            }
9681                        }
9682                        return Ok(ManagedPollOutcome::Handled);
9683                    }
9684                };
9685
9686                let completion = query_authority::Authority::protect(
9687                    authority.as_ref(),
9688                    self,
9689                    self.client.complete_query_task_with_envelope(
9690                        &query_task_id,
9691                        &lease_owner,
9692                        attempt,
9693                        value.clone().into_json()?,
9694                        result_envelope,
9695                    ),
9696                )
9697                .await;
9698                let Ok(completion) = completion else {
9699                    return Ok(ManagedPollOutcome::Handled);
9700                };
9701                if let Err(error) = completion {
9702                    if !query_task_rejection_is_final(&error) {
9703                        return Err(error);
9704                    }
9705                }
9706            }
9707            Err(failure) => {
9708                let result = query_authority::Authority::protect(
9709                    authority.as_ref(),
9710                    self,
9711                    self.client.fail_query_task(
9712                        &query_task_id,
9713                        &lease_owner,
9714                        attempt,
9715                        failure.message,
9716                        failure.reason,
9717                        failure.failure_type,
9718                    ),
9719                )
9720                .await;
9721                let Ok(result) = result else {
9722                    return Ok(ManagedPollOutcome::Handled);
9723                };
9724                if let Err(error) = result {
9725                    if !query_task_rejection_is_final(&error) {
9726                        return Err(error);
9727                    }
9728                }
9729            }
9730        }
9731
9732        task_metrics.outcome(task_outcome);
9733        Ok(ManagedPollOutcome::Handled)
9734    }
9735
9736    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
9737        while !stop.load(Ordering::SeqCst) {
9738            match self.poll_query_once().await {
9739                Ok(ManagedPollOutcome::Stop) => {
9740                    stop.store(true, Ordering::SeqCst);
9741                    break;
9742                }
9743                Err(error) => {
9744                    stop.store(true, Ordering::SeqCst);
9745                    return Err(error);
9746                }
9747                _ => {}
9748            }
9749        }
9750
9751        Ok(())
9752    }
9753
9754    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
9755    where
9756        F: FnMut() -> Fut,
9757        Fut: Future<Output = Result<T>>,
9758    {
9759        let mut retries = 0;
9760
9761        loop {
9762            if self
9763                .run_stop
9764                .as_ref()
9765                .is_some_and(|stop| stop.load(Ordering::SeqCst))
9766            {
9767                return Ok(None);
9768            }
9769            match operation().await {
9770                Err(error)
9771                    if (workflow_hydration::stopped(&error)
9772                        || activity_hydration::stopped(&error))
9773                        && self
9774                            .run_stop
9775                            .as_ref()
9776                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
9777                {
9778                    return Ok(None);
9779                }
9780                Err(error)
9781                    if worker_operation_is_retryable(&error)
9782                        && (retries < self.retry_policy.max_retries
9783                            || (self.recover_transient_outages
9784                                && self.run_stop.is_some()
9785                                && self.retry_policy.max_retries > 0)) =>
9786                {
9787                    retries = retries.saturating_add(1);
9788                    let delay = worker_retry_delay(self.retry_policy, retries)
9789                        .max(Duration::from_millis(1));
9790                    if let Some(stop) = &self.run_stop {
9791                        tokio::select! {
9792                            _ = tokio::time::sleep(delay) => {}
9793                            _ = wait_for_worker_stop(stop) => return Ok(None),
9794                        }
9795                    } else {
9796                        tokio::time::sleep(delay).await;
9797                    }
9798                }
9799                result => return result.map(Some),
9800            }
9801        }
9802    }
9803
9804    async fn settle_worker_poll_response<T>(
9805        &self,
9806        response: Result<Option<T>>,
9807    ) -> Result<Option<T>> {
9808        match response {
9809            Ok(response) => Ok(response),
9810            Err(error) => {
9811                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
9812                    return Err(error);
9813                };
9814                let minimum_delay = self
9815                    .retry_policy
9816                    .initial_backoff
9817                    .max(Duration::from_millis(1));
9818                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
9819                let delay = advertised_delay.max(minimum_delay).min(maximum_delay);
9820                if let Some(stop) = &self.run_stop {
9821                    tokio::select! {
9822                        biased;
9823                        _ = wait_for_worker_stop(stop) => {},
9824                        _ = tokio::time::sleep(delay) => {},
9825                    }
9826                } else {
9827                    tokio::time::sleep(delay).await;
9828                }
9829                Ok(None)
9830            }
9831        }
9832    }
9833
9834    #[cfg(test)]
9835    async fn execute_query_task(
9836        &self,
9837        task: QueryTask,
9838    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9839        self.execute_query_task_with_authority(task, None).await
9840    }
9841
9842    async fn execute_query_task_with_authority(
9843        &self,
9844        task: QueryTask,
9845        authority: Option<&query_authority::Authority>,
9846    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9847        #[cfg(feature = "telemetry")]
9848        if let Some(telemetry) = &self.telemetry {
9849            return telemetry
9850                .run_observed(
9851                    "durable.query.task",
9852                    self.query_telemetry_fields(&task),
9853                    false,
9854                    authority.and_then(|_| self.query_observations(&task)),
9855                    self.execute_query_task_inner(task, authority),
9856                )
9857                .await;
9858        }
9859        self.execute_query_task_inner(task, authority).await
9860    }
9861
9862    async fn execute_query_task_inner(
9863        &self,
9864        mut task: QueryTask,
9865        authority: Option<&query_authority::Authority>,
9866    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
9867        validate_query_task_payloads(&task).map_err(|error| {
9868            QueryTaskExecutionFailure::new(
9869                "query_payload_decode_failed",
9870                error.to_string(),
9871                "QueryPayloadDecodeFailed",
9872            )
9873        })?;
9874
9875        if !self.workflows.contains_key(&task.workflow_type) {
9876            return Err(QueryTaskExecutionFailure::new(
9877                "query_workflow_type_not_registered",
9878                format!("no workflow registered for type {:?}", task.workflow_type),
9879                "WorkflowTypeNotRegistered",
9880            ));
9881        }
9882
9883        let Some(handlers) = self.queries.get(&task.workflow_type) else {
9884            return Err(QueryTaskExecutionFailure::new(
9885                "query_handler_unavailable",
9886                format!(
9887                    "query handlers are unavailable for workflow type {:?}",
9888                    task.workflow_type
9889                ),
9890                "QueryHandlerUnavailable",
9891            ));
9892        };
9893        let Some(query) = handlers.get(&task.query_name) else {
9894            return Err(QueryTaskExecutionFailure::new(
9895                "rejected_unknown_query",
9896                format!("unknown query {:?}", task.query_name),
9897                "QueryFailed",
9898            ));
9899        };
9900
9901        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
9902            .map_err(|error| {
9903            QueryTaskExecutionFailure::new(
9904                "query_payload_decode_failed",
9905                format!("cannot decode query arguments: {error}"),
9906                "QueryPayloadDecodeFailed",
9907            )
9908        })?;
9909        let workflow_input_typed =
9910            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
9911                .map_err(|error| {
9912                    QueryTaskExecutionFailure::new(
9913                        "query_workflow_state_unavailable",
9914                        format!("cannot decode workflow start input: {error}"),
9915                        "QueryWorkflowStateUnavailable",
9916                    )
9917                })?;
9918        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
9919            QueryTaskExecutionFailure::new(
9920                "query_workflow_state_unavailable",
9921                format!("cannot project workflow start input: {error}"),
9922                "QueryWorkflowStateUnavailable",
9923            )
9924        })?;
9925        hydrate_query_history_from_export(&mut task).map_err(|error| {
9926            QueryTaskExecutionFailure::new(
9927                "query_workflow_state_unavailable",
9928                format!("cannot restore query history snapshot: {error}"),
9929                "QueryWorkflowStateUnavailable",
9930            )
9931        })?;
9932        enrich_query_history_from_export(&mut task).map_err(|error| {
9933            QueryTaskExecutionFailure::new(
9934                "query_workflow_state_unavailable",
9935                format!("cannot restore compact query history payloads: {error}"),
9936                "QueryWorkflowStateUnavailable",
9937            )
9938        })?;
9939        let signal_events = query_signal_events(&task).map_err(|error| {
9940            QueryTaskExecutionFailure::new(
9941                "query_workflow_state_unavailable",
9942                format!("cannot decode committed workflow signals: {error}"),
9943                "QueryWorkflowStateUnavailable",
9944            )
9945        })?;
9946        let history_events = Arc::new(std::mem::take(&mut task.history_events));
9947        let mut context = QueryContext {
9948            workflow_id: task.workflow_id,
9949            run_id: task.run_id,
9950            workflow_type: task.workflow_type.clone(),
9951            run_status: task.run_status,
9952            workflow_input,
9953            workflow_input_avro_value: workflow_input_typed.clone(),
9954            replay_time: replay_clock::snapshot_time(&history_events, &task.payload_codec),
9955            history_events: Arc::clone(&history_events),
9956            signal_events: Arc::new(signal_events),
9957        };
9958
9959        let future = match query {
9960            RegisteredQuery::Snapshot(handler) => {
9961                query_authority::before_handler(authority, &self.client).await?;
9962                handler(context, args)
9963            }
9964            RegisteredQuery::Replayed {
9965                state_type,
9966                handler,
9967            } => {
9968                let workflow = self
9969                    .workflows
9970                    .get(&task.workflow_type)
9971                    .expect("workflow registration was checked above");
9972                if workflow.state_type != Some(*state_type) {
9973                    return Err(QueryTaskExecutionFailure::new(
9974                        "query_workflow_state_unavailable",
9975                        "replayed query state type does not match its workflow registration",
9976                        "QueryWorkflowStateUnavailable",
9977                    ));
9978                }
9979                let replay = workflow.replay.as_ref().ok_or_else(|| {
9980                    QueryTaskExecutionFailure::new(
9981                        "query_workflow_state_unavailable",
9982                        format!(
9983                            "workflow type {:?} is not registered for instance-state replay",
9984                            task.workflow_type
9985                        ),
9986                        "QueryWorkflowStateUnavailable",
9987                    )
9988                })?;
9989                let workflow_state = Arc::new(Mutex::new(
9990                    WorkflowState::new_with_identity(
9991                        history_events.as_ref().clone(),
9992                        context.workflow_id.clone(),
9993                        context.run_id.clone(),
9994                        self.task_queue.clone(),
9995                        task.payload_codec,
9996                        None,
9997                    )
9998                    .map_err(|error| {
9999                        QueryTaskExecutionFailure::new(
10000                            "query_workflow_state_unavailable",
10001                            format!("workflow replay failed before query: {error}"),
10002                            "QueryWorkflowStateUnavailable",
10003                        )
10004                    })?,
10005                ));
10006                let workflow_context = WorkflowContext {
10007                    state: workflow_state,
10008                    cancellation_scope_id: "root".into(),
10009                };
10010                query_authority::before_handler(authority, &self.client).await?;
10011                let mut invocation = {
10012                    let _clock = replay_clock::Guard::query(&workflow_context);
10013                    replay(workflow_context.clone(), workflow_input_typed.clone())
10014                }
10015                .map_err(|error| {
10016                    QueryTaskExecutionFailure::new(
10017                        "query_workflow_state_unavailable",
10018                        error.to_string(),
10019                        "QueryWorkflowStateUnavailable",
10020                    )
10021                })?;
10022                let outcome = {
10023                    let mut cx = TaskContext::from_waker(noop_waker_ref());
10024                    let _clock = replay_clock::Guard::query(&workflow_context);
10025                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
10026                        .map_err(|error| {
10027                            QueryTaskExecutionFailure::new(
10028                                "query_workflow_state_unavailable",
10029                                error.to_string(),
10030                                "QueryWorkflowStateUnavailable",
10031                            )
10032                        })?;
10033                    invocation.future.as_mut().poll(&mut cx)
10034                };
10035                match outcome {
10036                    Poll::Ready(Ok(_)) => {
10037                        workflow_context
10038                            .ensure_history_consumed()
10039                            .map_err(|error| {
10040                                QueryTaskExecutionFailure::new(
10041                                    "query_workflow_state_unavailable",
10042                                    format!("workflow replay failed before query: {error}"),
10043                                    "QueryWorkflowStateUnavailable",
10044                                )
10045                            })?;
10046                    }
10047                    Poll::Ready(Err(error)) => {
10048                        return Err(QueryTaskExecutionFailure::new(
10049                            "query_workflow_state_unavailable",
10050                            format!("workflow replay failed before query: {error}"),
10051                            "QueryWorkflowStateUnavailable",
10052                        ));
10053                    }
10054                    Poll::Pending => {
10055                        let commands = workflow_context.take_commands().map_err(|error| {
10056                            QueryTaskExecutionFailure::new(
10057                                "query_workflow_state_unavailable",
10058                                format!("workflow replay failed before query: {error}"),
10059                                "QueryWorkflowStateUnavailable",
10060                            )
10061                        })?;
10062                        if commands.is_empty()
10063                            && !workflow_context
10064                                .matched_recorded_pending()
10065                                .map_err(|error| {
10066                                    QueryTaskExecutionFailure::new(
10067                                        "query_workflow_state_unavailable",
10068                                        format!("workflow replay failed before query: {error}"),
10069                                        "QueryWorkflowStateUnavailable",
10070                                    )
10071                                })?
10072                        {
10073                            return Err(QueryTaskExecutionFailure::new(
10074                                "query_workflow_state_unavailable",
10075                                "workflow replay yielded without a durable command",
10076                                "QueryWorkflowStateUnavailable",
10077                            ));
10078                        }
10079                    }
10080                }
10081                let state = (invocation.snapshot)().map_err(|error| {
10082                    QueryTaskExecutionFailure::new(
10083                        "query_workflow_state_unavailable",
10084                        format!("cannot snapshot replayed workflow state: {error}"),
10085                        "QueryWorkflowStateUnavailable",
10086                    )
10087                })?;
10088                query_authority::before_handler(authority, &self.client).await?;
10089                context.replay_time = workflow_context
10090                    .state
10091                    .lock()
10092                    .map_err(|_| {
10093                        QueryTaskExecutionFailure::new(
10094                            "query_workflow_state_unavailable",
10095                            "workflow state poisoned",
10096                            "QueryWorkflowStateUnavailable",
10097                        )
10098                    })?
10099                    .replay_time()
10100                    .ok();
10101                handler(context, state, args).map_err(|message| {
10102                    QueryTaskExecutionFailure::new(
10103                        "query_workflow_state_unavailable",
10104                        message,
10105                        "QueryWorkflowStateUnavailable",
10106                    )
10107                })?
10108            }
10109        };
10110
10111        future.await.map_err(|error| {
10112            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
10113        })
10114    }
10115
10116    #[cfg(test)]
10117    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
10118        Ok(self.execute_workflow_task_decision(task)?.commands)
10119    }
10120
10121    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
10122        self.execute_workflow_task_decision_with_cancellation(task, None)
10123    }
10124
10125    fn execute_workflow_task_decision_with_cancellation(
10126        &self,
10127        task: WorkflowTask,
10128        observation: Option<&CancellationRequest>,
10129    ) -> Result<WorkflowTaskDecision> {
10130        #[cfg(feature = "telemetry")]
10131        if let Some(telemetry) = &self.telemetry {
10132            return telemetry.run_sync_observed(
10133                "durable.workflow.task",
10134                self.workflow_telemetry_fields(&task),
10135                self.workflow_observations(&task),
10136                || {
10137                    let mut decision =
10138                        self.execute_workflow_task_decision_inner(task, observation)?;
10139                    self.stamp_observability_commands(&mut decision.commands);
10140                    Ok(decision)
10141                },
10142            );
10143        }
10144        self.execute_workflow_task_decision_inner(task, observation)
10145    }
10146
10147    fn execute_workflow_task_decision_inner(
10148        &self,
10149        task: WorkflowTask,
10150        observation: Option<&CancellationRequest>,
10151    ) -> Result<WorkflowTaskDecision> {
10152        match self.prepare_workflow_task_execution(task, observation)? {
10153            PreparedWorkflowTask::Decision(decision) => Ok(decision),
10154            PreparedWorkflowTask::Execution {
10155                task,
10156                context,
10157                mut future,
10158            } => {
10159                let outcome = Self::poll_workflow_future(&context, &mut future)?;
10160                self.finish_workflow_task_execution(&task, &context, outcome)
10161            }
10162        }
10163    }
10164
10165    fn prepare_workflow_task_execution(
10166        &self,
10167        task: WorkflowTask,
10168        observation: Option<&CancellationRequest>,
10169    ) -> Result<PreparedWorkflowTask> {
10170        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
10171            && !self.cooperative_cancellation_enabled
10172        {
10173            return Err(Error::CancellationScopeExecutionUnavailable);
10174        }
10175        validate_workflow_task_payloads(&task)?;
10176        cooperative_cancellation::assert_cancellation_scope_replay_supported(
10177            &task.history_events,
10178            self.allow_cancellation_scope_authoring,
10179            self.allow_cancellation_scope_delivery,
10180        )?;
10181        let cancellation_history = if let Some(observation) = observation {
10182            observation.validate_observation()?;
10183            cooperative_cancellation::cancellation_claim(&task)?;
10184            let canonical = CancellationHistory::from_events(
10185                &task.history_events,
10186                task.run_id.as_deref().unwrap_or_default(),
10187                Some(observation),
10188            )?;
10189            if canonical.request_index >= task.history_events.len() {
10190                return Err(Error::InvalidCooperativeCancellation(
10191                    "workflow replay requires the observed canonical request".into(),
10192                ));
10193            }
10194            Some(canonical)
10195        } else {
10196            None
10197        };
10198        if let Some(update_id) = task
10199            .workflow_update_id
10200            .as_deref()
10201            .filter(|update_id| !update_id.is_empty())
10202        {
10203            if self.allow_cancellation_scope_delivery {
10204                return Err(Error::CancellationScopeExecutionUnavailable);
10205            }
10206            CancellationHistory::from_events(
10207                &task.history_events,
10208                task.run_id.as_deref().unwrap_or_default(),
10209                None,
10210            )?;
10211            return self
10212                .execute_update_task(&task, update_id)
10213                .map(WorkflowTaskDecision::without_message_streams)
10214                .map(PreparedWorkflowTask::Decision);
10215        }
10216
10217        let workflow = self
10218            .workflows
10219            .get(&task.workflow_type)
10220            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
10221        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
10222        let resume_signal = decode_resume_signal(&task)?;
10223        let history_budget = WorkflowHistoryBudget {
10224            event_count: task
10225                .total_history_events
10226                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
10227            size_bytes: task.history_size_bytes,
10228            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
10229            pressure: task.history_budget_pressure.clone(),
10230        };
10231        let workflow_command_identity = task
10232            .workflow_command_id
10233            .clone()
10234            .filter(|identity| !identity.is_empty())
10235            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
10236            .unwrap_or_default();
10237        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
10238            task.history_events.clone(),
10239            task.workflow_id.clone(),
10240            task.run_id.clone(),
10241            self.task_queue.clone(),
10242            task.payload_codec.clone(),
10243            resume_signal,
10244            self.allow_cancellation_scope_authoring,
10245            self.allow_cancellation_scope_delivery,
10246        )?;
10247        workflow_state.observation_namespace = Some(self.client.namespace.clone());
10248        workflow_state.history_budget = history_budget;
10249        workflow_state.workflow_command_identity = workflow_command_identity;
10250        if let Some(canonical) = cancellation_history {
10251            workflow_state.cancellation_history = canonical;
10252            workflow_state.cancellation_delivery_enabled = true;
10253        }
10254        if workflow_state.cancellation_history.request.is_none() {
10255            workflow_state.cancel_requested = task.cancel_requested;
10256        }
10257        let state = Arc::new(Mutex::new(workflow_state));
10258        let ctx = WorkflowContext {
10259            state,
10260            cancellation_scope_id: "root".into(),
10261        };
10262        let future = {
10263            let _clock = replay_clock::Guard::enter(&ctx);
10264            (workflow.execute)(ctx.clone(), input)?
10265        };
10266        Ok(PreparedWorkflowTask::Execution {
10267            task,
10268            context: ctx,
10269            future,
10270        })
10271    }
10272
10273    fn poll_workflow_future(
10274        ctx: &WorkflowContext,
10275        future: &mut WorkflowFuture,
10276    ) -> Result<Poll<Result<AvroValue>>> {
10277        let mut cx = TaskContext::from_waker(noop_waker_ref());
10278        let _clock = replay_clock::Guard::enter(ctx);
10279        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
10280        Ok(future.as_mut().poll(&mut cx))
10281    }
10282
10283    fn finish_workflow_task_execution(
10284        &self,
10285        task: &WorkflowTask,
10286        ctx: &WorkflowContext,
10287        outcome: Poll<Result<AvroValue>>,
10288    ) -> Result<WorkflowTaskDecision> {
10289        if !ctx
10290            .state
10291            .lock()
10292            .map_err(|_| Error::WorkflowStatePoisoned)?
10293            .local_activity_requests
10294            .is_empty()
10295        {
10296            return Err(Error::CooperativeCancellationUnavailable(
10297                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
10298            ));
10299        }
10300        let awaiting_canonical_boundary = {
10301            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
10302            state.cancellation_delivery_intent.is_some()
10303                || state.cancellation_scope_opening.is_some()
10304                || state
10305                    .scope_delivery
10306                    .as_ref()
10307                    .is_some_and(|replay| replay.intent.is_some())
10308        };
10309        if awaiting_canonical_boundary {
10310            // A private delivery intent never becomes an application error.
10311            // Even a custom future which ignores a pending durable call cannot
10312            // publish terminal commands before canonical delivery and replay.
10313            if let Poll::Ready(Err(error)) = outcome {
10314                if workflow_task_integrity_error(&error) {
10315                    return Err(error);
10316                }
10317            }
10318            return self.message_stream_decision(&ctx, ctx.take_commands()?);
10319        }
10320
10321        match outcome {
10322            Poll::Ready(Ok(result)) => {
10323                ctx.ensure_history_consumed()?;
10324                let result = encode_typed_envelope(&result, &task.payload_codec)?;
10325                let mut commands = ctx.take_commands()?;
10326                commands.push(json!({
10327                    "type": "complete_workflow",
10328                    "result": result
10329                }));
10330                self.message_stream_decision(&ctx, commands)
10331            }
10332            Poll::Ready(Err(error)) => {
10333                if let Error::ContinueAsNew(request) = error {
10334                    let mut commands = ctx.take_commands()?;
10335                    if let Some(command) = ctx.continue_as_new_command(request)? {
10336                        commands.push(command);
10337                    }
10338                    ctx.ensure_history_consumed()?;
10339                    return self.message_stream_decision(&ctx, commands);
10340                }
10341                if workflow_task_integrity_error(&error) {
10342                    // Replay and protocol failures describe the workflow-task
10343                    // decision itself. Preserve their specific failure reason
10344                    // instead of replacing it with the derivative fact that
10345                    // recorded commands remain unconsumed.
10346                    return Err(error);
10347                }
10348                // A handler error must not hide a committed durable command that
10349                // upgraded workflow code no longer consumes.
10350                ctx.ensure_history_consumed()?;
10351                let mut commands = ctx.take_commands()?;
10352                commands.push(workflow_failure_command(
10353                    &error,
10354                    recorded_activity_failure_boundary(&ctx, &error),
10355                ));
10356                self.message_stream_decision(&ctx, commands)
10357            }
10358            Poll::Pending => {
10359                let commands = ctx.take_commands()?;
10360                if commands.is_empty() && !ctx.matched_recorded_pending()? {
10361                    Err(Error::WorkflowYieldedWithoutCommand)
10362                } else {
10363                    self.message_stream_decision(&ctx, commands)
10364                }
10365            }
10366        }
10367    }
10368
10369    fn message_stream_decision(
10370        &self,
10371        ctx: &WorkflowContext,
10372        commands: Vec<Value>,
10373    ) -> Result<WorkflowTaskDecision> {
10374        if !self.cooperative_cancellation_enabled
10375            && commands.iter().any(|command| {
10376                command["type"] == "schedule_activity"
10377                    && command.get("cancellation_policy").is_some()
10378            })
10379        {
10380            return Err(Error::CooperativeCancellationUnavailable(format!(
10381                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
10382                self.worker_id,
10383            )));
10384        }
10385        if !self.cooperative_cancellation_enabled
10386            && commands.iter().any(|command| {
10387                command["type"] == "start_child_workflow"
10388                    && (command["parent_close_policy"] == "request_cancellation"
10389                        || matches!(
10390                            command["cancellation_policy"].as_str(),
10391                            Some("try_cancel" | "wait_cancellation_completed")
10392                        ))
10393            })
10394        {
10395            return Err(Error::CooperativeCancellationUnavailable(format!(
10396                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
10397                self.worker_id,
10398            )));
10399        }
10400        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
10401        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
10402        let scope_delivery = state
10403            .scope_delivery
10404            .as_ref()
10405            .and_then(|replay| replay.intent.clone());
10406        if scope_delivery
10407            .as_ref()
10408            .is_some_and(|intent| commands.len() != intent.command_count)
10409        {
10410            return Err(invalid_recorded_history(
10411                "cancellation_scope_pending_call_escaped",
10412                scope_delivery.as_ref().unwrap().boundary.sequence,
10413                "commands preceding the pending scoped call",
10414                "commands after suspension",
10415                "workflow cannot publish beyond an uncommitted scope delivery",
10416            ));
10417        }
10418        if let Some(opening) = &state.cancellation_scope_opening {
10419            if commands.len() != opening.command_count {
10420                return Err(invalid_recorded_history(
10421                    "cancellation_scope_pending_call_escaped",
10422                    opening.sequence,
10423                    "commands before original scope opening",
10424                    "commands after suspended opening",
10425                    "workflow cannot publish beyond an uncommitted scope opening",
10426                ));
10427            }
10428        }
10429        if state.cancellation_delivery_intent.is_some()
10430            && commands.len() != state.cancellation_delivery_command_count
10431        {
10432            return Err(invalid_recorded_history(
10433                "cooperative_cancellation_pending_call_escaped",
10434                state
10435                    .cancellation_delivery_intent
10436                    .as_ref()
10437                    .expect("pending delivery")
10438                    .sequence,
10439                "only commands preceding the pending cancellation call",
10440                "commands authored after a suspended call",
10441                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
10442            ));
10443        }
10444        Ok(WorkflowTaskDecision {
10445            commands,
10446            message_stream_cursors,
10447            message_stream_waits,
10448            cancellation_delivery: state.cancellation_delivery_intent.clone(),
10449            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
10450            cancellation_scope_delivery: scope_delivery,
10451        })
10452    }
10453
10454    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
10455        if !self.workflows.contains_key(&task.workflow_type) {
10456            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
10457        }
10458
10459        let accepted = task.history_events.iter().rev().find_map(|event| {
10460            (event.event_type == "UpdateAccepted"
10461                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
10462            .then_some(&event.payload)
10463        });
10464        let update_name = accepted
10465            .and_then(|payload| payload.get("update_name"))
10466            .and_then(Value::as_str)
10467            .or(task.update_name.as_deref())
10468            .unwrap_or_default();
10469        let Some(handler) = self
10470            .updates
10471            .get(&task.workflow_type)
10472            .and_then(|handlers| handlers.get(update_name))
10473        else {
10474            return Ok(vec![json!({
10475                "type": "fail_update",
10476                "update_id": update_id,
10477                "message": format!(
10478                    "no update handler is registered for {}.{update_name}",
10479                    task.workflow_type
10480                ),
10481                "exception_type": "UnknownUpdate",
10482                "non_retryable": true,
10483            })]);
10484        };
10485        let arguments = accepted
10486            .and_then(|payload| payload.get("arguments"))
10487            .or(task.arguments.as_ref());
10488        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
10489        let workflow_input_avro_value =
10490            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
10491        let workflow_input = workflow_input_avro_value.clone().into_json()?;
10492        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
10493        let context = QueryContext {
10494            workflow_id: task.workflow_id.clone(),
10495            run_id: task.run_id.clone(),
10496            workflow_type: task.workflow_type.clone(),
10497            run_status: Some("running".to_string()),
10498            workflow_input,
10499            workflow_input_avro_value,
10500            replay_time: replay_clock::update_time(&task.history_events, update_id),
10501            history_events: Arc::new(task.history_events.clone()),
10502            signal_events: Arc::new(signal_events),
10503        };
10504        let mut future = handler(context, arguments);
10505        let mut cx = TaskContext::from_waker(noop_waker_ref());
10506
10507        match future.as_mut().poll(&mut cx) {
10508            Poll::Ready(Ok(result)) => Ok(vec![json!({
10509                "type": "complete_update",
10510                "update_id": update_id,
10511                "result": encode_typed_envelope(&result, &task.payload_codec)?,
10512            })]),
10513            Poll::Ready(Err(error)) => Ok(vec![json!({
10514                "type": "fail_update",
10515                "update_id": update_id,
10516                "message": error.to_string(),
10517                "exception_type": "UpdateFailed",
10518                "non_retryable": true,
10519            })]),
10520            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
10521        }
10522    }
10523
10524    #[cfg(test)]
10525    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
10526        let invocation = worker_session::ActivityInvocation::unknown(task.attempt_number);
10527        self.execute_session_activity_task(task, invocation).await
10528    }
10529
10530    async fn execute_session_activity_task(
10531        &self,
10532        task: ActivityTask,
10533        invocation: worker_session::ActivityInvocation,
10534    ) -> Result<AvroValue> {
10535        #[cfg(feature = "telemetry")]
10536        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
10537            !self
10538                .client
10539                .observability_context_supported
10540                .load(Ordering::SeqCst)
10541        }) {
10542            return telemetry
10543                .run(
10544                    "durable.activity.task",
10545                    self.activity_telemetry_fields(&task),
10546                    false,
10547                    self.execute_session_activity_task_inner(task, invocation),
10548                )
10549                .await;
10550        }
10551        self.execute_session_activity_task_inner(task, invocation)
10552            .await
10553    }
10554
10555    async fn execute_session_activity_task_inner(
10556        &self,
10557        task: ActivityTask,
10558        invocation: worker_session::ActivityInvocation,
10559    ) -> Result<AvroValue> {
10560        let worker_session::ActivityInvocation {
10561            worker_session,
10562            hydration_claim,
10563            retry_info,
10564        } = invocation;
10565        validate_activity_task_payloads(&task)?;
10566        if worker_session.is_some() {
10567            if task.lease_owner.as_deref() != Some(self.worker_id.as_str())
10568                || task
10569                    .activity_attempt_id
10570                    .as_deref()
10571                    .or(task.attempt_id.as_deref())
10572                    .is_none_or(str::is_empty)
10573                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b)
10574            {
10575                return Err(Error::ActivityExecutionAbandoned(
10576                    "session activity requires this worker's exact immutable claim".into(),
10577                ));
10578            }
10579        }
10580
10581        let handler = self
10582            .activities
10583            .get(&task.activity_type)
10584            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
10585        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
10586        let attempt_id = task
10587            .activity_attempt_id
10588            .clone()
10589            .or(task.attempt_id.clone())
10590            .unwrap_or_default();
10591        let lease_owner = task
10592            .lease_owner
10593            .clone()
10594            .unwrap_or_else(|| self.worker_id.clone());
10595        let session = worker_session.clone();
10596        if let Some(claim) = &hydration_claim {
10597            claim.confirm(&self.client).await?;
10598        }
10599        #[cfg(feature = "telemetry")]
10600        let observations = self.activity_observations(&task);
10601        #[cfg(feature = "telemetry")]
10602        let fields = self.activity_telemetry_fields(&task);
10603        let ctx = ActivityContext {
10604            client: self.client.clone(),
10605            task_id: task.task_id,
10606            activity_attempt_id: attempt_id,
10607            lease_owner,
10608            activity_type: task.activity_type,
10609            attempt_number: task.attempt_number,
10610            retry_info,
10611            activity_execution_id: task.activity_execution_id,
10612            workflow_id: task.workflow_id,
10613            run_id: task.run_id,
10614            task_queue: self.task_queue.clone(),
10615            worker_id: self.worker_id.clone(),
10616            claim_guard: None,
10617            local_heartbeats: None,
10618            worker_session,
10619        };
10620
10621        let operation = async {
10622            let callback = self.activity_callback(handler, ctx, args, false);
10623            if let Some(session) = session {
10624                tokio::select! {
10625                    biased;
10626                    _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
10627                    result = callback => if session.active() { result } else {
10628                        Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
10629                    },
10630                }
10631            } else {
10632                callback.await
10633            }
10634        };
10635        #[cfg(feature = "telemetry")]
10636        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
10637            self.client
10638                .observability_context_supported
10639                .load(Ordering::SeqCst)
10640        }) {
10641            return telemetry
10642                .run_observed(
10643                    "durable.activity.task",
10644                    fields,
10645                    false,
10646                    observations,
10647                    operation,
10648                )
10649                .await;
10650        }
10651        operation.await
10652    }
10653
10654    fn activity_callback(
10655        &self,
10656        handler: &ActivityHandler,
10657        context: ActivityContext,
10658        args: AvroValue,
10659        local: bool,
10660    ) -> ActivityFuture {
10661        #[cfg(feature = "telemetry")]
10662        if let Some(telemetry) = &self.telemetry {
10663            let telemetry = telemetry.clone();
10664            let fields = self.callback_telemetry_fields(&context, local);
10665            let handler = handler.clone();
10666            let name = if local {
10667                "durable.local_activity.attempt"
10668            } else {
10669                "durable.activity.attempt"
10670            };
10671            return Box::pin(async move {
10672                telemetry
10673                    .run(
10674                        name,
10675                        fields,
10676                        true,
10677                        async move { handler(context, args).await },
10678                    )
10679                    .await
10680            });
10681        }
10682        #[cfg(not(feature = "telemetry"))]
10683        let _ = local;
10684        handler(context, args)
10685    }
10686}
10687
10688fn poller_result(
10689    kind: &str,
10690    result: std::result::Result<Result<()>, tokio::task::JoinError>,
10691) -> Result<()> {
10692    match result {
10693        Ok(result) => result,
10694        Err(error) => Err(Error::WorkerLoop(format!(
10695            "{kind} poller join error: {error}"
10696        ))),
10697    }
10698}
10699
10700fn optional_poller_result(
10701    kind: &str,
10702    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
10703) -> Result<()> {
10704    match result {
10705        Some(result) => poller_result(kind, result),
10706        None => Ok(()),
10707    }
10708}
10709
10710async fn join_pollers(
10711    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10712    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10713    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
10714) -> Result<()> {
10715    let mut first_error = None;
10716
10717    if let Some(handle) = workflow_poller {
10718        if let Err(error) = poller_result("workflow", handle.await) {
10719            first_error.get_or_insert(error);
10720        }
10721    }
10722
10723    if let Some(handle) = activity_poller {
10724        if let Err(error) = poller_result("activity", handle.await) {
10725            first_error.get_or_insert(error);
10726        }
10727    }
10728
10729    if let Some(handle) = query_poller {
10730        if let Err(error) = poller_result("query", handle.await) {
10731            first_error.get_or_insert(error);
10732        }
10733    }
10734
10735    if let Some(error) = first_error {
10736        Err(error)
10737    } else {
10738        Ok(())
10739    }
10740}
10741
10742fn default_worker_id() -> String {
10743    let millis = SystemTime::now()
10744        .duration_since(UNIX_EPOCH)
10745        .unwrap_or_default()
10746        .as_millis();
10747    format!("rust-worker-{}-{millis}", std::process::id())
10748}
10749
10750/// Only the endpoint origin, since base paths can contain namespace identities
10751/// or proxy credentials that must not appear in logs.
10752fn tls_warning_endpoint(base_url: &str) -> String {
10753    match reqwest::Url::parse(base_url) {
10754        Ok(url) => url.origin().ascii_serialization(),
10755        Err(_) => "<unparseable base URL>".to_string(),
10756    }
10757}
10758
10759fn percent_encode_path_segment(segment: &str) -> String {
10760    const HEX: &[u8; 16] = b"0123456789ABCDEF";
10761    let mut encoded = String::with_capacity(segment.len());
10762
10763    for byte in segment.bytes() {
10764        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
10765            encoded.push(char::from(byte));
10766        } else {
10767            encoded.push('%');
10768            encoded.push(char::from(HEX[(byte >> 4) as usize]));
10769            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
10770        }
10771    }
10772
10773    encoded
10774}
10775
10776fn unique_request_id(prefix: &str) -> String {
10777    let nanos = SystemTime::now()
10778        .duration_since(UNIX_EPOCH)
10779        .unwrap_or_default()
10780        .as_nanos();
10781    format!("{prefix}-{}-{nanos}", std::process::id())
10782}
10783
10784#[derive(Debug)]
10785struct QueryTaskExecutionFailure {
10786    reason: String,
10787    message: String,
10788    failure_type: String,
10789}
10790
10791impl QueryTaskExecutionFailure {
10792    fn new(
10793        reason: impl Into<String>,
10794        message: impl Into<String>,
10795        failure_type: impl Into<String>,
10796    ) -> Self {
10797        Self {
10798            reason: reason.into(),
10799            message: message.into(),
10800            failure_type: failure_type.into(),
10801        }
10802    }
10803}
10804
10805/// Typed local state owned by one deterministic workflow invocation.
10806///
10807/// Use [`WorkflowInstance::update`] for the same state transitions during
10808/// ordinary execution and replay. A replayed query receives a detached
10809/// immutable `Arc<S>` rather than this mutation-capable handle.
10810#[derive(Clone, Debug)]
10811pub struct WorkflowInstance<S> {
10812    state: Arc<Mutex<S>>,
10813}
10814
10815impl<S> WorkflowInstance<S> {
10816    fn new(state: S) -> Self {
10817        Self {
10818            state: Arc::new(Mutex::new(state)),
10819        }
10820    }
10821
10822    /// Read the current workflow-instance state without changing it.
10823    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
10824        let state = self
10825            .state
10826            .lock()
10827            .map_err(|_| Error::WorkflowStatePoisoned)?;
10828        Ok(reader(&state))
10829    }
10830
10831    /// Apply one deterministic workflow-instance state transition.
10832    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
10833        let mut state = self
10834            .state
10835            .lock()
10836            .map_err(|_| Error::WorkflowStatePoisoned)?;
10837        Ok(transition(&mut state))
10838    }
10839}
10840
10841impl<S: Clone> WorkflowInstance<S> {
10842    fn snapshot(&self) -> Result<S> {
10843        self.read(Clone::clone)
10844    }
10845}
10846
10847#[derive(Clone, Debug, PartialEq)]
10848pub struct MessageStreamMessage {
10849    pub stream_name: String,
10850    pub message_id: String,
10851    pub position: u64,
10852    pub arguments: Vec<AvroValue>,
10853}
10854
10855#[derive(Clone, Debug)]
10856pub struct MessageStream {
10857    ctx: WorkflowContext,
10858    name: String,
10859}
10860
10861impl MessageStream {
10862    /// Wait for one message, then return a bounded currently-available batch.
10863    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
10864        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
10865            return Err(Error::Codec(format!(
10866                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
10867            )));
10868        }
10869        loop {
10870            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
10871                return Ok(batch);
10872            }
10873
10874            self.ctx.record_message_stream_wait(&self.name)?;
10875            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
10876            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
10877            self.ctx.buffer_message_stream_delivery(arguments)?;
10878            if let Some(sequence) = replay_wait_sequence {
10879                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
10880            }
10881        }
10882    }
10883
10884    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
10885        self.receive(1)
10886            .await?
10887            .into_iter()
10888            .next()
10889            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
10890    }
10891}
10892
10893#[derive(Clone, Debug)]
10894pub struct WorkflowContext {
10895    state: Arc<Mutex<WorkflowState>>,
10896    cancellation_scope_id: String,
10897}
10898
10899fn valid_memo_key(key: &str) -> bool {
10900    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
10901
10902    !key.is_empty()
10903        && key.len() <= 64
10904        && (numeric_candidate.is_empty()
10905            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
10906        && key
10907            .bytes()
10908            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
10909}
10910
10911fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
10912    BASE64
10913        .decode(encode_avro_value(value)?.blob)
10914        .map(|bytes| bytes.len())
10915        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
10916}
10917
10918fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
10919    let AvroValue::Map(entries) = value else {
10920        return Err(Error::InvalidMemoUpdate(
10921            "entries must serialize to an Avro string-keyed map".to_string(),
10922        ));
10923    };
10924    if require_entries && entries.is_empty() {
10925        return Err(Error::InvalidMemoUpdate(
10926            "at least one entry is required".to_string(),
10927        ));
10928    }
10929    if entries.len() > MAX_MEMO_ENTRIES {
10930        return Err(Error::InvalidMemoUpdate(format!(
10931            "at most {MAX_MEMO_ENTRIES} entries are allowed"
10932        )));
10933    }
10934
10935    for (key, value) in &entries {
10936        if !valid_memo_key(&key) {
10937            return Err(Error::InvalidMemoUpdate(
10938                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
10939            ));
10940        }
10941        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
10942            return Err(Error::InvalidMemoUpdate(format!(
10943                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
10944            )));
10945        }
10946    }
10947
10948    let value = AvroValue::Map(entries);
10949    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
10950        return Err(Error::InvalidMemoUpdate(format!(
10951            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
10952        )));
10953    }
10954    Ok(value)
10955}
10956
10957fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
10958    let object = envelope.as_object().ok_or_else(|| {
10959        Error::InvalidMemoUpdate(
10960            "history field must use the public {codec, blob} payload envelope".to_string(),
10961        )
10962    })?;
10963    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
10964        return Err(Error::InvalidMemoUpdate(
10965            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
10966        ));
10967    }
10968
10969    canonical_memo_entries(
10970        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
10971        require_entries,
10972    )
10973}
10974
10975impl WorkflowContext {
10976    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
10977        let name = name.into();
10978        if name.is_empty()
10979            || name.len() > 128
10980            || !name.bytes().all(|byte| {
10981                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
10982            })
10983        {
10984            return Err(Error::Codec(
10985                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
10986                    .to_string(),
10987            ));
10988        }
10989        Ok(MessageStream {
10990            ctx: self.clone(),
10991            name,
10992        })
10993    }
10994
10995    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
10996        let mut state = self
10997            .state
10998            .lock()
10999            .map_err(|_| Error::WorkflowStatePoisoned)?;
11000        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
11001        state
11002            .message_stream_waits
11003            .insert(name.to_string(), position);
11004        Ok(())
11005    }
11006
11007    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
11008        let mut state = self
11009            .state
11010            .lock()
11011            .map_err(|_| Error::WorkflowStatePoisoned)?;
11012        let cursor = state
11013            .message_stream_cursors
11014            .get(&message.stream_name)
11015            .copied()
11016            .unwrap_or(0);
11017        if message.position <= cursor {
11018            return Ok(());
11019        }
11020        let pending = state
11021            .message_stream_messages
11022            .entry(message.stream_name.clone())
11023            .or_default();
11024        if pending.iter().any(|candidate| {
11025            candidate.position == message.position || candidate.message_id == message.message_id
11026        }) {
11027            return Ok(());
11028        }
11029        pending.push(message);
11030        pending.sort_by_key(|candidate| candidate.position);
11031        Ok(())
11032    }
11033
11034    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
11035        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
11036            match delivery {
11037                MessageStreamDelivery::Message(message) => {
11038                    let stream_name = message.stream_name.clone();
11039                    self.buffer_message_stream(message)?;
11040                    return Ok(Some(stream_name));
11041                }
11042                MessageStreamDelivery::Cursor {
11043                    stream_name,
11044                    through_position,
11045                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
11046            }
11047        }
11048        Ok(None)
11049    }
11050
11051    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
11052        let state = self
11053            .state
11054            .lock()
11055            .map_err(|_| Error::WorkflowStatePoisoned)?;
11056        Ok(match state.recorded_commands.get(state.command_cursor) {
11057            Some(RecordedCommand::SignalWait {
11058                sequence,
11059                signal_name,
11060                ..
11061            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
11062            _ => None,
11063        })
11064    }
11065
11066    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
11067        let (history, payload_codec) = {
11068            let state = self
11069                .state
11070                .lock()
11071                .map_err(|_| Error::WorkflowStatePoisoned)?;
11072            (
11073                Arc::clone(&state.history_events),
11074                state.payload_codec.clone(),
11075            )
11076        };
11077
11078        let Some(opened_index) = history.iter().position(|event| {
11079            event.event_type == "SignalWaitOpened"
11080                && durable_event_sequence(event) == Some(wait_sequence)
11081                && event.payload.get("signal_name").and_then(Value::as_str)
11082                    == Some(MESSAGE_STREAM_SIGNAL)
11083        }) else {
11084            return Ok(());
11085        };
11086        let boundary_index = history
11087            .iter()
11088            .enumerate()
11089            .skip(opened_index + 1)
11090            .find_map(|(index, event)| {
11091                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
11092                    && is_authored_command_open_event(event))
11093                .then_some(index)
11094            })
11095            .unwrap_or(history.len());
11096
11097        for event in history[opened_index + 1..boundary_index]
11098            .iter()
11099            .filter(|event| {
11100                event.event_type == "SignalReceived"
11101                    && event.payload.get("signal_name").and_then(Value::as_str)
11102                        == Some(MESSAGE_STREAM_SIGNAL)
11103            })
11104        {
11105            let arguments = decode_signal_event_arguments(event, &payload_codec)?
11106                .into_iter()
11107                .map(AvroValue::into_json)
11108                .collect::<Result<Vec<_>>>()?;
11109            self.buffer_message_stream_delivery(arguments)?;
11110        }
11111        Ok(())
11112    }
11113
11114    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
11115        let mut state = self
11116            .state
11117            .lock()
11118            .map_err(|_| Error::WorkflowStatePoisoned)?;
11119        let cursor = state
11120            .message_stream_cursors
11121            .entry(name.to_string())
11122            .or_default();
11123        *cursor = (*cursor).max(through_position);
11124        if let Some(pending) = state.message_stream_messages.get_mut(name) {
11125            pending.retain(|message| message.position > through_position);
11126        }
11127        Ok(())
11128    }
11129
11130    fn take_message_stream_batch(
11131        &self,
11132        name: &str,
11133        max_items: usize,
11134    ) -> Result<Option<Vec<MessageStreamMessage>>> {
11135        let mut state = self
11136            .state
11137            .lock()
11138            .map_err(|_| Error::WorkflowStatePoisoned)?;
11139        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
11140        let pending = state
11141            .message_stream_messages
11142            .entry(name.to_string())
11143            .or_default();
11144        let count = contiguous_message_stream_count(pending, cursor, max_items);
11145        if count == 0 {
11146            return Ok(None);
11147        }
11148        let batch = pending.drain(..count).collect::<Vec<_>>();
11149        let position = batch.last().map(|message| message.position).unwrap_or(0);
11150        state
11151            .message_stream_cursors
11152            .insert(name.to_string(), position);
11153        state.message_stream_waits.remove(name);
11154        Ok(Some(batch))
11155    }
11156
11157    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
11158        let state = self
11159            .state
11160            .lock()
11161            .map_err(|_| Error::WorkflowStatePoisoned)?;
11162        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
11163        cursors.sort_by_key(|(name, _)| *name);
11164        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
11165        waits.sort_by_key(|(name, _)| *name);
11166        Ok((
11167            cursors
11168                .into_iter()
11169                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
11170                .collect(),
11171            waits
11172                .into_iter()
11173                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
11174                .collect(),
11175        ))
11176    }
11177    /// Identity of the parent workflow currently being replayed.
11178    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
11179        let state = self
11180            .state
11181            .lock()
11182            .map_err(|_| Error::WorkflowStatePoisoned)?;
11183        Ok(WorkflowIdentity {
11184            workflow_id: state.workflow_id.clone(),
11185            run_id: state.run_id.clone(),
11186        })
11187    }
11188
11189    /// Return the server-published history budget for this workflow task.
11190    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
11191        let state = self
11192            .state
11193            .lock()
11194            .map_err(|_| Error::WorkflowStatePoisoned)?;
11195        Ok(state.history_budget.clone())
11196    }
11197
11198    /// Continue this workflow instance as a fresh run with replacement arguments.
11199    ///
11200    /// Return this value directly from the workflow handler. The worker converts
11201    /// it to the terminal protocol command only after replay has consumed every
11202    /// recorded durable command.
11203    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
11204        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
11205    }
11206
11207    /// Continue as new with optional workflow-type and task-queue overrides.
11208    pub fn continue_as_new_with_options<T: Serialize>(
11209        &self,
11210        options: ContinueAsNewOptions,
11211        args: T,
11212    ) -> Result<Value> {
11213        options.validate()?;
11214        Err(Error::ContinueAsNew(ContinueAsNewRequest {
11215            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
11216            options,
11217        }))
11218    }
11219
11220    pub fn activity<T: Serialize>(
11221        &self,
11222        activity_type: impl Into<String>,
11223        args: T,
11224    ) -> ActivityCall {
11225        self.activity_with_options(activity_type, ActivityOptions::new(), args)
11226    }
11227
11228    pub fn activity_on_queue<T, Q>(
11229        &self,
11230        activity_type: impl Into<String>,
11231        task_queue: Option<Q>,
11232        args: T,
11233    ) -> ActivityCall
11234    where
11235        T: Serialize,
11236        Q: Into<String>,
11237    {
11238        let mut options = ActivityOptions::new();
11239        options.task_queue = task_queue.map(Into::into);
11240        self.activity_with_options(activity_type, options, args)
11241    }
11242
11243    /// Schedule one durable activity with retry, routing, and timeout options.
11244    ///
11245    /// Options are validated before the command is emitted. Once the command is
11246    /// recorded, replay consumes the same activity lifecycle at this command
11247    /// position and never emits a duplicate schedule.
11248    ///
11249    /// ```no_run
11250    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
11251    /// # use std::time::Duration;
11252    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
11253    /// let result = ctx
11254    ///     .activity_with_options(
11255    ///         "charge-card",
11256    ///         ActivityOptions::new()
11257    ///             .task_queue("payments")
11258    ///             .retry_policy(
11259    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
11260    ///                     Duration::from_secs(1),
11261    ///                     2,
11262    ///                     Some(Duration::from_secs(30)),
11263    ///                 ),
11264    ///             )
11265    ///             .start_to_close_timeout(Duration::from_secs(60))
11266    ///             .schedule_to_close_timeout(Duration::from_secs(180))
11267    ///             .heartbeat_timeout(Duration::from_secs(15)),
11268    ///         json!([{"order_id": "order-42"}]),
11269    ///     )
11270    ///     .await;
11271    /// match result {
11272    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
11273    ///         "reason": failure.reason,
11274    ///         "timeout_kind": failure.timeout_kind,
11275    ///     })),
11276    ///     other => other,
11277    /// }
11278    /// # }
11279    /// ```
11280    pub fn activity_with_options<T: Serialize>(
11281        &self,
11282        activity_type: impl Into<String>,
11283        options: ActivityOptions,
11284        args: T,
11285    ) -> ActivityCall {
11286        ActivityCall {
11287            ctx: self.clone(),
11288            activity_type: activity_type.into(),
11289            options,
11290            worker_session: None,
11291            args: Some(AvroValue::from_serialize(&args)),
11292            scheduled: false,
11293            local: false,
11294            local_result: None,
11295            parallel_group_path: Vec::new(),
11296        }
11297    }
11298
11299    pub async fn activity_avro_value<T: Serialize>(
11300        &self,
11301        activity_type: impl Into<String>,
11302        args: T,
11303    ) -> Result<AvroValue> {
11304        let mut call = self.activity(activity_type, args);
11305        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
11306    }
11307
11308    pub async fn activity_avro_value_with_options<T: Serialize>(
11309        &self,
11310        activity_type: impl Into<String>,
11311        options: ActivityOptions,
11312        args: T,
11313    ) -> Result<AvroValue> {
11314        let mut call = self.activity_with_options(activity_type, options, args);
11315        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
11316    }
11317
11318    /// Schedule an activity with a Serde request and decode its Serde result.
11319    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
11320    where
11321        I: Serialize,
11322        O: DeserializeOwned,
11323    {
11324        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
11325            .await
11326    }
11327
11328    /// Schedule an activity with options and decode its result into `O`.
11329    ///
11330    /// Both directions use the fixed Avro Value codec. In particular, this
11331    /// method does not deserialize the JSON-safe inspection projection returned
11332    /// by the dynamic [`ActivityCall`] future.
11333    pub async fn activity_typed_with_options<I, O>(
11334        &self,
11335        activity_type: impl Into<String>,
11336        options: ActivityOptions,
11337        args: I,
11338    ) -> Result<O>
11339    where
11340        I: Serialize,
11341        O: DeserializeOwned,
11342    {
11343        let activity_type = activity_type.into();
11344        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
11345            handler_type_error::<I>(
11346                HandlerKind::Activity,
11347                &activity_type,
11348                HandlerValueKind::Input,
11349                error.to_string(),
11350            )
11351        });
11352        let mut call = ActivityCall {
11353            ctx: self.clone(),
11354            activity_type: activity_type.clone(),
11355            options,
11356            worker_session: None,
11357            args: Some(encoded),
11358            scheduled: false,
11359            local: false,
11360            local_result: None,
11361            parallel_group_path: Vec::new(),
11362        };
11363        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
11364        decode_handler_result(result, HandlerKind::Activity, &activity_type)
11365    }
11366
11367    /// Schedule and join a deterministic activity/child/timer group.
11368    ///
11369    /// Nested groups retain their input shape. Every durable leaf is scheduled
11370    /// before this future yields, results are assembled by declaration order,
11371    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
11372    /// declaration path, stable group metadata, and completed siblings.
11373    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
11374        ParallelCall::new(self.clone(), operations)
11375    }
11376
11377    /// Alias for [`WorkflowContext::parallel`].
11378    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
11379        self.parallel(operations)
11380    }
11381
11382    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
11383    pub async fn parallel_avro_value(
11384        &self,
11385        operations: Vec<ParallelOperation>,
11386    ) -> Result<Vec<ParallelAvroResult>> {
11387        let mut call = self.parallel(operations);
11388        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
11389    }
11390
11391    /// Start every durable operation and resume from the one winner persisted
11392    /// by Server. Non-winning operations continue and remain addressable.
11393    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
11394        let operations = operations
11395            .into_iter()
11396            .enumerate()
11397            .map(|(index, operation)| (SelectionKey::Index(index), operation))
11398            .collect();
11399        SelectCall::new(self.clone(), operations)
11400    }
11401
11402    /// Named-key variant of [`WorkflowContext::select`].
11403    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
11404    where
11405        K: Into<SelectionKey>,
11406    {
11407        SelectCall::new(
11408            self.clone(),
11409            operations
11410                .into_iter()
11411                .map(|(key, operation)| (key.into(), operation))
11412                .collect(),
11413        )
11414    }
11415
11416    /// Create a workflow-local deterministic compensation registry.
11417    pub fn saga(&self) -> Saga {
11418        Saga::new(self.clone())
11419    }
11420
11421    /// Whether cancellation has reached this replay's authored boundary.
11422    ///
11423    /// Server's current `/cancel` route is terminal and does not set this flag.
11424    /// A canonical service request remains pending until its committed delivery
11425    /// is consumed. Request observation alone does not authorize an exception.
11426    pub fn is_cancellation_requested(&self) -> Result<bool> {
11427        let state = self
11428            .state
11429            .lock()
11430            .map_err(|_| Error::WorkflowStatePoisoned)?;
11431        if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
11432            return Ok(state
11433                .scope_delivery
11434                .as_ref()
11435                .unwrap()
11436                .contexts
11437                .contains_key(&self.cancellation_scope_id));
11438        }
11439        Ok(state.cancel_requested
11440            || state
11441                .scope_delivery
11442                .as_ref()
11443                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
11444    }
11445
11446    /// Raise a typed cooperative cancellation at an author-controlled point.
11447    ///
11448    /// Passing this result to [`Saga::finish`] compensates already registered
11449    /// forward steps before the cancellation remains the initiating outcome.
11450    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
11451        let mut state = self
11452            .state
11453            .lock()
11454            .map_err(|_| Error::WorkflowStatePoisoned)?;
11455        if state.cancellation_shield_depth == 0 {
11456            if let Some(replay) = &state.scope_delivery {
11457                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
11458                    let delivered = replay
11459                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
11460                        .ok_or_else(|| {
11461                            Error::InvalidCooperativeCancellation(
11462                                "scoped request lacks its consumed original delivery".into(),
11463                            )
11464                        })?;
11465                    return Err(Error::CancellationScopeRequested(
11466                        CancellationScopeRequested {
11467                            context: context
11468                                .clone()
11469                                .with_replay(Some(Arc::downgrade(&self.state))),
11470                            delivery: delivered.boundary.clone(),
11471                        },
11472                    ));
11473                }
11474            }
11475        }
11476        if state.cancel_requested && state.cancellation_shield_depth == 0 {
11477            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
11478                return Ok(());
11479            }
11480            return Err(state.cancellation_error());
11481        }
11482        Ok(())
11483    }
11484
11485    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
11486        SignalCall {
11487            ctx: self.clone(),
11488            signal_name: signal_name.into(),
11489            runtime_reserved_allowed: false,
11490            opened_wait: false,
11491            matched_pending: false,
11492            parallel_group_path: Vec::new(),
11493        }
11494    }
11495
11496    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
11497        SignalCall {
11498            ctx: self.clone(),
11499            signal_name: signal_name.into(),
11500            runtime_reserved_allowed: true,
11501            opened_wait: false,
11502            matched_pending: false,
11503            parallel_group_path: Vec::new(),
11504        }
11505    }
11506
11507    pub async fn wait_signal_avro_value(
11508        &self,
11509        signal_name: impl Into<String>,
11510    ) -> Result<Vec<AvroValue>> {
11511        let mut call = self.wait_signal(signal_name);
11512        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
11513    }
11514
11515    /// Return every committed signal argument list with the given name.
11516    ///
11517    /// This history-backed view is deterministic and is intended for
11518    /// condition predicates that must be re-evaluated after a signal while the
11519    /// workflow is blocked on [`WorkflowContext::wait_condition`].
11520    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
11521        self.signals_avro_value(signal_name)?
11522            .into_iter()
11523            .map(|arguments| {
11524                arguments
11525                    .into_iter()
11526                    .map(AvroValue::into_json)
11527                    .collect::<Result<Vec<_>>>()
11528            })
11529            .collect()
11530    }
11531
11532    /// Lossless fixed Avro Value view of committed signals with the given name.
11533    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
11534        let state = self
11535            .state
11536            .lock()
11537            .map_err(|_| Error::WorkflowStatePoisoned)?;
11538        state
11539            .history_events
11540            .iter()
11541            .filter(|event| {
11542                event.event_type == "SignalReceived"
11543                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
11544            })
11545            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
11546            .collect()
11547    }
11548
11549    /// Return every committed update argument list with the given name.
11550    ///
11551    /// Accepted and applied records for the same update ID are de-duplicated.
11552    /// A Server task created after an update therefore replays the workflow and
11553    /// re-evaluates an open condition without application polling.
11554    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
11555        self.updates_avro_value(update_name)?
11556            .into_iter()
11557            .map(|arguments| {
11558                arguments
11559                    .into_iter()
11560                    .map(AvroValue::into_json)
11561                    .collect::<Result<Vec<_>>>()
11562            })
11563            .collect()
11564    }
11565
11566    /// Lossless fixed Avro Value view of committed updates with the given name.
11567    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
11568        let state = self
11569            .state
11570            .lock()
11571            .map_err(|_| Error::WorkflowStatePoisoned)?;
11572        let mut seen = Vec::new();
11573        let mut updates = Vec::new();
11574        for event in state.history_events.iter() {
11575            if !matches!(
11576                event.event_type.as_str(),
11577                "UpdateAccepted" | "UpdateApplied"
11578            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
11579                || event.payload.get("arguments").is_none()
11580            {
11581                continue;
11582            }
11583            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
11584                if seen.iter().any(|recorded| recorded == update_id) {
11585                    continue;
11586                }
11587                seen.push(update_id.to_string());
11588            }
11589            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
11590        }
11591        Ok(updates)
11592    }
11593
11594    /// Wait for a deterministic predicate to become true or for its durable
11595    /// timeout to elapse.
11596    ///
11597    /// The timeout runs from the first time the wait opens. A signal or update
11598    /// that leaves the predicate false does not restart it.
11599    ///
11600    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
11601    /// predicate tokens automatically change the recorded definition
11602    /// fingerprint. Direct callers must provide an equally stable identity in
11603    /// [`ConditionWaitOptions`].
11604    pub fn wait_condition<F>(
11605        &self,
11606        options: ConditionWaitOptions,
11607        predicate: F,
11608    ) -> ConditionWaitCall
11609    where
11610        F: Fn() -> Result<bool> + Send + 'static,
11611    {
11612        ConditionWaitCall {
11613            ctx: self.clone(),
11614            options,
11615            predicate: Box::new(predicate),
11616            occurrence_id: None,
11617            opened_wait: false,
11618            parallel_group_path: Vec::new(),
11619        }
11620    }
11621
11622    /// Wait for server-backed durable time without blocking the worker executor.
11623    ///
11624    /// Polling this future emits one `start_timer` command and yields. The
11625    /// server records the deadline, so neither worker nor server restarts reset
11626    /// the wait. Replay resolves the future only from a `TimerScheduled` and
11627    /// `TimerFired` pair at the same position in the shared durable-command
11628    /// stream, with matching sequence, timer identity, and delay. Sub-second
11629    /// durations round up because protocol deadlines use whole seconds.
11630    ///
11631    /// ```no_run
11632    /// # use durable_workflow::{json, Client, Worker};
11633    /// # use std::time::Duration;
11634    /// # fn configure(client: Client) {
11635    /// let mut worker = Worker::new(client, "rust-workers");
11636    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
11637    ///     ctx.sleep(Duration::from_secs(5)).await?;
11638    ///     Ok(json!({"status": "timer fired"}))
11639    /// });
11640    /// # }
11641    /// ```
11642    pub fn sleep(&self, duration: Duration) -> TimerCall {
11643        let delay_seconds = duration
11644            .as_secs()
11645            .checked_add(u64::from(duration.subsec_nanos() > 0));
11646        TimerCall {
11647            ctx: self.clone(),
11648            delay_seconds,
11649            scheduled: false,
11650            matched_pending: false,
11651            parallel_group_path: Vec::new(),
11652        }
11653    }
11654
11655    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
11656    pub fn start_timer(&self, duration: Duration) -> TimerCall {
11657        self.sleep(duration)
11658    }
11659
11660    /// Evaluate a non-deterministic callback once and durably record its typed value.
11661    ///
11662    /// On replay the callback is not invoked: the value is decoded from the
11663    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
11664    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
11665    /// small values that must remain fixed for the lifetime of a workflow run.
11666    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
11667    where
11668        T: Serialize + DeserializeOwned,
11669        F: FnOnce() -> T,
11670    {
11671        {
11672            let mut state = self
11673                .state
11674                .lock()
11675                .map_err(|_| Error::WorkflowStatePoisoned)?;
11676            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11677                return match recorded {
11678                    RecordedCommand::SideEffect { sequence, value } => {
11679                        state.replay_clock.unavailable();
11680                        state.command_cursor += 1;
11681                        value.deserialize().map_err(|error| {
11682                            Error::NonDeterministicReplay(ReplayFailure::new(
11683                                "side_effect_type_mismatch",
11684                                Some(sequence),
11685                                Some(std::any::type_name::<T>().to_string()),
11686                                Some(error.to_string()),
11687                                "recorded side-effect value is incompatible with the requested Rust type",
11688                            ))
11689                        })
11690                    }
11691                    other => Err(command_mismatch(&other, "side effect")),
11692                };
11693            }
11694        }
11695
11696        let value = callback();
11697        let avro_value = AvroValue::from_serialize(&value)?;
11698        let mut state = self
11699            .state
11700            .lock()
11701            .map_err(|_| Error::WorkflowStatePoisoned)?;
11702        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
11703        state.replay_clock.unavailable();
11704        state.commands.push(json!({
11705            "type": "record_side_effect",
11706            "result": result,
11707        }));
11708        Ok(value)
11709    }
11710
11711    /// Record or replay a lossless fixed Avro Value side effect.
11712    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
11713    where
11714        F: FnOnce() -> AvroValue,
11715    {
11716        {
11717            let mut state = self
11718                .state
11719                .lock()
11720                .map_err(|_| Error::WorkflowStatePoisoned)?;
11721            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11722                return match recorded {
11723                    RecordedCommand::SideEffect { value, .. } => {
11724                        state.replay_clock.unavailable();
11725                        state.command_cursor += 1;
11726                        Ok(value)
11727                    }
11728                    other => Err(command_mismatch(&other, "side effect")),
11729                };
11730            }
11731        }
11732
11733        let value = callback();
11734        let mut state = self
11735            .state
11736            .lock()
11737            .map_err(|_| Error::WorkflowStatePoisoned)?;
11738        let result = encode_typed_envelope(&value, &state.payload_codec)?;
11739        state.replay_clock.unavailable();
11740        state.commands.push(json!({
11741            "type": "record_side_effect",
11742            "result": result,
11743        }));
11744        Ok(value)
11745    }
11746
11747    /// Append output items at a deterministic workflow command boundary.
11748    ///
11749    /// Stable idempotency keys are derived from the server-provided durable
11750    /// workflow command identity, command ordinal, and item index. Replay
11751    /// consumes the recorded side effect and never emits another append.
11752    pub fn append_workflow_stream(
11753        &self,
11754        stream_name: impl Into<String>,
11755        items: &[WorkflowStreamAppendItem],
11756        max_pending_items: Option<u64>,
11757    ) -> Result<()> {
11758        if items.is_empty() {
11759            return Err(Error::Codec(
11760                "workflow_stream_items_empty: append requires at least one item".to_string(),
11761            ));
11762        }
11763        if max_pending_items == Some(0) {
11764            return Err(Error::Codec(
11765                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
11766                    .to_string(),
11767            ));
11768        }
11769        let stream_name = stream_name.into();
11770        if stream_name.is_empty() {
11771            return Err(Error::Codec(
11772                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11773            ));
11774        }
11775
11776        let mut state = self
11777            .state
11778            .lock()
11779            .map_err(|_| Error::WorkflowStatePoisoned)?;
11780        let command_ordinal = state.workflow_stream_command_counter;
11781        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11782            state.workflow_stream_command_counter += 1;
11783            return match recorded {
11784                RecordedCommand::SideEffect { .. } => {
11785                    state.replay_clock.unavailable();
11786                    state.command_cursor += 1;
11787                    Ok(())
11788                }
11789                other => Err(command_mismatch(&other, "workflow stream append")),
11790            };
11791        }
11792
11793        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11794        state.workflow_stream_command_counter += 1;
11795        let wire_items = items
11796            .iter()
11797            .enumerate()
11798            .map(|(item_index, item)| {
11799                item.wire_value(Some(format!(
11800                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
11801                )))
11802            })
11803            .collect::<Vec<_>>();
11804        let mut directive = json!({
11805            "operation": "append",
11806            "stream_name": stream_name,
11807            "command_identity": identity,
11808            "command_ordinal": command_ordinal,
11809            "items": wire_items,
11810        });
11811        if let Some(max_pending_items) = max_pending_items {
11812            directive["max_pending_items"] = json!(max_pending_items);
11813        }
11814        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11815        state.replay_clock.unavailable();
11816        state.commands.push(json!({
11817            "type": "record_side_effect",
11818            "result": result,
11819            "workflow_stream": directive,
11820        }));
11821        Ok(())
11822    }
11823
11824    /// Close a run-scoped output stream at a deterministic command boundary.
11825    pub fn close_workflow_stream(
11826        &self,
11827        stream_name: impl Into<String>,
11828        retention_seconds: Option<u64>,
11829    ) -> Result<()> {
11830        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
11831    }
11832
11833    /// Mark a run-scoped output stream errored at a deterministic command boundary.
11834    pub fn error_workflow_stream(
11835        &self,
11836        stream_name: impl Into<String>,
11837        error_reason: impl Into<String>,
11838        retention_seconds: Option<u64>,
11839    ) -> Result<()> {
11840        let error_reason = error_reason.into();
11841        if error_reason.is_empty() {
11842            return Err(Error::Codec(
11843                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
11844            ));
11845        }
11846        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
11847    }
11848
11849    fn finish_workflow_stream(
11850        &self,
11851        stream_name: String,
11852        error_reason: Option<String>,
11853        retention_seconds: Option<u64>,
11854    ) -> Result<()> {
11855        if stream_name.is_empty() {
11856            return Err(Error::Codec(
11857                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
11858            ));
11859        }
11860        if retention_seconds == Some(0) {
11861            return Err(Error::Codec(
11862                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
11863            ));
11864        }
11865        let mut state = self
11866            .state
11867            .lock()
11868            .map_err(|_| Error::WorkflowStatePoisoned)?;
11869        let command_ordinal = state.workflow_stream_command_counter;
11870        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11871            state.workflow_stream_command_counter += 1;
11872            return match recorded {
11873                RecordedCommand::SideEffect { .. } => {
11874                    state.replay_clock.unavailable();
11875                    state.command_cursor += 1;
11876                    Ok(())
11877                }
11878                other => Err(command_mismatch(&other, "workflow stream close")),
11879            };
11880        }
11881        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
11882        state.workflow_stream_command_counter += 1;
11883        let mut directive = json!({
11884            "operation": if error_reason.is_some() { "error" } else { "close" },
11885            "stream_name": stream_name,
11886            "command_identity": identity,
11887            "command_ordinal": command_ordinal,
11888        });
11889        if let Some(error_reason) = error_reason {
11890            directive["error_reason"] = json!(error_reason);
11891        }
11892        if let Some(retention_seconds) = retention_seconds {
11893            directive["retention_seconds"] = json!(retention_seconds);
11894        }
11895        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
11896        state.replay_clock.unavailable();
11897        state.commands.push(json!({
11898            "type": "record_side_effect",
11899            "result": result,
11900            "workflow_stream": directive,
11901        }));
11902        Ok(())
11903    }
11904
11905    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
11906        let identity = state.workflow_command_identity.as_str();
11907        if identity.is_empty() {
11908            return Err(Error::MissingWorkflowCommandIdentity);
11909        }
11910        Ok(identity)
11911    }
11912
11913    /// Validate, emit, or replay a typed workflow search-attribute update.
11914    ///
11915    /// The command is non-blocking within a workflow decision, but its
11916    /// `SearchAttributesUpserted` event occupies the same deterministic command
11917    /// stream as activities, timers, conditions, and other durable operations.
11918    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
11919        update.validate()?;
11920        let (attributes, attribute_types) = update.into_wire_parts();
11921        let mut state = self
11922            .state
11923            .lock()
11924            .map_err(|_| Error::WorkflowStatePoisoned)?;
11925
11926        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
11927            return match recorded {
11928                RecordedCommand::SearchAttributes {
11929                    sequence,
11930                    attributes: recorded_attributes,
11931                    attribute_types: recorded_attribute_types,
11932                } => {
11933                    if recorded_attributes != attributes {
11934                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11935                            "search_attribute_value_mismatch",
11936                            Some(sequence),
11937                            Some(recorded_attributes.to_string()),
11938                            Some(attributes.to_string()),
11939                            "search-attribute values differ from the recorded durable command",
11940                        )));
11941                    }
11942                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
11943                        if recorded_types != attribute_types {
11944                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11945                                "search_attribute_type_mismatch",
11946                                Some(sequence),
11947                                Some(json!(recorded_types).to_string()),
11948                                Some(json!(attribute_types).to_string()),
11949                                "search-attribute declared types differ from the recorded durable command",
11950                            )));
11951                        }
11952                    }
11953                    state.replay_clock.unavailable();
11954                    state.command_cursor += 1;
11955                    Ok(())
11956                }
11957                other => Err(command_mismatch(&other, "search-attribute update")),
11958            };
11959        }
11960
11961        let mut command = serde_json::Map::from_iter([
11962            ("type".to_string(), json!("upsert_search_attributes")),
11963            ("attributes".to_string(), attributes),
11964        ]);
11965        if !attribute_types.is_empty() {
11966            command.insert("attribute_types".to_string(), json!(attribute_types));
11967        }
11968        state.replay_clock.unavailable();
11969        state.commands.push(Value::Object(command));
11970        Ok(())
11971    }
11972
11973    /// Record a UUIDv4 once and return the same UUID on every replay.
11974    pub fn uuid_v4(&self) -> Result<Uuid> {
11975        self.side_effect(Uuid::new_v4)
11976    }
11977
11978    /// Select the newest supported version for a change, or replay the version
11979    /// already committed for that stable change ID.
11980    ///
11981    /// An unmarked old history that reached its next durable operation, or
11982    /// already completed, selects `-1` when that version is supported. This
11983    /// leaves the original operation available and writes no additional marker.
11984    /// Consistent markers written by older workers retain their original ordered
11985    /// positions. Repeated calls consume a matching marker at the current cursor.
11986    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
11987    pub fn get_version(
11988        &self,
11989        change_id: impl Into<String>,
11990        min_supported: i32,
11991        max_supported: i32,
11992    ) -> Result<i32> {
11993        let change_id = change_id.into();
11994        if change_id.trim().is_empty() {
11995            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
11996                "version_change_id_invalid",
11997                None,
11998                Some("non-empty change ID".to_string()),
11999                Some(change_id),
12000                "version markers require a stable non-empty change ID",
12001            )));
12002        }
12003        if min_supported > max_supported {
12004            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
12005                "version_range_invalid",
12006                None,
12007                Some("min_supported <= max_supported".to_string()),
12008                Some(format!("{min_supported}..={max_supported}")),
12009                "version marker supported range is invalid",
12010            )));
12011        }
12012
12013        let mut state = self
12014            .state
12015            .lock()
12016            .map_err(|_| Error::WorkflowStatePoisoned)?;
12017        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
12018            if let Some(RecordedCommand::VersionMarker {
12019                sequence: alias_sequence,
12020                change_id: alias_change_id,
12021                version: alias_version,
12022            }) = state.recorded_commands.get(state.command_cursor)
12023            {
12024                if alias_change_id == &change_id {
12025                    if *alias_version != version {
12026                        return Err(invalid_recorded_history(
12027                            "version_marker_conflict",
12028                            *alias_sequence,
12029                            &format!("selected version {version} for change ID {change_id:?}"),
12030                            &format!("recorded version {alias_version}"),
12031                            "recorded marker conflicts with the decision already selected during replay",
12032                        ));
12033                    }
12034                    ensure_version_supported(
12035                        &change_id,
12036                        version,
12037                        min_supported,
12038                        max_supported,
12039                        *alias_sequence,
12040                    )?;
12041                    // Older workers could record the same decision again. Keep
12042                    // each physical boundary without skipping intervening work.
12043                    state.replay_clock.unavailable();
12044                    state.command_cursor += 1;
12045                    return Ok(version);
12046                }
12047            }
12048            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
12049            return Ok(version);
12050        }
12051
12052        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
12053            return match recorded {
12054                RecordedCommand::VersionMarker {
12055                    sequence,
12056                    change_id: recorded_change_id,
12057                    version,
12058                    ..
12059                } => {
12060                    if recorded_change_id != change_id {
12061                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
12062                            "version_change_id_mismatch",
12063                            Some(sequence),
12064                            Some(recorded_change_id),
12065                            Some(change_id),
12066                            "recorded version marker change ID differs from current workflow code",
12067                        )));
12068                    }
12069                    ensure_version_supported(
12070                        &change_id,
12071                        version,
12072                        min_supported,
12073                        max_supported,
12074                        sequence,
12075                    )?;
12076                    state.replay_clock.unavailable();
12077                    state.command_cursor += 1;
12078                    state.version_markers.insert(change_id, (version, sequence));
12079                    Ok(version)
12080                }
12081                other => {
12082                    let version = -1;
12083                    let sequence = other.sequence();
12084                    ensure_version_supported(
12085                        &change_id,
12086                        version,
12087                        min_supported,
12088                        max_supported,
12089                        sequence,
12090                    )?;
12091                    // The existing operation proves this patch site was reached
12092                    // before its marker existed. Keep its original cursor.
12093                    state.version_markers.insert(change_id, (version, sequence));
12094                    Ok(version)
12095                }
12096            };
12097        }
12098
12099        if state
12100            .history_events
12101            .iter()
12102            .any(|event| event.event_type == "WorkflowCompleted")
12103        {
12104            let version = -1;
12105            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
12106            state.version_markers.insert(change_id, (version, 0));
12107            return Ok(version);
12108        }
12109
12110        let version = max_supported;
12111        state.replay_clock.unavailable();
12112        state.commands.push(json!({
12113            "type": "record_version_marker",
12114            "change_id": change_id,
12115            "version": version,
12116            "min_supported": min_supported,
12117            "max_supported": max_supported,
12118        }));
12119        // Sequence numbers are assigned by the server. Zero identifies a marker
12120        // selected in this uncommitted decision batch for duplicate-call checks.
12121        state.version_markers.insert(change_id, (version, 0));
12122        Ok(version)
12123    }
12124
12125    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
12126    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
12127        Ok(self.get_version(change_id, -1, 1)? == 1)
12128    }
12129
12130    /// Keep a patch marker in history after the legacy branch has been removed.
12131    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
12132        self.get_version(change_id, -1, 1).map(|_| ())
12133    }
12134
12135    /// Merge non-indexed workflow memo metadata through durable history.
12136    ///
12137    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
12138    /// public Avro payload envelope consumed by Server and Cloud runtimes.
12139    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
12140        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
12141        let mut state = self
12142            .state
12143            .lock()
12144            .map_err(|_| Error::WorkflowStatePoisoned)?;
12145
12146        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
12147            return match recorded {
12148                RecordedCommand::Memo {
12149                    sequence,
12150                    entries: recorded_entries,
12151                } => {
12152                    if recorded_entries != entries {
12153                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
12154                            "memo_update_mismatch",
12155                            Some(sequence),
12156                            Some(format!("{recorded_entries:?}")),
12157                            Some(format!("{entries:?}")),
12158                            "recorded memo entries differ from the current workflow update",
12159                        )));
12160                    }
12161                    state.replay_clock.unavailable();
12162                    state.command_cursor += 1;
12163                    Ok(())
12164                }
12165                other => Err(command_mismatch(&other, "memo upsert")),
12166            };
12167        }
12168
12169        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
12170        state.replay_clock.unavailable();
12171        state.commands.push(json!({
12172            "type": "upsert_memo",
12173            "entries": entries_envelope,
12174        }));
12175        Ok(())
12176    }
12177
12178    /// Start a named durable child on an explicit queue and await its result.
12179    ///
12180    /// The command is recorded in the parent's sequence-ordered durable command
12181    /// stream. Replay keeps a scheduled child pending without emitting another
12182    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
12183    /// values preserve the history payload codec and include both sides of the
12184    /// durable relationship; failures are returned as
12185    /// [`Error::ChildWorkflowFailed`].
12186    ///
12187    /// ```no_run
12188    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
12189    /// # fn configure(client: Client) {
12190    /// let mut worker = Worker::new(client, "parent-workers");
12191    /// worker.register_workflow("order-parent", |ctx, _input| async move {
12192    ///     let child = ctx
12193    ///         .start_child_workflow(
12194    ///             "fulfil-order",
12195    ///             ChildWorkflowOptions::new("fulfilment-workers")
12196    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
12197    ///             json!([{"order_id": "order-42"}]),
12198    ///         )
12199    ///         .await?;
12200    ///     Ok(child.result)
12201    /// });
12202    /// # }
12203    /// ```
12204    pub fn start_child_workflow<T: Serialize>(
12205        &self,
12206        workflow_type: impl Into<String>,
12207        options: ChildWorkflowOptions,
12208        args: T,
12209    ) -> ChildWorkflowCall {
12210        ChildWorkflowCall {
12211            ctx: self.clone(),
12212            workflow_type: workflow_type.into(),
12213            options,
12214            args: Some(AvroValue::from_serialize(&args)),
12215            scheduled: false,
12216            matched_pending: false,
12217            parallel_group_path: Vec::new(),
12218        }
12219    }
12220
12221    pub async fn start_child_workflow_avro_value<T: Serialize>(
12222        &self,
12223        workflow_type: impl Into<String>,
12224        options: ChildWorkflowOptions,
12225        args: T,
12226    ) -> Result<ChildWorkflowAvroResult> {
12227        let mut call = self.start_child_workflow(workflow_type, options, args);
12228        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
12229    }
12230
12231    fn take_commands(&self) -> Result<Vec<Value>> {
12232        let mut state = self
12233            .state
12234            .lock()
12235            .map_err(|_| Error::WorkflowStatePoisoned)?;
12236        Ok(std::mem::take(&mut state.commands))
12237    }
12238
12239    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
12240        let mut state = self
12241            .state
12242            .lock()
12243            .map_err(|_| Error::WorkflowStatePoisoned)?;
12244
12245        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
12246            return Err(command_mismatch(&recorded, "continue as new"));
12247        }
12248        if state.recorded_continue_as_new_sequence.is_some() {
12249            state.continue_as_new_consumed = true;
12250            return Ok(None);
12251        }
12252
12253        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
12254        let mut command = serde_json::Map::from_iter([
12255            ("type".to_string(), json!("continue_as_new")),
12256            ("arguments".to_string(), arguments),
12257            ("queue".to_string(), json!(state.task_queue.clone())),
12258        ]);
12259        if let Some(workflow_type) = request.options.workflow_type {
12260            command.insert("workflow_type".to_string(), json!(workflow_type));
12261        }
12262        if let Some(task_queue) = request.options.task_queue {
12263            command.insert("queue".to_string(), json!(task_queue));
12264        }
12265        Ok(Some(Value::Object(command)))
12266    }
12267
12268    fn matched_recorded_pending(&self) -> Result<bool> {
12269        let state = self
12270            .state
12271            .lock()
12272            .map_err(|_| Error::WorkflowStatePoisoned)?;
12273        Ok(state.matched_recorded_pending)
12274    }
12275
12276    fn ensure_history_consumed(&self) -> Result<()> {
12277        let state = self
12278            .state
12279            .lock()
12280            .map_err(|_| Error::WorkflowStatePoisoned)?;
12281        if let Some(replay) = &state.scope_delivery {
12282            if let Some((&sequence, _)) = replay
12283                .canonical
12284                .deliveries
12285                .iter()
12286                .find(|(sequence, _)| !replay.consumed.contains(sequence))
12287            {
12288                return Err(invalid_recorded_history(
12289                    "cancellation_scope_delivery_unconsumed",
12290                    sequence,
12291                    "original scoped delivery",
12292                    "workflow completion",
12293                    "workflow completed without consuming its committed scope delivery",
12294                ));
12295            }
12296        }
12297        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
12298            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
12299                "recorded_commands_unconsumed",
12300                Some(command.sequence()),
12301                Some(command.shape().to_string()),
12302                Some("workflow completion".to_string()),
12303                "workflow completed before consuming all recorded durable commands",
12304            )));
12305        }
12306        if let Some(delivery) = state
12307            .cancellation_history
12308            .delivery
12309            .as_ref()
12310            .filter(|_| !state.cancellation_consumed)
12311        {
12312            return Err(invalid_recorded_history(
12313                "cooperative_cancellation_unconsumed",
12314                delivery.sequence,
12315                "committed cancellation call",
12316                "workflow completion",
12317                "workflow completed without reaching its committed cancellation boundary",
12318            ));
12319        }
12320        if let Some(sequence) = state
12321            .recorded_continue_as_new_sequence
12322            .filter(|_| !state.continue_as_new_consumed)
12323        {
12324            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
12325                "recorded_continue_as_new_unconsumed",
12326                Some(sequence),
12327                Some("continue as new".to_string()),
12328                Some("workflow completion".to_string()),
12329                "workflow completed without consuming its recorded continue-as-new transition",
12330            )));
12331        }
12332        Ok(())
12333    }
12334}
12335
12336fn contiguous_message_stream_count(
12337    pending: &[MessageStreamMessage],
12338    cursor: u64,
12339    max_items: usize,
12340) -> usize {
12341    pending
12342        .iter()
12343        .take(max_items)
12344        .enumerate()
12345        .take_while(|(offset, message)| {
12346            u64::try_from(*offset)
12347                .ok()
12348                .and_then(|offset| cursor.checked_add(offset + 1))
12349                == Some(message.position)
12350        })
12351        .count()
12352}
12353
12354fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
12355    matches!(
12356        event.event_type.as_str(),
12357        "ActivityScheduled"
12358            | "TimerScheduled"
12359            | "ChildWorkflowScheduled"
12360            | "SignalWaitOpened"
12361            | "ConditionWaitOpened"
12362            | "SearchAttributesUpserted"
12363            | "SideEffectRecorded"
12364            | "VersionMarkerRecorded"
12365            | "MemoUpserted"
12366            | "WorkflowContinuedAsNew"
12367    )
12368}
12369
12370#[derive(Debug)]
12371struct WorkflowState {
12372    observation_namespace: Option<String>,
12373    observation_terminal: bool,
12374    // A pending recorded call consumes its descriptor before yielding. Cursor
12375    // exhaustion alone therefore cannot make the surrounding poll live.
12376    observation_pending: bool,
12377    workflow_id: Option<String>,
12378    run_id: Option<String>,
12379    task_queue: String,
12380    payload_codec: String,
12381    history_events: Arc<Vec<HistoryEvent>>,
12382    history_budget: WorkflowHistoryBudget,
12383    cancel_requested: bool,
12384    cancellation_history: CancellationHistory,
12385    cancellation_consumed: bool,
12386    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
12387    replay_clock: replay_clock::Clock,
12388    cancellation_shield_depth: u64,
12389    cancellation_delivery_enabled: bool,
12390    cancellation_delivery_intent: Option<CancellationDelivery>,
12391    cancellation_delivery_command_count: usize,
12392    allow_cancellation_scope_authoring: bool,
12393    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
12394    cancellation_scope_memberships: BTreeMap<u64, String>,
12395    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
12396    resume_signal: Option<ResumeSignal>,
12397    recorded_commands: Vec<RecordedCommand>,
12398    selection_markers: Vec<SelectionMarker>,
12399    selection_marker_cursor: usize,
12400    cancelled_selection_members: Vec<SelectionCancellation>,
12401    recorded_continue_as_new_sequence: Option<u64>,
12402    continue_as_new_consumed: bool,
12403    command_cursor: usize,
12404    condition_wait_occurrence_counter: u64,
12405    matched_recorded_pending: bool,
12406    version_markers: HashMap<String, (i32, u64)>,
12407    workflow_command_identity: String,
12408    workflow_stream_command_counter: u64,
12409    commands: Vec<Value>,
12410    local_activity_requests: Vec<local_activity::Request>,
12411    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
12412    message_stream_cursors: HashMap<String, u64>,
12413    message_stream_waits: HashMap<String, u64>,
12414}
12415
12416/// `cancellation_reason` of an `ActivityCancelled` that the run's own close
12417/// recorded for an activity it never awaited, such as a `select()` loser
12418/// (workflow#1117, server#1193).
12419const RUN_CLOSED_CANCELLATION_REASON: &str = "run_closed";
12420
12421/// Whether this history event is an activity cancellation recorded by its
12422/// run's close rather than an outcome the workflow could have observed.
12423///
12424/// The close appends it in the closing transaction, after the workflow had
12425/// already moved past the operation, so replay never treats it as a
12426/// selection winner, an `all()` member failure or an awaited outcome.
12427fn settled_at_run_close(event: &HistoryEvent) -> bool {
12428    event.event_type == "ActivityCancelled"
12429        && event
12430            .payload
12431            .get("cancellation_reason")
12432            .and_then(Value::as_str)
12433            == Some(RUN_CLOSED_CANCELLATION_REASON)
12434}
12435
12436/// History as the workflow observed it: run-close cancellations are left
12437/// out, so each such activity replays as still open.
12438fn history_observed_by_workflow(mut history: Vec<HistoryEvent>) -> Vec<HistoryEvent> {
12439    history.retain(|event| !settled_at_run_close(event));
12440    history
12441}
12442
12443impl WorkflowState {
12444    #[cfg(test)]
12445    fn new(
12446        history: Vec<HistoryEvent>,
12447        task_queue: String,
12448        payload_codec: String,
12449        resume_signal: Option<ResumeSignal>,
12450    ) -> Result<Self> {
12451        Self::new_with_identity(
12452            history,
12453            None,
12454            None,
12455            task_queue,
12456            payload_codec,
12457            resume_signal,
12458        )
12459    }
12460
12461    fn new_with_identity(
12462        history: Vec<HistoryEvent>,
12463        workflow_id: Option<String>,
12464        run_id: Option<String>,
12465        task_queue: String,
12466        payload_codec: String,
12467        resume_signal: Option<ResumeSignal>,
12468    ) -> Result<Self> {
12469        Self::new_with_identity_and_scopes(
12470            history,
12471            workflow_id,
12472            run_id,
12473            task_queue,
12474            payload_codec,
12475            resume_signal,
12476            false,
12477        )
12478    }
12479
12480    fn new_with_identity_and_scopes(
12481        history: Vec<HistoryEvent>,
12482        workflow_id: Option<String>,
12483        run_id: Option<String>,
12484        task_queue: String,
12485        payload_codec: String,
12486        resume_signal: Option<ResumeSignal>,
12487        allow_cancellation_scope_authoring: bool,
12488    ) -> Result<Self> {
12489        Self::new_with_identity_and_scope_delivery(
12490            history,
12491            workflow_id,
12492            run_id,
12493            task_queue,
12494            payload_codec,
12495            resume_signal,
12496            allow_cancellation_scope_authoring,
12497            false,
12498        )
12499    }
12500
12501    fn new_with_identity_and_scope_delivery(
12502        history: Vec<HistoryEvent>,
12503        workflow_id: Option<String>,
12504        run_id: Option<String>,
12505        task_queue: String,
12506        payload_codec: String,
12507        resume_signal: Option<ResumeSignal>,
12508        allow_cancellation_scope_authoring: bool,
12509        allow_cancellation_scope_delivery: bool,
12510    ) -> Result<Self> {
12511        // The history budget counts every committed event, including any
12512        // the run's close recorded.
12513        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
12514        let history = history_observed_by_workflow(history);
12515        cooperative_cancellation::assert_cancellation_scope_replay_supported(
12516            &history,
12517            allow_cancellation_scope_authoring,
12518            allow_cancellation_scope_delivery,
12519        )?;
12520        let scopes = if allow_cancellation_scope_authoring {
12521            cancellation_scope::CancellationScopeHistory::read(
12522                &history,
12523                run_id.as_deref().unwrap_or_default(),
12524            )?
12525        } else {
12526            cancellation_scope::CancellationScopeHistory::default()
12527        };
12528        let cancellation_history = CancellationHistory::from_events(
12529            &history,
12530            run_id.as_deref().unwrap_or_default(),
12531            None,
12532        )?;
12533        if allow_cancellation_scope_authoring
12534            && cancellation_history.request.is_some()
12535            && !allow_cancellation_scope_delivery
12536        {
12537            return Err(Error::CancellationScopeExecutionUnavailable);
12538        }
12539        let scope_delivery = if allow_cancellation_scope_delivery {
12540            Some(cancellation_scope_replay::ScopeReplay::read(
12541                &history,
12542                &scopes,
12543                run_id.as_deref().unwrap_or_default(),
12544                workflow_id.as_deref().unwrap_or_default(),
12545            )?)
12546        } else {
12547            None
12548        };
12549        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
12550            &history,
12551            &payload_codec,
12552            WorkflowIdentity {
12553                workflow_id: workflow_id.clone(),
12554                run_id: run_id.clone(),
12555            },
12556        )?)?;
12557        for (sequence, opening) in &scopes.openings {
12558            if recorded_commands
12559                .iter()
12560                .any(|command| command.sequence() == *sequence)
12561            {
12562                return Err(invalid_recorded_history(
12563                    "invalid_cancellation_scope_history",
12564                    *sequence,
12565                    "distinct authored scope opening",
12566                    "operation collision",
12567                    "scope opening collides with a command",
12568                ));
12569            }
12570            recorded_commands.push(RecordedCommand::CancellationScope {
12571                sequence: *sequence,
12572                scope_id: opening.scope_id.clone(),
12573                parent_scope_id: opening.parent_scope_id.clone(),
12574                shield_parent: opening.shield_parent,
12575            });
12576        }
12577        recorded_commands.sort_by_key(RecordedCommand::sequence);
12578        if let Some(replay) = &scope_delivery {
12579            replay.bind_commands(&mut recorded_commands)?;
12580        }
12581        let recorded_commands = group_condition_reopens_by_member(recorded_commands);
12582        let selection_markers = recorded_selection_markers(&history)?;
12583        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
12584        let recorded_continue_as_new = history
12585            .iter()
12586            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
12587            .collect::<Vec<_>>();
12588        if recorded_continue_as_new.len() > 1 {
12589            return Err(invalid_recorded_history(
12590                "duplicate_continue_as_new_transition",
12591                recorded_continue_as_new
12592                    .last()
12593                    .and_then(|event| durable_event_sequence(event))
12594                    .unwrap_or(0),
12595                "one WorkflowContinuedAsNew event",
12596                &format!(
12597                    "{} WorkflowContinuedAsNew events",
12598                    recorded_continue_as_new.len()
12599                ),
12600                "workflow history records one continue-as-new transition more than once",
12601            ));
12602        }
12603        let recorded_continue_as_new_sequence = recorded_continue_as_new
12604            .first()
12605            .map(|event| {
12606                durable_event_sequence(event).ok_or_else(|| {
12607                    Error::NonDeterministicReplay(ReplayFailure::new(
12608                        "continue_as_new_sequence_missing",
12609                        None,
12610                        Some("recorded transition sequence".to_string()),
12611                        Some("missing sequence".to_string()),
12612                        "WorkflowContinuedAsNew history is missing its recorded sequence",
12613                    ))
12614                })
12615            })
12616            .transpose()?;
12617        let mut message_stream_cursors = HashMap::new();
12618        for event in &history {
12619            if !matches!(
12620                event.event_type.as_str(),
12621                "SignalReceived" | "SignalApplied"
12622            ) || event.payload.get("signal_name").and_then(Value::as_str)
12623                != Some(MESSAGE_STREAM_SIGNAL)
12624            {
12625                continue;
12626            }
12627            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
12628            if arguments.len() != 1 {
12629                continue;
12630            }
12631            let envelope = arguments[0].clone().into_json()?;
12632            let Some(envelope) = envelope.as_object() else {
12633                continue;
12634            };
12635            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
12636            {
12637                continue;
12638            }
12639            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
12640                continue;
12641            };
12642            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
12643            else {
12644                continue;
12645            };
12646            let cursor = message_stream_cursors
12647                .entry(stream_name.to_string())
12648                .or_insert(0);
12649            *cursor = (*cursor).max(through_position);
12650        }
12651        let cancel_requested = history.iter().any(|event| {
12652            matches!(
12653                event.event_type.as_str(),
12654                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
12655            )
12656        });
12657        let cancellation_clock = cancellation_history
12658            .request
12659            .as_ref()
12660            .and_then(|request| request.context.as_ref())
12661            .map(|_| {
12662                cancellation_replay_clock::ReplayClock::new(
12663                    &history,
12664                    &recorded_commands,
12665                    cancellation_history.delivery_index,
12666                )
12667            })
12668            .or_else(|| {
12669                scope_delivery.as_ref().map(|_| {
12670                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
12671                })
12672            });
12673        Ok(Self {
12674            observation_namespace: None,
12675            observation_terminal: history.iter().any(|event| {
12676                matches!(
12677                    event.event_type.as_str(),
12678                    "WorkflowCompleted"
12679                        | "WorkflowFailed"
12680                        | "WorkflowCancelled"
12681                        | "WorkflowTerminated"
12682                        | "WorkflowTimedOut"
12683                        | "WorkflowContinuedAsNew"
12684                )
12685            }),
12686            observation_pending: false,
12687            workflow_command_identity: String::new(),
12688            workflow_stream_command_counter: 0,
12689            workflow_id,
12690            run_id,
12691            task_queue,
12692            payload_codec,
12693            replay_clock: replay_clock::Clock::new(&history, &recorded_commands),
12694            history_events: Arc::new(history),
12695            history_budget: WorkflowHistoryBudget {
12696                event_count,
12697                ..WorkflowHistoryBudget::default()
12698            },
12699            cancel_requested,
12700            cancellation_history,
12701            cancellation_consumed: false,
12702            cancellation_clock,
12703            cancellation_shield_depth: 0,
12704            cancellation_delivery_enabled: false,
12705            cancellation_delivery_intent: None,
12706            cancellation_delivery_command_count: 0,
12707            allow_cancellation_scope_authoring,
12708            cancellation_scope_opening: None,
12709            cancellation_scope_memberships: scopes.memberships,
12710            scope_delivery,
12711            resume_signal,
12712            recorded_commands,
12713            selection_markers,
12714            selection_marker_cursor: 0,
12715            cancelled_selection_members,
12716            recorded_continue_as_new_sequence,
12717            continue_as_new_consumed: false,
12718            command_cursor: 0,
12719            condition_wait_occurrence_counter: 0,
12720            matched_recorded_pending: false,
12721            version_markers: HashMap::new(),
12722            commands: Vec::new(),
12723            local_activity_requests: Vec::new(),
12724            message_stream_messages: HashMap::new(),
12725            message_stream_cursors,
12726            message_stream_waits: HashMap::new(),
12727        })
12728    }
12729}
12730
12731enum MessageStreamDelivery {
12732    Message(MessageStreamMessage),
12733    Cursor {
12734        stream_name: String,
12735        through_position: u64,
12736    },
12737}
12738
12739fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
12740    if arguments.len() != 1 {
12741        return Ok(None);
12742    }
12743    let envelope = arguments
12744        .into_iter()
12745        .next()
12746        .expect("one argument was checked");
12747    let Some(envelope) = envelope.as_object() else {
12748        return Ok(None);
12749    };
12750    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
12751        return Ok(None);
12752    };
12753    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
12754        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
12755        else {
12756            return Ok(None);
12757        };
12758        return Ok(Some(MessageStreamDelivery::Cursor {
12759            stream_name: stream_name.to_string(),
12760            through_position,
12761        }));
12762    }
12763    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
12764        return Ok(None);
12765    }
12766    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
12767        return Ok(None);
12768    };
12769    let Some(position) = envelope
12770        .get("position")
12771        .and_then(Value::as_u64)
12772        .filter(|value| *value > 0)
12773    else {
12774        return Ok(None);
12775    };
12776    let Some(payload_envelope) = envelope.get("payload_envelope") else {
12777        return Ok(None);
12778    };
12779    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
12780    else {
12781        return Ok(None);
12782    };
12783    let decoded = decode_avro_value(&payload_envelope)?;
12784    let AvroValue::Array(values) = decoded else {
12785        return Ok(None);
12786    };
12787    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
12788        stream_name: stream_name.to_string(),
12789        message_id: message_id.to_string(),
12790        position,
12791        arguments: values,
12792    })))
12793}
12794
12795#[derive(Clone, Debug)]
12796enum RecordedCommand {
12797    ServiceOperation {
12798        sequence: u64,
12799        call: nexus::RecordedServiceCall,
12800    },
12801    CancellationScope {
12802        sequence: u64,
12803        scope_id: String,
12804        parent_scope_id: String,
12805        shield_parent: bool,
12806    },
12807    CancellationGroup {
12808        sequence: u64,
12809        span: u64,
12810        original: Vec<RecordedCommand>,
12811    },
12812    CancellationBoundary {
12813        sequence: u64,
12814        call_kind: CancellationCallKind,
12815        original: Option<Box<RecordedCommand>>,
12816    },
12817    Activity {
12818        sequence: u64,
12819        activity_type: Option<String>,
12820        cancellation_policy: String,
12821        options: Option<RecordedActivityOptions>,
12822        outcome: Option<ActivityOutcome>,
12823        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12824    },
12825    Timer {
12826        sequence: u64,
12827        delay_seconds: u64,
12828        fired: bool,
12829        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12830    },
12831    ChildWorkflow {
12832        sequence: u64,
12833        workflow_type: Option<String>,
12834        policies: RecordedChildPolicies,
12835        outcome: Option<ChildWorkflowOutcome>,
12836        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12837    },
12838    SignalWait {
12839        sequence: u64,
12840        signal_name: String,
12841        value: Option<Vec<AvroValue>>,
12842        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12843    },
12844    ConditionWait {
12845        sequence: u64,
12846        occurrence_id: String,
12847        condition_key: Option<String>,
12848        predicate_identity: String,
12849        timeout_seconds: Option<u64>,
12850        result: Option<ConditionWaitResult>,
12851        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
12852    },
12853    SearchAttributes {
12854        sequence: u64,
12855        attributes: Value,
12856        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
12857    },
12858    SideEffect {
12859        sequence: u64,
12860        value: AvroValue,
12861    },
12862    VersionMarker {
12863        sequence: u64,
12864        change_id: String,
12865        version: i32,
12866    },
12867    Memo {
12868        sequence: u64,
12869        entries: AvroValue,
12870    },
12871}
12872
12873#[derive(Clone, Debug, PartialEq, Eq)]
12874struct SelectionMarker {
12875    selection_group_id: String,
12876    selection_group_base_sequence: u64,
12877    selection_group_size: usize,
12878    member_key: SelectionKey,
12879    member_index: usize,
12880    member_base_sequence: u64,
12881    member_size: usize,
12882    operation_kind: String,
12883    operation_identity: String,
12884    outcome: String,
12885    resolution_event_id: String,
12886    resolution_event_type: String,
12887}
12888
12889#[derive(Clone, Debug, PartialEq, Eq)]
12890struct SelectionCancellation {
12891    selection_group_id: String,
12892    member_key: SelectionKey,
12893    member_index: usize,
12894    member_base_sequence: u64,
12895    member_size: usize,
12896    operation_kind: String,
12897    operation_identity: String,
12898}
12899
12900fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
12901    let mut markers: Vec<SelectionMarker> = Vec::new();
12902    for event in events
12903        .iter()
12904        .filter(|event| event.event_type == "SelectionResolved")
12905    {
12906        let payload = &event.payload;
12907        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
12908        let group_size = required_selection_usize(payload, "selection_group_size")?;
12909        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
12910        let member_size = required_selection_usize(payload, "member_size")?;
12911        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
12912        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
12913            invalid_recorded_history(
12914                "selection_marker_invalid",
12915                base_sequence,
12916                "non-empty selection_group_id",
12917                &payload.to_string(),
12918                "selection winner history is missing its durable group identity",
12919            )
12920        })?;
12921        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
12922        if group_id != expected_group_id {
12923            return Err(invalid_recorded_history(
12924                "selection_marker_invalid",
12925                base_sequence,
12926                &expected_group_id,
12927                &group_id,
12928                "selection winner history contains an incompatible group identity",
12929            ));
12930        }
12931        let group_end = base_sequence
12932            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
12933            .unwrap_or(u64::MAX);
12934        let member_end = member_base_sequence
12935            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
12936            .unwrap_or(u64::MAX);
12937        if member_index >= group_size
12938            || member_base_sequence < base_sequence
12939            || member_end > group_end
12940        {
12941            return Err(invalid_recorded_history(
12942                "selection_marker_invalid",
12943                base_sequence,
12944                "winner member within selection group bounds",
12945                &payload.to_string(),
12946                "selection winner history contains an invalid member range",
12947            ));
12948        }
12949        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
12950            invalid_recorded_history(
12951                "selection_marker_invalid",
12952                base_sequence,
12953                "selection operation kind",
12954                &payload.to_string(),
12955                "selection winner history is missing its operation kind",
12956            )
12957        })?;
12958        if !matches!(
12959            operation_kind.as_str(),
12960            "activity" | "child" | "timer" | "signal" | "condition" | "group"
12961        ) {
12962            return Err(invalid_recorded_history(
12963                "selection_marker_invalid",
12964                base_sequence,
12965                "activity, child, timer, signal, condition, or group",
12966                &operation_kind,
12967                "selection winner history contains an unsupported operation kind",
12968            ));
12969        }
12970        let operation_identity =
12971            payload_string(payload, "operation_identity").ok_or_else(|| {
12972                invalid_recorded_history(
12973                    "selection_marker_invalid",
12974                    base_sequence,
12975                    "non-empty operation identity",
12976                    &payload.to_string(),
12977                    "selection winner history is missing its durable operation identity",
12978                )
12979            })?;
12980        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
12981            invalid_recorded_history(
12982                "selection_marker_invalid",
12983                base_sequence,
12984                "completed or failed selection outcome",
12985                &payload.to_string(),
12986                "selection winner history is missing its outcome",
12987            )
12988        })?;
12989        if !matches!(outcome.as_str(), "completed" | "failed") {
12990            return Err(invalid_recorded_history(
12991                "selection_marker_invalid",
12992                base_sequence,
12993                "completed or failed selection outcome",
12994                &outcome,
12995                "selection winner history contains an unsupported outcome",
12996            ));
12997        }
12998        let marker = SelectionMarker {
12999            selection_group_id: group_id,
13000            selection_group_base_sequence: base_sequence,
13001            selection_group_size: group_size,
13002            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
13003            member_index,
13004            member_base_sequence,
13005            member_size,
13006            operation_kind,
13007            operation_identity,
13008            outcome,
13009            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
13010                || {
13011                    invalid_recorded_history(
13012                        "selection_marker_invalid",
13013                        base_sequence,
13014                        "durable resolution_event_id",
13015                        &payload.to_string(),
13016                        "selection winner history is missing its terminal event identity",
13017                    )
13018                },
13019            )?,
13020            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
13021                || {
13022                    invalid_recorded_history(
13023                        "selection_marker_invalid",
13024                        base_sequence,
13025                        "durable resolution_event_type",
13026                        &payload.to_string(),
13027                        "selection winner history is missing its terminal event type",
13028                    )
13029                },
13030            )?,
13031        };
13032        if let Some(existing) = markers
13033            .iter()
13034            .find(|existing| existing.selection_group_id == marker.selection_group_id)
13035        {
13036            if existing != &marker {
13037                return Err(invalid_recorded_history(
13038                    "selection_marker_conflict",
13039                    base_sequence,
13040                    &format!("one winner for {}", marker.selection_group_id),
13041                    &payload.to_string(),
13042                    "selection history records conflicting winners for one durable group",
13043                ));
13044            }
13045            continue;
13046        }
13047        markers.push(marker);
13048    }
13049    Ok(markers)
13050}
13051
13052fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
13053    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
13054    for event in events
13055        .iter()
13056        .filter(|event| event.event_type == "SelectionOperationCancelled")
13057    {
13058        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
13059            invalid_recorded_history(
13060                "selection_cancellation_invalid",
13061                0,
13062                "non-empty selection_group_id",
13063                &event.payload.to_string(),
13064                "selection cancellation history is missing its group identity",
13065            )
13066        })?;
13067        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
13068        let marker = SelectionCancellation {
13069            selection_group_id: group_id,
13070            member_key: selection_key_from_value(
13071                event.payload.get("member_key"),
13072                member_base_sequence,
13073            )?,
13074            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
13075            member_base_sequence,
13076            member_size: required_selection_usize(&event.payload, "member_size")?,
13077            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
13078                invalid_recorded_history(
13079                    "selection_cancellation_invalid",
13080                    member_base_sequence,
13081                    "selection operation kind",
13082                    &event.payload.to_string(),
13083                    "selection cancellation is missing its operation kind",
13084                )
13085            })?,
13086            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
13087                || {
13088                    invalid_recorded_history(
13089                        "selection_cancellation_invalid",
13090                        member_base_sequence,
13091                        "selection operation identity",
13092                        &event.payload.to_string(),
13093                        "selection cancellation is missing its operation identity",
13094                    )
13095                },
13096            )?,
13097        };
13098        if let Some(existing) = cancelled.iter().find(|recorded| {
13099            recorded.selection_group_id == marker.selection_group_id
13100                && recorded.member_base_sequence == marker.member_base_sequence
13101        }) {
13102            if existing != &marker {
13103                return Err(invalid_recorded_history(
13104                    "selection_cancellation_conflict",
13105                    member_base_sequence,
13106                    "one stable SelectionOperationCancelled marker",
13107                    &event.payload.to_string(),
13108                    "selection cancellation history contains conflicting member metadata",
13109                ));
13110            }
13111        } else {
13112            cancelled.push(marker);
13113        }
13114    }
13115    Ok(cancelled)
13116}
13117
13118fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
13119    payload
13120        .get(field)
13121        .and_then(value_as_u64)
13122        .filter(|value| *value > 0)
13123        .ok_or_else(|| {
13124            invalid_recorded_history(
13125                "selection_marker_invalid",
13126                0,
13127                &format!("positive integer {field}"),
13128                &payload.to_string(),
13129                "selection history contains invalid durable identity metadata",
13130            )
13131        })
13132}
13133
13134fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
13135    required_selection_usize_allow_zero(payload, field).and_then(|value| {
13136        if value > 0 {
13137            Ok(value)
13138        } else {
13139            Err(invalid_recorded_history(
13140                "selection_marker_invalid",
13141                0,
13142                &format!("positive integer {field}"),
13143                &payload.to_string(),
13144                "selection history contains invalid durable identity metadata",
13145            ))
13146        }
13147    })
13148}
13149
13150fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
13151    payload
13152        .get(field)
13153        .and_then(value_as_u64)
13154        .and_then(|value| usize::try_from(value).ok())
13155        .ok_or_else(|| {
13156            invalid_recorded_history(
13157                "selection_marker_invalid",
13158                0,
13159                &format!("non-negative integer {field}"),
13160                &payload.to_string(),
13161                "selection history contains invalid durable identity metadata",
13162            )
13163        })
13164}
13165
13166#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
13167struct RecordedActivityOptions {
13168    task_queue: RecordedSnapshotValue<Option<String>>,
13169    execution_mode: RecordedSnapshotValue<Option<String>>,
13170    retry_policy: ActivityRetrySnapshot,
13171    worker_session: Option<Value>,
13172}
13173
13174#[derive(Clone, Debug)]
13175struct RecordedChildPolicies {
13176    parent_close_policy: String,
13177    cancellation_policy: String,
13178}
13179
13180fn recorded_activity_cancellation_policy(
13181    events: &[&HistoryEvent],
13182    sequence: u64,
13183) -> Result<String> {
13184    let mut policy: Option<String> = None;
13185    for event in events.iter().filter(|event| {
13186        matches!(
13187            event.event_type.as_str(),
13188            "ActivityScheduled"
13189                | "ActivityStarted"
13190                | "ActivityCompleted"
13191                | "ActivityFailed"
13192                | "ActivityTimedOut"
13193                | "ActivityCancelled"
13194        )
13195    }) {
13196        for source in [Some(&event.payload), event.payload.get("activity")]
13197            .into_iter()
13198            .flatten()
13199        {
13200            let Some(value) = source.get("cancellation_policy") else {
13201                continue;
13202            };
13203            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
13204                value.as_str()
13205            else {
13206                return Err(invalid_recorded_history(
13207                    "invalid_activity_cancellation_policy_history",
13208                    sequence,
13209                    "supported Activity cancellation policy",
13210                    &value.to_string(),
13211                    "Activity history contains an invalid cancellation policy",
13212                ));
13213            };
13214            if let Some(previous) = policy.as_deref() {
13215                if previous != incoming {
13216                    return Err(invalid_recorded_history(
13217                        "activity_cancellation_policy_history_conflict",
13218                        sequence,
13219                        previous,
13220                        incoming,
13221                        "Activity cancellation policy changed between history events",
13222                    ));
13223                }
13224            }
13225            policy = Some(incoming.to_string());
13226        }
13227        policy.get_or_insert_with(|| "try_cancel".to_string());
13228    }
13229    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
13230}
13231
13232fn recorded_child_policy_value<'a>(
13233    payload: &'a Value,
13234    field: &str,
13235    sequence: u64,
13236) -> Result<Option<&'a str>> {
13237    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
13238        return Ok(None);
13239    };
13240    let valid = match (field, value.as_str()) {
13241        (
13242            "parent_close_policy",
13243            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
13244        ) => true,
13245        ("cancellation_policy", Some("abandon" | "try_cancel" | "wait_cancellation_completed")) => {
13246            true
13247        }
13248        _ => false,
13249    };
13250    if !valid {
13251        return Err(invalid_recorded_history(
13252            "invalid_child_workflow_policy_history",
13253            sequence,
13254            "supported child workflow policy",
13255            &value.to_string(),
13256            "child workflow history contains an invalid policy",
13257        ));
13258    }
13259    Ok(value.as_str())
13260}
13261
13262fn recorded_child_policies(
13263    events: &[&HistoryEvent],
13264    scheduled: &HistoryEvent,
13265    sequence: u64,
13266) -> Result<RecordedChildPolicies> {
13267    let parent_close_policy =
13268        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
13269            .unwrap_or("abandon")
13270            .to_string();
13271    let cancellation_policy =
13272        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
13273            .unwrap_or("abandon")
13274            .to_string();
13275    for event in events {
13276        for (field, expected) in [
13277            ("parent_close_policy", parent_close_policy.as_str()),
13278            ("cancellation_policy", cancellation_policy.as_str()),
13279        ] {
13280            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
13281                if actual != expected {
13282                    return Err(invalid_recorded_history(
13283                        "child_workflow_policy_history_conflict",
13284                        sequence,
13285                        expected,
13286                        actual,
13287                        "child workflow policy changed between history events",
13288                    ));
13289                }
13290            }
13291        }
13292    }
13293    Ok(RecordedChildPolicies {
13294        parent_close_policy,
13295        cancellation_policy,
13296    })
13297}
13298
13299fn ensure_child_policies_match(
13300    sequence: u64,
13301    recorded: &RecordedChildPolicies,
13302    current: &ChildWorkflowOptions,
13303) -> Result<()> {
13304    for (field, expected, actual) in [
13305        (
13306            "parent_close_policy",
13307            recorded.parent_close_policy.as_str(),
13308            current.parent_close_policy.as_str(),
13309        ),
13310        (
13311            "cancellation_policy",
13312            recorded.cancellation_policy.as_str(),
13313            current.cancellation_policy.as_str(),
13314        ),
13315    ] {
13316        if expected != actual {
13317            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13318                "child_workflow_policy_changed",
13319                Some(sequence),
13320                Some(expected.to_string()),
13321                Some(actual.to_string()),
13322                format!("child workflow {field} changed during replay"),
13323            )));
13324        }
13325    }
13326    Ok(())
13327}
13328
13329#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
13330enum RecordedSnapshotValue<T> {
13331    /// Older history did not persist this field, so it cannot constrain replay.
13332    Unknown,
13333    Known(T),
13334}
13335
13336impl<T: PartialEq> RecordedSnapshotValue<T> {
13337    fn matches_current(&self, current: &Self) -> bool {
13338        match self {
13339            Self::Unknown => true,
13340            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
13341        }
13342    }
13343}
13344
13345#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
13346struct ActivityRetrySnapshot {
13347    snapshot_version: RecordedSnapshotValue<Option<u64>>,
13348    max_attempts: RecordedSnapshotValue<Option<u64>>,
13349    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
13350    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
13351    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
13352    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
13353    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
13354    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
13355}
13356
13357impl ActivityRetrySnapshot {
13358    fn matches_current(&self, current: &Self) -> bool {
13359        self.snapshot_version
13360            .matches_current(&current.snapshot_version)
13361            && self.max_attempts.matches_current(&current.max_attempts)
13362            && self
13363                .backoff_seconds
13364                .matches_current(&current.backoff_seconds)
13365            && self
13366                .start_to_close_timeout
13367                .matches_current(&current.start_to_close_timeout)
13368            && self
13369                .schedule_to_start_timeout
13370                .matches_current(&current.schedule_to_start_timeout)
13371            && self
13372                .schedule_to_close_timeout
13373                .matches_current(&current.schedule_to_close_timeout)
13374            && self
13375                .heartbeat_timeout
13376                .matches_current(&current.heartbeat_timeout)
13377            && self
13378                .non_retryable_error_types
13379                .matches_current(&current.non_retryable_error_types)
13380    }
13381}
13382
13383fn recorded_optional_u64(
13384    object: Option<&serde_json::Map<String, Value>>,
13385    field: &str,
13386) -> RecordedSnapshotValue<Option<u64>> {
13387    match object.and_then(|object| object.get(field)) {
13388        None => RecordedSnapshotValue::Unknown,
13389        Some(Value::Null) => RecordedSnapshotValue::Known(None),
13390        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
13391    }
13392}
13393
13394fn recorded_optional_string(
13395    object: &serde_json::Map<String, Value>,
13396    field: &str,
13397) -> RecordedSnapshotValue<Option<String>> {
13398    match object.get(field) {
13399        None => RecordedSnapshotValue::Unknown,
13400        Some(Value::Null) => RecordedSnapshotValue::Known(None),
13401        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
13402    }
13403}
13404
13405fn recorded_activity_execution_mode(
13406    events: &[&HistoryEvent],
13407    sequence: u64,
13408) -> Result<RecordedSnapshotValue<Option<String>>> {
13409    let mut recorded = RecordedSnapshotValue::Unknown;
13410    for event in events {
13411        for object in [
13412            event.payload.as_object(),
13413            event.payload.get("activity").and_then(Value::as_object),
13414        ]
13415        .into_iter()
13416        .flatten()
13417        {
13418            let mode = match object.get("execution_mode") {
13419                None => None,
13420                Some(Value::Null) => Some(None),
13421                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
13422                Some(_) => {
13423                    return Err(invalid_recorded_history(
13424                        "activity_execution_mode_invalid",
13425                        sequence,
13426                        "null or a non-empty execution mode",
13427                        "invalid execution_mode",
13428                        "activity history contains an invalid execution mode",
13429                    ))
13430                }
13431            };
13432            let legacy_mode = match object.get("local_activity") {
13433                None => None,
13434                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
13435                Some(_) => {
13436                    return Err(invalid_recorded_history(
13437                        "activity_execution_mode_invalid",
13438                        sequence,
13439                        "boolean local_activity",
13440                        "invalid local_activity",
13441                        "activity history contains an invalid local-activity marker",
13442                    ))
13443                }
13444            };
13445            for mode in [mode, legacy_mode].into_iter().flatten() {
13446                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
13447                {
13448                    return Err(invalid_recorded_history(
13449                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
13450                        "activity lifecycle events at one workflow sequence disagree on execution mode",
13451                    ));
13452                }
13453                recorded = RecordedSnapshotValue::Known(mode);
13454            }
13455        }
13456    }
13457    Ok(recorded)
13458}
13459
13460fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
13461    let policy = policy.and_then(Value::as_object);
13462    let backoff_seconds = policy
13463        .and_then(|policy| policy.get("backoff_seconds"))
13464        .and_then(Value::as_array)
13465        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
13466        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
13467    let mut non_retryable_error_types = Vec::new();
13468    for error_type in policy
13469        .and_then(|policy| policy.get("non_retryable_error_types"))
13470        .and_then(Value::as_array)
13471        .into_iter()
13472        .flatten()
13473        .filter_map(Value::as_str)
13474        .map(str::trim)
13475        .filter(|error_type| !error_type.is_empty())
13476    {
13477        if !non_retryable_error_types
13478            .iter()
13479            .any(|recorded| recorded == error_type)
13480        {
13481            non_retryable_error_types.push(error_type.to_string());
13482        }
13483    }
13484
13485    ActivityRetrySnapshot {
13486        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
13487        max_attempts: recorded_optional_u64(policy, "max_attempts"),
13488        backoff_seconds,
13489        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
13490        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
13491        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
13492        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
13493        non_retryable_error_types: if policy
13494            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
13495        {
13496            RecordedSnapshotValue::Known(non_retryable_error_types)
13497        } else {
13498            RecordedSnapshotValue::Unknown
13499        },
13500    }
13501}
13502
13503fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
13504    let policy = options.retry_policy.as_ref();
13505    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
13506        Some(Value::Null) => None,
13507        Some(value) => value_as_u64(value),
13508        None => Some(1),
13509    };
13510    let backoff_seconds = policy
13511        .and_then(|policy| policy.get("backoff_seconds"))
13512        .and_then(Value::as_array)
13513        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
13514        .unwrap_or_default();
13515    let non_retryable_error_types = policy
13516        .and_then(|policy| policy.get("non_retryable_error_types"))
13517        .and_then(Value::as_array)
13518        .into_iter()
13519        .flatten()
13520        .filter_map(Value::as_str)
13521        .map(str::to_string)
13522        .collect();
13523
13524    ActivityRetrySnapshot {
13525        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
13526        max_attempts: RecordedSnapshotValue::Known(max_attempts),
13527        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
13528        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
13529        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
13530        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
13531        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
13532        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
13533    }
13534}
13535
13536fn activity_options_description(options: &RecordedActivityOptions) -> String {
13537    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
13538}
13539
13540impl RecordedCommand {
13541    fn sequence(&self) -> u64 {
13542        match self {
13543            Self::CancellationGroup { sequence, .. }
13544            | Self::CancellationScope { sequence, .. }
13545            | Self::CancellationBoundary { sequence, .. }
13546            | Self::Activity { sequence, .. }
13547            | Self::Timer { sequence, .. }
13548            | Self::ChildWorkflow { sequence, .. }
13549            | Self::SignalWait { sequence, .. }
13550            | Self::ConditionWait { sequence, .. }
13551            | Self::SearchAttributes { sequence, .. }
13552            | Self::SideEffect { sequence, .. }
13553            | Self::VersionMarker { sequence, .. }
13554            | Self::Memo { sequence, .. } => *sequence,
13555            Self::ServiceOperation { sequence, .. } => *sequence,
13556        }
13557    }
13558
13559    fn shape(&self) -> &'static str {
13560        match self {
13561            Self::CancellationScope { .. } => "cancellation scope",
13562            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
13563                "cooperative cancellation"
13564            }
13565            Self::Activity { .. } => "activity",
13566            Self::Timer { .. } => "timer",
13567            Self::ChildWorkflow { .. } => "child workflow",
13568            Self::SignalWait { .. } => "signal wait",
13569            Self::ConditionWait { .. } => "condition wait",
13570            Self::SearchAttributes { .. } => "search-attribute update",
13571            Self::SideEffect { .. } => "side effect",
13572            Self::VersionMarker { .. } => "version marker",
13573            Self::Memo { .. } => "memo upsert",
13574            Self::ServiceOperation { .. } => "service operation",
13575        }
13576    }
13577}
13578
13579fn ensure_version_supported(
13580    change_id: &str,
13581    version: i32,
13582    min_supported: i32,
13583    max_supported: i32,
13584    sequence: u64,
13585) -> Result<()> {
13586    if (min_supported..=max_supported).contains(&version) {
13587        return Ok(());
13588    }
13589    Err(Error::NonDeterministicReplay(ReplayFailure::new(
13590        "version_marker_incompatible_range",
13591        (sequence != 0).then_some(sequence),
13592        Some(format!("{min_supported}..={max_supported}")),
13593        Some(format!("{change_id}:{version}")),
13594        "recorded workflow version is outside the range supported by current code",
13595    )))
13596}
13597
13598#[derive(Clone, Debug)]
13599struct ResumeSignal {
13600    signal_name: String,
13601    arguments: Vec<AvroValue>,
13602}
13603
13604const MAX_PARALLEL_OPERATIONS: usize = 1000;
13605
13606fn parallel_group_prefix(kind: &str) -> &'static str {
13607    match kind {
13608        "activity" => "parallel-activities",
13609        "child" => "parallel-children",
13610        "timer" => "parallel-timers",
13611        _ => "parallel-calls",
13612    }
13613}
13614
13615fn parallel_group_entry(
13616    base_sequence: u64,
13617    size: usize,
13618    index: usize,
13619    kind: &str,
13620) -> ParallelGroupMetadata {
13621    ParallelGroupMetadata {
13622        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
13623        parallel_group_kind: kind.to_string(),
13624        parallel_group_base_sequence: base_sequence,
13625        parallel_group_size: size,
13626        parallel_group_index: index,
13627        parallel_group_mode: None,
13628        selection_member_key: None,
13629        selection_member_index: None,
13630        selection_member_base_sequence: None,
13631        selection_member_size: None,
13632        selection_member_kind: None,
13633    }
13634}
13635
13636struct SelectionMemberMetadata {
13637    key: SelectionKey,
13638    index: usize,
13639    base_sequence: u64,
13640    size: usize,
13641    kind: String,
13642}
13643
13644fn selection_group_entry(
13645    base_sequence: u64,
13646    size: usize,
13647    index: usize,
13648    kind: &str,
13649    member: &SelectionMemberMetadata,
13650) -> ParallelGroupMetadata {
13651    ParallelGroupMetadata {
13652        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
13653        parallel_group_kind: kind.to_string(),
13654        parallel_group_base_sequence: base_sequence,
13655        parallel_group_size: size,
13656        parallel_group_index: index,
13657        parallel_group_mode: Some("select".to_string()),
13658        selection_member_key: Some(member.key.clone()),
13659        selection_member_index: Some(member.index),
13660        selection_member_base_sequence: Some(member.base_sequence),
13661        selection_member_size: Some(member.size),
13662        selection_member_kind: Some(member.kind.clone()),
13663    }
13664}
13665
13666fn apply_parallel_group_path(
13667    command: &mut serde_json::Map<String, Value>,
13668    path: &[ParallelGroupMetadata],
13669) {
13670    let Some(inner) = path.last() else {
13671        return;
13672    };
13673    command.insert(
13674        "parallel_group_id".to_string(),
13675        json!(inner.parallel_group_id),
13676    );
13677    command.insert(
13678        "parallel_group_kind".to_string(),
13679        json!(inner.parallel_group_kind),
13680    );
13681    command.insert(
13682        "parallel_group_base_sequence".to_string(),
13683        json!(inner.parallel_group_base_sequence),
13684    );
13685    command.insert(
13686        "parallel_group_size".to_string(),
13687        json!(inner.parallel_group_size),
13688    );
13689    command.insert(
13690        "parallel_group_index".to_string(),
13691        json!(inner.parallel_group_index),
13692    );
13693    if let Some(mode) = &inner.parallel_group_mode {
13694        command.insert("parallel_group_mode".to_string(), json!(mode));
13695    }
13696    if let Some(key) = &inner.selection_member_key {
13697        command.insert("selection_member_key".to_string(), json!(key));
13698    }
13699    if let Some(index) = inner.selection_member_index {
13700        command.insert("selection_member_index".to_string(), json!(index));
13701    }
13702    if let Some(base_sequence) = inner.selection_member_base_sequence {
13703        command.insert(
13704            "selection_member_base_sequence".to_string(),
13705            json!(base_sequence),
13706        );
13707    }
13708    if let Some(size) = inner.selection_member_size {
13709        command.insert("selection_member_size".to_string(), json!(size));
13710    }
13711    if let Some(kind) = &inner.selection_member_kind {
13712        command.insert("selection_member_kind".to_string(), json!(kind));
13713    }
13714    command.insert("parallel_group_path".to_string(), json!(path));
13715}
13716
13717fn ensure_parallel_path_matches(
13718    sequence: u64,
13719    recorded: Option<&[ParallelGroupMetadata]>,
13720    expected: &[ParallelGroupMetadata],
13721) -> Result<()> {
13722    match (recorded, expected.is_empty()) {
13723        (None, true) => Ok(()),
13724        (Some(recorded), false) if recorded == expected => Ok(()),
13725        (None, false) => Err(invalid_recorded_history(
13726            "parallel_group_metadata_missing",
13727            sequence,
13728            &serde_json::to_string(expected).unwrap_or_default(),
13729            "<missing>",
13730            "recorded parallel member is missing its durable group path",
13731        )),
13732        (Some(recorded), true) => Err(invalid_recorded_history(
13733            "parallel_group_shape_mismatch",
13734            sequence,
13735            "sequential command",
13736            &serde_json::to_string(recorded).unwrap_or_default(),
13737            "recorded command belonged to a parallel group but current code schedules it sequentially",
13738        )),
13739        (Some(recorded), false) => Err(invalid_recorded_history(
13740            "parallel_group_shape_mismatch",
13741            sequence,
13742            &serde_json::to_string(recorded).unwrap_or_default(),
13743            &serde_json::to_string(expected).unwrap_or_default(),
13744            "recorded parallel-group identity or path changed during replay",
13745        )),
13746    }
13747}
13748
13749#[derive(Clone, Debug)]
13750enum ParallelShape {
13751    Leaf,
13752    Group(Vec<ParallelShape>),
13753}
13754
13755struct ParallelDescriptor {
13756    operation: ParallelOperation,
13757    offset: usize,
13758    member_path: Vec<usize>,
13759    group_path: Vec<ParallelGroupMetadata>,
13760}
13761
13762fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
13763    operations
13764        .iter()
13765        .map(|operation| match operation {
13766            ParallelOperation::Group(children) => parallel_leaf_count(children),
13767            _ => 1,
13768        })
13769        .sum()
13770}
13771
13772fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
13773    match operation {
13774        ParallelOperation::Activity { .. } => Some("activity"),
13775        ParallelOperation::ChildWorkflow { .. } => Some("child"),
13776        ParallelOperation::Timer(_) => Some("timer"),
13777        ParallelOperation::Signal(_) => Some("signal"),
13778        ParallelOperation::Condition { .. } => Some("condition"),
13779        ParallelOperation::Group(children) => parallel_group_kind(children),
13780    }
13781}
13782
13783fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
13784    let mut kind = None;
13785    for operation in operations {
13786        let Some(operation_kind) = parallel_operation_kind(operation) else {
13787            continue;
13788        };
13789        match kind {
13790            None => kind = Some(operation_kind),
13791            Some(current) if current == operation_kind => {}
13792            Some(_) => return Some("mixed"),
13793        }
13794    }
13795    kind
13796}
13797
13798fn validate_parallel_operations(
13799    operations: &[ParallelOperation],
13800    member_path: &mut Vec<usize>,
13801    root: bool,
13802) -> Result<()> {
13803    let leaves = parallel_leaf_count(operations);
13804    if leaves > MAX_PARALLEL_OPERATIONS {
13805        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13806            reason: "fan_out_limit_exceeded",
13807            member_path: member_path.clone(),
13808            message: format!(
13809                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
13810            ),
13811        }));
13812    }
13813    if !root && operations.is_empty() {
13814        return Err(Error::InvalidParallelGroup(ParallelGroupError {
13815            reason: "nested_group_empty",
13816            member_path: member_path.clone(),
13817            message: "a nested group must contain at least one durable leaf".to_string(),
13818        }));
13819    }
13820
13821    for (index, operation) in operations.iter().enumerate() {
13822        member_path.push(index);
13823        match operation {
13824            ParallelOperation::Activity {
13825                options, arguments, ..
13826            } => {
13827                options
13828                    .validate()
13829                    .map_err(|error| Error::InvalidActivityOptions(error))?;
13830                if let Err(error) = arguments {
13831                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13832                        reason: "arguments_invalid",
13833                        member_path: member_path.clone(),
13834                        message: error.to_string(),
13835                    }));
13836                }
13837            }
13838            ParallelOperation::ChildWorkflow {
13839                options, arguments, ..
13840            } => {
13841                validate_parallel_child_options(options)?;
13842                if let Err(error) = arguments {
13843                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13844                        reason: "arguments_invalid",
13845                        member_path: member_path.clone(),
13846                        message: error.to_string(),
13847                    }));
13848                }
13849            }
13850            ParallelOperation::Timer(duration)
13851                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
13852            {
13853                return Err(Error::TimerDurationOverflow);
13854            }
13855            ParallelOperation::Timer(_) => {}
13856            ParallelOperation::Signal(signal_name) => {
13857                validate_user_signal_name(signal_name)?;
13858                if signal_name.trim().is_empty() {
13859                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
13860                        reason: "signal_name_empty",
13861                        member_path: member_path.clone(),
13862                        message: "signal wait name must not be empty".to_string(),
13863                    }));
13864                }
13865            }
13866            ParallelOperation::Condition { options, .. } => {
13867                options.validate()?;
13868            }
13869            ParallelOperation::Group(children) => {
13870                validate_parallel_operations(children, member_path, false)?;
13871            }
13872        }
13873        member_path.pop();
13874    }
13875    Ok(())
13876}
13877
13878fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
13879    if options.task_queue.trim().is_empty() {
13880        return Err(Error::InvalidChildWorkflowOptions(
13881            "task_queue must not be empty".to_string(),
13882        ));
13883    }
13884    for (name, value) in [
13885        (
13886            "execution_timeout_seconds",
13887            options.execution_timeout_seconds,
13888        ),
13889        ("run_timeout_seconds", options.run_timeout_seconds),
13890    ] {
13891        if value == Some(0) {
13892            return Err(Error::InvalidChildWorkflowOptions(format!(
13893                "{name} must be at least 1"
13894            )));
13895        }
13896    }
13897    if options
13898        .retry_policy
13899        .as_ref()
13900        .is_some_and(|policy| policy.max_attempts == Some(0))
13901    {
13902        return Err(Error::InvalidChildWorkflowOptions(
13903            "retry_policy.max_attempts must be at least 1".to_string(),
13904        ));
13905    }
13906    Ok(())
13907}
13908
13909fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
13910    ParallelShape::Group(
13911        operations
13912            .iter()
13913            .map(|operation| match operation {
13914                ParallelOperation::Group(children) => parallel_shape(children),
13915                _ => ParallelShape::Leaf,
13916            })
13917            .collect(),
13918    )
13919}
13920
13921fn parallel_descriptors(
13922    operations: Vec<ParallelOperation>,
13923    base_sequence: u64,
13924) -> Result<Vec<ParallelDescriptor>> {
13925    let size = parallel_leaf_count(&operations);
13926    let kind = parallel_group_kind(&operations).unwrap_or("activity");
13927    let mut descriptors = Vec::with_capacity(size);
13928    let mut cursor = 0;
13929
13930    for (index, operation) in operations.into_iter().enumerate() {
13931        match operation {
13932            ParallelOperation::Group(children) => {
13933                let child_base = base_sequence
13934                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
13935                    .ok_or(Error::TimerDurationOverflow)?;
13936                for mut descriptor in parallel_descriptors(children, child_base)? {
13937                    let outer_index = cursor + descriptor.offset;
13938                    descriptor.group_path.insert(
13939                        0,
13940                        parallel_group_entry(base_sequence, size, outer_index, kind),
13941                    );
13942                    descriptor.member_path.insert(0, index);
13943                    descriptor.offset = outer_index;
13944                    descriptors.push(descriptor);
13945                }
13946                cursor = descriptors.len();
13947            }
13948            operation => {
13949                descriptors.push(ParallelDescriptor {
13950                    operation,
13951                    offset: cursor,
13952                    member_path: vec![index],
13953                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
13954                });
13955                cursor += 1;
13956            }
13957        }
13958    }
13959    Ok(descriptors)
13960}
13961
13962enum ParallelLeafCall {
13963    Activity(ActivityCall),
13964    ChildWorkflow(ChildWorkflowCall),
13965    Timer(TimerCall),
13966    Signal(SignalCall),
13967    Condition(ConditionWaitCall),
13968}
13969
13970fn parallel_leaf_call(
13971    ctx: &WorkflowContext,
13972    operation: ParallelOperation,
13973    parallel_group_path: Vec<ParallelGroupMetadata>,
13974) -> ParallelLeafCall {
13975    match operation {
13976        ParallelOperation::Activity {
13977            activity_type,
13978            options,
13979            arguments,
13980        } => ParallelLeafCall::Activity(ActivityCall {
13981            ctx: ctx.clone(),
13982            activity_type,
13983            options,
13984            worker_session: None,
13985            args: Some(arguments),
13986            scheduled: false,
13987            local: false,
13988            local_result: None,
13989            parallel_group_path,
13990        }),
13991        ParallelOperation::ChildWorkflow {
13992            workflow_type,
13993            options,
13994            arguments,
13995        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
13996            ctx: ctx.clone(),
13997            workflow_type,
13998            options,
13999            args: Some(arguments),
14000            scheduled: false,
14001            matched_pending: false,
14002            parallel_group_path,
14003        }),
14004        ParallelOperation::Timer(duration) => {
14005            let delay_seconds = duration
14006                .as_secs()
14007                .checked_add(u64::from(duration.subsec_nanos() > 0));
14008            ParallelLeafCall::Timer(TimerCall {
14009                ctx: ctx.clone(),
14010                delay_seconds,
14011                scheduled: false,
14012                matched_pending: false,
14013                parallel_group_path,
14014            })
14015        }
14016        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
14017            ctx: ctx.clone(),
14018            signal_name,
14019            runtime_reserved_allowed: false,
14020            opened_wait: false,
14021            matched_pending: false,
14022            parallel_group_path,
14023        }),
14024        ParallelOperation::Condition { options, predicate } => {
14025            ParallelLeafCall::Condition(ConditionWaitCall {
14026                ctx: ctx.clone(),
14027                options,
14028                predicate,
14029                occurrence_id: None,
14030                opened_wait: false,
14031                parallel_group_path,
14032            })
14033        }
14034        ParallelOperation::Group(_) => {
14035            unreachable!("parallel descriptors contain only durable leaves")
14036        }
14037    }
14038}
14039
14040impl ParallelLeafCall {
14041    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
14042        match self {
14043            Self::Activity(call) => Pin::new(call)
14044                .poll_avro_value(cx)
14045                .map_ok(ParallelAvroResult::Activity),
14046            Self::ChildWorkflow(call) => Pin::new(call)
14047                .poll_avro_value(cx)
14048                .map_ok(ParallelAvroResult::ChildWorkflow),
14049            Self::Timer(call) => Pin::new(call)
14050                .poll(cx)
14051                .map_ok(|()| ParallelAvroResult::Timer),
14052            Self::Signal(call) => Pin::new(call)
14053                .poll_avro_value(cx)
14054                .map_ok(ParallelAvroResult::Signal),
14055            Self::Condition(call) => Pin::new(call)
14056                .poll(cx)
14057                .map_ok(ParallelAvroResult::Condition),
14058        }
14059    }
14060}
14061
14062struct ParallelLeaf {
14063    call: ParallelLeafCall,
14064    sequence: u64,
14065    member_path: Vec<usize>,
14066    group_path: Vec<ParallelGroupMetadata>,
14067    result: Option<ParallelAvroResult>,
14068}
14069
14070/// Future returned by [`WorkflowContext::parallel`].
14071pub struct ParallelCall {
14072    ctx: WorkflowContext,
14073    operations: Option<Vec<ParallelOperation>>,
14074    shape: Option<ParallelShape>,
14075    leaves: Vec<ParallelLeaf>,
14076    pending_scope_delivery: bool,
14077    worker_session: Option<WorkerSessionOptions>,
14078}
14079
14080impl ParallelCall {
14081    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
14082        Self {
14083            ctx,
14084            operations: Some(operations),
14085            shape: None,
14086            leaves: Vec::new(),
14087            pending_scope_delivery: false,
14088            worker_session: None,
14089        }
14090    }
14091
14092    fn initialize(&mut self) -> Result<()> {
14093        if let Some(session) = &self.worker_session {
14094            session.to_wire()?;
14095        }
14096        let operations = self.operations.take().unwrap_or_default();
14097        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
14098        self.shape = Some(parallel_shape(&operations));
14099        if operations.is_empty() {
14100            return Ok(());
14101        }
14102
14103        let base_sequence = {
14104            let state = self
14105                .ctx
14106                .state
14107                .lock()
14108                .map_err(|_| Error::WorkflowStatePoisoned)?;
14109            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
14110                recorded.sequence()
14111            } else {
14112                let last = state.max_recorded_sequence();
14113                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
14114                    .and_then(|sequence| sequence.checked_add(1))
14115                    .ok_or_else(|| {
14116                        Error::InvalidParallelGroup(ParallelGroupError {
14117                            reason: "sequence_overflow",
14118                            member_path: Vec::new(),
14119                            message: "parallel group sequence identity overflowed u64".to_string(),
14120                        })
14121                    })?
14122            }
14123        };
14124
14125        let descriptors = parallel_descriptors(operations, base_sequence)?;
14126        {
14127            let mut state = self
14128                .ctx
14129                .state
14130                .lock()
14131                .map_err(|_| Error::WorkflowStatePoisoned)?;
14132            let cursor = state.command_cursor;
14133            self.ctx.validate_scope_membership(&mut state, cursor)?;
14134            if state.prepare_parallel_scope_cancellation(&descriptors)? {
14135                self.pending_scope_delivery = true;
14136                return Ok(());
14137            }
14138            state.expand_cancellation_group(&descriptors)?;
14139            state.prepare_group_cancellation(&descriptors)?;
14140        }
14141        self.leaves = descriptors
14142            .into_iter()
14143            .map(|descriptor| {
14144                let mut call = parallel_leaf_call(
14145                    &self.ctx,
14146                    descriptor.operation,
14147                    descriptor.group_path.clone(),
14148                );
14149                if let (Some(session), ParallelLeafCall::Activity(activity)) =
14150                    (&self.worker_session, &mut call)
14151                {
14152                    activity.worker_session = Some(session.clone());
14153                }
14154                ParallelLeaf {
14155                    call,
14156                    sequence: base_sequence + descriptor.offset as u64,
14157                    member_path: descriptor.member_path,
14158                    group_path: descriptor.group_path,
14159                    result: None,
14160                }
14161            })
14162            .collect();
14163        Ok(())
14164    }
14165
14166    fn poll_avro_value(
14167        mut self: Pin<&mut Self>,
14168        cx: &mut TaskContext<'_>,
14169    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
14170        if self.operations.is_some() {
14171            if let Err(error) = self.initialize() {
14172                return Poll::Ready(Err(error));
14173            }
14174        }
14175        if self.pending_scope_delivery {
14176            return Poll::Pending;
14177        }
14178        if self.leaves.is_empty() {
14179            return Poll::Ready(Ok(Vec::new()));
14180        }
14181
14182        let mut failures = Vec::new();
14183        let mut pending = false;
14184        for (index, leaf) in self.leaves.iter_mut().enumerate() {
14185            if leaf.result.is_some() {
14186                continue;
14187            }
14188            match leaf.call.poll_avro_value(cx) {
14189                Poll::Ready(Ok(result)) => leaf.result = Some(result),
14190                Poll::Ready(Err(error)) => failures.push((index, error)),
14191                Poll::Pending => pending = true,
14192            }
14193        }
14194
14195        if !failures.is_empty() {
14196            if let Some(position) = failures
14197                .iter()
14198                .position(|(_, error)| workflow_task_integrity_error(error))
14199            {
14200                return Poll::Ready(Err(failures.remove(position).1));
14201            }
14202            if self
14203                .ctx
14204                .state
14205                .lock()
14206                .map_err(|_| Error::WorkflowStatePoisoned)?
14207                .cancellation_delivery_intent
14208                .is_some()
14209            {
14210                return Poll::Pending;
14211            }
14212            if let Some(position) = failures
14213                .iter()
14214                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
14215            {
14216                return Poll::Ready(Err(failures.remove(position).1));
14217            }
14218            failures.sort_by_key(|(index, _)| *index);
14219            let (failed_index, cause) = failures.remove(0);
14220            let failed = &self.leaves[failed_index];
14221            let completed = self
14222                .leaves
14223                .iter()
14224                .filter_map(|leaf| {
14225                    leaf.result
14226                        .clone()
14227                        .and_then(|result| result.into_json_result().ok())
14228                        .map(|result| ParallelCompletion {
14229                            member_path: leaf.member_path.clone(),
14230                            result,
14231                        })
14232                })
14233                .collect();
14234            let group_id = failed
14235                .group_path
14236                .first()
14237                .map(|entry| entry.parallel_group_id.clone())
14238                .unwrap_or_default();
14239            let sequences = self
14240                .leaves
14241                .iter()
14242                .map(|leaf| leaf.sequence)
14243                .collect::<Vec<_>>();
14244            self.ctx
14245                .state
14246                .lock()
14247                .map_err(|_| Error::WorkflowStatePoisoned)?
14248                .consume_replay_group(&sequences, Some(failed.sequence));
14249            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
14250                group_id,
14251                member_path: failed.member_path.clone(),
14252                group_path: failed.group_path.clone(),
14253                completed,
14254                cause: Box::new(cause),
14255            })));
14256        }
14257        if pending
14258            || self
14259                .ctx
14260                .state
14261                .lock()
14262                .map_err(|_| Error::WorkflowStatePoisoned)?
14263                .cancellation_delivery_intent
14264                .is_some()
14265        {
14266            return Poll::Pending;
14267        }
14268
14269        let mut flat_results = self
14270            .leaves
14271            .iter_mut()
14272            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
14273            .collect::<Vec<_>>()
14274            .into_iter();
14275        let results = parallel_results_for_shape(
14276            self.shape.as_ref().expect("initialized parallel shape"),
14277            &mut flat_results,
14278        );
14279        let sequences = self
14280            .leaves
14281            .iter()
14282            .map(|leaf| leaf.sequence)
14283            .collect::<Vec<_>>();
14284        self.ctx
14285            .state
14286            .lock()
14287            .map_err(|_| Error::WorkflowStatePoisoned)?
14288            .consume_replay_group(&sequences, None);
14289        Poll::Ready(Ok(match results {
14290            ParallelAvroResult::Group(results) => results,
14291            ParallelAvroResult::Activity(_)
14292            | ParallelAvroResult::ChildWorkflow(_)
14293            | ParallelAvroResult::Timer
14294            | ParallelAvroResult::Signal(_)
14295            | ParallelAvroResult::Condition(_) => {
14296                unreachable!("root parallel shape is a group")
14297            }
14298        }))
14299    }
14300}
14301
14302fn parallel_results_for_shape(
14303    shape: &ParallelShape,
14304    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
14305) -> ParallelAvroResult {
14306    match shape {
14307        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
14308        ParallelShape::Group(children) => ParallelAvroResult::Group(
14309            children
14310                .iter()
14311                .map(|child| parallel_results_for_shape(child, flat_results))
14312                .collect(),
14313        ),
14314    }
14315}
14316
14317impl Future for ParallelCall {
14318    type Output = Result<Vec<ParallelResult>>;
14319
14320    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14321        self.poll_avro_value(cx)
14322            .map_ok(|results| {
14323                results
14324                    .into_iter()
14325                    .map(ParallelAvroResult::into_json_result)
14326                    .collect::<Result<Vec<_>>>()
14327            })
14328            .map_ok(|result| result)
14329            .flatten_result()
14330    }
14331}
14332
14333#[derive(Clone, Debug)]
14334struct SelectionMemberPlan {
14335    key: SelectionKey,
14336    index: usize,
14337    base_sequence: u64,
14338    size: usize,
14339    kind: String,
14340    shape: ParallelShape,
14341    leaf_start: usize,
14342}
14343
14344fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
14345    match operation {
14346        ParallelOperation::Activity { .. } => "activity",
14347        ParallelOperation::ChildWorkflow { .. } => "child",
14348        ParallelOperation::Timer(_) => "timer",
14349        ParallelOperation::Signal(_) => "signal",
14350        ParallelOperation::Condition { .. } => "condition",
14351        ParallelOperation::Group(_) => "group",
14352    }
14353}
14354
14355fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
14356    match operation {
14357        ParallelOperation::Group(children) => parallel_shape(children),
14358        _ => ParallelShape::Leaf,
14359    }
14360}
14361
14362fn selection_descriptors(
14363    operations: Vec<(SelectionKey, ParallelOperation)>,
14364    base_sequence: u64,
14365) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
14366    if operations.is_empty() {
14367        return Err(Error::InvalidParallelGroup(ParallelGroupError {
14368            reason: "selection_empty",
14369            member_path: Vec::new(),
14370            message: "durable selection requires at least one operation".to_string(),
14371        }));
14372    }
14373    let operation_refs = operations
14374        .iter()
14375        .map(|(_, operation)| operation)
14376        .collect::<Vec<_>>();
14377    let total_size = operation_refs
14378        .iter()
14379        .map(|operation| match operation {
14380            ParallelOperation::Group(children) => parallel_leaf_count(children),
14381            _ => 1,
14382        })
14383        .sum::<usize>();
14384    if total_size > MAX_PARALLEL_OPERATIONS {
14385        return Err(Error::InvalidParallelGroup(ParallelGroupError {
14386            reason: "fan_out_limit_exceeded",
14387            member_path: Vec::new(),
14388            message: format!(
14389                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
14390            ),
14391        }));
14392    }
14393    let group_kind = {
14394        let mut kind = None;
14395        for operation in &operation_refs {
14396            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
14397            match kind {
14398                None => kind = Some(operation_kind),
14399                Some(current) if current == operation_kind => {}
14400                Some(_) => {
14401                    kind = Some("mixed");
14402                    break;
14403                }
14404            }
14405        }
14406        kind.unwrap_or("mixed")
14407    };
14408
14409    let mut descriptors = Vec::with_capacity(total_size);
14410    let mut members = Vec::with_capacity(operations.len());
14411    let mut cursor = 0usize;
14412    let mut seen_keys: Vec<SelectionKey> = Vec::new();
14413    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
14414        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
14415            return Err(Error::InvalidParallelGroup(ParallelGroupError {
14416                reason: "selection_key_invalid",
14417                member_path: vec![member_index],
14418                message: "selection member keys must be non-empty strings or non-negative integers"
14419                    .to_string(),
14420            }));
14421        }
14422        if seen_keys.contains(&key) {
14423            return Err(Error::InvalidParallelGroup(ParallelGroupError {
14424                reason: "selection_key_duplicate",
14425                member_path: vec![member_index],
14426                message: format!("selection member key {key:?} is duplicated"),
14427            }));
14428        }
14429        seen_keys.push(key.clone());
14430        let member_size = match &operation {
14431            ParallelOperation::Group(children) => parallel_leaf_count(children),
14432            _ => 1,
14433        };
14434        if member_size == 0 {
14435            return Err(Error::InvalidParallelGroup(ParallelGroupError {
14436                reason: "selection_member_empty",
14437                member_path: vec![member_index],
14438                message: "a selection member must contain at least one durable leaf".to_string(),
14439            }));
14440        }
14441        let member_base = base_sequence
14442            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
14443            .ok_or(Error::TimerDurationOverflow)?;
14444        let member_kind = selection_operation_kind(&operation).to_string();
14445        let member_shape = selection_operation_shape(&operation);
14446        let leaf_start = descriptors.len();
14447        match operation {
14448            ParallelOperation::Group(children) => {
14449                validate_parallel_operations(&children, &mut vec![member_index], false)?;
14450                for mut descriptor in parallel_descriptors(children, member_base)? {
14451                    let flat_index = cursor + descriptor.offset;
14452                    descriptor.group_path.insert(
14453                        0,
14454                        selection_group_entry(
14455                            base_sequence,
14456                            total_size,
14457                            flat_index,
14458                            group_kind,
14459                            &SelectionMemberMetadata {
14460                                key: key.clone(),
14461                                index: member_index,
14462                                base_sequence: member_base,
14463                                size: member_size,
14464                                kind: member_kind.clone(),
14465                            },
14466                        ),
14467                    );
14468                    descriptor.member_path.insert(0, member_index);
14469                    descriptor.offset = flat_index;
14470                    descriptors.push(descriptor);
14471                }
14472            }
14473            operation => {
14474                validate_parallel_operations(
14475                    std::slice::from_ref(&operation),
14476                    &mut Vec::new(),
14477                    true,
14478                )?;
14479                descriptors.push(ParallelDescriptor {
14480                    operation,
14481                    offset: cursor,
14482                    member_path: vec![member_index],
14483                    group_path: vec![selection_group_entry(
14484                        base_sequence,
14485                        total_size,
14486                        cursor,
14487                        group_kind,
14488                        &SelectionMemberMetadata {
14489                            key: key.clone(),
14490                            index: member_index,
14491                            base_sequence: member_base,
14492                            size: member_size,
14493                            kind: member_kind.clone(),
14494                        },
14495                    )],
14496                });
14497            }
14498        }
14499        members.push(SelectionMemberPlan {
14500            key,
14501            index: member_index,
14502            base_sequence: member_base,
14503            size: member_size,
14504            kind: member_kind,
14505            shape: member_shape,
14506            leaf_start,
14507        });
14508        cursor += member_size;
14509    }
14510    Ok((descriptors, members))
14511}
14512
14513struct SelectionLeaf {
14514    call: ParallelLeafCall,
14515    outcome: Option<Result<ParallelAvroResult>>,
14516}
14517
14518/// Stable reference to one member of a durable selection group.
14519#[derive(Clone)]
14520pub struct DurableOperationHandle {
14521    ctx: WorkflowContext,
14522    pub key: SelectionKey,
14523    pub index: usize,
14524    pub kind: String,
14525    pub identity: String,
14526    pub base_sequence: u64,
14527    pub size: usize,
14528    pub selection_group_id: String,
14529    shape: ParallelShape,
14530}
14531
14532impl std::fmt::Debug for DurableOperationHandle {
14533    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14534        formatter
14535            .debug_struct("DurableOperationHandle")
14536            .field("key", &self.key)
14537            .field("index", &self.index)
14538            .field("kind", &self.kind)
14539            .field("identity", &self.identity)
14540            .field("base_sequence", &self.base_sequence)
14541            .field("size", &self.size)
14542            .field("selection_group_id", &self.selection_group_id)
14543            .finish()
14544    }
14545}
14546
14547impl DurableOperationHandle {
14548    /// Await this member after another member has already won the selection.
14549    pub fn await_result(&self) -> DurableOperationAwaitCall {
14550        DurableOperationAwaitCall {
14551            handle: self.clone(),
14552        }
14553    }
14554
14555    /// Request cancellation without affecting siblings. The future resolves
14556    /// to unit; only `SelectionOperationCancelled` history proves cancellation
14557    /// beat a concurrently committed terminal result.
14558    pub fn cancel(&self) -> CancelDurableOperationCall {
14559        CancelDurableOperationCall {
14560            handle: self.clone(),
14561            emitted: false,
14562        }
14563    }
14564}
14565
14566/// The one winner committed for a durable selection group.
14567#[derive(Debug)]
14568pub struct SelectionResult {
14569    pub key: SelectionKey,
14570    pub index: usize,
14571    pub kind: String,
14572    pub identity: String,
14573    pub value: Option<ParallelResult>,
14574    pub failure: Option<Error>,
14575    pub winner: DurableOperationHandle,
14576    pub handles: Vec<DurableOperationHandle>,
14577}
14578
14579impl SelectionResult {
14580    pub fn succeeded(&self) -> bool {
14581        self.failure.is_none()
14582    }
14583
14584    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
14585        self.handles.iter().find(|handle| &handle.key == key)
14586    }
14587
14588    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
14589        self.handles
14590            .iter()
14591            .filter(|handle| handle.index != self.index)
14592            .collect()
14593    }
14594
14595    pub fn into_result(self) -> Result<ParallelResult> {
14596        match (self.value, self.failure) {
14597            (Some(value), None) => Ok(value),
14598            (_, Some(error)) => Err(error),
14599            _ => Err(Error::WorkerLoop(
14600                "selection result contained neither a value nor a failure".to_string(),
14601            )),
14602        }
14603    }
14604}
14605
14606/// Future returned by [`WorkflowContext::select`].
14607pub struct SelectCall {
14608    ctx: WorkflowContext,
14609    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
14610    members: Vec<SelectionMemberPlan>,
14611    leaves: Vec<SelectionLeaf>,
14612    group_id: Option<String>,
14613}
14614
14615impl SelectCall {
14616    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
14617        Self {
14618            ctx,
14619            operations: Some(operations),
14620            members: Vec::new(),
14621            leaves: Vec::new(),
14622            group_id: None,
14623        }
14624    }
14625
14626    fn initialize(&mut self) -> Result<()> {
14627        let operations = self.operations.take().unwrap_or_default();
14628        let base_sequence = {
14629            let state = self
14630                .ctx
14631                .state
14632                .lock()
14633                .map_err(|_| Error::WorkflowStatePoisoned)?;
14634            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
14635                state.recorded_commands.get(state.command_cursor)
14636            {
14637                *sequence
14638            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
14639            {
14640                marker.selection_group_base_sequence
14641            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
14642                recorded.sequence()
14643            } else {
14644                let last = state.max_recorded_sequence();
14645                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
14646                    .and_then(|sequence| sequence.checked_add(1))
14647                    .ok_or(Error::TimerDurationOverflow)?
14648            }
14649        };
14650        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
14651        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
14652        {
14653            let mut state = self
14654                .ctx
14655                .state
14656                .lock()
14657                .map_err(|_| Error::WorkflowStatePoisoned)?;
14658            state.expand_cancellation_group(&descriptors)?;
14659            state.prepare_group_cancellation(&descriptors)?;
14660        }
14661        self.leaves = descriptors
14662            .into_iter()
14663            .map(|descriptor| SelectionLeaf {
14664                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
14665                outcome: None,
14666            })
14667            .collect();
14668        self.members = members;
14669        self.group_id = Some(group_id);
14670        Ok(())
14671    }
14672}
14673
14674impl Future for SelectCall {
14675    type Output = Result<SelectionResult>;
14676
14677    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
14678        if self.operations.is_some() {
14679            if let Err(error) = self.initialize() {
14680                return Poll::Ready(Err(error));
14681            }
14682        }
14683
14684        for leaf in &mut self.leaves {
14685            if leaf.outcome.is_some() {
14686                continue;
14687            }
14688            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
14689                if outcome
14690                    .as_ref()
14691                    .err()
14692                    .is_some_and(workflow_task_integrity_error)
14693                {
14694                    return Poll::Ready(outcome.map(|_| unreachable!()));
14695                }
14696                leaf.outcome = Some(outcome);
14697            }
14698        }
14699
14700        if self
14701            .ctx
14702            .state
14703            .lock()
14704            .map_err(|_| Error::WorkflowStatePoisoned)?
14705            .cancellation_delivery_intent
14706            .is_some()
14707        {
14708            return Poll::Pending;
14709        }
14710
14711        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
14712            matches!(
14713                leaf.outcome,
14714                Some(Err(Error::CooperativeCancellationRequested(_)))
14715            )
14716        }) {
14717            return Poll::Ready(
14718                leaf.outcome
14719                    .take()
14720                    .expect("matched cancellation")
14721                    .map(|_| unreachable!()),
14722            );
14723        }
14724
14725        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
14726        let selection_member_range = self
14727            .members
14728            .first()
14729            .map(|member| member.base_sequence)
14730            .zip(self.leaves.len().try_into().ok())
14731            .map(|(base_sequence, size): (u64, u64)| {
14732                base_sequence..base_sequence.saturating_add(size)
14733            });
14734        let marker = {
14735            let mut state = match self.ctx.state.lock() {
14736                Ok(state) => state,
14737                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14738            };
14739            let marker = state
14740                .selection_markers
14741                .get(state.selection_marker_cursor)
14742                .cloned();
14743            if marker.is_none()
14744                && all_members_terminal
14745                && selection_member_range.as_ref().is_some_and(|member_range| {
14746                    state
14747                        .recorded_commands
14748                        .iter()
14749                        .any(|command| member_range.contains(&command.sequence()))
14750                })
14751            {
14752                // Terminal member history can be committed before the server's
14753                // SelectionResolved marker becomes visible to this task. That
14754                // marker is the durable barrier the selection is still waiting
14755                // on, so an otherwise commandless replay remains legitimately
14756                // pending instead of failing as an untracked yield.
14757                state.matched_recorded_pending = true;
14758                state.observation_pending = true;
14759            }
14760            marker
14761        };
14762        let Some(marker) = marker else {
14763            return Poll::Pending;
14764        };
14765        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
14766            || marker.selection_group_size != self.leaves.len()
14767            || self.members.first().map(|member| member.base_sequence)
14768                != Some(marker.selection_group_base_sequence)
14769        {
14770            return Poll::Ready(Err(invalid_recorded_history(
14771                "selection_group_shape_mismatch",
14772                marker.selection_group_base_sequence,
14773                self.group_id
14774                    .as_deref()
14775                    .unwrap_or("initialized selection group"),
14776                &marker.selection_group_id,
14777                "recorded selection group differs from current workflow code",
14778            )));
14779        }
14780        let Some(member_position) = self.members.iter().position(|member| {
14781            member.key == marker.member_key
14782                && member.index == marker.member_index
14783                && member.base_sequence == marker.member_base_sequence
14784                && member.size == marker.member_size
14785                && member.kind == marker.operation_kind
14786        }) else {
14787            return Poll::Ready(Err(invalid_recorded_history(
14788                "selection_member_shape_mismatch",
14789                marker.member_base_sequence,
14790                "winner member matching current workflow code",
14791                &format!("{:?}", marker.member_key),
14792                "recorded selection winner differs from the authored member identity",
14793            )));
14794        };
14795        let member = self.members[member_position].clone();
14796        let (handles, resolution_sequence) = {
14797            let mut state = match self.ctx.state.lock() {
14798                Ok(state) => state,
14799                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
14800            };
14801            let identities = self
14802                .members
14803                .iter()
14804                .map(|candidate| {
14805                    selection_operation_identity(
14806                        &state,
14807                        &candidate.kind,
14808                        candidate.base_sequence,
14809                        candidate.size,
14810                    )
14811                })
14812                .collect::<Vec<_>>();
14813            if let Some((position, missing)) = identities
14814                .iter()
14815                .enumerate()
14816                .find(|(_, identity)| identity.is_empty())
14817                .map(|(position, identity)| (position, identity.clone()))
14818            {
14819                let candidate = &self.members[position];
14820                return Poll::Ready(Err(invalid_recorded_history(
14821                    "selection_operation_identity_missing",
14822                    candidate.base_sequence,
14823                    &format!(
14824                        "durable {} resource identity from scheduled/open history",
14825                        candidate.kind
14826                    ),
14827                    &missing,
14828                    "selection member history is missing its canonical durable identity",
14829                )));
14830            }
14831            let expected_winner_identity = &identities[member_position];
14832            let resolution_sequence = match validated_selection_resolution_sequence(
14833                &state,
14834                &marker,
14835                &member,
14836                expected_winner_identity,
14837            ) {
14838                Ok(sequence) => sequence,
14839                Err(error) => return Poll::Ready(Err(error)),
14840            };
14841            let handles = self
14842                .members
14843                .iter()
14844                .zip(identities)
14845                .map(|(member, identity)| DurableOperationHandle {
14846                    ctx: self.ctx.clone(),
14847                    key: member.key.clone(),
14848                    index: member.index,
14849                    kind: member.kind.clone(),
14850                    identity,
14851                    base_sequence: member.base_sequence,
14852                    size: member.size,
14853                    selection_group_id: marker.selection_group_id.clone(),
14854                    shape: member.shape.clone(),
14855                })
14856                .collect::<Vec<_>>();
14857            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
14858                return Poll::Ready(Err(error));
14859            }
14860            state.selection_marker_cursor += 1;
14861            (handles, resolution_sequence)
14862        };
14863
14864        let mut winner_failure = None;
14865        let mut flat_results = Vec::with_capacity(member.size);
14866        if marker.outcome == "failed" {
14867            let resolution_offset = match resolution_sequence
14868                .checked_sub(member.base_sequence)
14869                .and_then(|offset| usize::try_from(offset).ok())
14870            {
14871                Some(offset) if offset < member.size => offset,
14872                _ => {
14873                    return Poll::Ready(Err(invalid_recorded_history(
14874                        "selection_resolution_event_mismatch",
14875                        member.base_sequence,
14876                        "failure event within selected member bounds",
14877                        &resolution_sequence.to_string(),
14878                        "selection failure event is outside the authored member",
14879                    )))
14880                }
14881            };
14882            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
14883            match leaf.outcome.take() {
14884                Some(Err(error)) => winner_failure = Some(error),
14885                _ => {
14886                    return Poll::Ready(Err(invalid_recorded_history(
14887                        "selection_winner_outcome_mismatch",
14888                        member.base_sequence,
14889                        "exact failed terminal history referenced by SelectionResolved",
14890                        "missing or successful resolution event",
14891                        "selection winner marker disagrees with terminal operation history",
14892                    )))
14893                }
14894            }
14895        } else {
14896            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
14897                match leaf.outcome.take() {
14898                    Some(Ok(result)) => flat_results.push(result),
14899                    Some(Err(_)) => {
14900                        return Poll::Ready(Err(invalid_recorded_history(
14901                            "selection_winner_outcome_mismatch",
14902                            member.base_sequence,
14903                            "fully completed nested selection member",
14904                            "failed durable leaf",
14905                            "completed selection winner contains a failed leaf",
14906                        )))
14907                    }
14908                    None => {
14909                        return Poll::Ready(Err(invalid_recorded_history(
14910                            "selection_winner_unresolved",
14911                            member.base_sequence,
14912                            "terminal history for every completed winner leaf",
14913                            "pending member history",
14914                            "completed SelectionResolved member has an unfinished durable barrier",
14915                        )))
14916                    }
14917                }
14918            }
14919        }
14920        let value = if winner_failure.is_none() {
14921            let mut flat_results = flat_results.into_iter();
14922            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
14923            match value.into_json_result() {
14924                Ok(value) => Some(value),
14925                Err(error) => return Poll::Ready(Err(error)),
14926            }
14927        } else {
14928            None
14929        };
14930        let winner = handles[member_position].clone();
14931        self.ctx
14932            .state
14933            .lock()
14934            .map_err(|_| Error::WorkflowStatePoisoned)?
14935            .consume_replay_selection(&marker.selection_group_id);
14936        Poll::Ready(Ok(SelectionResult {
14937            key: winner.key.clone(),
14938            index: winner.index,
14939            kind: winner.kind.clone(),
14940            identity: winner.identity.clone(),
14941            value,
14942            failure: winner_failure,
14943            winner,
14944            handles,
14945        }))
14946    }
14947}
14948
14949fn selection_operation_identity(
14950    state: &WorkflowState,
14951    kind: &str,
14952    base_sequence: u64,
14953    size: usize,
14954) -> String {
14955    if kind == "group" {
14956        return format!("group:{base_sequence}:{size}");
14957    }
14958    let fields: &[&str] = match kind {
14959        "activity" => &["activity_execution_id"],
14960        "child" => &["child_workflow_run_id"],
14961        "timer" => &["timer_id"],
14962        "signal" => &["signal_wait_id"],
14963        "condition" => &["condition_wait_id"],
14964        _ => &[],
14965    };
14966    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
14967        for event in state
14968            .history_events
14969            .iter()
14970            .filter(|event| durable_event_sequence(event) == Some(sequence))
14971        {
14972            for field in fields {
14973                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
14974                    if !identity.is_empty() {
14975                        return identity.to_string();
14976                    }
14977                }
14978            }
14979        }
14980    }
14981    String::new()
14982}
14983
14984fn validated_selection_resolution_sequence(
14985    state: &WorkflowState,
14986    marker: &SelectionMarker,
14987    member: &SelectionMemberPlan,
14988    expected_identity: &str,
14989) -> Result<u64> {
14990    if expected_identity.is_empty() {
14991        return Err(invalid_recorded_history(
14992            "selection_operation_identity_missing",
14993            member.base_sequence,
14994            &format!(
14995                "durable {} resource identity from scheduled/open history",
14996                member.kind
14997            ),
14998            "missing operation identity",
14999            "selection member history is missing its canonical durable identity",
15000        ));
15001    }
15002    if marker.operation_identity != expected_identity {
15003        return Err(invalid_recorded_history(
15004            "selection_operation_identity_mismatch",
15005            member.base_sequence,
15006            expected_identity,
15007            &marker.operation_identity,
15008            "selection winner identity does not match durable scheduled/open history",
15009        ));
15010    }
15011
15012    let failure_types = [
15013        "ActivityFailed",
15014        "ActivityCancelled",
15015        "ActivityTimedOut",
15016        "ChildRunFailed",
15017        "ChildRunCancelled",
15018        "ChildRunTerminated",
15019    ];
15020    let success_types = [
15021        "ActivityCompleted",
15022        "ChildRunCompleted",
15023        "TimerFired",
15024        "SignalApplied",
15025        "ConditionWaitSatisfied",
15026        "ConditionWaitTimedOut",
15027    ];
15028    let terminal_types: &[&str] = if marker.outcome == "failed" {
15029        &failure_types
15030    } else {
15031        &success_types
15032    };
15033    let mut candidates = Vec::new();
15034    let member_commands = (member.base_sequence
15035        ..member.base_sequence.saturating_add(member.size as u64))
15036        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
15037        .map(|command| (command.sequence(), command))
15038        .collect::<BTreeMap<_, _>>();
15039    let mut resolved_conditions = BTreeSet::new();
15040    for event in state.history_events.iter() {
15041        let Some(sequence) = durable_event_sequence(event) else {
15042            continue;
15043        };
15044        let Some(command) = member_commands.get(&sequence) else {
15045            continue;
15046        };
15047        if !terminal_types.contains(&event.event_type.as_str()) {
15048            continue;
15049        }
15050        if matches!(command, RecordedCommand::ConditionWait { .. }) {
15051            if !matches!(
15052                event.event_type.as_str(),
15053                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
15054            ) && !(event.event_type == "TimerFired"
15055                && event.payload.get("timer_kind").and_then(Value::as_str)
15056                    == Some("condition_timeout"))
15057            {
15058                continue;
15059            }
15060            if !resolved_conditions.insert(sequence) {
15061                continue;
15062            }
15063        }
15064        let event_id = event
15065            .raw
15066            .get("id")
15067            .or_else(|| event.raw.get("event_id"))
15068            .and_then(Value::as_str)
15069            .filter(|value| !value.is_empty())
15070            .ok_or_else(|| {
15071                invalid_recorded_history(
15072                    "selection_resolution_event_id_missing",
15073                    member.base_sequence,
15074                    "terminal selection history with a durable event id",
15075                    &event.payload.to_string(),
15076                    "selection terminal history cannot be bound to its winner marker",
15077                )
15078            })?;
15079        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
15080    }
15081    let resolution = if marker.outcome == "failed" {
15082        candidates.first()
15083    } else {
15084        candidates.last()
15085    };
15086    let Some((event_id, event_type, sequence)) = resolution else {
15087        return Err(invalid_recorded_history(
15088            "selection_resolution_event_missing",
15089            member.base_sequence,
15090            "terminal history for the selected member",
15091            &format!("{:?}", marker.member_key),
15092            "selection winner marker has no matching durable terminal event",
15093        ));
15094    };
15095    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
15096        return Err(invalid_recorded_history(
15097            "selection_resolution_event_mismatch",
15098            member.base_sequence,
15099            &format!("{event_type}:{event_id}"),
15100            &format!(
15101                "{}:{}",
15102                marker.resolution_event_type, marker.resolution_event_id
15103            ),
15104            "selection winner marker does not reference the event that made its member terminal",
15105        ));
15106    }
15107    Ok(*sequence)
15108}
15109
15110fn selection_member_recorded_command(
15111    state: &WorkflowState,
15112    authored_sequence: u64,
15113) -> Option<&RecordedCommand> {
15114    let original = state
15115        .recorded_commands
15116        .iter()
15117        .find(|command| command.sequence() == authored_sequence)?;
15118    let RecordedCommand::ConditionWait {
15119        occurrence_id,
15120        parallel_group_path: Some(_),
15121        ..
15122    } = original
15123    else {
15124        return Some(original);
15125    };
15126    // Decoding proves each physical reopen has the same authored identity and
15127    // group path after a satisfied predecessor. Only its latest wait can make
15128    // this logical member terminal.
15129    state
15130        .recorded_commands
15131        .iter()
15132        .filter(|command| {
15133            matches!(command, RecordedCommand::ConditionWait {
15134                occurrence_id: candidate, ..
15135            } if candidate == occurrence_id)
15136        })
15137        .max_by_key(|command| command.sequence())
15138}
15139
15140fn recorded_selection_member_outcome(
15141    state: &WorkflowState,
15142    handle: &DurableOperationHandle,
15143) -> Result<Option<ParallelResult>> {
15144    for event in state.history_events.iter() {
15145        let Some(sequence) = durable_event_sequence(event) else {
15146            continue;
15147        };
15148        if sequence < handle.base_sequence
15149            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
15150            || !matches!(
15151                event.event_type.as_str(),
15152                "ActivityFailed"
15153                    | "ActivityCancelled"
15154                    | "ActivityTimedOut"
15155                    | "ChildRunFailed"
15156                    | "ChildRunCancelled"
15157                    | "ChildRunTerminated"
15158            )
15159        {
15160            continue;
15161        }
15162        let Some(command) = state
15163            .recorded_commands
15164            .iter()
15165            .find(|command| command.sequence() == sequence)
15166        else {
15167            continue;
15168        };
15169        match command {
15170            RecordedCommand::Activity {
15171                outcome: Some(Err(failure)),
15172                ..
15173            } => return Err(Error::ActivityFailed(failure.clone())),
15174            RecordedCommand::ChildWorkflow {
15175                outcome: Some(Err(failure)),
15176                ..
15177            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
15178            _ => {}
15179        }
15180    }
15181
15182    let mut results = Vec::with_capacity(handle.size);
15183    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
15184        let Some(command) = selection_member_recorded_command(state, sequence) else {
15185            return Ok(None);
15186        };
15187        let result = match command {
15188            RecordedCommand::Activity { outcome, .. } => match outcome {
15189                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
15190                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
15191                None => return Ok(None),
15192            },
15193            RecordedCommand::Timer { fired, .. } => {
15194                if !fired {
15195                    return Ok(None);
15196                }
15197                ParallelAvroResult::Timer
15198            }
15199            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
15200                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
15201                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
15202                None => return Ok(None),
15203            },
15204            RecordedCommand::SignalWait { value, .. } => match value {
15205                Some(value) => ParallelAvroResult::Signal(value.clone()),
15206                None => return Ok(None),
15207            },
15208            RecordedCommand::ConditionWait { result, .. } => match result {
15209                Some(result) => ParallelAvroResult::Condition(*result),
15210                None => return Ok(None),
15211            },
15212            other => {
15213                return Err(command_mismatch(
15214                    other,
15215                    format!("selected {} member", handle.kind),
15216                ))
15217            }
15218        };
15219        results.push(result);
15220    }
15221    let mut results = results.into_iter();
15222    parallel_results_for_shape(&handle.shape, &mut results)
15223        .into_json_result()
15224        .map(Some)
15225}
15226
15227fn recorded_selection_member_is_terminal(
15228    state: &WorkflowState,
15229    handle: &DurableOperationHandle,
15230) -> bool {
15231    let mut completed = 0usize;
15232    let mut all_completed = true;
15233    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
15234        let Some(command) = selection_member_recorded_command(state, sequence) else {
15235            all_completed = false;
15236            continue;
15237        };
15238        let terminal = match command {
15239            RecordedCommand::Activity {
15240                outcome: Some(Err(_)),
15241                ..
15242            }
15243            | RecordedCommand::ChildWorkflow {
15244                outcome: Some(Err(_)),
15245                ..
15246            } => return true,
15247            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
15248            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
15249            RecordedCommand::Timer { fired, .. } => *fired,
15250            RecordedCommand::SignalWait { value, .. } => value.is_some(),
15251            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
15252            RecordedCommand::SearchAttributes { .. }
15253            | RecordedCommand::CancellationScope { .. }
15254            | RecordedCommand::SideEffect { .. }
15255            | RecordedCommand::VersionMarker { .. }
15256            | RecordedCommand::Memo { .. }
15257            | RecordedCommand::CancellationBoundary { .. }
15258            | RecordedCommand::CancellationGroup { .. } => false,
15259            RecordedCommand::ServiceOperation { .. } => false,
15260        };
15261        if !terminal {
15262            all_completed = false;
15263            continue;
15264        }
15265        completed += 1;
15266    }
15267    all_completed && completed == handle.size
15268}
15269
15270fn selection_cancellation_for_handle(
15271    state: &WorkflowState,
15272    handle: &DurableOperationHandle,
15273) -> Result<bool> {
15274    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
15275        recorded.selection_group_id == handle.selection_group_id
15276            && recorded.member_base_sequence == handle.base_sequence
15277    }) else {
15278        return Ok(false);
15279    };
15280    validate_selection_cancellation_marker(marker, handle)?;
15281    Ok(true)
15282}
15283
15284fn validate_selection_cancellations_for_handles(
15285    state: &WorkflowState,
15286    handles: &[DurableOperationHandle],
15287) -> Result<()> {
15288    let Some(group_id) = handles
15289        .first()
15290        .map(|handle| handle.selection_group_id.as_str())
15291    else {
15292        return Ok(());
15293    };
15294    for marker in state
15295        .cancelled_selection_members
15296        .iter()
15297        .filter(|marker| marker.selection_group_id == group_id)
15298    {
15299        let Some(handle) = handles
15300            .iter()
15301            .find(|handle| handle.base_sequence == marker.member_base_sequence)
15302        else {
15303            return Err(invalid_recorded_history(
15304                "selection_cancellation_member_mismatch",
15305                marker.member_base_sequence,
15306                "SelectionOperationCancelled matching an authored selection handle",
15307                &format!("{marker:?}"),
15308                "selection cancellation member base does not name an authored member",
15309            ));
15310        };
15311        validate_selection_cancellation_marker(marker, handle)?;
15312    }
15313    Ok(())
15314}
15315
15316fn validate_selection_cancellation_marker(
15317    marker: &SelectionCancellation,
15318    handle: &DurableOperationHandle,
15319) -> Result<()> {
15320    if marker.selection_group_id != handle.selection_group_id
15321        || marker.member_key != handle.key
15322        || marker.member_index != handle.index
15323        || marker.member_base_sequence != handle.base_sequence
15324        || marker.member_size != handle.size
15325        || marker.operation_kind != handle.kind
15326        || marker.operation_identity != handle.identity
15327    {
15328        return Err(invalid_recorded_history(
15329            "selection_cancellation_member_mismatch",
15330            handle.base_sequence,
15331            "SelectionOperationCancelled matching the authored selection handle",
15332            &format!("{marker:?}"),
15333            "selection cancellation history targets different authored member metadata",
15334        ));
15335    }
15336    Ok(())
15337}
15338
15339/// Future returned by [`DurableOperationHandle::await_result`].
15340pub struct DurableOperationAwaitCall {
15341    handle: DurableOperationHandle,
15342}
15343
15344impl Future for DurableOperationAwaitCall {
15345    type Output = Result<ParallelResult>;
15346
15347    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15348        let mut state = match self.handle.ctx.state.lock() {
15349            Ok(state) => state,
15350            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15351        };
15352        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
15353            return Poll::Ready(Err(error));
15354        }
15355        match state.prepare_selection_handle_cancellation(&self.handle) {
15356            Ok(true) => return Poll::Pending,
15357            Ok(false) => {}
15358            Err(error) => return Poll::Ready(Err(error)),
15359        }
15360        match selection_cancellation_for_handle(&state, &self.handle) {
15361            Err(error) => return Poll::Ready(Err(error)),
15362            Ok(false) => {}
15363            Ok(true) => {
15364                state.consume_replay_receipt(
15365                    &self.handle.selection_group_id,
15366                    self.handle.base_sequence,
15367                );
15368                return Poll::Ready(Err(Error::DurableOperationCancelled(
15369                    DurableOperationCancelled {
15370                        selection_group_id: self.handle.selection_group_id.clone(),
15371                        member_key: self.handle.key.clone(),
15372                        member_index: self.handle.index,
15373                        operation_kind: self.handle.kind.clone(),
15374                        operation_identity: self.handle.identity.clone(),
15375                    },
15376                )));
15377            }
15378        }
15379        match recorded_selection_member_outcome(&state, &self.handle) {
15380            Ok(Some(result)) => {
15381                state.consume_replay_handle(&self.handle, false);
15382                Poll::Ready(Ok(result))
15383            }
15384            Ok(None) => Poll::Pending,
15385            Err(error) => {
15386                if !workflow_task_integrity_error(&error) {
15387                    state.consume_replay_handle(&self.handle, true);
15388                }
15389                Poll::Ready(Err(error))
15390            }
15391        }
15392    }
15393}
15394
15395fn validate_selection_delivery_handle(
15396    state: &WorkflowState,
15397    handle: &DurableOperationHandle,
15398) -> Result<()> {
15399    let path = state
15400        .recorded_commands
15401        .iter()
15402        .find(|command| command.sequence() == handle.base_sequence)
15403        .and_then(|command| match command {
15404            RecordedCommand::Activity {
15405                parallel_group_path,
15406                ..
15407            }
15408            | RecordedCommand::ChildWorkflow {
15409                parallel_group_path,
15410                ..
15411            }
15412            | RecordedCommand::Timer {
15413                parallel_group_path,
15414                ..
15415            }
15416            | RecordedCommand::SignalWait {
15417                parallel_group_path,
15418                ..
15419            }
15420            | RecordedCommand::ConditionWait {
15421                parallel_group_path,
15422                ..
15423            } => parallel_group_path.as_ref(),
15424            _ => None,
15425        })
15426        .and_then(|path| path.first());
15427    let matches = path.is_some_and(|entry| {
15428        entry.parallel_group_mode.as_deref() == Some("select")
15429            && entry.parallel_group_id == handle.selection_group_id
15430            && entry.selection_member_key.as_ref() == Some(&handle.key)
15431            && entry.selection_member_index == Some(handle.index)
15432            && entry.selection_member_base_sequence == Some(handle.base_sequence)
15433            && entry.selection_member_size == Some(handle.size)
15434            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
15435    });
15436    if !matches
15437        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
15438            != handle.identity
15439    {
15440        return Err(invalid_recorded_history(
15441            "cooperative_cancellation_call_mismatch",
15442            handle.base_sequence,
15443            "selection handle matching its authored durable identity",
15444            &format!("{handle:?}"),
15445            "selection handle identity or member metadata changed before cancellation replay",
15446        ));
15447    }
15448    Ok(())
15449}
15450
15451/// Future returned by [`DurableOperationHandle::cancel`].
15452pub struct CancelDurableOperationCall {
15453    handle: DurableOperationHandle,
15454    emitted: bool,
15455}
15456
15457impl Future for CancelDurableOperationCall {
15458    type Output = Result<()>;
15459
15460    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15461        let ctx = self.handle.ctx.clone();
15462        let mut state = match ctx.state.lock() {
15463            Ok(state) => state,
15464            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15465        };
15466        match selection_cancellation_for_handle(&state, &self.handle) {
15467            Err(error) => return Poll::Ready(Err(error)),
15468            Ok(true) => {
15469                state.consume_replay_receipt(
15470                    &self.handle.selection_group_id,
15471                    self.handle.base_sequence,
15472                );
15473                return Poll::Ready(Ok(()));
15474            }
15475            Ok(false) => {}
15476        }
15477        if recorded_selection_member_is_terminal(&state, &self.handle) {
15478            return Poll::Ready(Ok(()));
15479        }
15480        if !self.emitted {
15481            state.commands.push(json!({
15482                "type": "cancel_selection_operation",
15483                "selection_group_id": self.handle.selection_group_id,
15484                "member_key": self.handle.key,
15485                "member_index": self.handle.index,
15486                "member_base_sequence": self.handle.base_sequence,
15487                "member_size": self.handle.size,
15488                "operation_kind": self.handle.kind,
15489                "operation_identity": self.handle.identity,
15490            }));
15491            self.emitted = true;
15492        }
15493        // Unit completes the request, not the member's outcome. Following
15494        // workflow commands commit atomically with this cancellation request.
15495        // Waiting here would need another workflow task that cancellation
15496        // alone does not create. await_result still requires recorded history.
15497        Poll::Ready(Ok(()))
15498    }
15499}
15500
15501trait PollNestedResultExt<T> {
15502    fn flatten_result(self) -> Poll<Result<T>>;
15503}
15504
15505impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
15506    fn flatten_result(self) -> Poll<Result<T>> {
15507        match self {
15508            Poll::Ready(Ok(result)) => Poll::Ready(result),
15509            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15510            Poll::Pending => Poll::Pending,
15511        }
15512    }
15513}
15514
15515struct SagaCompensation {
15516    activity_type: String,
15517    options: ActivityOptions,
15518    arguments: AvroValue,
15519    registration_order: usize,
15520}
15521
15522/// Workflow-local deterministic saga compensation helper.
15523///
15524/// Register each compensation only after its forward step succeeds. Passing
15525/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
15526/// reverse registration order after any failure, including cooperative
15527/// cancellation. Each compensation is an ordinary durable activity, so replay,
15528/// duplicate delivery, and worker restart use existing history semantics.
15529pub struct Saga {
15530    ctx: WorkflowContext,
15531    compensations: Vec<SagaCompensation>,
15532}
15533
15534impl Saga {
15535    fn new(ctx: WorkflowContext) -> Self {
15536        Self {
15537            ctx,
15538            compensations: Vec::new(),
15539        }
15540    }
15541
15542    pub fn add_compensation<T: Serialize>(
15543        &mut self,
15544        activity_type: impl Into<String>,
15545        args: T,
15546    ) -> Result<&mut Self> {
15547        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
15548    }
15549
15550    pub fn add_compensation_with_options<T: Serialize>(
15551        &mut self,
15552        activity_type: impl Into<String>,
15553        options: ActivityOptions,
15554        args: T,
15555    ) -> Result<&mut Self> {
15556        let activity_type = activity_type.into();
15557        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
15558            return Err(Error::Codec(
15559                "saga compensation activity type must be non-empty without surrounding whitespace"
15560                    .to_string(),
15561            ));
15562        }
15563        options.validate().map_err(Error::InvalidActivityOptions)?;
15564        let arguments = AvroValue::from_serialize(&args)?;
15565        let registration_order = self.compensations.len() + 1;
15566        self.compensations.push(SagaCompensation {
15567            activity_type,
15568            options,
15569            arguments,
15570            registration_order,
15571        });
15572        Ok(self)
15573    }
15574
15575    /// Compensate `initiating_failure` and return the failure that must remain.
15576    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
15577        let _shield = match self.ctx.cancellation_shield() {
15578            Ok(shield) => shield,
15579            Err(error) => return error,
15580        };
15581        while let Some(compensation) = self.compensations.pop() {
15582            if let Err(compensation_failure) = self
15583                .ctx
15584                .activity_with_options(
15585                    compensation.activity_type.clone(),
15586                    compensation.options,
15587                    compensation.arguments,
15588                )
15589                .await
15590            {
15591                if workflow_task_integrity_error(&compensation_failure) {
15592                    return compensation_failure;
15593                }
15594                return Error::SagaCompensationFailed(SagaCompensationFailure {
15595                    initiating_failure: Box::new(initiating_failure),
15596                    compensation_failure: Box::new(compensation_failure),
15597                    compensation_activity_type: compensation.activity_type,
15598                    compensation_registration_order: compensation.registration_order,
15599                });
15600            }
15601        }
15602        initiating_failure
15603    }
15604
15605    /// Return a successful forward value or compensate and preserve its failure.
15606    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
15607        match outcome {
15608            Ok(value) => Ok(value),
15609            Err(error) => Err(self.compensate(error).await),
15610        }
15611    }
15612}
15613
15614pub struct ActivityCall {
15615    ctx: WorkflowContext,
15616    activity_type: String,
15617    options: ActivityOptions,
15618    worker_session: Option<WorkerSessionOptions>,
15619    args: Option<Result<AvroValue>>,
15620    scheduled: bool,
15621    local: bool,
15622    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
15623    parallel_group_path: Vec<ParallelGroupMetadata>,
15624}
15625
15626impl ActivityCall {
15627    fn poll_avro_value(
15628        mut self: Pin<&mut Self>,
15629        _cx: &mut TaskContext<'_>,
15630    ) -> Poll<Result<AvroValue>> {
15631        let ctx = self.ctx.clone();
15632        let mut state = match ctx.state.lock() {
15633            Ok(state) => state,
15634            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15635        };
15636
15637        if let Some(result) = &self.local_result {
15638            return match result.lock() {
15639                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
15640                    state.replay_clock.unavailable();
15641                    Poll::Ready(result.map_err(Error::ActivityFailed))
15642                }),
15643                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15644            };
15645        }
15646        if self.scheduled {
15647            return Poll::Pending;
15648        }
15649
15650        let options = match self.options.validate() {
15651            Ok(options) => options,
15652            Err(error) => {
15653                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
15654            }
15655        };
15656        if self.local {
15657            if self.worker_session.is_some() {
15658                return Poll::Ready(Err(Error::WorkerLoop(
15659                    "local activities cannot use worker-session routing".into(),
15660                )));
15661            }
15662            if let Err(error) = local_activity::validate(&options) {
15663                return Poll::Ready(Err(error));
15664            }
15665        }
15666        let session = match self
15667            .worker_session
15668            .as_ref()
15669            .map(WorkerSessionOptions::to_wire)
15670            .transpose()
15671        {
15672            Ok(value) => value,
15673            Err(error) => return Poll::Ready(Err(error)),
15674        };
15675        let session_queue = session
15676            .as_ref()
15677            .and_then(|session| session["queue"].as_str());
15678        let task_queue = options
15679            .task_queue
15680            .clone()
15681            .or_else(|| session_queue.map(str::to_owned))
15682            .unwrap_or_else(|| state.task_queue.clone());
15683        if session_queue.is_some_and(|queue| queue != task_queue) {
15684            return Poll::Ready(Err(Error::WorkerLoop(
15685                "worker-session queue must match the activity task queue".into(),
15686            )));
15687        }
15688        let current_recorded_options = RecordedActivityOptions {
15689            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
15690            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
15691            retry_policy: current_activity_retry_snapshot(&options),
15692            worker_session: session,
15693        };
15694
15695        let cursor = state.command_cursor;
15696        let call_kind = if self.local {
15697            CancellationCallKind::LocalActivity
15698        } else {
15699            CancellationCallKind::Activity
15700        };
15701        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15702            return Poll::Ready(Err(error));
15703        }
15704        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
15705            Ok(recorded) => recorded,
15706            Err(error) => return Poll::Ready(Err(error)),
15707        };
15708        if let Some(recorded) = recorded {
15709            let sequence = recorded.sequence();
15710            match recorded {
15711                RecordedCommand::Activity {
15712                    activity_type,
15713                    cancellation_policy,
15714                    options: recorded_options,
15715                    outcome,
15716                    parallel_group_path,
15717                    ..
15718                } => {
15719                    let current_policy = options
15720                        .cancellation_policy
15721                        .unwrap_or(CancellationPolicy::TryCancel)
15722                        .as_str();
15723                    if cancellation_policy != current_policy {
15724                        return Poll::Ready(Err(Error::NonDeterministicReplay(
15725                            ReplayFailure::new(
15726                                "activity_cancellation_policy_changed",
15727                                Some(sequence),
15728                                Some(cancellation_policy),
15729                                Some(current_policy.to_string()),
15730                                "Activity cancellation policy changed during replay",
15731                            ),
15732                        )));
15733                    }
15734                    if let Err(error) = ensure_parallel_path_matches(
15735                        sequence,
15736                        parallel_group_path.as_deref(),
15737                        &self.parallel_group_path,
15738                    ) {
15739                        return Poll::Ready(Err(error));
15740                    }
15741                    if let Some(recorded_type) = activity_type {
15742                        if recorded_type != self.activity_type {
15743                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15744                                ReplayFailure::new(
15745                                    "recorded_command_detail_mismatch",
15746                                    Some(sequence),
15747                                    Some(format!("activity:{recorded_type}")),
15748                                    Some(format!("activity:{}", self.activity_type)),
15749                                    "recorded activity type differs from the current workflow command",
15750                                ),
15751                            )));
15752                        }
15753                    }
15754                    if let Some(recorded_options) = recorded_options {
15755                        if recorded_options.worker_session
15756                            != current_recorded_options.worker_session
15757                        {
15758                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
15759                                "activity_worker_session_mismatch", Some(sequence),
15760                                Some(activity_options_description(&recorded_options)),
15761                                Some(activity_options_description(&current_recorded_options)),
15762                                "recorded worker-session routing differs from the current activity",
15763                            ))));
15764                        }
15765                        if !recorded_options
15766                            .task_queue
15767                            .matches_current(&current_recorded_options.task_queue)
15768                        {
15769                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15770                                ReplayFailure::new(
15771                                    "activity_task_queue_mismatch",
15772                                    Some(sequence),
15773                                    Some(activity_options_description(&recorded_options)),
15774                                    Some(activity_options_description(&current_recorded_options)),
15775                                    "recorded activity task queue differs from the current workflow command",
15776                                ),
15777                            )));
15778                        }
15779                        if (self.local
15780                            && matches!(
15781                                recorded_options.execution_mode,
15782                                RecordedSnapshotValue::Unknown
15783                            ))
15784                            || !recorded_options
15785                                .execution_mode
15786                                .matches_current(&current_recorded_options.execution_mode)
15787                        {
15788                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15789                                ReplayFailure::new(
15790                                    "activity_execution_mode_mismatch",
15791                                    Some(sequence),
15792                                    Some(activity_options_description(&recorded_options)),
15793                                    Some(activity_options_description(&current_recorded_options)),
15794                                    "recorded activity execution mode differs from the current workflow command",
15795                                ),
15796                            )));
15797                        }
15798                        if !recorded_options
15799                            .retry_policy
15800                            .matches_current(&current_recorded_options.retry_policy)
15801                        {
15802                            return Poll::Ready(Err(Error::NonDeterministicReplay(
15803                                ReplayFailure::new(
15804                                    "activity_retry_policy_mismatch",
15805                                    Some(sequence),
15806                                    Some(activity_options_description(&recorded_options)),
15807                                    Some(activity_options_description(&current_recorded_options)),
15808                                    "recorded activity retry policy differs from the current workflow command",
15809                                ),
15810                            )));
15811                        }
15812                    }
15813                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
15814                        return Poll::Ready(Err(error));
15815                    }
15816                    match state.prepare_scalar_cancellation(
15817                        cursor,
15818                        call_kind,
15819                        &self.parallel_group_path,
15820                    ) {
15821                        Ok(true) => {
15822                            self.scheduled = true;
15823                            return Poll::Pending;
15824                        }
15825                        Ok(false) => {}
15826                        Err(error) => return Poll::Ready(Err(error)),
15827                    }
15828                    state.command_cursor += 1;
15829                    if let Some(outcome) = outcome {
15830                        state.consume_replay_sequence(sequence, &self.parallel_group_path);
15831                        if self.local {
15832                            state.replay_clock.unavailable();
15833                        }
15834                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
15835                    }
15836                    state.matched_recorded_pending = true;
15837                    state.observation_pending = true;
15838                    self.scheduled = true;
15839                    return Poll::Pending;
15840                }
15841                other => {
15842                    return Poll::Ready(Err(command_mismatch(
15843                        &other,
15844                        format!("activity:{}", self.activity_type),
15845                    )));
15846                }
15847            }
15848        }
15849
15850        if !self.scheduled {
15851            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
15852                Ok(args) => args,
15853                Err(error) => return Poll::Ready(Err(error)),
15854            };
15855            let arguments = normalize_avro_arguments(args);
15856            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
15857                Ok(envelope) => envelope,
15858                Err(error) => return Poll::Ready(Err(error)),
15859            };
15860
15861            let mut command = serde_json::Map::from_iter([
15862                (
15863                    "type".to_string(),
15864                    json!(if self.local {
15865                        "record_local_activity"
15866                    } else {
15867                        "schedule_activity"
15868                    }),
15869                ),
15870                (
15871                    "activity_type".to_string(),
15872                    json!(self.activity_type.clone()),
15873                ),
15874                ("queue".to_string(), json!(task_queue)),
15875                ("arguments".to_string(), envelope),
15876            ]);
15877            for (field, value) in [
15878                ("start_to_close_timeout", options.start_to_close_timeout),
15879                (
15880                    "schedule_to_start_timeout",
15881                    options.schedule_to_start_timeout,
15882                ),
15883                (
15884                    "schedule_to_close_timeout",
15885                    options.schedule_to_close_timeout,
15886                ),
15887                ("heartbeat_timeout", options.heartbeat_timeout),
15888            ] {
15889                if let Some(value) = value {
15890                    command.insert(field.to_string(), json!(value));
15891                }
15892            }
15893            if let Some(retry_policy) = &options.retry_policy {
15894                command.insert("retry_policy".to_string(), retry_policy.clone());
15895            }
15896            if let Some(policy) = options.cancellation_policy {
15897                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
15898            }
15899            if let Some(session) = current_recorded_options.worker_session {
15900                command.insert("worker_session".into(), session);
15901            }
15902            apply_parallel_group_path(&mut command, &self.parallel_group_path);
15903            ctx.apply_scope_membership(&mut command);
15904            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
15905                Ok(true) => {
15906                    self.scheduled = true;
15907                    return Poll::Pending;
15908                }
15909                Ok(false) => {}
15910                Err(error) => return Poll::Ready(Err(error)),
15911            }
15912            if self.local {
15913                command.remove("queue");
15914                command.insert("execution_mode".into(), json!("local"));
15915                let result = Arc::new(Mutex::new(None));
15916                let command_index = state.commands.len();
15917                state.local_activity_requests.push(local_activity::Request {
15918                    command_index,
15919                    options,
15920                    arguments,
15921                    result: result.clone(),
15922                });
15923                self.local_result = Some(result);
15924            }
15925            state.commands.push(Value::Object(command));
15926            self.scheduled = true;
15927        }
15928
15929        Poll::Pending
15930    }
15931}
15932
15933impl Future for ActivityCall {
15934    type Output = Result<Value>;
15935
15936    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15937        match self.poll_avro_value(cx) {
15938            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
15939            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
15940            Poll::Pending => Poll::Pending,
15941        }
15942    }
15943}
15944
15945/// Future returned by [`WorkflowContext::sleep`].
15946pub struct TimerCall {
15947    ctx: WorkflowContext,
15948    delay_seconds: Option<u64>,
15949    scheduled: bool,
15950    matched_pending: bool,
15951    parallel_group_path: Vec<ParallelGroupMetadata>,
15952}
15953
15954impl Future for TimerCall {
15955    type Output = Result<()>;
15956
15957    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15958        if self.matched_pending {
15959            return Poll::Pending;
15960        }
15961
15962        let ctx = self.ctx.clone();
15963        let Some(requested_delay) = self.delay_seconds else {
15964            return Poll::Ready(Err(Error::TimerDurationOverflow));
15965        };
15966        let mut state = match ctx.state.lock() {
15967            Ok(state) => state,
15968            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15969        };
15970
15971        let cursor = state.command_cursor;
15972        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
15973            return Poll::Ready(Err(error));
15974        }
15975        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
15976        {
15977            Ok(recorded) => recorded,
15978            Err(error) => return Poll::Ready(Err(error)),
15979        };
15980        if let Some(recorded) = recorded {
15981            match recorded {
15982                RecordedCommand::Timer {
15983                    sequence,
15984                    delay_seconds,
15985                    fired,
15986                    parallel_group_path,
15987                    ..
15988                } => {
15989                    if let Err(error) =
15990                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
15991                    {
15992                        return Poll::Ready(Err(error));
15993                    }
15994                    if let Err(error) = ensure_parallel_path_matches(
15995                        sequence,
15996                        parallel_group_path.as_deref(),
15997                        &self.parallel_group_path,
15998                    ) {
15999                        return Poll::Ready(Err(error));
16000                    }
16001                    if delay_seconds != requested_delay {
16002                        return Poll::Ready(Err(Error::NonDeterministicReplay(
16003                            ReplayFailure::new(
16004                                "timer_delay_mismatch",
16005                                Some(sequence),
16006                                Some(format!("timer:{delay_seconds}s")),
16007                                Some(format!("timer:{requested_delay}s")),
16008                                "recorded timer delay differs from the current workflow command",
16009                            ),
16010                        )));
16011                    }
16012                    if let Err(error) =
16013                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
16014                    {
16015                        return Poll::Ready(Err(error));
16016                    }
16017                    match state.prepare_scalar_cancellation(
16018                        cursor,
16019                        CancellationCallKind::Timer,
16020                        &self.parallel_group_path,
16021                    ) {
16022                        Ok(true) => {
16023                            self.scheduled = true;
16024                            self.matched_pending = true;
16025                            return Poll::Pending;
16026                        }
16027                        Ok(false) => {}
16028                        Err(error) => return Poll::Ready(Err(error)),
16029                    }
16030                    state.command_cursor += 1;
16031                    if fired {
16032                        state.consume_replay_sequence(sequence, &self.parallel_group_path);
16033                        return Poll::Ready(Ok(()));
16034                    }
16035                    state.matched_recorded_pending = true;
16036                    state.observation_pending = true;
16037                    self.scheduled = true;
16038                    self.matched_pending = true;
16039                    return Poll::Pending;
16040                }
16041                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
16042            }
16043        }
16044
16045        if !self.scheduled {
16046            let mut command = serde_json::Map::from_iter([
16047                ("type".to_string(), json!("start_timer")),
16048                ("delay_seconds".to_string(), json!(requested_delay)),
16049            ]);
16050            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
16051                Ok(Some(proof)) => {
16052                    command.insert("cancellation_cleanup".into(), proof);
16053                }
16054                Ok(None) => {}
16055                Err(error) => return Poll::Ready(Err(error)),
16056            }
16057            apply_parallel_group_path(&mut command, &self.parallel_group_path);
16058            ctx.apply_scope_membership(&mut command);
16059            match state.prepare_scalar_cancellation(
16060                cursor,
16061                CancellationCallKind::Timer,
16062                &self.parallel_group_path,
16063            ) {
16064                Ok(true) => {
16065                    self.scheduled = true;
16066                    self.matched_pending = true;
16067                    return Poll::Pending;
16068                }
16069                Ok(false) => {}
16070                Err(error) => return Poll::Ready(Err(error)),
16071            }
16072            state.commands.push(Value::Object(command));
16073            self.scheduled = true;
16074        }
16075
16076        Poll::Pending
16077    }
16078}
16079
16080/// Future returned by [`WorkflowContext::wait_condition`].
16081pub struct ConditionWaitCall {
16082    ctx: WorkflowContext,
16083    options: ConditionWaitOptions,
16084    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
16085    occurrence_id: Option<String>,
16086    opened_wait: bool,
16087    parallel_group_path: Vec<ParallelGroupMetadata>,
16088}
16089
16090impl Future for ConditionWaitCall {
16091    type Output = Result<ConditionWaitResult>;
16092
16093    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
16094        if self.opened_wait {
16095            return Poll::Pending;
16096        }
16097
16098        let mut options = match self.options.validate() {
16099            Ok(options) => options,
16100            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
16101        };
16102        let ctx = self.ctx.clone();
16103        let occurrence_id = match self.occurrence_id.as_ref() {
16104            Some(occurrence_id) => occurrence_id.clone(),
16105            None => {
16106                let mut state = match ctx.state.lock() {
16107                    Ok(state) => state,
16108                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16109                };
16110                let ordinal = state.condition_wait_occurrence_counter;
16111                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
16112                    Some(next) => next,
16113                    None => {
16114                        return Poll::Ready(Err(Error::WorkerLoop(
16115                            "condition wait occurrence counter overflowed".to_string(),
16116                        )))
16117                    }
16118                };
16119                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
16120                drop(state);
16121                self.occurrence_id = Some(occurrence_id.clone());
16122                occurrence_id
16123            }
16124        };
16125
16126        let recorded_result = {
16127            let mut state = match ctx.state.lock() {
16128                Ok(state) => state,
16129                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16130            };
16131            let initial_cursor = state.command_cursor;
16132            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
16133                return Poll::Ready(Err(error));
16134            }
16135            let recorded = match state
16136                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
16137            {
16138                Ok(recorded) => recorded,
16139                Err(error) => return Poll::Ready(Err(error)),
16140            };
16141            let Some(recorded) = recorded else {
16142                drop(state);
16143                return self.poll_new_condition(options);
16144            };
16145            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
16146                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
16147            }
16148
16149            let mut cursor = state.command_cursor;
16150            let mut result = None;
16151            let mut pending_delivery = false;
16152            let mut first_sequence = None;
16153            let mut latest_timeout_seconds = None;
16154            let mut previous_sequence = None;
16155            loop {
16156                if cursor > initial_cursor
16157                    && matches!(
16158                        state.recorded_commands.get(cursor),
16159                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
16160                    )
16161                {
16162                    break;
16163                }
16164                let recorded = match state
16165                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
16166                {
16167                    Ok(recorded) => recorded,
16168                    Err(error) => return Poll::Ready(Err(error)),
16169                };
16170                let Some(RecordedCommand::ConditionWait {
16171                    sequence,
16172                    occurrence_id: ref recorded_occurrence_id,
16173                    ref condition_key,
16174                    ref predicate_identity,
16175                    timeout_seconds,
16176                    result: recorded_result,
16177                    ref parallel_group_path,
16178                    ..
16179                }) = recorded
16180                else {
16181                    break;
16182                };
16183
16184                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
16185                    break;
16186                }
16187                if let Err(error) = ensure_parallel_path_matches(
16188                    sequence,
16189                    parallel_group_path.as_deref(),
16190                    &self.parallel_group_path,
16191                ) {
16192                    return Poll::Ready(Err(error));
16193                }
16194                if let Err(error) = validate_recorded_condition_wait(
16195                    sequence,
16196                    recorded_occurrence_id,
16197                    condition_key.as_deref(),
16198                    predicate_identity,
16199                    timeout_seconds,
16200                    &occurrence_id,
16201                    &options,
16202                    cursor > initial_cursor,
16203                ) {
16204                    return Poll::Ready(Err(error));
16205                }
16206                first_sequence.get_or_insert(sequence);
16207                latest_timeout_seconds = timeout_seconds;
16208                if result == Some(ConditionWaitResult::TimedOut)
16209                    && !previous_sequence.is_some_and(|previous| {
16210                        condition_wait_opened_before_timeout(
16211                            &state.history_events,
16212                            &occurrence_id,
16213                            previous,
16214                            sequence,
16215                        )
16216                    })
16217                {
16218                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
16219                        "condition_wait_reopened_after_timeout",
16220                        Some(sequence),
16221                        Some("timed-out condition is terminal".to_string()),
16222                        Some("another physical wait-open".to_string()),
16223                        "condition history reopened one logical wait after its durable timeout",
16224                    ))));
16225                }
16226                if let Err(error) =
16227                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
16228                {
16229                    return Poll::Ready(Err(error));
16230                }
16231                match state.prepare_scalar_cancellation(
16232                    cursor,
16233                    CancellationCallKind::Condition,
16234                    &self.parallel_group_path,
16235                ) {
16236                    Ok(pending) => pending_delivery |= pending,
16237                    Err(error) => return Poll::Ready(Err(error)),
16238                }
16239                result = recorded_result;
16240                if result.is_some() {
16241                    state.consume_replay_sequence(sequence, &self.parallel_group_path);
16242                }
16243                previous_sequence = Some(sequence);
16244                cursor += 1;
16245            }
16246            state.command_cursor = cursor;
16247            if pending_delivery {
16248                self.opened_wait = true;
16249                return Poll::Pending;
16250            }
16251            match (result, first_sequence) {
16252                // A grouped (parallel or select) reopen keeps the authored
16253                // timeout while the history does: the PHP Server accepts a
16254                // grouped reopen only when its timeout equals both the original
16255                // and the latest open (#189), so the remaining time would stall
16256                // the run. A history that already recorded a shorter grouped
16257                // reopen came from a Server that accepts them; keep its
16258                // convention.
16259                (None, Some(_))
16260                    if !self.parallel_group_path.is_empty()
16261                        && latest_timeout_seconds == options.timeout_seconds =>
16262                {
16263                    None
16264                }
16265                (None, Some(first_sequence)) => {
16266                    // The logical wait stays open: its deadline is fixed at the
16267                    // first physical open, not reset by a wake that left the
16268                    // predicate false.
16269                    options.timeout_seconds = condition_reopen_timeout(
16270                        &state.history_events,
16271                        first_sequence,
16272                        &occurrence_id,
16273                        options.timeout_seconds,
16274                    );
16275                    None
16276                }
16277                (result, _) => result,
16278            }
16279        };
16280
16281        if let Some(result) = recorded_result {
16282            return Poll::Ready(Ok(result));
16283        }
16284
16285        self.poll_open_condition(options, true)
16286    }
16287}
16288
16289/// Whether the physical wait at `next` was opened while the one at `previous`
16290/// was still open, so that a later timeout of `previous` belongs to an orphaned
16291/// duplicate open rather than ending the logical wait (#192, sdk-php#283). A
16292/// Server can record a second open of a still-open wait (server#1015); the
16293/// first wait's timer then fires after the chain has moved on.
16294fn condition_wait_opened_before_timeout(
16295    history: &[HistoryEvent],
16296    occurrence_id: &str,
16297    previous: u64,
16298    next: u64,
16299) -> bool {
16300    let opened = |sequence: u64| {
16301        history.iter().position(|event| {
16302            event.event_type == "ConditionWaitOpened"
16303                && event.payload.get("sequence").and_then(Value::as_u64) == Some(sequence)
16304                && event
16305                    .payload
16306                    .get("condition_wait_occurrence_id")
16307                    .and_then(Value::as_str)
16308                    == Some(occurrence_id)
16309        })
16310    };
16311    let (Some(previous_open), Some(next_open)) = (opened(previous), opened(next)) else {
16312        return false;
16313    };
16314    let previous_wait_id = history[previous_open]
16315        .payload
16316        .get("condition_wait_id")
16317        .cloned();
16318    let timed_out = history
16319        .iter()
16320        .position(|event| match event.event_type.as_str() {
16321            "ConditionWaitTimedOut" => {
16322                event.payload.get("sequence").and_then(Value::as_u64) == Some(previous)
16323                    && event
16324                        .payload
16325                        .get("condition_wait_occurrence_id")
16326                        .and_then(Value::as_str)
16327                        == Some(occurrence_id)
16328            }
16329            "TimerFired" => {
16330                event.payload.get("timer_kind").and_then(Value::as_str) == Some("condition_timeout")
16331                    && previous_wait_id.is_some()
16332                    && event.payload.get("condition_wait_id") == previous_wait_id.as_ref()
16333            }
16334            _ => false,
16335        });
16336    timed_out.is_some_and(|timed_out| next_open < timed_out)
16337}
16338
16339/// The timeout for reopening a recorded logical condition wait: the authored
16340/// timeout less the time from its first physical open to the latest recorded
16341/// history event, rounded up and clamped to `0..=authored`. Without both
16342/// times, the authored timeout is kept.
16343fn condition_reopen_timeout(
16344    history: &[HistoryEvent],
16345    first_sequence: u64,
16346    occurrence_id: &str,
16347    authored: Option<u64>,
16348) -> Option<u64> {
16349    let authored = authored?;
16350    let wall_time = |event: &HistoryEvent| {
16351        event
16352            .raw
16353            .get("timestamp")
16354            .filter(|value| !value.is_null())
16355            .or_else(|| event.raw.get("recorded_at"))
16356            .and_then(Value::as_str)
16357            .and_then(|time| DateTime::parse_from_rfc3339(time).ok())
16358            .map(|time| time.with_timezone(&chrono::Utc))
16359    };
16360    let opened_at = history
16361        .iter()
16362        .find(|event| {
16363            event.event_type == "ConditionWaitOpened"
16364                && event.payload.get("sequence").and_then(Value::as_u64) == Some(first_sequence)
16365                && event
16366                    .payload
16367                    .get("condition_wait_occurrence_id")
16368                    .and_then(Value::as_str)
16369                    == Some(occurrence_id)
16370        })
16371        .and_then(wall_time);
16372    let latest = history.iter().filter_map(wall_time).max();
16373    let (Some(opened_at), Some(latest)) = (opened_at, latest) else {
16374        return Some(authored);
16375    };
16376    let elapsed_ms = i128::from((latest - opened_at).num_milliseconds().max(0));
16377    let remaining_ms = i128::from(authored) * 1000 - elapsed_ms;
16378    if remaining_ms <= 0 {
16379        return Some(0);
16380    }
16381    let remaining = (remaining_ms + 999) / 1000;
16382    Some(u64::try_from(remaining).map_or(authored, |remaining| remaining.min(authored)))
16383}
16384
16385impl ConditionWaitCall {
16386    fn poll_new_condition(
16387        self: Pin<&mut Self>,
16388        options: ValidatedConditionWaitOptions,
16389    ) -> Poll<Result<ConditionWaitResult>> {
16390        self.poll_open_condition(options, false)
16391    }
16392
16393    fn poll_open_condition(
16394        mut self: Pin<&mut Self>,
16395        options: ValidatedConditionWaitOptions,
16396        recorded_wait: bool,
16397    ) -> Poll<Result<ConditionWaitResult>> {
16398        {
16399            let ctx = self.ctx.clone();
16400            let mut state = match ctx.state.lock() {
16401                Ok(state) => state,
16402                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16403            };
16404            let cursor = state.command_cursor;
16405            match state.prepare_scalar_cancellation(
16406                cursor,
16407                CancellationCallKind::Condition,
16408                &self.parallel_group_path,
16409            ) {
16410                Ok(true) => {
16411                    self.opened_wait = true;
16412                    return Poll::Pending;
16413                }
16414                Ok(false) => {}
16415                Err(error) => return Poll::Ready(Err(error)),
16416            }
16417        }
16418        let selection_member = self
16419            .parallel_group_path
16420            .first()
16421            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
16422        let predicate_result = {
16423            // This predicate inspects the full signal/update view; the current
16424            // executor does not retain its exact triggering event prefix.
16425            let _clock = replay_clock::Guard::unavailable();
16426            (self.predicate)()
16427        };
16428        match predicate_result {
16429            Ok(true) if !selection_member || recorded_wait => {
16430                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
16431            }
16432            Ok(_) => {}
16433            Err(error) => return Poll::Ready(Err(error)),
16434        }
16435        // A recorded wait reopened after its deadline still opens, with a zero
16436        // timeout, so the Server resolves its wait and timer as timed out.
16437        if options.timeout_seconds == Some(0) && !selection_member && !recorded_wait {
16438            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
16439        }
16440
16441        let ctx = self.ctx.clone();
16442        let mut state = match ctx.state.lock() {
16443            Ok(state) => state,
16444            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16445        };
16446        let mut command = serde_json::Map::from_iter([
16447            ("type".to_string(), json!("open_condition_wait")),
16448            (
16449                "condition_wait_occurrence_id".to_string(),
16450                json!(self.occurrence_id.as_deref().unwrap_or_default()),
16451            ),
16452            ("condition_key".to_string(), json!(options.condition_key)),
16453            (
16454                "condition_definition_fingerprint".to_string(),
16455                json!(options.predicate_identity),
16456            ),
16457        ]);
16458        if let Some(timeout_seconds) = options.timeout_seconds {
16459            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
16460        }
16461        apply_parallel_group_path(&mut command, &self.parallel_group_path);
16462        ctx.apply_scope_membership(&mut command);
16463        state.commands.push(Value::Object(command));
16464        drop(state);
16465        self.opened_wait = true;
16466        Poll::Pending
16467    }
16468}
16469
16470fn validate_recorded_condition_wait(
16471    sequence: u64,
16472    recorded_occurrence_id: &str,
16473    recorded_key: Option<&str>,
16474    recorded_predicate_identity: &str,
16475    recorded_timeout_seconds: Option<u64>,
16476    current_occurrence_id: &str,
16477    current: &ValidatedConditionWaitOptions,
16478    physical_reopen: bool,
16479) -> Result<()> {
16480    if recorded_occurrence_id != current_occurrence_id {
16481        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
16482            "condition_wait_occurrence_mismatch",
16483            Some(sequence),
16484            Some(recorded_occurrence_id.to_string()),
16485            Some(current_occurrence_id.to_string()),
16486            "recorded condition occurrence differs from the current authored wait position",
16487        )));
16488    }
16489    if recorded_key != Some(current.condition_key.as_str()) {
16490        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
16491            "condition_wait_key_mismatch",
16492            Some(sequence),
16493            recorded_key.map(str::to_string),
16494            Some(current.condition_key.clone()),
16495            "recorded condition identity differs from the current workflow wait",
16496        )));
16497    }
16498    if recorded_predicate_identity != current.predicate_identity {
16499        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
16500            "condition_wait_predicate_mismatch",
16501            Some(sequence),
16502            Some(recorded_predicate_identity.to_string()),
16503            Some(current.predicate_identity.clone()),
16504            "recorded condition predicate behavior differs from current workflow code",
16505        )));
16506    }
16507    // A physical reopen carries the remaining time of the first open, so it may
16508    // record less than the authored timeout, never more.
16509    let timeout_matches = match (recorded_timeout_seconds, current.timeout_seconds) {
16510        (Some(recorded), Some(authored)) if physical_reopen => recorded <= authored,
16511        (recorded, authored) => recorded == authored,
16512    };
16513    if !timeout_matches {
16514        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
16515            "condition_wait_timeout_mismatch",
16516            Some(sequence),
16517            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
16518            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
16519            "recorded condition timeout differs from the current workflow wait",
16520        )));
16521    }
16522    Ok(())
16523}
16524
16525/// Future returned by [`WorkflowContext::start_child_workflow`].
16526pub struct ChildWorkflowCall {
16527    ctx: WorkflowContext,
16528    workflow_type: String,
16529    options: ChildWorkflowOptions,
16530    args: Option<Result<AvroValue>>,
16531    scheduled: bool,
16532    matched_pending: bool,
16533    parallel_group_path: Vec<ParallelGroupMetadata>,
16534}
16535
16536impl ChildWorkflowCall {
16537    fn poll_avro_value(
16538        mut self: Pin<&mut Self>,
16539        _cx: &mut TaskContext<'_>,
16540    ) -> Poll<Result<ChildWorkflowAvroResult>> {
16541        if self.matched_pending {
16542            return Poll::Pending;
16543        }
16544
16545        let ctx = self.ctx.clone();
16546        let mut state = match ctx.state.lock() {
16547            Ok(state) => state,
16548            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16549        };
16550
16551        let cursor = state.command_cursor;
16552        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
16553            return Poll::Ready(Err(error));
16554        }
16555        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
16556        {
16557            Ok(recorded) => recorded,
16558            Err(error) => return Poll::Ready(Err(error)),
16559        };
16560        if let Some(recorded) = recorded {
16561            let sequence = recorded.sequence();
16562            match recorded {
16563                RecordedCommand::ChildWorkflow {
16564                    workflow_type,
16565                    policies,
16566                    outcome,
16567                    parallel_group_path,
16568                    ..
16569                } => {
16570                    if let Err(error) = ensure_parallel_path_matches(
16571                        sequence,
16572                        parallel_group_path.as_deref(),
16573                        &self.parallel_group_path,
16574                    ) {
16575                        return Poll::Ready(Err(error));
16576                    }
16577                    if let Some(recorded_type) = workflow_type {
16578                        if recorded_type != self.workflow_type {
16579                            return Poll::Ready(Err(Error::NonDeterministicReplay(
16580                                ReplayFailure::new(
16581                                    "recorded_command_detail_mismatch",
16582                                    Some(sequence),
16583                                    Some(format!("child workflow:{recorded_type}")),
16584                                    Some(format!("child workflow:{}", self.workflow_type)),
16585                                    "recorded child workflow type differs from the current workflow command",
16586                                ),
16587                            )));
16588                        }
16589                    }
16590                    if let Err(error) =
16591                        ensure_child_policies_match(sequence, &policies, &self.options)
16592                    {
16593                        return Poll::Ready(Err(error));
16594                    }
16595                    if let Err(error) =
16596                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
16597                    {
16598                        return Poll::Ready(Err(error));
16599                    }
16600                    match state.prepare_scalar_cancellation(
16601                        cursor,
16602                        CancellationCallKind::Child,
16603                        &self.parallel_group_path,
16604                    ) {
16605                        Ok(true) => {
16606                            self.scheduled = true;
16607                            self.matched_pending = true;
16608                            return Poll::Pending;
16609                        }
16610                        Ok(false) => {}
16611                        Err(error) => return Poll::Ready(Err(error)),
16612                    }
16613                    state.command_cursor += 1;
16614                    if let Some(outcome) = outcome {
16615                        state.consume_replay_sequence(sequence, &self.parallel_group_path);
16616                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
16617                    }
16618                    state.matched_recorded_pending = true;
16619                    state.observation_pending = true;
16620                    self.scheduled = true;
16621                    self.matched_pending = true;
16622                    return Poll::Pending;
16623                }
16624                other => {
16625                    return Poll::Ready(Err(command_mismatch(
16626                        &other,
16627                        format!("child workflow:{}", self.workflow_type),
16628                    )));
16629                }
16630            }
16631        }
16632
16633        if !self.scheduled {
16634            if self.options.task_queue.trim().is_empty() {
16635                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
16636                    "task_queue must not be empty".to_string(),
16637                )));
16638            }
16639            for (name, value) in [
16640                (
16641                    "execution_timeout_seconds",
16642                    self.options.execution_timeout_seconds,
16643                ),
16644                ("run_timeout_seconds", self.options.run_timeout_seconds),
16645            ] {
16646                if value == Some(0) {
16647                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
16648                        "{name} must be at least 1"
16649                    ))));
16650                }
16651            }
16652
16653            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
16654                Ok(args) => args,
16655                Err(error) => return Poll::Ready(Err(error)),
16656            };
16657            let arguments = match encode_typed_envelope(
16658                &normalize_avro_arguments(args),
16659                &state.payload_codec,
16660            ) {
16661                Ok(arguments) => arguments,
16662                Err(error) => return Poll::Ready(Err(error)),
16663            };
16664            let mut command = json!({
16665                "type": "start_child_workflow",
16666                "workflow_type": self.workflow_type,
16667                "queue": self.options.task_queue,
16668                "parent_close_policy": self.options.parent_close_policy.as_str(),
16669                "arguments": arguments,
16670            });
16671            let object = command
16672                .as_object_mut()
16673                .expect("child workflow command is always an object");
16674            if self.options.cancellation_policy != CancellationPolicy::Abandon {
16675                object.insert(
16676                    "cancellation_policy".to_string(),
16677                    json!(self.options.cancellation_policy.as_str()),
16678                );
16679            }
16680            if let Some(policy) = &self.options.retry_policy {
16681                let mut retry_policy = serde_json::Map::new();
16682                if let Some(max_attempts) = policy.max_attempts {
16683                    if max_attempts == 0 {
16684                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
16685                            "retry_policy.max_attempts must be at least 1".to_string(),
16686                        )));
16687                    }
16688                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
16689                }
16690                if !policy.backoff_seconds.is_empty() {
16691                    retry_policy
16692                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
16693                }
16694                if !policy.non_retryable_error_types.is_empty() {
16695                    retry_policy.insert(
16696                        "non_retryable_error_types".to_string(),
16697                        json!(policy.non_retryable_error_types),
16698                    );
16699                }
16700                if retry_policy.is_empty() {
16701                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
16702                        "retry_policy must configure at least one field".to_string(),
16703                    )));
16704                }
16705                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
16706            }
16707            if let Some(seconds) = self.options.execution_timeout_seconds {
16708                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
16709            }
16710            if let Some(seconds) = self.options.run_timeout_seconds {
16711                object.insert("run_timeout_seconds".to_string(), json!(seconds));
16712            }
16713            apply_parallel_group_path(object, &self.parallel_group_path);
16714            ctx.apply_scope_membership(object);
16715            match state.prepare_scalar_cancellation(
16716                cursor,
16717                CancellationCallKind::Child,
16718                &self.parallel_group_path,
16719            ) {
16720                Ok(true) => {
16721                    self.scheduled = true;
16722                    self.matched_pending = true;
16723                    return Poll::Pending;
16724                }
16725                Ok(false) => {}
16726                Err(error) => return Poll::Ready(Err(error)),
16727            }
16728            state.commands.push(command);
16729            self.scheduled = true;
16730        }
16731
16732        Poll::Pending
16733    }
16734}
16735
16736impl Future for ChildWorkflowCall {
16737    type Output = Result<ChildWorkflowResult>;
16738
16739    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
16740        match self.poll_avro_value(cx) {
16741            Poll::Ready(Ok(result)) => match result.result.into_json() {
16742                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
16743                    parent: result.parent,
16744                    child: result.child,
16745                    child_workflow_type: result.child_workflow_type,
16746                    result: projected,
16747                })),
16748                Err(error) => Poll::Ready(Err(error)),
16749            },
16750            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
16751            Poll::Pending => Poll::Pending,
16752        }
16753    }
16754}
16755
16756fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
16757    Error::NonDeterministicReplay(ReplayFailure::new(
16758        "recorded_command_mismatch",
16759        Some(recorded.sequence()),
16760        Some(recorded.shape().to_string()),
16761        Some(actual.into()),
16762        "current workflow command does not match the recorded durable command sequence",
16763    ))
16764}
16765
16766pub struct SignalCall {
16767    ctx: WorkflowContext,
16768    signal_name: String,
16769    runtime_reserved_allowed: bool,
16770    opened_wait: bool,
16771    matched_pending: bool,
16772    parallel_group_path: Vec<ParallelGroupMetadata>,
16773}
16774
16775impl SignalCall {
16776    fn poll_avro_value(
16777        mut self: Pin<&mut Self>,
16778        _cx: &mut TaskContext<'_>,
16779    ) -> Poll<Result<Vec<AvroValue>>> {
16780        if self.matched_pending {
16781            return Poll::Pending;
16782        }
16783        if !self.runtime_reserved_allowed {
16784            if let Err(error) = validate_user_signal_name(&self.signal_name) {
16785                return Poll::Ready(Err(error));
16786            }
16787        }
16788
16789        let ctx = self.ctx.clone();
16790        let mut state = match ctx.state.lock() {
16791            Ok(state) => state,
16792            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16793        };
16794
16795        let cursor = state.command_cursor;
16796        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
16797            return Poll::Ready(Err(error));
16798        }
16799        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
16800        {
16801            Ok(recorded) => recorded,
16802            Err(error) => return Poll::Ready(Err(error)),
16803        };
16804        if let Some(recorded) = recorded {
16805            match recorded {
16806                RecordedCommand::SignalWait {
16807                    sequence,
16808                    signal_name,
16809                    value,
16810                    parallel_group_path,
16811                } => {
16812                    if let Err(error) = ensure_parallel_path_matches(
16813                        sequence,
16814                        parallel_group_path.as_deref(),
16815                        &self.parallel_group_path,
16816                    ) {
16817                        return Poll::Ready(Err(error));
16818                    }
16819                    if signal_name != self.signal_name {
16820                        return Poll::Ready(Err(Error::NonDeterministicReplay(
16821                            ReplayFailure::new(
16822                                "recorded_command_detail_mismatch",
16823                                Some(sequence),
16824                                Some(format!("signal wait:{signal_name}")),
16825                                Some(format!("signal wait:{}", self.signal_name)),
16826                                "recorded signal name differs from the current workflow command",
16827                            ),
16828                        )));
16829                    }
16830
16831                    if let Err(error) =
16832                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
16833                    {
16834                        return Poll::Ready(Err(error));
16835                    }
16836                    match state.prepare_scalar_cancellation(
16837                        cursor,
16838                        CancellationCallKind::Signal,
16839                        &self.parallel_group_path,
16840                    ) {
16841                        Ok(true) => {
16842                            self.opened_wait = true;
16843                            self.matched_pending = true;
16844                            return Poll::Pending;
16845                        }
16846                        Ok(false) => {}
16847                        Err(error) => return Poll::Ready(Err(error)),
16848                    }
16849                    state.command_cursor += 1;
16850                    if let Some(value) = value {
16851                        state.consume_replay_sequence(sequence, &self.parallel_group_path);
16852                        return Poll::Ready(Ok(value));
16853                    }
16854                    if state
16855                        .resume_signal
16856                        .as_ref()
16857                        .is_some_and(|signal| signal.signal_name == self.signal_name)
16858                    {
16859                        let signal = state
16860                            .resume_signal
16861                            .take()
16862                            .expect("matching resume signal is present");
16863                        state.consume_unproven_boundary(&self.parallel_group_path);
16864                        return Poll::Ready(Ok(signal.arguments));
16865                    }
16866
16867                    state.matched_recorded_pending = true;
16868                    state.observation_pending = true;
16869                    self.opened_wait = true;
16870                    self.matched_pending = true;
16871                    return Poll::Pending;
16872                }
16873                other => {
16874                    return Poll::Ready(Err(command_mismatch(
16875                        &other,
16876                        format!("signal wait:{}", self.signal_name),
16877                    )));
16878                }
16879            }
16880        }
16881
16882        match state.prepare_scalar_cancellation(
16883            cursor,
16884            CancellationCallKind::Signal,
16885            &self.parallel_group_path,
16886        ) {
16887            Ok(true) => {
16888                self.opened_wait = true;
16889                self.matched_pending = true;
16890                return Poll::Pending;
16891            }
16892            Ok(false) => {}
16893            Err(error) => return Poll::Ready(Err(error)),
16894        }
16895
16896        if state
16897            .resume_signal
16898            .as_ref()
16899            .is_some_and(|signal| signal.signal_name == self.signal_name)
16900        {
16901            let signal = state
16902                .resume_signal
16903                .take()
16904                .expect("matching resume signal is present");
16905            state.consume_unproven_boundary(&self.parallel_group_path);
16906            return Poll::Ready(Ok(signal.arguments));
16907        }
16908
16909        if !self.opened_wait {
16910            let mut command = serde_json::Map::from_iter([
16911                ("type".to_string(), json!("open_signal_wait")),
16912                ("signal_name".to_string(), json!(self.signal_name)),
16913            ]);
16914            apply_parallel_group_path(&mut command, &self.parallel_group_path);
16915            ctx.apply_scope_membership(&mut command);
16916            state.commands.push(Value::Object(command));
16917            self.opened_wait = true;
16918        }
16919
16920        Poll::Pending
16921    }
16922}
16923
16924impl Future for SignalCall {
16925    type Output = Result<Vec<Value>>;
16926
16927    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
16928        match self.poll_avro_value(cx) {
16929            Poll::Ready(Ok(values)) => Poll::Ready(
16930                values
16931                    .into_iter()
16932                    .map(AvroValue::into_json)
16933                    .collect::<Result<Vec<_>>>(),
16934            ),
16935            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
16936            Poll::Pending => Poll::Pending,
16937        }
16938    }
16939}
16940
16941#[derive(Clone, Debug)]
16942pub struct ActivityContext {
16943    client: Client,
16944    pub task_id: String,
16945    pub activity_attempt_id: String,
16946    pub lease_owner: String,
16947    pub activity_type: String,
16948    pub attempt_number: u64,
16949    retry_info: ActivityRetryInfo,
16950    activity_execution_id: Option<String>,
16951    workflow_id: Option<String>,
16952    run_id: Option<String>,
16953    pub task_queue: String,
16954    pub worker_id: String,
16955    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
16956    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
16957    worker_session: Option<WorkerSession>,
16958}
16959
16960impl ActivityContext {
16961    /// Logical Server activity execution ID, stable across that activity's retries.
16962    ///
16963    /// This is the received claim identity, including for worker-session activities.
16964    /// It is unavailable when an older Server omits it, for inline local activities
16965    /// before the Server records their command, and in Server-free tests. It is
16966    /// never derived from a per-attempt task or attempt ID. Use an application
16967    /// business key when this value is unavailable.
16968    pub fn activity_execution_id(&self) -> Option<&str> {
16969        self.activity_execution_id.as_deref()
16970    }
16971
16972    /// Owning workflow instance ID from the claim (or parent local workflow task).
16973    /// Older claims and Server-free activity tests can report `None`.
16974    pub fn workflow_id(&self) -> Option<&str> {
16975        self.workflow_id.as_deref()
16976    }
16977
16978    /// Owning workflow run ID from the claim (or parent local workflow task).
16979    /// Older claims and Server-free activity tests can report `None`.
16980    pub fn run_id(&self) -> Option<&str> {
16981        self.run_id.as_deref()
16982    }
16983
16984    /// Immutable original attempt identity and received retry policy.
16985    pub fn retry_info(&self) -> &ActivityRetryInfo {
16986        &self.retry_info
16987    }
16988
16989    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
16990        if let Some(heartbeats) = &self.local_heartbeats {
16991            return heartbeats
16992                .lock()
16993                .map_err(|_| Error::WorkflowStatePoisoned)?
16994                .record(details);
16995        }
16996        if let Some(guard) = &self.claim_guard {
16997            return guard.heartbeat(self, details).await;
16998        }
16999        if let Some(session) = &self.worker_session {
17000            if !session.active() {
17001                return Err(Error::ActivityExecutionAbandoned(
17002                    "worker-session lease or TTL is no longer active".into(),
17003                ));
17004            }
17005            let result = self
17006                .client
17007                .heartbeat_activity_task_value(
17008                    &self.task_id,
17009                    &self.activity_attempt_id,
17010                    &self.lease_owner,
17011                    details,
17012                )
17013                .await;
17014            return worker_session::settle_activity_heartbeat(
17015                session,
17016                result,
17017                &self.task_id,
17018                &self.activity_attempt_id,
17019                &self.lease_owner,
17020            );
17021        }
17022        self.client
17023            .heartbeat_activity_task(
17024                &self.task_id,
17025                &self.activity_attempt_id,
17026                &self.lease_owner,
17027                details,
17028            )
17029            .await
17030    }
17031}
17032
17033fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
17034    validate_payload_codec(codec)?;
17035    match value {
17036        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
17037            value, codec,
17038        )?)),
17039        None => Ok(AvroValue::Array(Vec::new())),
17040    }
17041}
17042
17043fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
17044    let Some(signal_name) = task
17045        .signal_name
17046        .as_deref()
17047        .filter(|value| !value.is_empty())
17048    else {
17049        return Ok(None);
17050    };
17051    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
17052    let AvroValue::Array(arguments) = decoded else {
17053        unreachable!("normalize_avro_arguments always returns an array");
17054    };
17055
17056    Ok(Some(ResumeSignal {
17057        signal_name: signal_name.to_string(),
17058        arguments,
17059    }))
17060}
17061
17062fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
17063    validate_payload_codec(&task.payload_codec)?;
17064    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
17065    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
17066    for event in &task.history_events {
17067        validate_history_event_payloads(event, &task.payload_codec)?;
17068    }
17069    Ok(())
17070}
17071
17072fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
17073    validate_payload_codec(&task.payload_codec)?;
17074    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
17075}
17076
17077fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
17078    validate_payload_codec(&task.payload_codec)?;
17079    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
17080    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
17081    for event in &task.history_events {
17082        validate_history_event_payloads(event, &task.payload_codec)?;
17083    }
17084
17085    let Some(export) = task.history_export.as_ref() else {
17086        return Ok(());
17087    };
17088    let export_codec = match export.get("payloads") {
17089        Some(payloads) => declared_payload_codec(payloads, "codec")?,
17090        None => None,
17091    }
17092    .unwrap_or(&task.payload_codec);
17093    validate_payload_codec(export_codec)?;
17094
17095    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
17096        for event in events {
17097            let event_type = event
17098                .get("event_type")
17099                .or_else(|| event.get("type"))
17100                .and_then(Value::as_str)
17101                .unwrap_or_default();
17102            if let Some(payload) = event.get("payload") {
17103                validate_history_payloads(event_type, payload, export_codec)?;
17104            }
17105        }
17106    }
17107    for signal in export
17108        .get("signals")
17109        .and_then(Value::as_array)
17110        .into_iter()
17111        .flatten()
17112    {
17113        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
17114        validate_payload_codec(codec)?;
17115        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
17116    }
17117    for activity in export
17118        .get("activities")
17119        .and_then(Value::as_array)
17120        .into_iter()
17121        .flatten()
17122    {
17123        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
17124        validate_payload_codec(codec)?;
17125        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
17126        validate_optional_inbound_payload(activity.get("result"), codec)?;
17127    }
17128    Ok(())
17129}
17130
17131fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
17132    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
17133}
17134
17135fn validate_history_payloads(
17136    event_type: &str,
17137    payload: &Value,
17138    fallback_codec: &str,
17139) -> Result<()> {
17140    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
17141    validate_payload_codec(codec)?;
17142    for field in history_payload_fields(event_type) {
17143        validate_optional_inbound_payload(payload.get(*field), codec)?;
17144    }
17145    Ok(())
17146}
17147
17148const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
17149
17150fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
17151    match event_type {
17152        "ActivityCompleted" => &["result"],
17153        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
17154        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => &["arguments"],
17155        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
17156        "ChildRunCompleted" => &["result", "output"],
17157        "WorkflowCompleted" => &["output"],
17158        "ServiceCallStarted"
17159        | "ServiceCallCompleted"
17160        | "ServiceCallFailed"
17161        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
17162        _ => &[],
17163    }
17164}
17165
17166fn signal_history_payload(payload: &Value) -> Option<&Value> {
17167    SIGNAL_HISTORY_PAYLOAD_FIELDS
17168        .iter()
17169        .find_map(|field| payload.get(*field))
17170}
17171
17172fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
17173    match value.get(field) {
17174        None => Ok(None),
17175        Some(Value::String(codec)) => Ok(Some(codec)),
17176        Some(_) => Err(invalid_payload_envelope()),
17177    }
17178}
17179
17180fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
17181    validate_payload_codec(codec)?;
17182    if let Some(value) = value.filter(|value| !value.is_null()) {
17183        decode_wire_avro_value(value, codec)?;
17184    }
17185    Ok(())
17186}
17187
17188fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
17189    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
17190        invalid_recorded_history(
17191            "parallel_group_metadata_invalid",
17192            sequence,
17193            "non-empty parallel_group_id",
17194            &payload.to_string(),
17195            "parallel-group history is missing its stable identity",
17196        )
17197    })?;
17198    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
17199        invalid_recorded_history(
17200            "parallel_group_metadata_invalid",
17201            sequence,
17202            "activity, child, timer, signal, condition, or mixed group kind",
17203            &payload.to_string(),
17204            "parallel-group history is missing its group kind",
17205        )
17206    })?;
17207    if !matches!(
17208        kind.as_str(),
17209        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
17210    ) {
17211        return Err(invalid_recorded_history(
17212            "parallel_group_metadata_invalid",
17213            sequence,
17214            "activity, child, timer, signal, condition, or mixed group kind",
17215            &kind,
17216            "parallel-group history contains an unsupported group kind",
17217        ));
17218    }
17219    let base_sequence = payload
17220        .get("parallel_group_base_sequence")
17221        .and_then(value_as_u64)
17222        .filter(|value| *value > 0)
17223        .ok_or_else(|| {
17224            invalid_recorded_history(
17225                "parallel_group_metadata_invalid",
17226                sequence,
17227                "positive parallel_group_base_sequence",
17228                &payload.to_string(),
17229                "parallel-group history contains an invalid base sequence",
17230            )
17231        })?;
17232    let size = payload
17233        .get("parallel_group_size")
17234        .and_then(value_as_u64)
17235        .and_then(|value| usize::try_from(value).ok())
17236        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
17237        .ok_or_else(|| {
17238            invalid_recorded_history(
17239                "parallel_group_metadata_invalid",
17240                sequence,
17241                "bounded positive parallel_group_size",
17242                &payload.to_string(),
17243                "parallel-group history contains an invalid group size",
17244            )
17245        })?;
17246    let index = payload
17247        .get("parallel_group_index")
17248        .and_then(value_as_u64)
17249        .and_then(|value| usize::try_from(value).ok())
17250        .filter(|value| *value < size)
17251        .ok_or_else(|| {
17252            invalid_recorded_history(
17253                "parallel_group_metadata_invalid",
17254                sequence,
17255                "parallel_group_index within group bounds",
17256                &payload.to_string(),
17257                "parallel-group history contains an invalid member index",
17258            )
17259        })?;
17260    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
17261        return Err(invalid_recorded_history(
17262            "parallel_group_metadata_invalid",
17263            sequence,
17264            "base sequence plus member index equals workflow sequence",
17265            &payload.to_string(),
17266            "parallel-group path does not preserve durable workflow position",
17267        ));
17268    }
17269    let mode = payload
17270        .get("parallel_group_mode")
17271        .and_then(Value::as_str)
17272        .unwrap_or("all");
17273    if !matches!(mode, "all" | "select") {
17274        return Err(invalid_recorded_history(
17275            "parallel_group_metadata_invalid",
17276            sequence,
17277            "parallel group mode all or select",
17278            mode,
17279            "parallel-group history contains an unsupported group mode",
17280        ));
17281    }
17282    let expected_id = if mode == "select" {
17283        format!("select-calls:{base_sequence}:{size}")
17284    } else {
17285        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
17286    };
17287    if group_id != expected_id {
17288        return Err(invalid_recorded_history(
17289            "parallel_group_metadata_invalid",
17290            sequence,
17291            &expected_id,
17292            &group_id,
17293            "parallel-group history contains an incompatible stable group ID",
17294        ));
17295    }
17296    let selection_member_key = if mode == "select" {
17297        Some(selection_key_from_value(
17298            payload.get("selection_member_key"),
17299            sequence,
17300        )?)
17301    } else {
17302        None
17303    };
17304    let selection_member_index = if mode == "select" {
17305        Some(required_parallel_usize(
17306            payload,
17307            "selection_member_index",
17308            sequence,
17309        )?)
17310    } else {
17311        None
17312    };
17313    let selection_member_base_sequence = if mode == "select" {
17314        Some(
17315            payload
17316                .get("selection_member_base_sequence")
17317                .and_then(value_as_u64)
17318                .filter(|value| *value >= base_sequence)
17319                .ok_or_else(|| {
17320                    invalid_recorded_history(
17321                        "parallel_group_metadata_invalid",
17322                        sequence,
17323                        "selection member base within its group",
17324                        &payload.to_string(),
17325                        "selection history contains an invalid member base sequence",
17326                    )
17327                })?,
17328        )
17329    } else {
17330        None
17331    };
17332    let selection_member_size = if mode == "select" {
17333        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
17334        if member_size == 0 {
17335            return Err(invalid_recorded_history(
17336                "parallel_group_metadata_invalid",
17337                sequence,
17338                "positive selection member size",
17339                &payload.to_string(),
17340                "selection history contains an invalid member size",
17341            ));
17342        }
17343        Some(member_size)
17344    } else {
17345        None
17346    };
17347    let selection_member_kind = if mode == "select" {
17348        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
17349            invalid_recorded_history(
17350                "parallel_group_metadata_invalid",
17351                sequence,
17352                "selection member operation kind",
17353                &payload.to_string(),
17354                "selection history is missing its authored member kind",
17355            )
17356        })?;
17357        if !matches!(
17358            kind.as_str(),
17359            "activity" | "child" | "timer" | "signal" | "condition" | "group"
17360        ) {
17361            return Err(invalid_recorded_history(
17362                "parallel_group_metadata_invalid",
17363                sequence,
17364                "activity, child, timer, signal, condition, or group selection member kind",
17365                &kind,
17366                "selection history contains an unsupported member kind",
17367            ));
17368        }
17369        Some(kind)
17370    } else {
17371        None
17372    };
17373    if let (Some(member_base), Some(member_size)) =
17374        (selection_member_base_sequence, selection_member_size)
17375    {
17376        let member_end = member_base
17377            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
17378            .ok_or_else(|| {
17379                invalid_recorded_history(
17380                    "parallel_group_metadata_invalid",
17381                    sequence,
17382                    "bounded selection member range",
17383                    &payload.to_string(),
17384                    "selection member range overflowed",
17385                )
17386            })?;
17387        let group_end = base_sequence
17388            .checked_add(u64::try_from(size).unwrap_or(u64::MAX))
17389            .unwrap_or(u64::MAX);
17390        if sequence < member_base || sequence >= member_end || member_end > group_end {
17391            return Err(invalid_recorded_history(
17392                "parallel_group_metadata_invalid",
17393                sequence,
17394                "workflow sequence within one bounded selection member",
17395                &payload.to_string(),
17396                "selection member range does not contain its durable leaf",
17397            ));
17398        }
17399    }
17400    Ok(ParallelGroupMetadata {
17401        parallel_group_id: group_id,
17402        parallel_group_kind: kind,
17403        parallel_group_base_sequence: base_sequence,
17404        parallel_group_size: size,
17405        parallel_group_index: index,
17406        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
17407        selection_member_key,
17408        selection_member_index,
17409        selection_member_base_sequence,
17410        selection_member_size,
17411        selection_member_kind,
17412    })
17413}
17414
17415fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
17416    payload
17417        .get(field)
17418        .and_then(value_as_u64)
17419        .and_then(|value| usize::try_from(value).ok())
17420        .ok_or_else(|| {
17421            invalid_recorded_history(
17422                "parallel_group_metadata_invalid",
17423                sequence,
17424                &format!("non-negative integer {field}"),
17425                &payload.to_string(),
17426                "selection history contains invalid member metadata",
17427            )
17428        })
17429}
17430
17431fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
17432    match value {
17433        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
17434        Some(value) => value_as_u64(value)
17435            .and_then(|value| usize::try_from(value).ok())
17436            .map(SelectionKey::Index)
17437            .ok_or_else(|| {
17438                invalid_recorded_history(
17439                    "selection_member_key_invalid",
17440                    sequence,
17441                    "non-empty string or non-negative integer member key",
17442                    &value.to_string(),
17443                    "selection history contains an invalid member key",
17444                )
17445            }),
17446        None => Err(invalid_recorded_history(
17447            "selection_member_key_missing",
17448            sequence,
17449            "selection_member_key",
17450            "<missing>",
17451            "selection history is missing its stable member key",
17452        )),
17453    }
17454}
17455
17456fn recorded_parallel_group_path(
17457    events: &[&HistoryEvent],
17458    sequence: u64,
17459) -> Result<Option<Vec<ParallelGroupMetadata>>> {
17460    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
17461    for event in events {
17462        let payload = &event.payload;
17463        let has_metadata = payload.get("parallel_group_path").is_some()
17464            || payload.get("parallel_group_id").is_some()
17465            || payload.get("parallel_group_kind").is_some()
17466            || payload.get("parallel_group_base_sequence").is_some()
17467            || payload.get("parallel_group_size").is_some()
17468            || payload.get("parallel_group_index").is_some()
17469            || payload.get("parallel_group_mode").is_some()
17470            || payload.get("selection_member_key").is_some();
17471        if !has_metadata {
17472            continue;
17473        }
17474
17475        let top_level = recorded_parallel_group_entry(payload, sequence)?;
17476        let path = match payload.get("parallel_group_path") {
17477            None => vec![top_level.clone()],
17478            Some(Value::Array(entries)) if !entries.is_empty() => entries
17479                .iter()
17480                .map(|entry| recorded_parallel_group_entry(entry, sequence))
17481                .collect::<Result<Vec<_>>>()?,
17482            Some(value) => {
17483                return Err(invalid_recorded_history(
17484                    "parallel_group_metadata_invalid",
17485                    sequence,
17486                    "non-empty parallel_group_path list",
17487                    &value.to_string(),
17488                    "parallel-group history contains an invalid group path",
17489                ));
17490            }
17491        };
17492        if path.last() != Some(&top_level) {
17493            return Err(invalid_recorded_history(
17494                "parallel_group_metadata_invalid",
17495                sequence,
17496                &serde_json::to_string(&path.last()).unwrap_or_default(),
17497                &serde_json::to_string(&top_level).unwrap_or_default(),
17498                "parallel-group top-level fields do not match the innermost path entry",
17499            ));
17500        }
17501        if recorded.as_ref().is_some_and(|existing| existing != &path) {
17502            return Err(invalid_recorded_history(
17503                "parallel_group_history_conflict",
17504                sequence,
17505                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
17506                &serde_json::to_string(&path).unwrap_or_default(),
17507                "parallel-group metadata changed between scheduling and resolution history",
17508            ));
17509        }
17510        recorded = Some(path);
17511    }
17512    Ok(recorded)
17513}
17514
17515fn recorded_commands(
17516    events: &[HistoryEvent],
17517    fallback_codec: &str,
17518    parent: WorkflowIdentity,
17519) -> Result<Vec<RecordedCommand>> {
17520    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
17521    let mut last_new_sequence = None;
17522
17523    for event in events {
17524        let is_activity = matches!(
17525            event.event_type.as_str(),
17526            "ActivityScheduled"
17527                | "ActivityStarted"
17528                | "ActivityHeartbeatRecorded"
17529                | "ActivityRetryScheduled"
17530                | "ActivityCompleted"
17531                | "ActivityFailed"
17532                | "ActivityCancelled"
17533                | "ActivityTimedOut"
17534        );
17535        let is_workflow_timer = matches!(
17536            event.event_type.as_str(),
17537            "TimerScheduled" | "TimerCancelled" | "TimerFired"
17538        ) && !is_internal_timer_event(event);
17539        let is_child_workflow = matches!(
17540            event.event_type.as_str(),
17541            "ChildWorkflowScheduled"
17542                | "ChildRunStarted"
17543                | "ChildRunCompleted"
17544                | "ChildRunFailed"
17545                | "ChildRunCancelled"
17546                | "ChildRunTerminated"
17547        );
17548        let is_signal_wait = is_recorded_signal_wait_event(event);
17549        let is_condition_wait = is_recorded_condition_wait_event(event);
17550        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
17551        let is_side_effect = event.event_type == "SideEffectRecorded";
17552        let is_version_marker = event.event_type == "VersionMarkerRecorded";
17553        let is_memo = event.event_type == "MemoUpserted";
17554        let is_service_operation = nexus::is_service_event(event);
17555        if !is_activity
17556            && !is_workflow_timer
17557            && !is_child_workflow
17558            && !is_signal_wait
17559            && !is_condition_wait
17560            && !is_search_attributes
17561            && !is_side_effect
17562            && !is_version_marker
17563            && !is_memo
17564            && !is_service_operation
17565        {
17566            continue;
17567        }
17568
17569        let sequence = durable_event_sequence(event).ok_or_else(|| {
17570            Error::NonDeterministicReplay(ReplayFailure::new(
17571                "durable_command_sequence_missing",
17572                None,
17573                Some("positive workflow sequence".to_string()),
17574                Some(event.event_type.clone()),
17575                "durable command history event has no workflow sequence",
17576            ))
17577        })?;
17578        if sequence == 0 {
17579            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
17580                "durable_command_sequence_invalid",
17581                Some(sequence),
17582                Some("positive workflow sequence".to_string()),
17583                Some(sequence.to_string()),
17584                "durable command history uses an invalid workflow sequence",
17585            )));
17586        }
17587        if !events_by_sequence.contains_key(&sequence) {
17588            if let Some(previous) = last_new_sequence {
17589                if sequence < previous {
17590                    return Err(invalid_recorded_history(
17591                        "durable_command_sequence_mismatch",
17592                        sequence,
17593                        &format!("workflow sequence greater than {previous}"),
17594                        &sequence.to_string(),
17595                        "durable commands are not strictly ordered by their recorded workflow sequence",
17596                    ));
17597                }
17598            }
17599            last_new_sequence = Some(sequence);
17600        }
17601        events_by_sequence.entry(sequence).or_default().push(event);
17602    }
17603
17604    let commands: Vec<RecordedCommand> = events_by_sequence
17605        .into_iter()
17606        .map(|(sequence, sequence_events)| {
17607            let activity_events: Vec<_> = sequence_events
17608                .iter()
17609                .copied()
17610                .filter(|event| event.event_type.starts_with("Activity"))
17611                .collect();
17612            let timer_events: Vec<_> = sequence_events
17613                .iter()
17614                .copied()
17615                .filter(|event| event.event_type.starts_with("Timer"))
17616                .collect();
17617            let child_events: Vec<_> = sequence_events
17618                .iter()
17619                .copied()
17620                .filter(|event| {
17621                    event.event_type == "ChildWorkflowScheduled"
17622                        || event.event_type.starts_with("ChildRun")
17623                })
17624                .collect();
17625            let signal_wait_events: Vec<_> = sequence_events
17626                .iter()
17627                .copied()
17628                .filter(|event| is_recorded_signal_wait_event(event))
17629                .collect();
17630            let condition_wait_events: Vec<_> = sequence_events
17631                .iter()
17632                .copied()
17633                .filter(|event| is_recorded_condition_wait_event(event))
17634                .collect();
17635            let search_attribute_events: Vec<_> = sequence_events
17636                .iter()
17637                .copied()
17638                .filter(|event| event.event_type == "SearchAttributesUpserted")
17639                .collect();
17640            let side_effect_events: Vec<_> = sequence_events
17641                .iter()
17642                .copied()
17643                .filter(|event| event.event_type == "SideEffectRecorded")
17644                .collect();
17645            let version_marker_events: Vec<_> = sequence_events
17646                .iter()
17647                .copied()
17648                .filter(|event| event.event_type == "VersionMarkerRecorded")
17649                .collect();
17650            let memo_events: Vec<_> = sequence_events
17651                .iter()
17652                .copied()
17653                .filter(|event| event.event_type == "MemoUpserted")
17654                .collect();
17655            let service_events: Vec<_> = sequence_events.iter().copied()
17656                .filter(|event| nexus::is_service_event(event)).collect();
17657
17658            let command_kind_count = usize::from(!activity_events.is_empty())
17659                + usize::from(!timer_events.is_empty())
17660                + usize::from(!child_events.is_empty())
17661                + usize::from(!signal_wait_events.is_empty())
17662                + usize::from(!condition_wait_events.is_empty())
17663                + usize::from(!search_attribute_events.is_empty())
17664                + usize::from(!side_effect_events.is_empty())
17665                + usize::from(!version_marker_events.is_empty())
17666                + usize::from(!memo_events.is_empty())
17667                + usize::from(!service_events.is_empty());
17668            if command_kind_count > 1 {
17669                let actual = [
17670                    (!activity_events.is_empty()).then_some("activity"),
17671                    (!timer_events.is_empty()).then_some("timer"),
17672                    (!child_events.is_empty()).then_some("child workflow"),
17673                    (!signal_wait_events.is_empty()).then_some("signal wait"),
17674                    (!condition_wait_events.is_empty()).then_some("condition wait"),
17675                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
17676                    (!side_effect_events.is_empty()).then_some("side effect"),
17677                    (!version_marker_events.is_empty()).then_some("version marker"),
17678                    (!memo_events.is_empty()).then_some("memo upsert"),
17679                    (!service_events.is_empty()).then_some("service operation"),
17680                ]
17681                .into_iter()
17682                .flatten()
17683                .collect::<Vec<_>>()
17684                .join(" and ");
17685                return Err(invalid_recorded_history(
17686                    "durable_command_sequence_collision",
17687                    sequence,
17688                    "one durable command kind",
17689                    &actual,
17690                    "one workflow sequence records more than one durable command kind",
17691                ));
17692            }
17693
17694            if !service_events.is_empty() {
17695                return Ok(RecordedCommand::ServiceOperation {
17696                    sequence, call: nexus::recorded_call(&service_events, sequence, fallback_codec, &parent)?,
17697                });
17698            }
17699
17700            if !activity_events.is_empty() {
17701                let parallel_group_path =
17702                    recorded_parallel_group_path(&activity_events, sequence)?;
17703                let scheduled_count = activity_events
17704                    .iter()
17705                    .filter(|event| event.event_type == "ActivityScheduled")
17706                    .count();
17707                if scheduled_count > 1 {
17708                    return Err(invalid_recorded_history(
17709                        "duplicate_activity_schedule",
17710                        sequence,
17711                        "at most one ActivityScheduled event",
17712                        "multiple ActivityScheduled events",
17713                        "activity history schedules more than one command at one workflow sequence",
17714                    ));
17715                }
17716                let activity_type = activity_events.iter().find_map(|event| {
17717                    event
17718                        .payload
17719                        .get("activity_type")
17720                        .or_else(|| event.payload.get("activity_name"))
17721                        .and_then(Value::as_str)
17722                        .map(str::to_string)
17723                });
17724                if activity_events.iter().filter_map(|event| {
17725                    event
17726                        .payload
17727                        .get("activity_type")
17728                        .or_else(|| event.payload.get("activity_name"))
17729                        .and_then(Value::as_str)
17730                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
17731                    return Err(invalid_recorded_history(
17732                        "activity_identity_mismatch",
17733                        sequence,
17734                        activity_type.as_deref().unwrap_or("one activity identity"),
17735                        "conflicting activity identities",
17736                        "activity lifecycle events at one workflow sequence disagree on identity",
17737                    ));
17738                }
17739                let terminal: Vec<_> = activity_events
17740                    .iter()
17741                    .copied()
17742                    .filter(|event| {
17743                        matches!(
17744                            event.event_type.as_str(),
17745                            "ActivityCompleted"
17746                                | "ActivityFailed"
17747                                | "ActivityCancelled"
17748                                | "ActivityTimedOut"
17749                        )
17750                    })
17751                    .collect();
17752                let duplicate_delivery = terminal.first().is_some_and(|first| {
17753                    terminal.iter().all(|event| {
17754                        event.event_type == first.event_type && event.payload == first.payload
17755                    })
17756                });
17757                if terminal.len() > 1 && !duplicate_delivery {
17758                    return Err(invalid_recorded_history(
17759                        "duplicate_activity_terminal_event",
17760                        sequence,
17761                        "at most one terminal activity event",
17762                        "multiple terminal activity events",
17763                        "activity history settles one command more than once",
17764                    ));
17765                }
17766                let outcome = terminal
17767                    .first()
17768                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
17769                    .transpose()?;
17770                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
17771                let activity_snapshot = activity_events
17772                    .iter()
17773                    .find(|event| event.event_type == "ActivityScheduled")
17774                    .and_then(|event| event.payload.get("activity"))
17775                    .and_then(Value::as_object);
17776                let options = Some(match activity_snapshot {
17777                    Some(activity) => RecordedActivityOptions {
17778                        task_queue: recorded_optional_string(activity, "queue"),
17779                        execution_mode,
17780                        retry_policy: recorded_activity_retry_snapshot(
17781                            activity.get("retry_policy"),
17782                        ),
17783                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
17784                    },
17785                    None => RecordedActivityOptions {
17786                        task_queue: RecordedSnapshotValue::Unknown,
17787                        execution_mode,
17788                        retry_policy: recorded_activity_retry_snapshot(None),
17789                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
17790                    },
17791                });
17792                return Ok(RecordedCommand::Activity {
17793                    sequence,
17794                    activity_type,
17795                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
17796                    options,
17797                    outcome,
17798                    parallel_group_path,
17799                });
17800            }
17801
17802            if !child_events.is_empty() {
17803                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
17804                let scheduled: Vec<_> = child_events
17805                    .iter()
17806                    .copied()
17807                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
17808                    .collect();
17809                if scheduled.len() != 1 {
17810                    return Err(invalid_recorded_history(
17811                        "child_workflow_schedule_missing_or_duplicate",
17812                        sequence,
17813                        "one ChildWorkflowScheduled event",
17814                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
17815                        "child workflow replay requires exactly one recorded schedule event",
17816                    ));
17817                }
17818                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
17819                let workflow_type = child_events.iter().find_map(|event| {
17820                    event
17821                        .payload
17822                        .get("child_workflow_type")
17823                        .or_else(|| event.payload.get("workflow_type"))
17824                        .and_then(Value::as_str)
17825                        .filter(|value| !value.is_empty())
17826                        .map(str::to_string)
17827                });
17828                if child_events
17829                    .iter()
17830                    .filter_map(|event| {
17831                        event
17832                            .payload
17833                            .get("child_workflow_type")
17834                            .or_else(|| event.payload.get("workflow_type"))
17835                            .and_then(Value::as_str)
17836                    })
17837                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
17838                {
17839                    return Err(invalid_recorded_history(
17840                        "child_workflow_identity_mismatch",
17841                        sequence,
17842                        workflow_type
17843                            .as_deref()
17844                            .unwrap_or("one child workflow type"),
17845                        "conflicting child workflow types",
17846                        "child workflow lifecycle events at one sequence disagree on type",
17847                    ));
17848                }
17849                let mut outcomes = child_workflow_outcomes(
17850                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
17851                    fallback_codec,
17852                    parent.clone(),
17853                )?;
17854                let terminal_events = child_events
17855                    .iter()
17856                    .copied()
17857                    .filter(|event| event.event_type.starts_with("ChildRun"))
17858                    .collect::<Vec<_>>();
17859                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
17860                    terminal_events.iter().all(|event| {
17861                        event.event_type == first.event_type && event.payload == first.payload
17862                    })
17863                });
17864                if outcomes.len() > 1 && !duplicate_delivery {
17865                    return Err(invalid_recorded_history(
17866                        "duplicate_child_workflow_terminal_event",
17867                        sequence,
17868                        "at most one terminal child event",
17869                        "multiple terminal child events",
17870                        "child workflow history settles one command more than once",
17871                    ));
17872                }
17873                return Ok(RecordedCommand::ChildWorkflow {
17874                    sequence,
17875                    workflow_type,
17876                    policies,
17877                    outcome: outcomes.pop(),
17878                    parallel_group_path,
17879                });
17880            }
17881
17882            if !signal_wait_events.is_empty() {
17883                let opened: Vec<_> = signal_wait_events
17884                    .iter()
17885                    .copied()
17886                    .filter(|event| event.event_type == "SignalWaitOpened")
17887                    .collect();
17888                if opened.len() != 1 {
17889                    return Err(invalid_recorded_history(
17890                        "signal_wait_open_missing_or_duplicate",
17891                        sequence,
17892                        "one SignalWaitOpened event",
17893                        &format!("{} SignalWaitOpened events", opened.len()),
17894                        "signal replay requires exactly one canonical wait-open event",
17895                    ));
17896                }
17897
17898                let applied: Vec<_> = signal_wait_events
17899                    .iter()
17900                    .copied()
17901                    .filter(|event| event.event_type == "SignalApplied")
17902                    .collect();
17903                if applied.len() > 1 {
17904                    return Err(invalid_recorded_history(
17905                        "duplicate_signal_wait_apply",
17906                        sequence,
17907                        "at most one SignalApplied event",
17908                        "multiple SignalApplied events",
17909                        "signal history applies one durable wait more than once",
17910                    ));
17911                }
17912
17913                let signal_names = signal_wait_events
17914                    .iter()
17915                    .map(|event| required_signal_wait_name(event, sequence))
17916                    .collect::<Result<Vec<_>>>()?;
17917                let signal_name = signal_names
17918                    .first()
17919                    .expect("signal wait events are not empty")
17920                    .clone();
17921                if signal_names.iter().any(|candidate| candidate != &signal_name) {
17922                    return Err(invalid_recorded_history(
17923                        "signal_wait_identity_mismatch",
17924                        sequence,
17925                        &signal_name,
17926                        "conflicting signal names",
17927                        "signal wait lifecycle events at one workflow sequence disagree on identity",
17928                    ));
17929                }
17930                let value = applied
17931                    .first()
17932                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
17933                    .transpose()?;
17934                return Ok(RecordedCommand::SignalWait {
17935                    sequence,
17936                    signal_name,
17937                    value,
17938                    parallel_group_path: recorded_parallel_group_path(
17939                        &signal_wait_events,
17940                        sequence,
17941                    )?,
17942                });
17943            }
17944
17945            if !condition_wait_events.is_empty() {
17946                return recorded_condition_wait(
17947                    sequence,
17948                    &condition_wait_events,
17949                    events,
17950                );
17951            }
17952
17953            if !search_attribute_events.is_empty() {
17954                if search_attribute_events.len() != 1 {
17955                    return Err(invalid_recorded_history(
17956                        "duplicate_search_attribute_update",
17957                        sequence,
17958                        "one SearchAttributesUpserted event",
17959                        &format!(
17960                            "{} SearchAttributesUpserted events",
17961                            search_attribute_events.len()
17962                        ),
17963                        "search-attribute history records one workflow command more than once",
17964                    ));
17965                }
17966                let payload = &search_attribute_events[0].payload;
17967                let attributes = payload
17968                    .get("attributes")
17969                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
17970                    .cloned()
17971                    .ok_or_else(|| {
17972                        invalid_recorded_history(
17973                            "search_attribute_update_missing",
17974                            sequence,
17975                            "non-empty attributes object",
17976                            "missing or invalid attributes",
17977                            "search-attribute history is missing its recorded mutation",
17978                        )
17979                    })?;
17980                let attribute_types =
17981                    recorded_search_attribute_types(payload, &attributes, sequence)?;
17982                return Ok(RecordedCommand::SearchAttributes {
17983                    sequence,
17984                    attributes,
17985                    attribute_types,
17986                });
17987            }
17988
17989            if !side_effect_events.is_empty() {
17990                if side_effect_events.len() != 1 {
17991                    return Err(invalid_recorded_history(
17992                        "duplicate_side_effect_record",
17993                        sequence,
17994                        "one SideEffectRecorded event",
17995                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
17996                        "side-effect history records one workflow command more than once",
17997                    ));
17998                }
17999                let event = side_effect_events[0];
18000                let result = event.payload.get("result").ok_or_else(|| {
18001                    invalid_recorded_history(
18002                        "side_effect_result_missing",
18003                        sequence,
18004                        "recorded result payload",
18005                        "missing result",
18006                        "side-effect history is missing its recorded value",
18007                    )
18008                })?;
18009                let has_published_envelope = result.as_str().is_some()
18010                    || result.as_object().is_some_and(|envelope| {
18011                        envelope.get("codec").and_then(Value::as_str).is_some()
18012                            && envelope.get("blob").and_then(Value::as_str).is_some()
18013                    });
18014                if !has_published_envelope {
18015                    return Err(invalid_recorded_history(
18016                        "side_effect_payload_malformed",
18017                        sequence,
18018                        "payload blob or {codec, blob} envelope",
18019                        &result.to_string(),
18020                        "side-effect history result does not use a published payload envelope",
18021                    ));
18022                }
18023                let codec = event
18024                    .payload
18025                    .get("payload_codec")
18026                    .and_then(Value::as_str)
18027                    .unwrap_or(fallback_codec);
18028                let value = decode_wire_avro_value(result, codec).map_err(|error| {
18029                    if error.to_string().contains("unsupported_payload_codec") {
18030                        return error;
18031                    }
18032
18033                    invalid_recorded_history(
18034                        "side_effect_payload_incompatible",
18035                        sequence,
18036                        &format!("valid {codec} payload envelope"),
18037                        &error.to_string(),
18038                        "side-effect history payload cannot be decoded with its recorded codec",
18039                    )
18040                })?;
18041                return Ok(RecordedCommand::SideEffect { sequence, value });
18042            }
18043
18044            if !version_marker_events.is_empty() {
18045                if version_marker_events.len() != 1 {
18046                    return Err(invalid_recorded_history(
18047                        "duplicate_version_marker_record",
18048                        sequence,
18049                        "one VersionMarkerRecorded event",
18050                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
18051                        "version-marker history records one workflow command more than once",
18052                    ));
18053                }
18054                let payload = &version_marker_events[0].payload;
18055                let change_id = payload
18056                    .get("change_id")
18057                    .and_then(Value::as_str)
18058                    .filter(|value| !value.is_empty())
18059                    .map(str::to_string)
18060                    .ok_or_else(|| {
18061                        invalid_recorded_history(
18062                            "version_marker_field_missing",
18063                            sequence,
18064                            "non-empty change_id",
18065                            "missing or invalid change_id",
18066                            "version-marker history is missing its stable change ID",
18067                        )
18068                    })?;
18069                let version = required_version_i32(payload, "version", sequence)?;
18070                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
18071                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
18072                if min_supported > max_supported || version < min_supported || version > max_supported {
18073                    return Err(invalid_recorded_history(
18074                        "version_marker_history_range_invalid",
18075                        sequence,
18076                        "min_supported <= version <= max_supported",
18077                        &format!("{min_supported} <= {version} <= {max_supported}"),
18078                        "recorded version marker contains an internally incompatible range",
18079                    ));
18080                }
18081                return Ok(RecordedCommand::VersionMarker {
18082                    sequence,
18083                    change_id,
18084                    version,
18085                });
18086            }
18087
18088            if !memo_events.is_empty() {
18089                if memo_events.len() != 1 {
18090                    return Err(invalid_recorded_history(
18091                        "duplicate_memo_upsert_record",
18092                        sequence,
18093                        "one MemoUpserted event",
18094                        &format!("{} MemoUpserted events", memo_events.len()),
18095                        "memo history records one workflow update more than once",
18096                    ));
18097                }
18098                let payload = &memo_events[0].payload;
18099                let entries = payload.get("entries").cloned().ok_or_else(|| {
18100                    invalid_recorded_history(
18101                        "memo_entries_missing",
18102                        sequence,
18103                        "memo entries object",
18104                        "missing entries",
18105                        "MemoUpserted history is missing replay identity entries",
18106                    )
18107                })?;
18108                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
18109                    invalid_recorded_history(
18110                        "memo_entries_invalid",
18111                        sequence,
18112                        "valid canonical memo entries",
18113                        &error.to_string(),
18114                        "MemoUpserted history contains invalid replay identity entries",
18115                    )
18116                })?;
18117                let merged = payload.get("merged").cloned().ok_or_else(|| {
18118                    invalid_recorded_history(
18119                        "memo_merged_projection_missing",
18120                        sequence,
18121                        "merged memo projection",
18122                        "missing merged",
18123                        "MemoUpserted history is missing its merged projection",
18124                    )
18125                })?;
18126                decode_memo_history_map(&merged, false).map_err(|error| {
18127                    invalid_recorded_history(
18128                        "memo_merged_projection_invalid",
18129                        sequence,
18130                        "valid merged memo projection",
18131                        &error.to_string(),
18132                        "MemoUpserted history contains an invalid merged projection",
18133                    )
18134                })?;
18135
18136                return Ok(RecordedCommand::Memo { sequence, entries });
18137            }
18138            let scheduled: Vec<_> = timer_events
18139                .iter()
18140                .copied()
18141                .filter(|event| event.event_type == "TimerScheduled")
18142                .collect();
18143            let fired: Vec<_> = timer_events
18144                .iter()
18145                .copied()
18146                .filter(|event| event.event_type == "TimerFired")
18147                .collect();
18148            if scheduled.len() != 1 {
18149                return Err(invalid_recorded_history(
18150                    "timer_schedule_missing_or_duplicate",
18151                    sequence,
18152                    "one TimerScheduled event",
18153                    &format!("{} TimerScheduled events", scheduled.len()),
18154                    "timer replay requires exactly one recorded schedule event",
18155                ));
18156            }
18157            if fired.len() > 1 {
18158                return Err(invalid_recorded_history(
18159                    "duplicate_timer_fire",
18160                    sequence,
18161                    "at most one TimerFired event",
18162                    "multiple TimerFired events",
18163                    "timer history contains more than one fire event for a workflow sequence",
18164                ));
18165            }
18166
18167            let scheduled = scheduled[0];
18168            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
18169            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
18170            if let Some(fired) = fired.first() {
18171                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
18172                if fired_timer_id != timer_id {
18173                    return Err(invalid_recorded_history(
18174                        "timer_identity_mismatch",
18175                        sequence,
18176                        &timer_id,
18177                        &fired_timer_id,
18178                        "TimerFired does not correspond to the recorded TimerScheduled event",
18179                    ));
18180                }
18181                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
18182                if fired_delay != delay_seconds {
18183                    return Err(invalid_recorded_history(
18184                        "timer_history_delay_mismatch",
18185                        sequence,
18186                        &delay_seconds.to_string(),
18187                        &fired_delay.to_string(),
18188                        "TimerScheduled and TimerFired record different delays",
18189                    ));
18190                }
18191            }
18192
18193            Ok(RecordedCommand::Timer {
18194                sequence,
18195                delay_seconds,
18196                fired: !fired.is_empty(),
18197                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
18198            })
18199        })
18200        .collect::<Result<_>>()?;
18201
18202    let mut marker_decisions = HashMap::new();
18203    for command in &commands {
18204        if let RecordedCommand::VersionMarker {
18205            sequence,
18206            change_id,
18207            version,
18208        } = command
18209        {
18210            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
18211                if version != first_version {
18212                    return Err(invalid_recorded_history(
18213                        "version_marker_conflict",
18214                        *sequence,
18215                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
18216                        &format!("version {version} at sequence {sequence}"),
18217                        "workflow history contains conflicting decisions for one stable change ID",
18218                    ));
18219                }
18220            } else {
18221                marker_decisions.insert(change_id.clone(), (*version, *sequence));
18222            }
18223        }
18224    }
18225
18226    Ok(commands)
18227}
18228
18229/// Within a run of commands from one parallel group, move each physical
18230/// condition reopen directly after the earlier waits of the same member; other
18231/// leaves keep their place.
18232///
18233/// Members replay in order from one shared cursor, and a member's chain reads
18234/// only adjacent commands. When several members are woken in one task, the
18235/// Server records their reopens after all originals (a1, b1, a2, b2), so each
18236/// chain would stop at its sibling and leave reopens unconsumed (#191).
18237/// Outcomes are looked up by sequence and occurrence, so only consumption order
18238/// changes.
18239fn group_condition_reopens_by_member(commands: Vec<RecordedCommand>) -> Vec<RecordedCommand> {
18240    // Every leaf of a group belongs to the run; a condition member is keyed by
18241    // its occurrence so its reopens join it, any other leaf by its sequence so
18242    // it keeps its place (#194: a timer between condition members).
18243    fn grouped_member(command: &RecordedCommand) -> Option<(String, String)> {
18244        let (path, member) = match command {
18245            RecordedCommand::ConditionWait {
18246                occurrence_id,
18247                parallel_group_path: Some(path),
18248                ..
18249            } => (path, format!("condition:{occurrence_id}")),
18250            RecordedCommand::Activity {
18251                parallel_group_path: Some(path),
18252                ..
18253            }
18254            | RecordedCommand::Timer {
18255                parallel_group_path: Some(path),
18256                ..
18257            }
18258            | RecordedCommand::ChildWorkflow {
18259                parallel_group_path: Some(path),
18260                ..
18261            }
18262            | RecordedCommand::SignalWait {
18263                parallel_group_path: Some(path),
18264                ..
18265            } => (path, format!("leaf:{}", command.sequence())),
18266            _ => return None,
18267        };
18268        path.first()
18269            .map(|entry| (entry.parallel_group_id.clone(), member))
18270    }
18271    let mut ordered = Vec::with_capacity(commands.len());
18272    let mut run: Vec<RecordedCommand> = Vec::new();
18273    let mut run_group: Option<String> = None;
18274    let flush = |run: &mut Vec<RecordedCommand>, ordered: &mut Vec<RecordedCommand>| {
18275        let mut members: Vec<(String, Vec<RecordedCommand>)> = Vec::new();
18276        for command in run.drain(..) {
18277            let occurrence = grouped_member(&command)
18278                .map(|(_, occurrence)| occurrence)
18279                .unwrap_or_default();
18280            match members.iter_mut().find(|(member, _)| *member == occurrence) {
18281                Some((_, chain)) => chain.push(command),
18282                None => members.push((occurrence, vec![command])),
18283            }
18284        }
18285        ordered.extend(members.into_iter().flat_map(|(_, chain)| chain));
18286    };
18287    for command in commands {
18288        match grouped_member(&command) {
18289            Some((group, _)) if run_group.as_deref() == Some(group.as_str()) => run.push(command),
18290            Some((group, _)) => {
18291                flush(&mut run, &mut ordered);
18292                run_group = Some(group);
18293                run.push(command);
18294            }
18295            None => {
18296                flush(&mut run, &mut ordered);
18297                run_group = None;
18298                ordered.push(command);
18299            }
18300        }
18301    }
18302    flush(&mut run, &mut ordered);
18303    ordered
18304}
18305
18306/// A two-member condition group where only member `a` was reopened:
18307/// a1 (seq 1), b1 (seq 2), a1 satisfied, a2 (seq 3). Replay consumes it as
18308/// a1, a2, b1, so the last recorded command is not the highest sequence.
18309#[cfg(test)]
18310fn one_sided_grouped_reopen_history(extra: Vec<HistoryEvent>) -> Vec<HistoryEvent> {
18311    let member = |event_type: &str, sequence: u64, index: u64, key: &str| HistoryEvent {
18312        event_type: event_type.to_string(),
18313        payload: json!({
18314            "sequence": sequence,
18315            "condition_wait_id": format!("condition:{sequence}"),
18316            "condition_wait_occurrence_id": format!("rust:condition-wait:{index}"),
18317            "condition_key": key,
18318            "condition_definition_fingerprint": format!("sha256:{key}-v1"),
18319            "timeout_seconds": 300,
18320            "parallel_group_id": "parallel-calls:1:2",
18321            "parallel_group_kind": "condition",
18322            "parallel_group_base_sequence": 1,
18323            "parallel_group_size": 2,
18324            "parallel_group_index": index,
18325        }),
18326        raw: HashMap::new(),
18327    };
18328    let mut history = vec![
18329        member("ConditionWaitOpened", 1, 0, "votes"),
18330        member("ConditionWaitOpened", 2, 1, "approvals"),
18331        member("ConditionWaitSatisfied", 1, 0, "votes"),
18332        member("ConditionWaitOpened", 3, 0, "votes"),
18333    ];
18334    history.extend(extra);
18335    history
18336}
18337
18338impl WorkflowState {
18339    /// The highest recorded durable sequence. Recorded commands are consumed in
18340    /// replay order, which is not always sequence order (grouped condition
18341    /// reopens are ordered by member, #191), so the next authored sequence must
18342    /// not be read from the last command.
18343    fn max_recorded_sequence(&self) -> u64 {
18344        self.recorded_commands
18345            .iter()
18346            .map(RecordedCommand::sequence)
18347            .max()
18348            .unwrap_or(0)
18349    }
18350}
18351
18352fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
18353    payload
18354        .get(field)
18355        .and_then(Value::as_i64)
18356        .and_then(|value| i32::try_from(value).ok())
18357        .ok_or_else(|| {
18358            invalid_recorded_history(
18359                "version_marker_field_missing",
18360                sequence,
18361                &format!("integer {field}"),
18362                "missing or out-of-range integer",
18363                "version-marker history is missing a required integer field",
18364            )
18365        })
18366}
18367
18368fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
18369    event
18370        .payload
18371        .get("sequence")
18372        .or_else(|| event.payload.get("workflow_sequence"))
18373        .or_else(|| event.raw.get("sequence"))
18374        .or_else(|| event.raw.get("workflow_sequence"))
18375        .and_then(value_as_u64)
18376}
18377
18378fn is_internal_timer_event(event: &HistoryEvent) -> bool {
18379    matches!(
18380        event
18381            .payload
18382            .get("timer_kind")
18383            .or_else(|| event.raw.get("timer_kind"))
18384            .and_then(Value::as_str),
18385        Some("condition_timeout" | "signal_timeout")
18386    )
18387}
18388
18389fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
18390    matches!(
18391        event.event_type.as_str(),
18392        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
18393    )
18394}
18395
18396fn recorded_condition_wait(
18397    sequence: u64,
18398    condition_events: &[&HistoryEvent],
18399    all_events: &[HistoryEvent],
18400) -> Result<RecordedCommand> {
18401    let opened = condition_events
18402        .iter()
18403        .copied()
18404        .filter(|event| event.event_type == "ConditionWaitOpened")
18405        .collect::<Vec<_>>();
18406    if opened.len() != 1 {
18407        return Err(invalid_recorded_history(
18408            "condition_wait_open_missing_or_duplicate",
18409            sequence,
18410            "one ConditionWaitOpened event",
18411            &format!("{} ConditionWaitOpened events", opened.len()),
18412            "condition replay requires exactly one canonical wait-open event",
18413        ));
18414    }
18415    let terminal = condition_events
18416        .iter()
18417        .copied()
18418        .filter(|event| {
18419            matches!(
18420                event.event_type.as_str(),
18421                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
18422            )
18423        })
18424        .collect::<Vec<_>>();
18425    if terminal.len() > 1 {
18426        return Err(invalid_recorded_history(
18427            "duplicate_condition_wait_terminal_event",
18428            sequence,
18429            "at most one condition terminal event",
18430            "multiple condition terminal events",
18431            "condition history settles one durable wait more than once",
18432        ));
18433    }
18434
18435    let opened = opened[0];
18436    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
18437    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
18438    for event in condition_events
18439        .iter()
18440        .copied()
18441        .filter(|event| !std::ptr::eq(*event, opened))
18442    {
18443        let event_wait_id = required_condition_wait_id(event, sequence)?;
18444        if event_wait_id != condition_wait_id {
18445            return Err(invalid_recorded_history(
18446                "condition_wait_id_mismatch",
18447                sequence,
18448                &condition_wait_id,
18449                &event_wait_id,
18450                "condition lifecycle events at one sequence disagree on wait identity",
18451            ));
18452        }
18453        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
18454        if event_occurrence_id != occurrence_id {
18455            return Err(invalid_recorded_history(
18456                "condition_wait_occurrence_history_mismatch",
18457                sequence,
18458                &occurrence_id,
18459                &event_occurrence_id,
18460                "condition lifecycle events at one sequence disagree on authored occurrence identity",
18461            ));
18462        }
18463    }
18464
18465    let condition_key = optional_non_empty_history_string(opened, "condition_key");
18466    let predicate_identity = opened
18467        .payload
18468        .get("condition_definition_fingerprint")
18469        .and_then(Value::as_str)
18470        .filter(|value| !value.is_empty())
18471        .map(str::to_string)
18472        .ok_or_else(|| {
18473            invalid_recorded_history(
18474                "condition_wait_predicate_fingerprint_missing",
18475                sequence,
18476                "non-empty condition_definition_fingerprint",
18477                &opened.event_type,
18478                "canonical condition history is missing its predicate identity",
18479            )
18480        })?;
18481    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
18482    for event in condition_events
18483        .iter()
18484        .copied()
18485        .filter(|event| !std::ptr::eq(*event, opened))
18486    {
18487        for (field, opened_value) in [
18488            ("condition_key", condition_key.as_deref()),
18489            (
18490                "condition_definition_fingerprint",
18491                Some(predicate_identity.as_str()),
18492            ),
18493        ] {
18494            if let Some(value) = optional_non_empty_history_string(event, field) {
18495                if opened_value.is_some_and(|opened_value| opened_value != value) {
18496                    return Err(invalid_recorded_history(
18497                        "condition_wait_definition_history_mismatch",
18498                        sequence,
18499                        opened_value.unwrap_or_default(),
18500                        &value,
18501                        "condition lifecycle events disagree on the recorded definition",
18502                    ));
18503                }
18504            }
18505        }
18506        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
18507            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
18508                return Err(invalid_recorded_history(
18509                    "condition_wait_definition_history_mismatch",
18510                    sequence,
18511                    &format!("{}s", timeout_seconds.unwrap_or_default()),
18512                    &format!("{event_timeout}s"),
18513                    "condition lifecycle events disagree on the recorded timeout",
18514                ));
18515            }
18516        }
18517    }
18518
18519    let timeout_timer_events = all_events
18520        .iter()
18521        .filter(|event| {
18522            matches!(
18523                event.event_type.as_str(),
18524                "TimerScheduled" | "TimerCancelled" | "TimerFired"
18525            ) && event.payload.get("timer_kind").and_then(Value::as_str)
18526                == Some("condition_timeout")
18527                && event
18528                    .payload
18529                    .get("condition_wait_id")
18530                    .and_then(Value::as_str)
18531                    == Some(condition_wait_id.as_str())
18532        })
18533        .collect::<Vec<_>>();
18534    let scheduled = timeout_timer_events
18535        .iter()
18536        .copied()
18537        .filter(|event| event.event_type == "TimerScheduled")
18538        .collect::<Vec<_>>();
18539    let fired = timeout_timer_events
18540        .iter()
18541        .copied()
18542        .filter(|event| event.event_type == "TimerFired")
18543        .collect::<Vec<_>>();
18544    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
18545        return Err(invalid_recorded_history(
18546            "condition_wait_timeout_history_invalid",
18547            sequence,
18548            "one timeout schedule and at most one fire",
18549            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
18550            "condition timeout history has a missing or duplicate lifecycle event",
18551        ));
18552    }
18553    if let Some(scheduled) = scheduled.first() {
18554        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
18555        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
18556        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
18557            return Err(invalid_recorded_history(
18558                "condition_wait_timeout_delay_mismatch",
18559                sequence,
18560                &format!("{}s", timeout_seconds.unwrap_or_default()),
18561                &format!("{delay_seconds}s"),
18562                "condition timeout timer differs from the wait definition",
18563            ));
18564        }
18565        if let Some(fired) = fired.first() {
18566            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
18567            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
18568            if fired_timer_id != timer_id || fired_delay != delay_seconds {
18569                return Err(invalid_recorded_history(
18570                    "condition_wait_timeout_identity_mismatch",
18571                    sequence,
18572                    &format!("{timer_id}:{delay_seconds}s"),
18573                    &format!("{fired_timer_id}:{fired_delay}s"),
18574                    "condition timeout fire does not match its durable schedule",
18575                ));
18576            }
18577        }
18578    }
18579
18580    let result = terminal.first().map(|event| {
18581        if event.event_type == "ConditionWaitTimedOut" {
18582            ConditionWaitResult::TimedOut
18583        } else {
18584            ConditionWaitResult::Satisfied
18585        }
18586    });
18587    let result = if !fired.is_empty() {
18588        if result == Some(ConditionWaitResult::Satisfied) {
18589            return Err(invalid_recorded_history(
18590                "condition_wait_terminal_conflict",
18591                sequence,
18592                "one satisfied or timed-out outcome",
18593                "satisfied event and fired timeout",
18594                "condition history records conflicting terminal outcomes",
18595            ));
18596        }
18597        Some(ConditionWaitResult::TimedOut)
18598    } else {
18599        result
18600    };
18601
18602    Ok(RecordedCommand::ConditionWait {
18603        sequence,
18604        occurrence_id,
18605        condition_key,
18606        predicate_identity,
18607        timeout_seconds,
18608        result,
18609        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
18610    })
18611}
18612
18613fn recorded_condition_group_path(
18614    condition_events: &[&HistoryEvent],
18615    all_events: &[HistoryEvent],
18616    sequence: u64,
18617) -> Result<Option<Vec<ParallelGroupMetadata>>> {
18618    let opened = condition_events
18619        .iter()
18620        .copied()
18621        .find(|event| event.event_type == "ConditionWaitOpened")
18622        .expect("canonical condition opener is validated first");
18623    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
18624    let previous_events = all_events
18625        .iter()
18626        .take_while(|event| !std::ptr::eq(*event, opened))
18627        .collect::<Vec<_>>();
18628    let originals = previous_events
18629        .iter()
18630        .copied()
18631        .filter(|event| event.event_type == "ConditionWaitOpened")
18632        .filter(|event| {
18633            event
18634                .payload
18635                .get("condition_wait_occurrence_id")
18636                .and_then(Value::as_str)
18637                == Some(occurrence.as_str())
18638        })
18639        .collect::<Vec<_>>();
18640    let Some(original) = originals.first().copied() else {
18641        return recorded_parallel_group_path(condition_events, sequence);
18642    };
18643    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
18644    if authored_sequence == sequence {
18645        return recorded_parallel_group_path(condition_events, sequence);
18646    }
18647    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
18648    if original_path.is_none() {
18649        return recorded_parallel_group_path(condition_events, sequence);
18650    }
18651    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
18652    // A reopen carries the time remaining since the original open (#187), so
18653    // its timeout may be smaller than the original's, never larger.
18654    let timeout_matches = match (
18655        opened
18656            .payload
18657            .get("timeout_seconds")
18658            .filter(|value| !value.is_null()),
18659        original
18660            .payload
18661            .get("timeout_seconds")
18662            .filter(|value| !value.is_null()),
18663    ) {
18664        (None, None) => true,
18665        (Some(reopened), Some(original)) => reopened
18666            .as_u64()
18667            .zip(original.as_u64())
18668            .is_some_and(|(reopened, original)| reopened <= original),
18669        _ => false,
18670    };
18671    let identity_matches = timeout_matches
18672        && ["condition_key", "condition_definition_fingerprint"]
18673            .iter()
18674            .all(|field| opened.payload.get(*field) == original.payload.get(*field));
18675    let previous = originals
18676        .iter()
18677        .copied()
18678        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
18679        .max_by_key(|event| durable_event_sequence(event));
18680    let previously_satisfied = previous.is_some_and(|previous| {
18681        previous_events.iter().any(|event| {
18682            event.event_type == "ConditionWaitSatisfied"
18683                && event.payload.get("condition_wait_id")
18684                    == previous.payload.get("condition_wait_id")
18685                && event.payload.get("condition_wait_occurrence_id")
18686                    == previous.payload.get("condition_wait_occurrence_id")
18687                && durable_event_sequence(event) == durable_event_sequence(previous)
18688        })
18689    });
18690    // The PHP Server also accepts a grouped re-send of a member whose latest
18691    // wait is still open, and records it as a new physical open without
18692    // resolving the earlier one (#191). That predecessor was unresolved when
18693    // this wait opened: it is a repeated open of the same logical member.
18694    let previously_unresolved = previous.is_some_and(|previous| {
18695        !previous_events
18696            .iter()
18697            .any(|event| match event.event_type.as_str() {
18698                "ConditionWaitSatisfied" | "ConditionWaitTimedOut" => {
18699                    event.payload.get("condition_wait_id")
18700                        == previous.payload.get("condition_wait_id")
18701                        && durable_event_sequence(event) == durable_event_sequence(previous)
18702                }
18703                "TimerFired" => {
18704                    event.payload.get("timer_kind").and_then(Value::as_str)
18705                        == Some("condition_timeout")
18706                        && event.payload.get("condition_wait_id")
18707                            == previous.payload.get("condition_wait_id")
18708                }
18709                _ => false,
18710            })
18711    });
18712    if !identity_matches
18713        || reopened_path != original_path
18714        || !(previously_satisfied || previously_unresolved)
18715    {
18716        return Err(invalid_recorded_history(
18717            "condition_wait_group_reopen_mismatch",
18718            sequence,
18719            "same authored condition and group path after a satisfied physical wait",
18720            &opened.payload.to_string(),
18721            "grouped condition reopen has no matching recorded predecessor",
18722        ));
18723    }
18724    Ok(reopened_path)
18725}
18726
18727fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
18728    event
18729        .payload
18730        .get("condition_wait_occurrence_id")
18731        .and_then(Value::as_str)
18732        .filter(|value| !value.is_empty())
18733        .map(str::to_string)
18734        .ok_or_else(|| {
18735            invalid_recorded_history(
18736                "condition_wait_occurrence_id_missing",
18737                sequence,
18738                "non-empty condition_wait_occurrence_id",
18739                &event.event_type,
18740                "condition history is missing authored occurrence identity",
18741            )
18742        })
18743}
18744
18745fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
18746    event
18747        .payload
18748        .get("condition_wait_id")
18749        .and_then(Value::as_str)
18750        .filter(|value| !value.is_empty())
18751        .map(str::to_string)
18752        .ok_or_else(|| {
18753            invalid_recorded_history(
18754                "condition_wait_id_missing",
18755                sequence,
18756                "non-empty condition_wait_id",
18757                &event.event_type,
18758                "canonical condition history is missing its durable wait identity",
18759            )
18760        })
18761}
18762
18763fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
18764    event
18765        .payload
18766        .get(field)
18767        .and_then(Value::as_str)
18768        .filter(|value| !value.is_empty())
18769        .map(str::to_string)
18770}
18771
18772fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
18773    match event.payload.get(field) {
18774        None | Some(Value::Null) => Ok(None),
18775        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
18776            invalid_recorded_history(
18777                "condition_wait_definition_invalid",
18778                sequence,
18779                &format!("non-negative integer {field}"),
18780                &value.to_string(),
18781                "condition history contains an invalid numeric definition field",
18782            )
18783        }),
18784    }
18785}
18786
18787fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
18788    event
18789        .payload
18790        .get("signal_name")
18791        .or_else(|| event.raw.get("signal_name"))
18792        .and_then(Value::as_str)
18793        .filter(|value| !value.is_empty())
18794        .map(str::to_string)
18795        .ok_or_else(|| {
18796            invalid_recorded_history(
18797                "signal_wait_name_missing",
18798                sequence,
18799                "non-empty signal_name",
18800                &event.event_type,
18801                "canonical signal-wait history is missing its signal identity",
18802            )
18803        })
18804}
18805
18806fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
18807    // Applying a buffered control-plane signal has no authored call sequence.
18808    // Its outer sequence orders history events and must not become a wait.
18809    if event.event_type == "SignalApplied"
18810        && event
18811            .payload
18812            .get("signal_wait_id")
18813            .and_then(Value::as_str)
18814            .is_some_and(|id| id.starts_with("signal-command:"))
18815        && event.payload.get("sequence").is_none()
18816        && event.payload.get("workflow_sequence").is_none()
18817    {
18818        return false;
18819    }
18820    matches!(
18821        event.event_type.as_str(),
18822        "SignalWaitOpened" | "SignalApplied"
18823    )
18824}
18825
18826fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
18827    event
18828        .payload
18829        .get(field)
18830        .and_then(Value::as_str)
18831        .filter(|value| !value.is_empty())
18832        .map(str::to_string)
18833        .ok_or_else(|| {
18834            invalid_recorded_history(
18835                "timer_history_field_missing",
18836                sequence,
18837                field,
18838                &event.event_type,
18839                "timer history is missing a required identity field",
18840            )
18841        })
18842}
18843
18844fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
18845    event
18846        .payload
18847        .get(field)
18848        .and_then(value_as_u64)
18849        .ok_or_else(|| {
18850            invalid_recorded_history(
18851                "timer_history_field_missing",
18852                sequence,
18853                field,
18854                &event.event_type,
18855                "timer history is missing a required numeric field",
18856            )
18857        })
18858}
18859
18860fn recorded_search_attribute_types(
18861    payload: &Value,
18862    attributes: &Value,
18863    sequence: u64,
18864) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
18865    let Some(raw_types) = payload.get("attribute_types") else {
18866        // This is the explicit compatibility rule for histories recorded
18867        // before typed identity was persisted. Values still constrain replay;
18868        // the unknown type snapshot does not assert a typed match.
18869        return Ok(RecordedSnapshotValue::Unknown);
18870    };
18871    let Some(raw_types) = raw_types.as_object() else {
18872        return Err(invalid_recorded_history(
18873            "search_attribute_types_malformed",
18874            sequence,
18875            "canonical attribute type map",
18876            &raw_types.to_string(),
18877            "search-attribute history contains malformed type identity",
18878        ));
18879    };
18880    let attribute_keys = attributes
18881        .as_object()
18882        .expect("recorded search attributes were validated as an object");
18883    let mut types = BTreeMap::new();
18884    for (key, value) in raw_types {
18885        let Some(attribute_type) = value.as_str() else {
18886            return Err(invalid_recorded_history(
18887                "search_attribute_types_malformed",
18888                sequence,
18889                "canonical string type name",
18890                &value.to_string(),
18891                "search-attribute history contains a non-string type identity",
18892            ));
18893        };
18894        if !attribute_keys.contains_key(key)
18895            || !matches!(
18896                attribute_type,
18897                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
18898            )
18899        {
18900            return Err(invalid_recorded_history(
18901                "search_attribute_types_malformed",
18902                sequence,
18903                "canonical types for keys present in attributes",
18904                &format!("{key}:{attribute_type}"),
18905                "search-attribute history contains unsupported or orphaned type identity",
18906            ));
18907        }
18908        types.insert(key.clone(), attribute_type.to_string());
18909    }
18910    Ok(RecordedSnapshotValue::Known(types))
18911}
18912
18913fn invalid_recorded_history(
18914    reason: &str,
18915    sequence: u64,
18916    expected: &str,
18917    actual: &str,
18918    message: &str,
18919) -> Error {
18920    Error::NonDeterministicReplay(ReplayFailure::new(
18921        reason,
18922        Some(sequence),
18923        Some(expected.to_string()),
18924        Some(actual.to_string()),
18925        message,
18926    ))
18927}
18928
18929type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
18930
18931fn activity_outcome(
18932    event: &HistoryEvent,
18933    fallback_codec: &str,
18934    recorded_activity_type: Option<String>,
18935) -> Result<ActivityOutcome> {
18936    if event.event_type == "ActivityCompleted" {
18937        let codec = event
18938            .payload
18939            .get("payload_codec")
18940            .and_then(Value::as_str)
18941            .unwrap_or(fallback_codec);
18942        return Ok(Ok(decode_wire_avro_value(
18943            event.payload.get("result").unwrap_or(&Value::Null),
18944            codec,
18945        )?));
18946    }
18947
18948    let payload = &event.payload;
18949    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
18950        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
18951        "ActivityCancelled" => (
18952            ActivityFailureKind::Cancelled,
18953            "cancelled",
18954            "activity was cancelled",
18955        ),
18956        "ActivityTimedOut" => (
18957            ActivityFailureKind::TimedOut,
18958            "timeout",
18959            "activity timed out",
18960        ),
18961        _ => unreachable!("activity_outcome is called only for terminal activity events"),
18962    };
18963    let exception = payload
18964        .get("exception")
18965        .filter(|value| !value.is_null())
18966        .cloned();
18967    let failure_category = payload_string(payload, "failure_category");
18968    let timeout_kind = payload_string(payload, "timeout_kind");
18969    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
18970        ActivityFailureKind::Failed => failure_category
18971            .clone()
18972            .unwrap_or_else(|| fallback_reason.to_string()),
18973        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
18974        ActivityFailureKind::TimedOut => timeout_kind
18975            .clone()
18976            .unwrap_or_else(|| fallback_reason.to_string()),
18977    });
18978    let message = payload_string(payload, "message")
18979        .or_else(|| {
18980            exception
18981                .as_ref()
18982                .and_then(|value| payload_string(value, "message"))
18983        })
18984        .unwrap_or_else(|| fallback_message.to_string());
18985
18986    Ok(Err(ActivityFailure {
18987        kind,
18988        reason,
18989        message,
18990        activity_execution_id: payload_string(payload, "activity_execution_id"),
18991        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
18992        activity_type: payload_string(payload, "activity_type")
18993            .or_else(|| payload_string(payload, "activity_name"))
18994            .or(recorded_activity_type),
18995        activity_class: payload_string(payload, "activity_class"),
18996        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
18997        failure_id: payload_string(payload, "failure_id"),
18998        failure_category,
18999        timeout_kind,
19000        non_retryable: payload
19001            .get("non_retryable")
19002            .and_then(Value::as_bool)
19003            .unwrap_or(false),
19004        exception_type: payload_string(payload, "exception_type").or_else(|| {
19005            exception
19006                .as_ref()
19007                .and_then(|value| payload_string(value, "type"))
19008        }),
19009        exception_class: payload_string(payload, "exception_class").or_else(|| {
19010            exception
19011                .as_ref()
19012                .and_then(|value| payload_string(value, "class"))
19013        }),
19014        code: payload
19015            .get("code")
19016            .filter(|value| !value.is_null())
19017            .cloned(),
19018        exception,
19019    }))
19020}
19021
19022type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
19023
19024fn child_workflow_outcomes(
19025    events: &[HistoryEvent],
19026    fallback_codec: &str,
19027    parent: WorkflowIdentity,
19028) -> Result<Vec<ChildWorkflowOutcome>> {
19029    let mut outcomes = Vec::new();
19030
19031    for event in events {
19032        let kind = match event.event_type.as_str() {
19033            "ChildRunCompleted" => None,
19034            "ChildRunFailed" => Some((
19035                ChildWorkflowFailureKind::Failed,
19036                "child_workflow",
19037                "child workflow failed",
19038            )),
19039            "ChildRunCancelled" => Some((
19040                ChildWorkflowFailureKind::Cancelled,
19041                "cancelled",
19042                "child workflow was cancelled",
19043            )),
19044            "ChildRunTerminated" => Some((
19045                ChildWorkflowFailureKind::Terminated,
19046                "terminated",
19047                "child workflow was terminated",
19048            )),
19049            _ => continue,
19050        };
19051        let payload = &event.payload;
19052        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
19053        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
19054        let child_workflow_type = payload_string(payload, "child_workflow_type");
19055
19056        if let Some((kind, reason, fallback_message)) = kind {
19057            let exception = payload
19058                .get("exception")
19059                .filter(|value| !value.is_null())
19060                .cloned();
19061            let message = payload_string(payload, "message")
19062                .or_else(|| {
19063                    exception
19064                        .as_ref()
19065                        .and_then(|value| payload_string(value, "message"))
19066                })
19067                .unwrap_or_else(|| fallback_message.to_string());
19068            let exception_type = payload_string(payload, "exception_type").or_else(|| {
19069                exception
19070                    .as_ref()
19071                    .and_then(|value| payload_string(value, "type"))
19072            });
19073            let exception_class = payload_string(payload, "exception_class").or_else(|| {
19074                exception
19075                    .as_ref()
19076                    .and_then(|value| payload_string(value, "class"))
19077            });
19078            outcomes.push(Err(ChildWorkflowFailure {
19079                kind,
19080                reason: reason.to_string(),
19081                message,
19082                parent_workflow_id: parent.workflow_id.clone(),
19083                parent_workflow_run_id: parent.run_id.clone(),
19084                child_workflow_id,
19085                child_workflow_run_id,
19086                child_workflow_type,
19087                failure_id: payload_string(payload, "failure_id"),
19088                failure_category: payload_string(payload, "failure_category"),
19089                exception_type,
19090                exception_class,
19091                non_retryable: payload
19092                    .get("non_retryable")
19093                    .and_then(Value::as_bool)
19094                    .unwrap_or(false),
19095                code: payload
19096                    .get("code")
19097                    .filter(|value| !value.is_null())
19098                    .cloned(),
19099                exception,
19100            }));
19101            continue;
19102        }
19103
19104        let codec = payload
19105            .get("payload_codec")
19106            .and_then(Value::as_str)
19107            .unwrap_or(fallback_codec);
19108        let result = payload
19109            .get("result")
19110            .or_else(|| payload.get("output"))
19111            .unwrap_or(&Value::Null);
19112        outcomes.push(Ok(ChildWorkflowAvroResult {
19113            parent: parent.clone(),
19114            child: WorkflowIdentity {
19115                workflow_id: child_workflow_id,
19116                run_id: child_workflow_run_id,
19117            },
19118            child_workflow_type,
19119            result: decode_wire_avro_value(result, codec)?,
19120        }));
19121    }
19122
19123    Ok(outcomes)
19124}
19125
19126fn payload_string(payload: &Value, key: &str) -> Option<String> {
19127    payload
19128        .get(key)
19129        .and_then(Value::as_str)
19130        .filter(|value| !value.is_empty())
19131        .map(str::to_string)
19132}
19133
19134fn recorded_activity_failure_boundary(
19135    ctx: &WorkflowContext,
19136    error: &Error,
19137) -> Option<(u64, String)> {
19138    let Error::ActivityFailed(failure) = error else {
19139        return None;
19140    };
19141    if failure.kind != ActivityFailureKind::Failed {
19142        return None;
19143    }
19144    let activity_execution_id = failure
19145        .activity_execution_id
19146        .as_deref()
19147        .filter(|value| !value.is_empty())?;
19148    let state = ctx.state.lock().ok()?;
19149    let mut matches = state.recorded_commands.iter().filter_map(|command| {
19150        let RecordedCommand::Activity {
19151            sequence,
19152            outcome: Some(Err(recorded_failure)),
19153            ..
19154        } = command
19155        else {
19156            return None;
19157        };
19158        (*sequence > 0 && recorded_failure == failure)
19159            .then_some((*sequence, activity_execution_id.to_string()))
19160    });
19161    let boundary = matches.next()?;
19162    matches.next().is_none().then_some(boundary)
19163}
19164
19165fn workflow_failure_command(
19166    error: &Error,
19167    failed_activity_boundary: Option<(u64, String)>,
19168) -> Value {
19169    let (exception_type, exception_class, properties) = match error {
19170        Error::NexusOperationFailed(failure) => (
19171            "NexusOperationFailed",
19172            "durable_workflow::NexusOperationFailure",
19173            json!({"service_call_id":failure.service_call_id, "status":failure.status,
19174                "caller_observed_error_type":failure.exception_type, "service_exception":failure.exception}),
19175        ),
19176        Error::ActivityFailed(failure) => (
19177            match failure.kind {
19178                ActivityFailureKind::Failed => "ActivityFailed",
19179                ActivityFailureKind::Cancelled => "ActivityCancelled",
19180                ActivityFailureKind::TimedOut => "ActivityTimedOut",
19181            },
19182            "durable_workflow::ActivityFailure",
19183            json!({
19184                "reason": failure.reason,
19185                "activity_execution_id": failure.activity_execution_id,
19186                "activity_attempt_id": failure.activity_attempt_id,
19187                "activity_type": failure.activity_type,
19188                "activity_class": failure.activity_class,
19189                "attempt_number": failure.attempt_number,
19190                "failure_id": failure.failure_id,
19191                "failure_category": failure.failure_category,
19192                "timeout_kind": failure.timeout_kind,
19193                "activity_non_retryable": failure.non_retryable,
19194                "activity_exception_type": failure.exception_type,
19195                "activity_exception_class": failure.exception_class,
19196                "activity_code": failure.code,
19197                "activity_exception": failure.exception,
19198            }),
19199        ),
19200        Error::ChildWorkflowFailed(failure) => (
19201            match failure.kind {
19202                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
19203                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
19204                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
19205            },
19206            "durable_workflow::ChildWorkflowFailure",
19207            json!({
19208                "reason": failure.reason,
19209                "parent_workflow_id": failure.parent_workflow_id,
19210                "parent_workflow_run_id": failure.parent_workflow_run_id,
19211                "child_workflow_id": failure.child_workflow_id,
19212                "child_workflow_run_id": failure.child_workflow_run_id,
19213                "child_workflow_type": failure.child_workflow_type,
19214                "failure_id": failure.failure_id,
19215                "failure_category": failure.failure_category,
19216                "child_exception_type": failure.exception_type,
19217                "child_exception_class": failure.exception_class,
19218                "child_non_retryable": failure.non_retryable,
19219                "child_code": failure.code,
19220                "child_exception": failure.exception,
19221            }),
19222        ),
19223        Error::ParallelFailed(failure) => (
19224            "ParallelFailed",
19225            "durable_workflow::ParallelFailure",
19226            json!({
19227                "parallel_group_id": failure.group_id,
19228                "parallel_member_path": failure.member_path,
19229                "parallel_group_path": failure.group_path,
19230                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
19231                "cause_type": workflow_error_type(&failure.cause),
19232                "cause_message": failure.cause.to_string(),
19233            }),
19234        ),
19235        Error::SagaCompensationFailed(failure) => (
19236            "SagaCompensationFailed",
19237            "durable_workflow::SagaCompensationFailure",
19238            json!({
19239                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
19240                "initiating_failure_message": failure.initiating_failure.to_string(),
19241                "compensation_activity_type": failure.compensation_activity_type,
19242                "compensation_registration_order": failure.compensation_registration_order,
19243                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
19244                "compensation_failure_message": failure.compensation_failure.to_string(),
19245            }),
19246        ),
19247        Error::WorkflowCancellationRequested(_) => (
19248            "WorkflowCancellationRequested",
19249            "durable_workflow::WorkflowCancellationRequested",
19250            json!({"reason": "cancelled"}),
19251        ),
19252        Error::CooperativeCancellationRequested(cancellation) => (
19253            "WorkflowCancellationRequested",
19254            "durable_workflow::CooperativeCancellationRequested",
19255            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
19256                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
19257        ),
19258        Error::CancellationScopeRequested(cancellation) => (
19259            "WorkflowCancellationRequested",
19260            "durable_workflow::CancellationScopeRequested",
19261            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
19262                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
19263                "cancellation":cancellation.context.to_value()}),
19264        ),
19265        Error::NonDeterministicReplay(_) => (
19266            "NonDeterministicReplay",
19267            "durable_workflow::Error",
19268            Value::Null,
19269        ),
19270        Error::WorkflowTaskCompletionTooLarge(refusal) => (
19271            "StructuralLimitExceeded",
19272            "durable_workflow::WorkflowTaskCompletionTooLarge",
19273            json!({
19274                "structural_limit_kind": refusal.limit_kind,
19275                "structural_limit_value": refusal.size,
19276                "structural_limit_configured": refusal.limit,
19277            }),
19278        ),
19279        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
19280    };
19281    let non_retryable = match error {
19282        Error::ActivityFailed(failure) => failure.non_retryable,
19283        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
19284        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
19285        Error::SagaCompensationFailed(failure) => {
19286            workflow_error_non_retryable(&failure.compensation_failure)
19287        }
19288        Error::WorkflowCancellationRequested(_)
19289        | Error::CooperativeCancellationRequested(_)
19290        | Error::CancellationScopeRequested(_) => true,
19291        Error::NonDeterministicReplay(_) => true,
19292        Error::WorkflowTaskCompletionTooLarge(_) => true,
19293        _ => false,
19294    };
19295
19296    let mut command = json!({
19297        "type": "fail_workflow",
19298        "message": error.to_string(),
19299        "exception_type": exception_type,
19300        "exception_class": exception_class,
19301        "non_retryable": non_retryable,
19302        "exception": {
19303            "type": exception_type,
19304            "class": exception_class,
19305            "message": error.to_string(),
19306            "properties": properties,
19307        }
19308    });
19309
19310    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
19311        command["failed_step_sequence"] = json!(sequence);
19312        command["failed_activity_execution_id"] = json!(activity_execution_id);
19313    }
19314
19315    command
19316}
19317
19318fn workflow_error_type(error: &Error) -> &'static str {
19319    match error {
19320        Error::NexusOperationFailed(_) => "NexusOperationFailed",
19321        Error::ActivityFailed(failure) => match failure.kind {
19322            ActivityFailureKind::Failed => "ActivityFailed",
19323            ActivityFailureKind::Cancelled => "ActivityCancelled",
19324            ActivityFailureKind::TimedOut => "ActivityTimedOut",
19325        },
19326        Error::ChildWorkflowFailed(failure) => match failure.kind {
19327            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
19328            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
19329            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
19330        },
19331        Error::ParallelFailed(_) => "ParallelFailed",
19332        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
19333        Error::WorkflowCancellationRequested(_)
19334        | Error::CooperativeCancellationRequested(_)
19335        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
19336        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
19337        _ => "RustWorkflowError",
19338    }
19339}
19340
19341fn workflow_error_non_retryable(error: &Error) -> bool {
19342    match error {
19343        Error::ActivityFailed(failure) => failure.non_retryable,
19344        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
19345        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
19346        Error::SagaCompensationFailed(failure) => {
19347            workflow_error_non_retryable(&failure.compensation_failure)
19348        }
19349        Error::WorkflowCancellationRequested(_)
19350        | Error::CooperativeCancellationRequested(_)
19351        | Error::CancellationScopeRequested(_)
19352        | Error::NonDeterministicReplay(_) => true,
19353        _ => false,
19354    }
19355}
19356
19357fn workflow_task_integrity_error(error: &Error) -> bool {
19358    matches!(
19359        error,
19360        Error::NonDeterministicReplay(_)
19361            | Error::Protocol(_)
19362            | Error::CancellationScopeExecutionUnavailable
19363            | Error::MissingWorkflowCommandIdentity
19364            | Error::WorkflowStatePoisoned
19365    )
19366}
19367
19368fn decode_signal_event_arguments(
19369    event: &HistoryEvent,
19370    fallback_codec: &str,
19371) -> Result<Vec<AvroValue>> {
19372    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
19373    validate_payload_codec(codec)?;
19374    let raw = signal_history_payload(&event.payload);
19375    let decoded = match raw.filter(|value| !value.is_null()) {
19376        Some(value) => decode_wire_avro_value(value, codec)?,
19377        None => AvroValue::Array(Vec::new()),
19378    };
19379    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
19380        unreachable!("normalize_avro_arguments always returns an array");
19381    };
19382    Ok(arguments)
19383}
19384
19385fn decode_update_event_arguments(
19386    event: &HistoryEvent,
19387    fallback_codec: &str,
19388) -> Result<Vec<AvroValue>> {
19389    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
19390    validate_payload_codec(codec)?;
19391    let decoded = match event
19392        .payload
19393        .get("arguments")
19394        .filter(|value| !value.is_null())
19395    {
19396        Some(value) => decode_wire_avro_value(value, codec)?,
19397        None => AvroValue::Array(Vec::new()),
19398    };
19399    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
19400        unreachable!("normalize_avro_arguments always returns an array");
19401    };
19402    Ok(arguments)
19403}
19404
19405fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
19406    let Some(export_events) = task
19407        .history_export
19408        .as_ref()
19409        .and_then(|export| export.get("history_events"))
19410        .and_then(Value::as_array)
19411    else {
19412        return Ok(());
19413    };
19414
19415    if export_events.len() > task.history_events.len() {
19416        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
19417    }
19418
19419    Ok(())
19420}
19421
19422fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
19423    let Some(export) = task.history_export.as_ref() else {
19424        return Ok(());
19425    };
19426    let signals = export
19427        .get("signals")
19428        .and_then(Value::as_array)
19429        .cloned()
19430        .unwrap_or_default();
19431    let activities = export
19432        .get("activities")
19433        .and_then(Value::as_array)
19434        .cloned()
19435        .unwrap_or_default();
19436    let export_codec = export
19437        .get("payloads")
19438        .and_then(|payloads| payloads.get("codec"))
19439        .and_then(Value::as_str)
19440        .unwrap_or(&task.payload_codec)
19441        .to_string();
19442    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
19443
19444    for event in &mut task.history_events {
19445        if event.event_type == "ActivityCompleted" {
19446            let sequence = event
19447                .payload
19448                .get("sequence")
19449                .or_else(|| event.payload.get("workflow_sequence"))
19450                .and_then(value_as_u64);
19451            let Some(activity) = sequence.and_then(|sequence| {
19452                activities.iter().find(|activity| {
19453                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
19454                })
19455            }) else {
19456                continue;
19457            };
19458            let Some(payload) = event.payload.as_object_mut() else {
19459                continue;
19460            };
19461            if missing_payload(payload.get("result")) {
19462                if let Some(result) = activity
19463                    .get("result")
19464                    .filter(|value| !missing_payload(Some(value)))
19465                {
19466                    payload.insert("result".to_string(), result.clone());
19467                }
19468            }
19469            for field in ["payload_codec", "activity_type"] {
19470                if payload
19471                    .get(field)
19472                    .and_then(Value::as_str)
19473                    .unwrap_or_default()
19474                    .is_empty()
19475                {
19476                    if let Some(value) = activity.get(field) {
19477                        payload.insert(field.to_string(), value.clone());
19478                    }
19479                }
19480            }
19481            continue;
19482        }
19483
19484        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
19485            continue;
19486        }
19487        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
19488        let command_id = event
19489            .payload
19490            .get("workflow_command_id")
19491            .or_else(|| event.raw.get("workflow_command_id"))
19492            .and_then(Value::as_str);
19493        let signal_name = event
19494            .payload
19495            .get("signal_name")
19496            .and_then(Value::as_str)
19497            .unwrap_or_default()
19498            .to_string();
19499        let matched = signals
19500            .iter()
19501            .find(|signal| {
19502                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
19503            })
19504            .or_else(|| {
19505                signals.iter().find(|signal| {
19506                    command_id.is_some()
19507                        && signal.get("command_id").and_then(Value::as_str) == command_id
19508                })
19509            })
19510            .or_else(|| {
19511                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
19512                let signal = signals
19513                    .iter()
19514                    .filter(|signal| {
19515                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
19516                    })
19517                    .nth(*offset);
19518                if signal.is_some() {
19519                    *offset += 1;
19520                }
19521                signal
19522            });
19523        let Some(signal) = matched else {
19524            continue;
19525        };
19526        let signal_codec = signal
19527            .get("payload_codec")
19528            .and_then(Value::as_str)
19529            .unwrap_or(&export_codec);
19530        let Some(payload) = event.payload.as_object_mut() else {
19531            continue;
19532        };
19533        if missing_payload(payload.get("arguments")) {
19534            if let Some(arguments) = signal
19535                .get("arguments")
19536                .filter(|value| !missing_payload(Some(value)))
19537            {
19538                let envelope = match arguments {
19539                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
19540                    other => other.clone(),
19541                };
19542                payload.insert("arguments".to_string(), envelope);
19543            }
19544        }
19545        if payload
19546            .get("payload_codec")
19547            .and_then(Value::as_str)
19548            .unwrap_or_default()
19549            .is_empty()
19550        {
19551            payload.insert("payload_codec".to_string(), json!(signal_codec));
19552        }
19553    }
19554
19555    Ok(())
19556}
19557
19558fn missing_payload(value: Option<&Value>) -> bool {
19559    match value {
19560        None | Some(Value::Null) => true,
19561        Some(Value::String(value)) => value.is_empty(),
19562        Some(_) => false,
19563    }
19564}
19565
19566fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
19567    history_signal_events(
19568        &task.history_events,
19569        task.history_export.as_ref(),
19570        &task.payload_codec,
19571    )
19572}
19573
19574fn history_signal_events(
19575    history_events: &[HistoryEvent],
19576    history_export: Option<&Value>,
19577    payload_codec: &str,
19578) -> Result<Vec<QuerySignal>> {
19579    let export_signals = history_export
19580        .and_then(|export| export.get("signals"))
19581        .and_then(Value::as_array)
19582        .cloned()
19583        .unwrap_or_default();
19584    let export_codec = history_export
19585        .and_then(|export| export.get("payloads"))
19586        .and_then(|payloads| payloads.get("codec"))
19587        .and_then(Value::as_str)
19588        .unwrap_or(payload_codec);
19589    let mut name_offsets: HashMap<String, usize> = HashMap::new();
19590    let mut signals: Vec<QuerySignal> = Vec::new();
19591    let mut signal_indices = HashMap::new();
19592    let mut command_indices = HashMap::new();
19593
19594    for event in history_events {
19595        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
19596            continue;
19597        }
19598
19599        let name = event
19600            .payload
19601            .get("signal_name")
19602            .and_then(Value::as_str)
19603            .unwrap_or_default();
19604        if name.is_empty() {
19605            continue;
19606        }
19607        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
19608        let command_id = event
19609            .payload
19610            .get("workflow_command_id")
19611            .or_else(|| event.raw.get("workflow_command_id"))
19612            .and_then(Value::as_str);
19613        let matched_export = export_signals
19614            .iter()
19615            .find(|candidate| {
19616                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
19617            })
19618            .or_else(|| {
19619                export_signals.iter().find(|candidate| {
19620                    command_id.is_some()
19621                        && candidate.get("command_id").and_then(Value::as_str) == command_id
19622                })
19623            })
19624            .or_else(|| {
19625                let offset = name_offsets.entry(name.to_string()).or_default();
19626                let candidate = export_signals
19627                    .iter()
19628                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
19629                    .nth(*offset);
19630                if candidate.is_some() {
19631                    *offset += 1;
19632                }
19633                candidate
19634            });
19635        let codec = event
19636            .payload
19637            .get("payload_codec")
19638            .and_then(Value::as_str)
19639            .or_else(|| {
19640                matched_export
19641                    .and_then(|signal| signal.get("payload_codec"))
19642                    .and_then(Value::as_str)
19643            })
19644            .unwrap_or(export_codec);
19645        let raw_arguments = signal_history_payload(&event.payload)
19646            .filter(|value| !value.is_null())
19647            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
19648        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
19649        let workflow_sequence = event
19650            .payload
19651            .get("workflow_sequence")
19652            .and_then(value_as_u64)
19653            .or_else(|| {
19654                matched_export
19655                    .and_then(|signal| signal.get("workflow_sequence"))
19656                    .and_then(value_as_u64)
19657            });
19658
19659        let id = signal_id.or_else(|| {
19660            matched_export
19661                .and_then(|signal| signal.get("id"))
19662                .and_then(Value::as_str)
19663        });
19664        let command_id = command_id.or_else(|| {
19665            matched_export
19666                .and_then(|signal| signal.get("command_id"))
19667                .and_then(Value::as_str)
19668        });
19669        let duplicate = id
19670            .and_then(|id| signal_indices.get(id))
19671            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
19672            .copied();
19673        let index = duplicate.unwrap_or(signals.len());
19674        if let Some(index) = duplicate {
19675            let original = &mut signals[index];
19676            let same_arguments = if event.event_type == "SignalApplied" {
19677                if let Some(value) = event.payload.get("value") {
19678                    let expected = match original.avro_arguments.as_slice() {
19679                        [] => AvroValue::Boolean(true),
19680                        [value] => value.clone(),
19681                        values => AvroValue::Array(values.to_vec()),
19682                    };
19683                    let applied = decode_wire_avro_value(value, codec)?;
19684                    applied == expected
19685                        || applied == AvroValue::Array(original.avro_arguments.clone())
19686                } else {
19687                    original.avro_arguments == avro_arguments
19688                }
19689            } else {
19690                original.avro_arguments == avro_arguments
19691            };
19692            if original.name != name
19693                || !same_arguments
19694                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
19695            {
19696                return Err(Error::Codec("conflicting committed signal identity".into()));
19697            }
19698            if original.id.is_none() {
19699                original.id = id.map(str::to_string);
19700            }
19701            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
19702        } else {
19703            signals.push(QuerySignal {
19704                id: id.map(str::to_string),
19705                name: name.to_string(),
19706                arguments,
19707                avro_arguments,
19708                workflow_sequence,
19709            });
19710        }
19711        if let Some(id) = id {
19712            signal_indices.insert(id.to_string(), index);
19713        }
19714        if let Some(id) = command_id {
19715            command_indices.insert(id.to_string(), index);
19716        }
19717    }
19718
19719    if signals.is_empty() {
19720        for signal in export_signals {
19721            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
19722                continue;
19723            }
19724            let Some(name) = signal.get("name").and_then(Value::as_str) else {
19725                continue;
19726            };
19727            let codec = signal
19728                .get("payload_codec")
19729                .and_then(Value::as_str)
19730                .unwrap_or(export_codec);
19731            let (arguments, avro_arguments) =
19732                decode_query_signal_arguments(signal.get("arguments"), codec)?;
19733            signals.push(QuerySignal {
19734                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
19735                name: name.to_string(),
19736                arguments,
19737                avro_arguments,
19738                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
19739            });
19740        }
19741        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
19742    }
19743
19744    Ok(signals)
19745}
19746
19747fn decode_query_signal_arguments(
19748    raw: Option<&Value>,
19749    codec: &str,
19750) -> Result<(Vec<Value>, Vec<AvroValue>)> {
19751    validate_payload_codec(codec)?;
19752    let decoded = match raw.filter(|value| !value.is_null()) {
19753        Some(value) => decode_wire_avro_value(value, codec)?,
19754        None => AvroValue::Array(Vec::new()),
19755    };
19756    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
19757        unreachable!("normalize_avro_arguments always returns an array");
19758    };
19759    let arguments = avro_arguments
19760        .iter()
19761        .cloned()
19762        .map(AvroValue::into_json)
19763        .collect::<Result<Vec<_>>>()?;
19764    Ok((arguments, avro_arguments))
19765}
19766
19767fn value_as_u64(value: &Value) -> Option<u64> {
19768    value
19769        .as_u64()
19770        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
19771}
19772
19773#[cfg(test)]
19774mod tests {
19775    use super::*;
19776    #[cfg(feature = "telemetry")]
19777    static OBSERVABILITY_PROPAGATOR_TEST_LOCK: tokio::sync::Mutex<()> =
19778        tokio::sync::Mutex::const_new(());
19779    mod activity_cancellation_policies;
19780    mod activity_lease_worker;
19781    mod cancellation_scope_admission;
19782    mod cancellation_scope_authoring;
19783    mod cancellation_scope_history;
19784    mod cancellation_scope_opening;
19785    mod cancellation_scope_replay;
19786    mod child_workflow_policies;
19787    mod completion_limits;
19788    mod condition_fingerprint;
19789    mod cooperative_cancellation;
19790    mod local_activity;
19791    mod nexus;
19792    mod path_segments;
19793    mod run_closed_settlement;
19794    mod runtime_payloads;
19795    mod runtime_uploads;
19796    mod static_credentials;
19797    mod version_marker_contract;
19798    mod worker_capacity;
19799    mod worker_session;
19800    use std::{
19801        fs,
19802        io::{Read, Write},
19803        net::{SocketAddr, TcpListener, TcpStream},
19804        process::Command as ProcessCommand,
19805        sync::atomic::AtomicUsize,
19806        thread,
19807    };
19808
19809    #[derive(Clone, Copy, Debug)]
19810    enum InvalidTaskPayloadCodec {
19811        Missing,
19812        Null,
19813        NonString,
19814    }
19815
19816    impl InvalidTaskPayloadCodec {
19817        fn label(self) -> &'static str {
19818            match self {
19819                Self::Missing => "missing",
19820                Self::Null => "null",
19821                Self::NonString => "non-string",
19822            }
19823        }
19824
19825        fn apply(self, task: &mut Value) {
19826            let task = task.as_object_mut().expect("task fixture object");
19827            match self {
19828                Self::Missing => {
19829                    task.remove("payload_codec");
19830                }
19831                Self::Null => {
19832                    task.insert("payload_codec".to_string(), Value::Null);
19833                }
19834                Self::NonString => {
19835                    task.insert("payload_codec".to_string(), json!(42));
19836                }
19837            }
19838        }
19839    }
19840
19841    fn fixture_envelope(value: Value) -> Value {
19842        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
19843    }
19844
19845    fn fixture_blob(value: Value) -> String {
19846        encode_payload(&value, DEFAULT_CODEC)
19847            .expect("encode Avro test fixture")
19848            .blob
19849    }
19850
19851    #[test]
19852    fn client_builder_rejects_the_sdk_owned_api_suffix() {
19853        for base_url in [
19854            "http://127.0.0.1:8080/api",
19855            "http://localhost:8080/api/",
19856            "https://runtime.example.test/namespaces/orders/api",
19857        ] {
19858            let error = Client::builder(base_url)
19859                .build()
19860                .expect_err("SDK-owned /api suffix must be rejected during build");
19861
19862            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
19863            assert!(
19864                error.to_string().contains("SDK appends /api automatically"),
19865                "the validation error must explain how to fix the endpoint"
19866            );
19867        }
19868    }
19869
19870    #[test]
19871    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
19872        for (base_url, expected) in [
19873            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
19874            (
19875                "http://localhost:8080/durable-workflow/",
19876                "http://localhost:8080/durable-workflow",
19877            ),
19878            (
19879                "https://runtime.example.test/namespaces/orders",
19880                "https://runtime.example.test/namespaces/orders",
19881            ),
19882            (
19883                "https://runtime.example.test/gateway/api/namespaces/orders",
19884                "https://runtime.example.test/gateway/api/namespaces/orders",
19885            ),
19886            (
19887                "https://api.example.test/runtime/orders/",
19888                "https://api.example.test/runtime/orders",
19889            ),
19890        ] {
19891            let client = Client::builder(base_url)
19892                .build()
19893                .expect("Server and Cloud runtime base URL must remain valid");
19894
19895            assert_eq!(client.base_url, expected);
19896        }
19897    }
19898
19899    #[test]
19900    fn workflow_completion_uses_the_additive_command_protocol_floor() {
19901        assert_eq!(
19902            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
19903            MINIMUM_WORKER_PROTOCOL_VERSION
19904        );
19905        assert_eq!(
19906            workflow_completion_protocol_version(&[json!({
19907                "type": "upsert_search_attributes",
19908                "attributes": {"OrderStatus": "waiting"},
19909            })]),
19910            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
19911        );
19912        assert_eq!(
19913            workflow_completion_protocol_version(&[json!({
19914                "type": "upsert_search_attributes",
19915                "attributes": {"OrderStatus": "waiting"},
19916                "attribute_types": {"OrderStatus": "keyword"},
19917            })]),
19918            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
19919        );
19920        assert_eq!(
19921            workflow_completion_protocol_version(&[
19922                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
19923                json!({"type": "open_condition_wait", "condition_key": "ready"}),
19924            ]),
19925            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
19926        );
19927        assert_eq!(
19928            workflow_completion_protocol_version(&[
19929                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
19930                json!({"type": "open_condition_wait", "condition_key": "ready"}),
19931            ]),
19932            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
19933        );
19934        assert_eq!(
19935            workflow_completion_protocol_version(&[json!({
19936                "type": "open_condition_wait",
19937                "condition_wait_occurrence_id": "rust:condition-wait:0",
19938                "condition_key": "ready",
19939            })]),
19940            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
19941        );
19942        assert_eq!(
19943            workflow_completion_protocol_version_with_message_streams(
19944                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
19945                true,
19946            ),
19947            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
19948        );
19949        assert_eq!(
19950            workflow_completion_protocol_version_with_message_streams(
19951                &[json!({
19952                    "type": "open_condition_wait",
19953                    "condition_wait_occurrence_id": "rust:condition-wait:0",
19954                    "condition_key": "ready",
19955                })],
19956                true,
19957            ),
19958            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
19959        );
19960    }
19961
19962    #[test]
19963    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
19964        let manifest = portable_worker_affinity_capability_manifest();
19965
19966        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
19967            assert_eq!(manifest[capability]["supported"], json!(false));
19968            assert_eq!(
19969                manifest[capability]["minimum_protocol_version"],
19970                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
19971            );
19972            assert!(manifest[capability]["reason"]
19973                .as_str()
19974                .is_some_and(|reason| !reason.is_empty()));
19975        }
19976    }
19977
19978    fn typed_fidelity_probe() -> AvroValue {
19979        AvroValue::Map(BTreeMap::from([
19980            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
19981            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
19982            (
19983                "numeric".to_string(),
19984                AvroValue::Map(BTreeMap::from([
19985                    ("0".to_string(), AvroValue::String("zero".to_string())),
19986                    ("1".to_string(), AvroValue::String("one".to_string())),
19987                ])),
19988            ),
19989            (
19990                "nested".to_string(),
19991                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
19992                    "enabled".to_string(),
19993                    AvroValue::Boolean(true),
19994                )]))]),
19995            ),
19996            (
19997                "projection_collisions".to_string(),
19998                AvroValue::Array(projection_collision_probe()),
19999            ),
20000        ]))
20001    }
20002
20003    fn projection_collision_probe() -> Vec<AvroValue> {
20004        vec![
20005            AvroValue::Map(BTreeMap::from([
20006                ("$type".to_string(), AvroValue::String("bytes".to_string())),
20007                (
20008                    "base64".to_string(),
20009                    AvroValue::String("ordinary user text".to_string()),
20010                ),
20011            ])),
20012            AvroValue::Map(BTreeMap::from([
20013                ("$type".to_string(), AvroValue::String("map".to_string())),
20014                (
20015                    "entries".to_string(),
20016                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
20017                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
20018                        (
20019                            "value".to_string(),
20020                            AvroValue::String("user map".to_string()),
20021                        ),
20022                    ]))]),
20023                ),
20024            ])),
20025        ]
20026    }
20027
20028    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
20029    struct TypedContract {
20030        nested: TypedNested,
20031        mode: TypedMode,
20032        optional: Option<String>,
20033        absent: Option<String>,
20034        items: Vec<i64>,
20035        labels: BTreeMap<String, String>,
20036        bytes: serde_bytes::ByteBuf,
20037        signed: i64,
20038        finite: f64,
20039    }
20040
20041    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
20042    struct TypedNested {
20043        enabled: bool,
20044    }
20045
20046    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
20047    enum TypedMode {
20048        Detailed { label: String },
20049    }
20050
20051    fn typed_contract() -> TypedContract {
20052        TypedContract {
20053            nested: TypedNested { enabled: true },
20054            mode: TypedMode::Detailed {
20055                label: "compiler-checked".to_string(),
20056            },
20057            optional: Some("present".to_string()),
20058            absent: None,
20059            items: vec![i64::MIN, 0, i64::MAX],
20060            labels: BTreeMap::from([
20061                ("language".to_string(), "rust".to_string()),
20062                ("wire".to_string(), "avro".to_string()),
20063            ]),
20064            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
20065            signed: -9_223_372_036_854_775_000,
20066            finite: 12.5,
20067        }
20068    }
20069
20070    #[derive(Clone, Debug, Default, PartialEq)]
20071    struct ReplayCounterState {
20072        loaded: Option<String>,
20073        count: i64,
20074        finished: bool,
20075    }
20076
20077    fn replay_counter_worker() -> Worker {
20078        let client = Client::new("http://127.0.0.1:8080").expect("client");
20079        let mut worker = Worker::new(client, "rust-workers");
20080        worker.register_replayed_workflow(
20081            "replay-counter",
20082            ReplayCounterState::default,
20083            |ctx, _input, state| async move {
20084                let loaded = ctx.activity("load-counter", json!([])).await?;
20085                state.update(|current| {
20086                    current.loaded = loaded.as_str().map(str::to_string);
20087                })?;
20088                for _ in 0..2 {
20089                    let signal = ctx.wait_signal("increment").await?;
20090                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
20091                    state.update(|current| current.count += amount)?;
20092                }
20093                state.update(|current| current.finished = true)?;
20094                state.read(|current| Ok(json!(current.count)))?
20095            },
20096        );
20097        worker.register_replayed_query::<ReplayCounterState, _, _>(
20098            "replay-counter",
20099            "current",
20100            |_ctx, state, _args| async move {
20101                Ok(json!({
20102                    "loaded": state.loaded,
20103                    "count": state.count,
20104                    "finished": state.finished,
20105                }))
20106            },
20107        );
20108        worker.register_replayed_query::<ReplayCounterState, _, _>(
20109            "replay-counter",
20110            "detached-mutation",
20111            |_ctx, state, _args| async move {
20112                let mut detached = (*state).clone();
20113                detached.count = 999;
20114                Ok(json!(detached.count))
20115            },
20116        );
20117        worker.register_replayed_query::<ReplayCounterState, _, _>(
20118            "replay-counter",
20119            "failed-mutation",
20120            |_ctx, state, _args| async move {
20121                let mut detached = (*state).clone();
20122                detached.count = 999;
20123                Err(Error::WorkerLoop("query refused".to_string()))
20124            },
20125        );
20126        worker
20127    }
20128
20129    fn replay_counter_query(
20130        query_name: &str,
20131        history_events: Value,
20132        run_status: &str,
20133    ) -> QueryTask {
20134        let arguments = fixture_envelope(json!([]));
20135        serde_json::from_value(json!({
20136            "query_task_id": format!("query-{query_name}"),
20137            "workflow_type": "replay-counter",
20138            "query_name": query_name,
20139            "payload_codec": DEFAULT_CODEC,
20140            "workflow_arguments": arguments.clone(),
20141            "query_arguments": arguments,
20142            "history_events": history_events,
20143            "run_status": run_status,
20144        }))
20145        .expect("query task")
20146    }
20147
20148    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
20149        workflow_context_with_codec(history, DEFAULT_CODEC)
20150    }
20151
20152    fn workflow_context_with_codec(
20153        history: Vec<HistoryEvent>,
20154        payload_codec: &str,
20155    ) -> WorkflowContext {
20156        WorkflowContext {
20157            cancellation_scope_id: "root".into(),
20158            state: Arc::new(Mutex::new(
20159                WorkflowState::new_with_identity(
20160                    history,
20161                    None,
20162                    None,
20163                    "rust-workers".to_string(),
20164                    payload_codec.to_string(),
20165                    None,
20166                )
20167                .expect("valid workflow history"),
20168            )),
20169        }
20170    }
20171
20172    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
20173        HistoryEvent {
20174            event_type: event_type.to_string(),
20175            payload,
20176            raw: HashMap::new(),
20177        }
20178    }
20179
20180    fn parallel_path_entry(
20181        kind: &str,
20182        base: u64,
20183        size: usize,
20184        index: usize,
20185    ) -> ParallelGroupMetadata {
20186        parallel_group_entry(base, size, index, kind)
20187    }
20188
20189    fn parallel_history_event(
20190        event_type: &str,
20191        sequence: u64,
20192        identity_field: &str,
20193        identity: &str,
20194        path: Vec<ParallelGroupMetadata>,
20195        result: Option<Value>,
20196    ) -> HistoryEvent {
20197        let mut payload = serde_json::Map::from_iter([
20198            ("sequence".to_string(), json!(sequence)),
20199            (identity_field.to_string(), json!(identity)),
20200        ]);
20201        let inner = path.last().expect("parallel history path");
20202        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
20203        payload.insert("parallel_group_path".to_string(), json!(path));
20204        if let Some(result) = result {
20205            let field = if event_type == "ChildRunCompleted" {
20206                "result"
20207            } else {
20208                "result"
20209            };
20210            payload.insert(field.to_string(), fixture_envelope(result));
20211            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
20212        }
20213        history_event(event_type, Value::Object(payload))
20214    }
20215
20216    fn nested_parallel_operations() -> Vec<ParallelOperation> {
20217        vec![
20218            ParallelOperation::activity("first", json!([])),
20219            ParallelOperation::group(vec![
20220                ParallelOperation::child_workflow(
20221                    "second",
20222                    ChildWorkflowOptions::new("child-workers"),
20223                    json!([]),
20224                ),
20225                ParallelOperation::activity("third", json!([])),
20226            ]),
20227        ]
20228    }
20229
20230    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
20231        let outer = [
20232            parallel_path_entry("mixed", 1, 3, 0),
20233            parallel_path_entry("mixed", 1, 3, 1),
20234            parallel_path_entry("mixed", 1, 3, 2),
20235        ];
20236        [
20237            vec![outer[0].clone()],
20238            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
20239            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
20240        ]
20241    }
20242
20243    #[test]
20244    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
20245        let ctx = workflow_context(Vec::new());
20246        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
20247        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20248
20249        assert!(matches!(
20250            call.as_mut().poll(&mut task_context),
20251            Poll::Pending
20252        ));
20253        let commands = ctx.take_commands().expect("parallel commands");
20254        assert_eq!(
20255            commands
20256                .iter()
20257                .map(|command| command["type"].as_str().unwrap_or_default())
20258                .collect::<Vec<_>>(),
20259            [
20260                "schedule_activity",
20261                "start_child_workflow",
20262                "schedule_activity"
20263            ]
20264        );
20265        let paths = nested_parallel_paths();
20266        for (command, path) in commands.iter().zip(paths) {
20267            assert_eq!(command["parallel_group_path"], json!(path));
20268            assert_eq!(
20269                command["parallel_group_id"],
20270                json!(path.last().expect("inner group").parallel_group_id)
20271            );
20272        }
20273    }
20274
20275    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
20276        let paths = nested_parallel_paths();
20277        let third = parallel_history_event(
20278            "ActivityCompleted",
20279            3,
20280            "activity_type",
20281            "third",
20282            paths[2].clone(),
20283            Some(json!("three")),
20284        );
20285        vec![
20286            parallel_history_event(
20287                "ActivityCompleted",
20288                1,
20289                "activity_type",
20290                "first",
20291                paths[0].clone(),
20292                Some(json!("one")),
20293            ),
20294            parallel_history_event(
20295                "ChildWorkflowScheduled",
20296                2,
20297                "child_workflow_type",
20298                "second",
20299                paths[1].clone(),
20300                None,
20301            ),
20302            parallel_history_event(
20303                "ChildRunCompleted",
20304                2,
20305                "child_workflow_type",
20306                "second",
20307                paths[1].clone(),
20308                Some(json!("two")),
20309            ),
20310            third.clone(),
20311            third,
20312        ]
20313    }
20314
20315    #[test]
20316    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
20317        for _restart_or_completed_replay in 0..2 {
20318            let ctx = workflow_context(completed_nested_parallel_history());
20319            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
20320            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20321            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
20322                panic!("completed nested parallel history must replay");
20323            };
20324            assert_eq!(
20325                results,
20326                vec![
20327                    ParallelResult::Activity(json!("one")),
20328                    ParallelResult::Group(vec![
20329                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
20330                            parent: WorkflowIdentity {
20331                                workflow_id: None,
20332                                run_id: None,
20333                            },
20334                            child: WorkflowIdentity {
20335                                workflow_id: None,
20336                                run_id: None,
20337                            },
20338                            child_workflow_type: Some("second".to_string()),
20339                            result: json!("two"),
20340                        }),
20341                        ParallelResult::Activity(json!("three")),
20342                    ]),
20343                ]
20344            );
20345            assert!(ctx.take_commands().expect("commands").is_empty());
20346            ctx.ensure_history_consumed().expect("history consumed");
20347        }
20348    }
20349
20350    #[test]
20351    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
20352        let paths = nested_parallel_paths();
20353        let history = vec![
20354            parallel_history_event(
20355                "ActivityCompleted",
20356                1,
20357                "activity_type",
20358                "first",
20359                paths[0].clone(),
20360                Some(json!("one")),
20361            ),
20362            parallel_history_event(
20363                "ChildWorkflowScheduled",
20364                2,
20365                "child_workflow_type",
20366                "second",
20367                paths[1].clone(),
20368                None,
20369            ),
20370            parallel_history_event(
20371                "ChildRunFailed",
20372                2,
20373                "child_workflow_type",
20374                "second",
20375                paths[1].clone(),
20376                None,
20377            ),
20378            parallel_history_event(
20379                "ActivityCompleted",
20380                3,
20381                "activity_type",
20382                "third",
20383                paths[2].clone(),
20384                Some(json!("late")),
20385            ),
20386        ];
20387        let ctx = workflow_context(history);
20388        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
20389        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20390        let outcome = call.as_mut().poll(&mut task_context);
20391        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
20392            panic!("one failed child must return a typed partial failure: {outcome:?}");
20393        };
20394        assert_eq!(failure.member_path, [1, 0]);
20395        assert_eq!(failure.group_id, "parallel-calls:1:3");
20396        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
20397        assert_eq!(
20398            failure
20399                .completed
20400                .iter()
20401                .map(|completion| completion.member_path.clone())
20402                .collect::<Vec<_>>(),
20403            [vec![0], vec![1, 1]]
20404        );
20405    }
20406
20407    #[test]
20408    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
20409        let paths = nested_parallel_paths();
20410        let history = vec![
20411            parallel_history_event(
20412                "ActivityScheduled",
20413                1,
20414                "activity_type",
20415                "first",
20416                paths[0].clone(),
20417                None,
20418            ),
20419            parallel_history_event(
20420                "ChildWorkflowScheduled",
20421                2,
20422                "child_workflow_type",
20423                "second",
20424                paths[1].clone(),
20425                None,
20426            ),
20427            parallel_history_event(
20428                "ActivityScheduled",
20429                3,
20430                "activity_type",
20431                "third",
20432                paths[2].clone(),
20433                None,
20434            ),
20435        ];
20436        for _restart in 0..2 {
20437            let ctx = workflow_context(history.clone());
20438            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
20439            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20440            let outcome = call.as_mut().poll(&mut task_context);
20441            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
20442            assert!(ctx.take_commands().expect("commands").is_empty());
20443        }
20444    }
20445
20446    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
20447        vec![selection_group_entry(
20448            1,
20449            2,
20450            index,
20451            "activity",
20452            &SelectionMemberMetadata {
20453                key: SelectionKey::Name(key.to_string()),
20454                index,
20455                base_sequence: index as u64 + 1,
20456                size: 1,
20457                kind: "activity".to_string(),
20458            },
20459        )]
20460    }
20461
20462    fn selection_activity_event(
20463        event_type: &str,
20464        index: usize,
20465        key: &str,
20466        result: Option<Value>,
20467    ) -> HistoryEvent {
20468        let sequence = index as u64 + 1;
20469        let mut event = parallel_history_event(
20470            event_type,
20471            sequence,
20472            "activity_type",
20473            &format!("{key}-activity"),
20474            selection_path(index, key),
20475            result,
20476        );
20477        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
20478        event.raw.insert(
20479            "id".to_string(),
20480            json!(if event_type == "ActivityCompleted" {
20481                format!("event-{key}")
20482            } else {
20483                format!("{event_type}-{key}")
20484            }),
20485        );
20486        event
20487    }
20488
20489    fn selection_winner_marker() -> HistoryEvent {
20490        history_event(
20491            "SelectionResolved",
20492            json!({
20493                "selection_group_id": "select-calls:1:2",
20494                "selection_group_base_sequence": 1,
20495                "selection_group_size": 2,
20496                "member_key": "fast",
20497                "member_index": 1,
20498                "member_base_sequence": 2,
20499                "member_size": 1,
20500                "operation_kind": "activity",
20501                "operation_identity": "activity-fast",
20502                "outcome": "completed",
20503                "resolution_event_id": "event-fast",
20504                "resolution_event_type": "ActivityCompleted",
20505            }),
20506        )
20507    }
20508
20509    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
20510        ctx.select_keyed(vec![
20511            (
20512                "slow",
20513                ParallelOperation::activity_with_options(
20514                    "slow-activity",
20515                    ActivityOptions::new().task_queue("default"),
20516                    json!([]),
20517                ),
20518            ),
20519            (
20520                "fast",
20521                ParallelOperation::activity_with_options(
20522                    "fast-activity",
20523                    ActivityOptions::new().task_queue("default"),
20524                    json!([]),
20525                ),
20526            ),
20527        ])
20528    }
20529
20530    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
20531        let ctx = workflow_context(history);
20532        let mut call = Box::pin(keyed_activity_selection(&ctx));
20533        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20534        let selected = match call.as_mut().poll(&mut task_context) {
20535            Poll::Ready(Ok(selected)) => selected,
20536            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
20537            Poll::Pending => panic!("persisted selection winner must replay without pending"),
20538        };
20539        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
20540        assert_eq!(
20541            selected.value,
20542            Some(ParallelResult::Activity(json!("winner-value")))
20543        );
20544        let slow = selected
20545            .handle(&SelectionKey::Name("slow".to_string()))
20546            .expect("slow handle")
20547            .clone();
20548        let mut await_slow = Box::pin(slow.await_result());
20549        assert!(matches!(
20550            await_slow.as_mut().poll(&mut task_context),
20551            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
20552        ));
20553        assert!(ctx.take_commands().expect("commands").is_empty());
20554    }
20555
20556    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
20557
20558    fn canonical_selection_history() -> Vec<HistoryEvent> {
20559        const FIXTURE: &[u8] =
20560            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
20561        assert_eq!(
20562            format!("{:x}", Sha256::digest(FIXTURE)),
20563            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
20564        );
20565        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
20566
20567        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
20568    }
20569
20570    #[test]
20571    fn selection_fresh_process_entrypoint() {
20572        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
20573            return;
20574        };
20575        let persisted = fs::read(path).expect("persisted selection history");
20576        assert_eq!(
20577            format!("{:x}", Sha256::digest(&persisted)),
20578            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
20579        );
20580        let fixture: Value =
20581            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
20582        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
20583            .expect("valid persisted selection history");
20584
20585        assert_persisted_selection_replay(history);
20586    }
20587
20588    #[test]
20589    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
20590        let ctx = workflow_context(Vec::new());
20591        let mut call = Box::pin(keyed_activity_selection(&ctx));
20592        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20593
20594        assert!(matches!(
20595            call.as_mut().poll(&mut task_context),
20596            Poll::Pending
20597        ));
20598        let commands = ctx.take_commands().expect("selection commands");
20599        assert_eq!(commands.len(), 2);
20600        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
20601        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
20602        assert!(commands.iter().all(|command| {
20603            command["parallel_group_id"] == json!("select-calls:1:2")
20604                && command["parallel_group_mode"] == json!("select")
20605        }));
20606    }
20607
20608    #[test]
20609    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
20610        let ctx = workflow_context(Vec::new());
20611        let mut invalid = Box::pin(ctx.select_keyed(vec![(
20612            "",
20613            ParallelOperation::activity("invalid", json!([])),
20614        )]));
20615        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20616        assert!(matches!(
20617            invalid.as_mut().poll(&mut task_context),
20618            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
20619                reason: "selection_key_invalid",
20620                ..
20621            })))
20622        ));
20623
20624        for invalid_key in [json!(""), json!(-1)] {
20625            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
20626            event.payload["selection_member_key"] = invalid_key.clone();
20627            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
20628            assert!(matches!(
20629                WorkflowState::new_with_identity(
20630                    vec![event],
20631                    None,
20632                    None,
20633                    "rust-workers".to_string(),
20634                    DEFAULT_CODEC.to_string(),
20635                    None,
20636                ),
20637                Err(Error::NonDeterministicReplay(_))
20638            ));
20639        }
20640    }
20641
20642    #[test]
20643    fn selection_preserves_valid_named_and_numeric_keys() {
20644        let ctx = workflow_context(Vec::new());
20645        let mut selection = Box::pin(ctx.select_keyed(vec![
20646            (
20647                SelectionKey::Index(0),
20648                ParallelOperation::activity("numeric", json!([])),
20649            ),
20650            (
20651                SelectionKey::Name("named".to_string()),
20652                ParallelOperation::timer(Duration::from_secs(1)),
20653            ),
20654        ]));
20655        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20656
20657        assert!(matches!(
20658            selection.as_mut().poll(&mut task_context),
20659            Poll::Pending
20660        ));
20661        let commands = ctx.take_commands().expect("selection commands");
20662        assert_eq!(commands[0]["selection_member_key"], json!(0));
20663        assert_eq!(commands[1]["selection_member_key"], json!("named"));
20664    }
20665
20666    #[test]
20667    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
20668        let history = canonical_selection_history();
20669        assert_persisted_selection_replay(history.clone());
20670
20671        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
20672            .join("tests/fixtures/durable_selection_runtime_history.json");
20673        let output =
20674            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
20675                .args([
20676                    "--exact",
20677                    "tests::selection_fresh_process_entrypoint",
20678                    "--nocapture",
20679                ])
20680                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
20681                .output()
20682                .expect("run fresh selection replay process");
20683
20684        assert!(
20685            output.status.success(),
20686            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
20687            String::from_utf8_lossy(&output.stdout),
20688            String::from_utf8_lossy(&output.stderr),
20689        );
20690    }
20691
20692    #[test]
20693    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
20694        let mut history = canonical_selection_history();
20695        history.retain(|event| event.event_type != "SelectionResolved");
20696        let ctx = workflow_context(history);
20697        let mut selection = Box::pin(keyed_activity_selection(&ctx));
20698        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20699
20700        assert!(matches!(
20701            selection.as_mut().poll(&mut task_context),
20702            Poll::Pending
20703        ));
20704        assert!(ctx.take_commands().expect("commands").is_empty());
20705        assert!(
20706            ctx.matched_recorded_pending()
20707                .expect("selection pending state"),
20708            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
20709        );
20710    }
20711
20712    #[test]
20713    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
20714        for (terminal_event, predicate_satisfied, timeout_seconds) in [
20715            ("ConditionWaitSatisfied", true, None),
20716            ("ConditionWaitTimedOut", false, Some(0)),
20717        ] {
20718            let member = SelectionMemberMetadata {
20719                key: SelectionKey::Name("condition".to_string()),
20720                index: 0,
20721                base_sequence: 1,
20722                size: 1,
20723                kind: "condition".to_string(),
20724            };
20725            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
20726            let mut payload = json!({
20727                "sequence": 1,
20728                "condition_wait_id": "condition-1",
20729                "condition_wait_occurrence_id": "rust:condition-wait:0",
20730                "condition_key": "ready",
20731                "condition_definition_fingerprint": "sha256:ready-v1",
20732                "parallel_group_path": path,
20733            });
20734            payload
20735                .as_object_mut()
20736                .expect("condition history payload")
20737                .extend(
20738                    serde_json::to_value(&path[0])
20739                        .expect("condition selection metadata")
20740                        .as_object()
20741                        .expect("condition selection metadata object")
20742                        .clone(),
20743                );
20744            if let Some(timeout_seconds) = timeout_seconds {
20745                payload["timeout_seconds"] = json!(timeout_seconds);
20746            }
20747            let history = vec![
20748                history_event("ConditionWaitOpened", payload.clone()),
20749                history_event(terminal_event, payload),
20750            ];
20751            let ctx = workflow_context(history);
20752            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
20753            if timeout_seconds.is_some() {
20754                options = options.timeout(Duration::ZERO);
20755            }
20756            let mut selection = Box::pin(ctx.select_keyed(vec![(
20757                "condition",
20758                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
20759            )]));
20760            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20761
20762            assert!(matches!(
20763                selection.as_mut().poll(&mut task_context),
20764                Poll::Pending
20765            ));
20766            assert!(ctx.take_commands().expect("commands").is_empty());
20767            assert!(
20768                ctx.matched_recorded_pending()
20769                    .expect("condition selection pending state"),
20770                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
20771            );
20772        }
20773    }
20774
20775    #[test]
20776    fn selection_immediate_condition_members_open_a_durable_wait() {
20777        for predicate_satisfied in [true, false] {
20778            let ctx = workflow_context(Vec::new());
20779            let mut selection = Box::pin(ctx.select_keyed(vec![(
20780                "condition",
20781                ParallelOperation::condition(
20782                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
20783                    move || Ok(predicate_satisfied),
20784                ),
20785            )]));
20786            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20787
20788            assert!(matches!(
20789                selection.as_mut().poll(&mut task_context),
20790                Poll::Pending
20791            ));
20792            let commands = ctx.take_commands().expect("condition selection command");
20793            assert_eq!(commands.len(), 1);
20794            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
20795            assert_eq!(commands[0]["timeout_seconds"], json!(0));
20796            assert_eq!(
20797                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
20798                json!("select")
20799            );
20800        }
20801    }
20802
20803    #[test]
20804    fn selection_loser_cancellation_is_explicit_and_idempotent() {
20805        let history = vec![
20806            selection_activity_event("ActivityScheduled", 0, "slow", None),
20807            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
20808            selection_winner_marker(),
20809        ];
20810        let ctx = workflow_context(history.clone());
20811        let mut call = Box::pin(keyed_activity_selection(&ctx));
20812        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20813        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
20814            panic!("winner must replay");
20815        };
20816        let slow = selected
20817            .handle(&SelectionKey::Name("slow".to_string()))
20818            .expect("slow handle")
20819            .clone();
20820        let mut cancel = Box::pin(slow.cancel());
20821        assert!(matches!(
20822            cancel.as_mut().poll(&mut task_context),
20823            Poll::Ready(Ok(()))
20824        ));
20825        assert!(matches!(
20826            cancel.as_mut().poll(&mut task_context),
20827            Poll::Ready(Ok(()))
20828        ));
20829        let mut outcome = Box::pin(slow.await_result());
20830        assert!(matches!(
20831            outcome.as_mut().poll(&mut task_context),
20832            Poll::Pending
20833        ));
20834        let commands = ctx.take_commands().expect("cancel command");
20835        assert_eq!(commands.len(), 1);
20836        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
20837        assert_eq!(commands[0]["member_key"], json!("slow"));
20838
20839        let mut cancelled_history = history;
20840        cancelled_history.push(history_event(
20841            "SelectionOperationCancelled",
20842            json!({
20843                "selection_group_id": "select-calls:1:2",
20844                "member_key": "slow",
20845                "member_index": 0,
20846                "member_base_sequence": 1,
20847                "member_size": 1,
20848                "operation_kind": "activity",
20849                "operation_identity": "activity-slow",
20850                "cancelled_at": "2026-08-27T00:00:00Z",
20851            }),
20852        ));
20853        let replayed = workflow_context(cancelled_history);
20854        let mut call = Box::pin(keyed_activity_selection(&replayed));
20855        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
20856            panic!("winner must replay after cancellation");
20857        };
20858        let slow = selected
20859            .handle(&SelectionKey::Name("slow".to_string()))
20860            .expect("slow handle")
20861            .clone();
20862        let mut cancel = Box::pin(slow.cancel());
20863        assert!(matches!(
20864            cancel.as_mut().poll(&mut task_context),
20865            Poll::Ready(Ok(()))
20866        ));
20867        assert!(replayed.take_commands().expect("commands").is_empty());
20868    }
20869
20870    #[test]
20871    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
20872        let base_history = vec![
20873            selection_activity_event("ActivityScheduled", 0, "slow", None),
20874            selection_activity_event("ActivityScheduled", 1, "fast", None),
20875            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
20876            selection_winner_marker(),
20877        ];
20878        for (field, corrupt) in [
20879            ("member_key", json!("fast")),
20880            ("member_index", json!(1)),
20881            ("member_base_sequence", json!(3)),
20882            ("member_size", json!(2)),
20883            ("operation_kind", json!("timer")),
20884            ("operation_identity", json!("forged")),
20885        ] {
20886            let mut cancellation = json!({
20887                "selection_group_id": "select-calls:1:2",
20888                "member_key": "slow",
20889                "member_index": 0,
20890                "member_base_sequence": 1,
20891                "member_size": 1,
20892                "operation_kind": "activity",
20893                "operation_identity": "activity-slow",
20894            });
20895            cancellation[field] = corrupt;
20896            let mut history = base_history.clone();
20897            history.push(history_event("SelectionOperationCancelled", cancellation));
20898            let ctx = workflow_context(history);
20899            let mut selection = Box::pin(keyed_activity_selection(&ctx));
20900            let mut task_context = TaskContext::from_waker(noop_waker_ref());
20901
20902            assert!(matches!(
20903                selection.as_mut().poll(&mut task_context),
20904                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
20905            ));
20906        }
20907    }
20908
20909    #[test]
20910    fn selection_child_identity_prefers_the_durable_run_id() {
20911        let ctx = workflow_context(vec![history_event(
20912            "ChildWorkflowScheduled",
20913            json!({
20914                "sequence": 1,
20915                "child_workflow_type": "child",
20916                "child_workflow_instance_id": "child-instance",
20917                "child_workflow_run_id": "child-run",
20918            }),
20919        )]);
20920        let state = ctx.state.lock().expect("workflow state");
20921
20922        assert_eq!(
20923            selection_operation_identity(&state, "child", 1, 1),
20924            "child-run"
20925        );
20926    }
20927
20928    #[test]
20929    fn selection_activity_identity_requires_canonical_execution_id() {
20930        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
20931        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
20932        let mut fast_completed =
20933            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
20934        for event in [&mut fast_open, &mut fast_completed] {
20935            event
20936                .payload
20937                .as_object_mut()
20938                .expect("activity payload")
20939                .remove("activity_execution_id");
20940            event.payload["activity_id"] = json!("forged-activity-id");
20941        }
20942        let mut marker = selection_winner_marker();
20943        marker.payload["operation_identity"] = json!("forged-activity-id");
20944        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
20945        let mut selection = Box::pin(keyed_activity_selection(&ctx));
20946        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20947
20948        assert!(matches!(
20949            selection.as_mut().poll(&mut task_context),
20950            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
20951        ));
20952    }
20953
20954    #[test]
20955    fn selection_completion_before_cancellation_remains_awaitable() {
20956        let history = vec![
20957            selection_activity_event("ActivityScheduled", 0, "slow", None),
20958            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
20959            selection_winner_marker(),
20960            selection_activity_event(
20961                "ActivityCompleted",
20962                0,
20963                "slow",
20964                Some(json!("completed-first")),
20965            ),
20966        ];
20967        let ctx = workflow_context(history);
20968        let mut selection = Box::pin(keyed_activity_selection(&ctx));
20969        let mut task_context = TaskContext::from_waker(noop_waker_ref());
20970        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
20971            panic!("winner must replay");
20972        };
20973        let slow = selected
20974            .handle(&SelectionKey::Name("slow".to_string()))
20975            .expect("slow handle")
20976            .clone();
20977        let mut cancel = Box::pin(slow.cancel());
20978        assert!(matches!(
20979            cancel.as_mut().poll(&mut task_context),
20980            Poll::Ready(Ok(()))
20981        ));
20982        let mut await_slow = Box::pin(slow.await_result());
20983        assert!(matches!(
20984            await_slow.as_mut().poll(&mut task_context),
20985            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
20986        ));
20987        let commands = ctx.take_commands().expect("commands");
20988        assert!(commands.is_empty());
20989    }
20990
20991    #[test]
20992    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
20993        let nested_member = SelectionMemberMetadata {
20994            key: SelectionKey::Name("nested".to_string()),
20995            index: 0,
20996            base_sequence: 1,
20997            size: 2,
20998            kind: "group".to_string(),
20999        };
21000        let deadline_member = SelectionMemberMetadata {
21001            key: SelectionKey::Name("deadline".to_string()),
21002            index: 1,
21003            base_sequence: 3,
21004            size: 1,
21005            kind: "timer".to_string(),
21006        };
21007        let nested_paths = [
21008            vec![
21009                selection_group_entry(1, 3, 0, "mixed", &nested_member),
21010                parallel_group_entry(1, 2, 0, "activity"),
21011            ],
21012            vec![
21013                selection_group_entry(1, 3, 1, "mixed", &nested_member),
21014                parallel_group_entry(1, 2, 1, "activity"),
21015            ],
21016        ];
21017        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
21018        let mut timer_fired = parallel_history_event(
21019            "TimerFired",
21020            3,
21021            "timer_id",
21022            "timer-3",
21023            deadline_path.clone(),
21024            None,
21025        );
21026        timer_fired.payload["delay_seconds"] = json!(0);
21027        timer_fired
21028            .raw
21029            .insert("id".to_string(), json!("timer-fired"));
21030        let mut timer_scheduled = parallel_history_event(
21031            "TimerScheduled",
21032            3,
21033            "timer_id",
21034            "timer-3",
21035            deadline_path,
21036            None,
21037        );
21038        timer_scheduled.payload["delay_seconds"] = json!(0);
21039        let history = vec![
21040            parallel_history_event(
21041                "ActivityScheduled",
21042                1,
21043                "activity_type",
21044                "nested-first",
21045                nested_paths[0].clone(),
21046                None,
21047            ),
21048            parallel_history_event(
21049                "ActivityScheduled",
21050                2,
21051                "activity_type",
21052                "nested-second",
21053                nested_paths[1].clone(),
21054                None,
21055            ),
21056            timer_scheduled,
21057            timer_fired,
21058            history_event(
21059                "SelectionResolved",
21060                json!({
21061                    "selection_group_id": "select-calls:1:3",
21062                    "selection_group_base_sequence": 1,
21063                    "selection_group_size": 3,
21064                    "member_key": "deadline",
21065                    "member_index": 1,
21066                    "member_base_sequence": 3,
21067                    "member_size": 1,
21068                    "operation_kind": "timer",
21069                    "operation_identity": "timer-3",
21070                    "outcome": "completed",
21071                    "resolution_event_id": "timer-fired",
21072                    "resolution_event_type": "TimerFired",
21073                }),
21074            ),
21075            parallel_history_event(
21076                "ActivityFailed",
21077                2,
21078                "activity_type",
21079                "nested-second",
21080                nested_paths[1].clone(),
21081                None,
21082            ),
21083        ];
21084        let ctx = workflow_context(history);
21085        let mut selection = Box::pin(ctx.select_keyed(vec![
21086            (
21087                "nested",
21088                ParallelOperation::group(vec![
21089                    ParallelOperation::activity("nested-first", json!([])),
21090                    ParallelOperation::activity("nested-second", json!([])),
21091                ]),
21092            ),
21093            ("deadline", ParallelOperation::timer(Duration::ZERO)),
21094        ]));
21095        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21096        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
21097            panic!("deadline winner must replay");
21098        };
21099        let nested = selected
21100            .handle(&SelectionKey::Name("nested".to_string()))
21101            .expect("nested handle")
21102            .clone();
21103        let mut cancel = Box::pin(nested.cancel());
21104        assert!(matches!(
21105            cancel.as_mut().poll(&mut task_context),
21106            Poll::Ready(Ok(()))
21107        ));
21108        let mut await_nested = Box::pin(nested.await_result());
21109
21110        assert!(matches!(
21111            await_nested.as_mut().poll(&mut task_context),
21112            Poll::Ready(Err(Error::ActivityFailed(_)))
21113        ));
21114        assert!(ctx.take_commands().expect("commands").is_empty());
21115    }
21116
21117    #[test]
21118    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
21119        let ctx = workflow_context(Vec::new());
21120        let mut call = Box::pin(ctx.select(vec![
21121            ParallelOperation::child_workflow(
21122                "child",
21123                ChildWorkflowOptions::new("children"),
21124                json!([]),
21125            ),
21126            ParallelOperation::timer(Duration::from_secs(30)),
21127            ParallelOperation::signal("approval"),
21128            ParallelOperation::condition(
21129                ConditionWaitOptions::new("ready", "sha256:ready"),
21130                || Ok(false),
21131            ),
21132            ParallelOperation::group(vec![
21133                ParallelOperation::activity("nested-one", json!([])),
21134                ParallelOperation::activity("nested-two", json!([])),
21135            ]),
21136        ]));
21137        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21138        assert!(matches!(
21139            call.as_mut().poll(&mut task_context),
21140            Poll::Pending
21141        ));
21142        let commands = ctx.take_commands().expect("selection commands");
21143        assert_eq!(
21144            commands
21145                .iter()
21146                .map(|command| command["type"].as_str().unwrap_or_default())
21147                .collect::<Vec<_>>(),
21148            [
21149                "start_child_workflow",
21150                "start_timer",
21151                "open_signal_wait",
21152                "open_condition_wait",
21153                "schedule_activity",
21154                "schedule_activity",
21155            ]
21156        );
21157        assert!(commands.iter().all(|command| {
21158            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
21159        }));
21160        assert_eq!(
21161            commands[4]["parallel_group_path"].as_array().map(Vec::len),
21162            Some(2)
21163        );
21164        assert_eq!(
21165            commands[4]["parallel_group_path"][0]["selection_member_kind"],
21166            json!("group")
21167        );
21168        assert_eq!(
21169            commands[5]["parallel_group_path"][0]["selection_member_kind"],
21170            json!("group")
21171        );
21172
21173        let one_leaf_ctx = workflow_context(Vec::new());
21174        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
21175            ParallelOperation::activity("nested-only", json!([])),
21176        ])]));
21177        assert!(matches!(
21178            one_leaf.as_mut().poll(&mut task_context),
21179            Poll::Pending
21180        ));
21181        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
21182        assert_eq!(one_leaf_commands.len(), 1);
21183        assert_eq!(
21184            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
21185            json!("group")
21186        );
21187        assert_eq!(
21188            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
21189            json!(1)
21190        );
21191    }
21192
21193    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
21194        let mut saga = ctx.saga();
21195        let outcome = async {
21196            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
21197            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
21198            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
21199            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
21200            ctx.activity("trip.charge", json!([])).await?;
21201            Ok(json!({"status": "booked"}))
21202        }
21203        .await;
21204        saga.finish(outcome).await
21205    }
21206
21207    fn saga_activity(
21208        event_type: &str,
21209        sequence: u64,
21210        activity_type: &str,
21211        result: Option<Value>,
21212    ) -> HistoryEvent {
21213        let mut payload = json!({
21214            "sequence": sequence,
21215            "activity_type": activity_type,
21216            "message": format!("{activity_type} failed"),
21217            "exception_type": "PlannedFailure",
21218            "non_retryable": true,
21219        });
21220        if let Some(result) = result {
21221            payload["result"] = fixture_envelope(result);
21222        }
21223        history_event(event_type, payload)
21224    }
21225
21226    #[test]
21227    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
21228        let completed_hotel_compensation = saga_activity(
21229            "ActivityCompleted",
21230            4,
21231            "trip.cancel-hotel",
21232            Some(Value::Null),
21233        );
21234        let history = vec![
21235            saga_activity(
21236                "ActivityCompleted",
21237                1,
21238                "trip.reserve-flight",
21239                Some(json!("flight-1")),
21240            ),
21241            saga_activity(
21242                "ActivityCompleted",
21243                2,
21244                "trip.reserve-hotel",
21245                Some(json!("hotel-1")),
21246            ),
21247            saga_activity("ActivityFailed", 3, "trip.charge", None),
21248            completed_hotel_compensation.clone(),
21249            completed_hotel_compensation,
21250        ];
21251
21252        for _restart in 0..2 {
21253            let ctx = workflow_context(history.clone());
21254            let mut future = Box::pin(trip_saga(ctx.clone()));
21255            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21256            assert!(matches!(
21257                future.as_mut().poll(&mut task_context),
21258                Poll::Pending
21259            ));
21260            let commands = ctx.take_commands().expect("compensation command");
21261            assert_eq!(commands.len(), 1);
21262            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
21263        }
21264    }
21265
21266    #[test]
21267    fn saga_compensation_failure_preserves_both_typed_failures() {
21268        let history = vec![
21269            saga_activity(
21270                "ActivityCompleted",
21271                1,
21272                "trip.reserve-flight",
21273                Some(json!("flight-1")),
21274            ),
21275            saga_activity(
21276                "ActivityCompleted",
21277                2,
21278                "trip.reserve-hotel",
21279                Some(json!("hotel-1")),
21280            ),
21281            saga_activity("ActivityFailed", 3, "trip.charge", None),
21282            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
21283        ];
21284        let ctx = workflow_context(history);
21285        let mut future = Box::pin(trip_saga(ctx));
21286        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21287        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
21288            future.as_mut().poll(&mut task_context)
21289        else {
21290            panic!("compensation failure must remain structured");
21291        };
21292        assert!(matches!(
21293            *failure.initiating_failure,
21294            Error::ActivityFailed(_)
21295        ));
21296        assert!(matches!(
21297            *failure.compensation_failure,
21298            Error::ActivityFailed(_)
21299        ));
21300        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
21301        assert_eq!(failure.compensation_registration_order, 2);
21302    }
21303
21304    #[test]
21305    fn saga_compensates_cooperative_cancellation() {
21306        let ctx = workflow_context(vec![saga_activity(
21307            "ActivityCompleted",
21308            1,
21309            "trip.reserve-flight",
21310            Some(json!("flight-1")),
21311        )]);
21312        ctx.state.lock().expect("state").cancel_requested = true;
21313        let run = {
21314            let ctx = ctx.clone();
21315            async move {
21316                let mut saga = ctx.saga();
21317                let outcome = async {
21318                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
21319                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
21320                    ctx.throw_if_cancellation_requested()?;
21321                    Ok(json!("unexpected"))
21322                }
21323                .await;
21324                saga.finish(outcome).await
21325            }
21326        };
21327        let mut future = Box::pin(run);
21328        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21329        assert!(matches!(
21330            future.as_mut().poll(&mut task_context),
21331            Poll::Pending
21332        ));
21333        let commands = ctx.take_commands().expect("cancellation compensation");
21334        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
21335    }
21336
21337    #[test]
21338    fn optional_task_observability_fields_round_trip_without_interpretation() {
21339        let context = json!({"schema": "unknown", "carrier": {"traceparent": "untrusted"}});
21340        let dispatch = json!({"task_id": "other-task"});
21341        let links = json!({"links": []});
21342        let mut value = json!({
21343            "task_id": "task", "query_task_id": "query", "workflow_type": "workflow",
21344            "activity_type": "activity", "query_name": "query", "payload_codec": "avro"
21345        });
21346        let workflow: WorkflowTask =
21347            serde_json::from_value(value.clone()).expect("legacy workflow task");
21348        let activity: ActivityTask =
21349            serde_json::from_value(value.clone()).expect("legacy activity task");
21350        let query: QueryTask = serde_json::from_value(value.clone()).expect("legacy query task");
21351        assert!(workflow.observability_context.is_none());
21352        assert!(activity.observability_context.is_none());
21353        assert!(query.observability_context.is_none());
21354        assert!(activity.workflow_id.is_none());
21355        assert!(activity.run_id.is_none());
21356        assert!(activity.activity_execution_id.is_none());
21357
21358        value["observability_context"] = context.clone();
21359        value["dispatch_observability_context"] = dispatch.clone();
21360        value["observability_links"] = links.clone();
21361        value["workflow_id"] = json!("workflow-id");
21362        value["run_id"] = json!("run-id");
21363        value["activity_execution_id"] = json!("activity-id");
21364        let workflow: WorkflowTask =
21365            serde_json::from_value(value.clone()).expect("workflow metadata");
21366        let activity: ActivityTask =
21367            serde_json::from_value(value.clone()).expect("activity metadata");
21368        let query: QueryTask = serde_json::from_value(value).expect("query metadata");
21369        for fields in [
21370            (
21371                workflow.observability_context,
21372                workflow.dispatch_observability_context,
21373                workflow.observability_links,
21374            ),
21375            (
21376                activity.observability_context,
21377                activity.dispatch_observability_context,
21378                activity.observability_links,
21379            ),
21380            (
21381                query.observability_context,
21382                query.dispatch_observability_context,
21383                query.observability_links,
21384            ),
21385        ] {
21386            assert_eq!(
21387                fields,
21388                (
21389                    Some(context.clone()),
21390                    Some(dispatch.clone()),
21391                    Some(links.clone())
21392                )
21393            );
21394        }
21395        assert_eq!(activity.workflow_id.as_deref(), Some("workflow-id"));
21396        assert_eq!(activity.run_id.as_deref(), Some("run-id"));
21397        assert_eq!(
21398            activity.activity_execution_id.as_deref(),
21399            Some("activity-id")
21400        );
21401    }
21402
21403    fn workflow_task(
21404        workflow_type: &str,
21405        history_events: Vec<HistoryEvent>,
21406        payload_codec: &str,
21407    ) -> WorkflowTask {
21408        WorkflowTask {
21409            task_id: format!("wft-{workflow_type}"),
21410            observability_context: None,
21411            dispatch_observability_context: None,
21412            observability_links: None,
21413            workflow_command_id: None,
21414            workflow_id: Some(format!("wf-{workflow_type}")),
21415            run_id: Some(format!("run-{workflow_type}")),
21416            workflow_type: workflow_type.to_string(),
21417            cancel_requested: false,
21418            payload_codec: payload_codec.to_string(),
21419            arguments: Some(
21420                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
21421            ),
21422            total_history_events: Some(history_events.len() as u64),
21423            history_size_bytes: None,
21424            continue_as_new_recommended: None,
21425            history_budget_pressure: None,
21426            history_events,
21427            next_history_page_token: None,
21428            workflow_task_attempt: 1,
21429            workflow_signal_id: None,
21430            signal_name: None,
21431            signal_arguments: None,
21432            workflow_update_id: None,
21433            update_name: None,
21434            lease_owner: Some("rust-worker".to_string()),
21435        }
21436    }
21437
21438    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
21439    struct SideEffectProbe {
21440        request_id: String,
21441        attempt: u32,
21442    }
21443
21444    #[test]
21445    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
21446        let calls = AtomicUsize::new(0);
21447        let ctx = workflow_context(Vec::new());
21448        let value = ctx
21449            .side_effect(|| {
21450                calls.fetch_add(1, Ordering::SeqCst);
21451                SideEffectProbe {
21452                    request_id: "request-42".to_string(),
21453                    attempt: 3,
21454                }
21455            })
21456            .expect("first side effect");
21457        assert_eq!(value.attempt, 3);
21458        assert_eq!(calls.load(Ordering::SeqCst), 1);
21459        let commands = ctx.take_commands().expect("commands");
21460        assert_eq!(commands.len(), 1);
21461        assert_eq!(commands[0]["type"], "record_side_effect");
21462        assert_eq!(
21463            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
21464            serde_json::to_value(&value).expect("value")
21465        );
21466
21467        let replay = workflow_context(vec![history_event(
21468            "SideEffectRecorded",
21469            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
21470        )]);
21471        let replayed: SideEffectProbe = replay
21472            .side_effect(|| {
21473                calls.fetch_add(1, Ordering::SeqCst);
21474                panic!("committed side-effect callbacks must not run during replay")
21475            })
21476            .expect("replayed side effect");
21477        assert_eq!(replayed, value);
21478        assert_eq!(calls.load(Ordering::SeqCst), 1);
21479        assert!(replay.take_commands().expect("commands").is_empty());
21480        replay.ensure_history_consumed().expect("history consumed");
21481    }
21482
21483    #[test]
21484    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
21485        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
21486        let value = ctx
21487            .side_effect(|| SideEffectProbe {
21488                request_id: "avro-request".to_string(),
21489                attempt: 1,
21490            })
21491            .expect("Avro side effect");
21492        let uuid = ctx.uuid_v4().expect("deterministic UUID");
21493        let commands = ctx.take_commands().expect("commands");
21494        assert_eq!(commands.len(), 2);
21495        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
21496        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
21497        assert_eq!(
21498            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
21499            serde_json::to_value(&value).expect("value")
21500        );
21501
21502        let replay = workflow_context_with_codec(
21503            vec![
21504                history_event(
21505                    "SideEffectRecorded",
21506                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
21507                ),
21508                history_event(
21509                    "SideEffectRecorded",
21510                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
21511                ),
21512            ],
21513            DEFAULT_CODEC,
21514        );
21515        let replayed: SideEffectProbe = replay
21516            .side_effect(|| panic!("Avro callback must not run"))
21517            .expect("replayed Avro value");
21518        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
21519        assert_eq!(replayed, value);
21520        assert_eq!(replayed_uuid, uuid);
21521        assert!(replay.take_commands().expect("commands").is_empty());
21522    }
21523
21524    #[test]
21525    fn typed_side_effect_replay_preserves_bytes_and_maps() {
21526        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
21527        let value = ctx
21528            .side_effect_avro_value(typed_fidelity_probe)
21529            .expect("typed side effect");
21530        let commands = ctx.take_commands().expect("side-effect command");
21531        assert_eq!(
21532            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
21533                .expect("recorded side effect"),
21534            value
21535        );
21536
21537        let replay = workflow_context_with_codec(
21538            vec![history_event(
21539                "SideEffectRecorded",
21540                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
21541            )],
21542            DEFAULT_CODEC,
21543        );
21544        assert_eq!(
21545            replay
21546                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
21547                .expect("replayed typed side effect"),
21548            value
21549        );
21550    }
21551
21552    #[test]
21553    fn ordered_side_effects_share_the_durable_command_stream() {
21554        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
21555        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
21556        let ctx = workflow_context(vec![
21557            history_event(
21558                "SideEffectRecorded",
21559                json!({"sequence": 1, "result": first}),
21560            ),
21561            history_event(
21562                "SideEffectRecorded",
21563                json!({"sequence": 2, "result": second}),
21564            ),
21565        ]);
21566        let first: String = ctx
21567            .side_effect(|| panic!("first callback must not run"))
21568            .expect("first replay");
21569        let second: i32 = ctx
21570            .side_effect(|| panic!("second callback must not run"))
21571            .expect("second replay");
21572        assert_eq!(first, "first");
21573        assert_eq!(second, 29);
21574        ctx.ensure_history_consumed().expect("ordered history");
21575
21576        let reordered = workflow_context(vec![history_event(
21577            "VersionMarkerRecorded",
21578            json!({
21579                "sequence": 1,
21580                "change_id": "before-side-effect",
21581                "version": 1,
21582                "min_supported": 1,
21583                "max_supported": 1,
21584            }),
21585        )]);
21586        let error = reordered
21587            .side_effect(|| "new".to_string())
21588            .expect_err("command reordering must fail");
21589        assert!(matches!(
21590            error,
21591            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21592                if reason == "recorded_command_mismatch"
21593        ));
21594    }
21595
21596    #[test]
21597    fn legacy_patch_preserves_pending_and_completed_activity_history() {
21598        for completed in [false, true] {
21599            let mut history = vec![history_event(
21600                "ActivityScheduled",
21601                json!({"sequence": 1, "activity_type": "old"}),
21602            )];
21603            if completed {
21604                history.push(history_event(
21605                    "ActivityCompleted",
21606                    json!({
21607                        "sequence": 1,
21608                        "activity_type": "old",
21609                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
21610                    }),
21611                ));
21612            }
21613            for _cold_replay in 0..2 {
21614                let ctx = workflow_context(history.clone());
21615                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
21616                assert!(!ctx.patched("added-step").expect("same frozen decision"));
21617                ctx.deprecate_patch("added-step")
21618                    .expect("retained boundary");
21619                let mut activity = Box::pin(ctx.activity("old", json!([])));
21620                let mut context = TaskContext::from_waker(noop_waker_ref());
21621                match activity.as_mut().poll(&mut context) {
21622                    Poll::Ready(result) => {
21623                        assert!(completed);
21624                        assert_eq!(result.expect("recorded result"), json!(41));
21625                        ctx.ensure_history_consumed().expect("old command retained");
21626                    }
21627                    Poll::Pending => assert!(!completed),
21628                }
21629                assert!(ctx.take_commands().expect("commands").is_empty());
21630            }
21631        }
21632    }
21633
21634    #[test]
21635    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
21636        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
21637        assert!(!ctx.patched("added-step").expect("legacy completed run"));
21638        ctx.deprecate_patch("added-step")
21639            .expect("same legacy decision");
21640        assert!(ctx.take_commands().expect("commands").is_empty());
21641        ctx.ensure_history_consumed().expect("completed history");
21642    }
21643
21644    #[test]
21645    fn legacy_patch_rejects_a_range_without_the_original_branch() {
21646        let ctx = workflow_context(vec![history_event(
21647            "ActivityScheduled",
21648            json!({"sequence": 1, "activity_type": "old"}),
21649        )]);
21650        let error = ctx
21651            .get_version("added-step", 0, 1)
21652            .expect_err("legacy is unsupported");
21653        assert!(matches!(
21654            error,
21655            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21656                if reason == "version_marker_incompatible_range"
21657        ));
21658        assert!(!ctx
21659            .patched("supported-step")
21660            .expect("failed check did not consume history"));
21661        assert!(ctx.take_commands().expect("commands").is_empty());
21662    }
21663
21664    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
21665        let mut event = history_event(
21666            "VersionMarkerRecorded",
21667            json!({
21668                "sequence": sequence,
21669                "change_id": "retained-patch",
21670                "version": version,
21671                "min_supported": -1,
21672                "max_supported": 1,
21673            }),
21674        );
21675        event.raw.insert("timestamp".into(), json!(time));
21676        event
21677    }
21678
21679    #[test]
21680    fn retained_patch_markers_preserve_each_original_boundary() {
21681        for completed in [false, true] {
21682            let mut history = vec![
21683                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
21684                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
21685                history_event(
21686                    "ActivityScheduled",
21687                    json!({"sequence": 3, "activity_type": "old"}),
21688                ),
21689            ];
21690            if completed {
21691                history.push(history_event(
21692                    "ActivityCompleted",
21693                    json!({
21694                        "sequence": 3,
21695                        "activity_type": "old",
21696                        "result": fixture_envelope(json!(41)),
21697                    }),
21698                ));
21699            }
21700            for _cold_replay in 0..2 {
21701                let ctx = workflow_context(history.clone());
21702                assert!(ctx.patched("retained-patch").unwrap());
21703                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21704                assert!(ctx.patched("retained-patch").unwrap());
21705                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
21706                ctx.deprecate_patch("retained-patch").unwrap();
21707                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
21708                let mut activity = Box::pin(ctx.activity("old", json!([])));
21709                let mut context = TaskContext::from_waker(noop_waker_ref());
21710                match activity.as_mut().poll(&mut context) {
21711                    Poll::Ready(result) => {
21712                        assert!(completed);
21713                        assert_eq!(result.unwrap(), json!(41));
21714                        ctx.ensure_history_consumed().unwrap();
21715                    }
21716                    Poll::Pending => assert!(!completed),
21717                }
21718                assert!(ctx.take_commands().unwrap().is_empty());
21719                let state = ctx.state.lock().unwrap();
21720                for (actual, original) in state.history_events.iter().zip(&history) {
21721                    assert_eq!(actual.payload, original.payload);
21722                    assert_eq!(actual.raw, original.raw);
21723                }
21724            }
21725        }
21726    }
21727
21728    #[test]
21729    fn retained_patch_aliases_do_not_skip_intervening_operations() {
21730        let ctx = workflow_context(vec![
21731            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
21732            history_event(
21733                "SideEffectRecorded",
21734                json!({
21735                    "sequence": 2, "result": fixture_envelope(json!("between")),
21736                }),
21737            ),
21738            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
21739            history_event(
21740                "VersionMarkerRecorded",
21741                json!({
21742                    "sequence": 4, "change_id": "other-patch", "version": 1,
21743                    "min_supported": -1, "max_supported": 1,
21744                }),
21745            ),
21746        ]);
21747        assert!(ctx.patched("retained-patch").unwrap());
21748        assert!(ctx.patched("retained-patch").unwrap());
21749        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21750        assert_eq!(
21751            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
21752            "between"
21753        );
21754        ctx.deprecate_patch("retained-patch").unwrap();
21755        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
21756        ctx.deprecate_patch("retained-patch").unwrap();
21757        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
21758        assert!(ctx.patched("other-patch").unwrap());
21759        ctx.ensure_history_consumed().unwrap();
21760        assert!(ctx.take_commands().unwrap().is_empty());
21761    }
21762
21763    #[test]
21764    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
21765        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
21766        alias.payload["max_supported"] = json!(3);
21767        let ctx = workflow_context(vec![
21768            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
21769            alias,
21770        ]);
21771        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
21772        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
21773        assert!(matches!(error,
21774            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21775                if reason == "version_marker_incompatible_range"));
21776        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
21777        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
21778        ctx.ensure_history_consumed().unwrap();
21779        assert!(ctx.take_commands().unwrap().is_empty());
21780    }
21781
21782    #[test]
21783    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
21784        let ctx = workflow_context(Vec::new());
21785        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
21786        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
21787        assert!(ctx.patched("new-search").expect("patch"));
21788        ctx.deprecate_patch("new-search").expect("deprecate patch");
21789        let commands = ctx.take_commands().expect("commands");
21790        assert_eq!(commands.len(), 2);
21791        assert_eq!(commands[0]["type"], "record_version_marker");
21792        assert_eq!(commands[0]["version"], 2);
21793        assert_eq!(commands[1]["change_id"], "new-search");
21794
21795        let replay = workflow_context(vec![history_event(
21796            "VersionMarkerRecorded",
21797            json!({
21798                "sequence": 1,
21799                "change_id": "checkout-v2",
21800                "version": 2,
21801                "min_supported": 1,
21802                "max_supported": 2,
21803            }),
21804        )]);
21805        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
21806        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
21807        assert!(replay.take_commands().expect("commands").is_empty());
21808        replay.ensure_history_consumed().expect("history consumed");
21809    }
21810
21811    #[test]
21812    fn version_markers_reject_incompatible_or_malformed_history() {
21813        let incompatible = workflow_context(vec![history_event(
21814            "VersionMarkerRecorded",
21815            json!({
21816                "sequence": 1,
21817                "change_id": "checkout-v2",
21818                "version": 1,
21819                "min_supported": 1,
21820                "max_supported": 2,
21821            }),
21822        )]);
21823        let error = incompatible
21824            .get_version("checkout-v2", 2, 3)
21825            .expect_err("old version is unsupported");
21826        assert!(matches!(
21827            error,
21828            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
21829                if reason == "version_marker_incompatible_range"
21830        ));
21831
21832        for (history, reason) in [
21833            (
21834                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
21835                "side_effect_result_missing",
21836            ),
21837            (
21838                vec![history_event(
21839                    "SideEffectRecorded",
21840                    json!({
21841                        "sequence": 1,
21842                        "result": {"codec": "avro", "blob": "not-base64"},
21843                    }),
21844                )],
21845                "side_effect_payload_incompatible",
21846            ),
21847            (
21848                vec![history_event(
21849                    "SideEffectRecorded",
21850                    json!({"sequence": 1, "result": {"unwrapped": true}}),
21851                )],
21852                "side_effect_payload_malformed",
21853            ),
21854            (
21855                vec![history_event(
21856                    "VersionMarkerRecorded",
21857                    json!({
21858                        "sequence": 1,
21859                        "change_id": "change",
21860                        "version": 1,
21861                        "min_supported": 2,
21862                        "max_supported": 1,
21863                    }),
21864                )],
21865                "version_marker_history_range_invalid",
21866            ),
21867        ] {
21868            let error = WorkflowState::new(
21869                history,
21870                "rust-workers".to_string(),
21871                DEFAULT_CODEC.to_string(),
21872                None,
21873            )
21874            .expect_err("malformed history must fail");
21875            assert!(matches!(
21876                error,
21877                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
21878                    if actual == reason
21879            ));
21880        }
21881    }
21882
21883    #[test]
21884    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
21885        let history = vec![history_event(
21886            "SearchAttributesUpserted",
21887            json!({
21888                "sequence": 1,
21889                "attributes": {"customer_tier": "gold"},
21890                "attribute_types": {"customer_tier": "keyword"},
21891                "merged": {"customer_tier": "gold"}
21892            }),
21893        )];
21894
21895        let matching = workflow_context(history.clone());
21896        matching
21897            .upsert_search_attributes(
21898                SearchAttributeUpdate::new()
21899                    .keyword("customer_tier", "gold")
21900                    .expect("keyword update"),
21901            )
21902            .expect("matching typed update must replay");
21903        matching
21904            .ensure_history_consumed()
21905            .expect("history consumed");
21906
21907        let changed_type = workflow_context(history.clone());
21908        let error = changed_type
21909            .upsert_search_attributes(
21910                SearchAttributeUpdate::new()
21911                    .string("customer_tier", "gold")
21912                    .expect("string update"),
21913            )
21914            .expect_err("same JSON value with a different declaration must be nondeterministic");
21915        let Error::NonDeterministicReplay(failure) = error else {
21916            panic!("typed identity drift must be a replay failure");
21917        };
21918        assert_eq!(failure.reason, "search_attribute_type_mismatch");
21919        assert_eq!(failure.sequence, Some(1));
21920
21921        let changed_value = workflow_context(history);
21922        let error = changed_value
21923            .upsert_search_attributes(
21924                SearchAttributeUpdate::new()
21925                    .keyword("customer_tier", "platinum")
21926                    .expect("keyword update"),
21927            )
21928            .expect_err("changed values must be nondeterministic");
21929        let Error::NonDeterministicReplay(failure) = error else {
21930            panic!("value drift must be a replay failure");
21931        };
21932        assert_eq!(failure.reason, "search_attribute_value_mismatch");
21933    }
21934
21935    #[test]
21936    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
21937        let history = vec![history_event(
21938            "SearchAttributesUpserted",
21939            json!({
21940                "sequence": 1,
21941                "attributes": {"customer_tier": "gold"},
21942                "merged": {"customer_tier": "gold"}
21943            }),
21944        )];
21945
21946        for update in [
21947            SearchAttributeUpdate::new()
21948                .keyword("customer_tier", "gold")
21949                .expect("keyword update"),
21950            SearchAttributeUpdate::new()
21951                .string("customer_tier", "gold")
21952                .expect("string update"),
21953        ] {
21954            let restarted = workflow_context(history.clone());
21955            restarted
21956                .upsert_search_attributes(update)
21957                .expect("legacy history constrains values but has unknown type identity");
21958            restarted
21959                .ensure_history_consumed()
21960                .expect("history consumed");
21961        }
21962    }
21963
21964    #[test]
21965    fn search_attribute_command_emits_canonical_types() {
21966        let ctx = workflow_context(Vec::new());
21967        ctx.upsert_search_attributes(
21968            SearchAttributeUpdate::new()
21969                .keyword("customer_tier", "gold")
21970                .expect("keyword update")
21971                .int("attempts", 3)
21972                .expect("int update")
21973                .delete("obsolete")
21974                .expect("delete update"),
21975        )
21976        .expect("valid search attributes");
21977
21978        assert_eq!(
21979            ctx.take_commands().expect("commands"),
21980            vec![json!({
21981                "type": "upsert_search_attributes",
21982                "attributes": {
21983                    "attempts": 3,
21984                    "customer_tier": "gold",
21985                    "obsolete": null
21986                },
21987                "attribute_types": {
21988                    "attempts": "int",
21989                    "customer_tier": "keyword"
21990                }
21991            })]
21992        );
21993    }
21994
21995    #[test]
21996    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
21997        let duplicate_side_effect = WorkflowState::new(
21998            vec![
21999                history_event(
22000                    "SideEffectRecorded",
22001                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
22002                ),
22003                history_event(
22004                    "SideEffectRecorded",
22005                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
22006                ),
22007            ],
22008            "rust-workers".to_string(),
22009            DEFAULT_CODEC.to_string(),
22010            None,
22011        )
22012        .expect_err("duplicate side effect");
22013        assert!(matches!(
22014            duplicate_side_effect,
22015            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22016                if reason == "duplicate_side_effect_record"
22017        ));
22018
22019        let marker = |sequence, version| {
22020            history_event(
22021                "VersionMarkerRecorded",
22022                json!({
22023                    "sequence": sequence,
22024                    "change_id": "same-change",
22025                    "version": version,
22026                    "min_supported": -1,
22027                    "max_supported": 1,
22028                }),
22029            )
22030        };
22031        let duplicate_marker = WorkflowState::new(
22032            vec![marker(1, 1), marker(3, -1)],
22033            "rust-workers".to_string(),
22034            DEFAULT_CODEC.to_string(),
22035            None,
22036        )
22037        .expect_err("conflicting marker");
22038        assert!(matches!(
22039            duplicate_marker,
22040            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22041                if reason == "version_marker_conflict"
22042        ));
22043    }
22044
22045    #[test]
22046    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
22047        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
22048        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
22049        invalid_alias.payload["max_supported"] = json!(0);
22050        for (history, expected_reason) in [
22051            (
22052                vec![marker.clone(), marker.clone()],
22053                "duplicate_version_marker_record",
22054            ),
22055            (
22056                vec![marker, invalid_alias],
22057                "version_marker_history_range_invalid",
22058            ),
22059        ] {
22060            let error =
22061                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
22062                    .expect_err("invalid historical alias");
22063            assert!(matches!(error,
22064                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
22065                    if reason == expected_reason));
22066        }
22067    }
22068
22069    #[test]
22070    fn retained_patch_aliases_require_the_original_call_boundary() {
22071        let ctx = workflow_context(vec![
22072            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
22073            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
22074        ]);
22075        assert!(ctx.patched("retained-patch").unwrap());
22076        assert!(ctx.ensure_history_consumed().is_err());
22077        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
22078        ctx.deprecate_patch("retained-patch").unwrap();
22079        ctx.ensure_history_consumed().unwrap();
22080        assert!(ctx.take_commands().unwrap().is_empty());
22081    }
22082
22083    #[test]
22084    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
22085        let ctx = workflow_context(vec![
22086            history_event(
22087                "SideEffectRecorded",
22088                json!({
22089                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
22090                }),
22091            ),
22092            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
22093        ]);
22094        assert!(!ctx.patched("retained-patch").unwrap());
22095        assert_eq!(
22096            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
22097            "old-operation"
22098        );
22099        let error = ctx.patched("retained-patch").unwrap_err();
22100        assert!(matches!(error,
22101            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22102                if reason == "version_marker_conflict"));
22103        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
22104        assert!(ctx.take_commands().unwrap().is_empty());
22105    }
22106
22107    #[test]
22108    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
22109        let mut state = WorkflowState::new(
22110            Vec::new(),
22111            "rust-workers".to_string(),
22112            DEFAULT_CODEC.to_string(),
22113            None,
22114        )
22115        .expect("workflow state");
22116        state.workflow_command_identity = "command-7".to_string();
22117        let context = WorkflowContext {
22118            state: Arc::new(Mutex::new(state)),
22119            cancellation_scope_id: "root".into(),
22120        };
22121        let item =
22122            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
22123
22124        context
22125            .append_workflow_stream("output", &[item], Some(10))
22126            .expect("append command");
22127        context
22128            .error_workflow_stream("output", "producer failed", None)
22129            .expect("error command");
22130        let commands = context.take_commands().expect("commands");
22131
22132        assert_eq!(commands[0]["type"], "record_side_effect");
22133        assert_eq!(
22134            commands[0]["workflow_stream"]["command_identity"],
22135            "command-7"
22136        );
22137        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
22138        assert_eq!(
22139            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
22140            "dw-stream:command-7:0:0"
22141        );
22142        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
22143
22144        let recorded = history_event(
22145            "SideEffectRecorded",
22146            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
22147        );
22148        let mut replay_state = WorkflowState::new(
22149            vec![recorded],
22150            "rust-workers".to_string(),
22151            DEFAULT_CODEC.to_string(),
22152            None,
22153        )
22154        .expect("replay state");
22155        replay_state.workflow_command_identity = "command-7".to_string();
22156        let replay_context = WorkflowContext {
22157            state: Arc::new(Mutex::new(replay_state)),
22158            cancellation_scope_id: "root".into(),
22159        };
22160        replay_context
22161            .append_workflow_stream(
22162                "output",
22163                &[WorkflowStreamAppendItem::from_reference(
22164                    "s3://bucket/item.avro",
22165                )],
22166                Some(10),
22167            )
22168            .expect("replayed append");
22169        assert!(replay_context
22170            .take_commands()
22171            .expect("replayed commands")
22172            .is_empty());
22173    }
22174
22175    #[test]
22176    fn workflow_stream_authoring_requires_server_durable_command_identity() {
22177        let context = workflow_context(Vec::new());
22178        let error = context
22179            .append_workflow_stream(
22180                "output",
22181                &[WorkflowStreamAppendItem::from_reference(
22182                    "s3://bucket/item.avro",
22183                )],
22184                None,
22185            )
22186            .expect_err("stream append without durable command identity must fail closed");
22187
22188        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
22189        assert!(context.take_commands().expect("commands").is_empty());
22190    }
22191
22192    #[test]
22193    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
22194        let client = Client::builder("http://localhost:8080").build().unwrap();
22195        let mut worker = Worker::new(client, "rust-workers");
22196        worker.register_workflow("streams.worker", |ctx, _| async move {
22197            ctx.append_workflow_stream(
22198                "output",
22199                &[WorkflowStreamAppendItem::new(json!("hello"))?],
22200                None,
22201            )?;
22202            ctx.close_workflow_stream("output", None)?;
22203            Ok(json!("done"))
22204        });
22205        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
22206            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
22207            task.workflow_command_id = command_id.clone();
22208            let expected_identity = command_id
22209                .as_deref()
22210                .filter(|id| !id.is_empty())
22211                .unwrap_or(&task.task_id)
22212                .to_string();
22213            let commands = worker
22214                .execute_workflow_task(task)
22215                .expect("ordinary worker stream output");
22216            assert_eq!(commands.len(), 3);
22217            assert_eq!(
22218                commands[0]["workflow_stream"]["command_identity"],
22219                expected_identity
22220            );
22221            assert_eq!(
22222                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
22223                format!("dw-stream:{expected_identity}:0:0")
22224            );
22225            assert_eq!(
22226                commands[1]["workflow_stream"]["command_identity"],
22227                expected_identity
22228            );
22229            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
22230            let history = commands[..2]
22231                .iter()
22232                .enumerate()
22233                .map(|(index, command)| {
22234                    history_event(
22235                        "SideEffectRecorded",
22236                        json!({"sequence":index + 1,"result":command["result"]}),
22237                    )
22238                })
22239                .collect();
22240            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
22241            replay.task_id = "replacement-task".to_string();
22242            let replayed = worker
22243                .execute_workflow_task(replay)
22244                .expect("replacement worker consumes recorded stream effects");
22245            assert_eq!(replayed.len(), 1);
22246            assert_eq!(replayed[0]["type"], "complete_workflow");
22247        }
22248        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
22249        missing.task_id.clear();
22250        assert!(matches!(
22251            worker.execute_workflow_task(missing),
22252            Err(Error::MissingWorkflowCommandIdentity)
22253        ));
22254    }
22255
22256    #[test]
22257    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
22258        fn worker(calls: Arc<AtomicUsize>) -> Worker {
22259            let client = Client::new("http://127.0.0.1:8080").expect("client");
22260            let mut worker = Worker::new(client, "rust-workers");
22261            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
22262                let calls = Arc::clone(&calls);
22263                async move {
22264                    let captured = ctx.side_effect(|| {
22265                        calls.fetch_add(1, Ordering::SeqCst);
22266                        "captured-once".to_string()
22267                    })?;
22268                    let version = ctx.get_version("cold-restart", 1, 2)?;
22269                    Ok(json!({"captured": captured, "version": version}))
22270                }
22271            });
22272            worker
22273        }
22274
22275        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
22276            WorkflowTask {
22277                task_id: "wft-side-effect-version".to_string(),
22278                observability_context: None,
22279                dispatch_observability_context: None,
22280                observability_links: None,
22281                workflow_command_id: None,
22282                workflow_id: Some("wf-side-effect-version".to_string()),
22283                run_id: Some("run-side-effect-version".to_string()),
22284                workflow_type: "rust.side-effect-version".to_string(),
22285                cancel_requested: false,
22286                payload_codec: DEFAULT_CODEC.to_string(),
22287                arguments: Some(
22288                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
22289                ),
22290                history_events,
22291                total_history_events: None,
22292                history_size_bytes: None,
22293                continue_as_new_recommended: None,
22294                history_budget_pressure: None,
22295                next_history_page_token: None,
22296                workflow_task_attempt: 1,
22297                workflow_signal_id: None,
22298                signal_name: None,
22299                signal_arguments: None,
22300                workflow_update_id: None,
22301                update_name: None,
22302                lease_owner: Some("rust-worker".to_string()),
22303            }
22304        }
22305
22306        let calls = Arc::new(AtomicUsize::new(0));
22307        let initial = worker(Arc::clone(&calls))
22308            .execute_workflow_task(task(Vec::new()))
22309            .expect("initial execution");
22310        assert_eq!(
22311            initial
22312                .iter()
22313                .map(|command| &command["type"])
22314                .collect::<Vec<_>>(),
22315            vec![
22316                "record_side_effect",
22317                "record_version_marker",
22318                "complete_workflow"
22319            ]
22320        );
22321        assert_eq!(calls.load(Ordering::SeqCst), 1);
22322
22323        let restarted = worker(Arc::clone(&calls));
22324        let replayed = restarted
22325            .execute_workflow_task(task(vec![
22326                history_event(
22327                    "SideEffectRecorded",
22328                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
22329                ),
22330                history_event(
22331                    "VersionMarkerRecorded",
22332                    json!({
22333                        "sequence": 2,
22334                        "change_id": "cold-restart",
22335                        "version": 2,
22336                        "min_supported": 1,
22337                        "max_supported": 2,
22338                    }),
22339                ),
22340            ]))
22341            .expect("cold replay");
22342        assert_eq!(replayed.len(), 1);
22343        assert_eq!(replayed[0]["type"], "complete_workflow");
22344        assert_eq!(calls.load(Ordering::SeqCst), 1);
22345    }
22346
22347    #[test]
22348    fn side_effect_replay_rejects_changed_rust_value_type() {
22349        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
22350        let ctx = workflow_context(vec![history_event(
22351            "SideEffectRecorded",
22352            json!({"sequence": 1, "result": result}),
22353        )]);
22354        let error = ctx
22355            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
22356            .expect_err("changed type must fail replay");
22357        assert!(matches!(
22358            error,
22359            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22360                if reason == "side_effect_type_mismatch"
22361        ));
22362    }
22363
22364    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
22365        vec![
22366            history_event(
22367                "ActivityScheduled",
22368                json!({
22369                    "sequence": 1,
22370                    "activity_type": "flaky",
22371                    "activity_execution_id": "act-1",
22372                    "activity": {
22373                        "id": "act-1",
22374                        "sequence": 1,
22375                        "type": "flaky",
22376                        "queue": "critical-activities",
22377                        "execution_mode": null,
22378                        "retry_policy": {
22379                            "snapshot_version": 1,
22380                            "max_attempts": 3,
22381                            "backoff_seconds": [2, 4],
22382                            "start_to_close_timeout": 30,
22383                            "schedule_to_start_timeout": 5,
22384                            "schedule_to_close_timeout": 90,
22385                            "heartbeat_timeout": 10,
22386                            "non_retryable_error_types": ["PermanentError"]
22387                        }
22388                    }
22389                }),
22390            ),
22391            history_event(
22392                "ActivityStarted",
22393                json!({
22394                    "sequence": 1,
22395                    "activity_type": "flaky",
22396                    "activity_execution_id": "act-1",
22397                    "activity_attempt_id": "attempt-1",
22398                    "attempt_number": 1
22399                }),
22400            ),
22401            history_event(
22402                "ActivityRetryScheduled",
22403                json!({
22404                    "sequence": 1,
22405                    "activity_type": "flaky",
22406                    "activity_execution_id": "act-1",
22407                    "activity_attempt_id": "attempt-1",
22408                    "attempt_number": 1,
22409                    "retry_after_attempt": 1,
22410                    "retry_backoff_seconds": 2,
22411                    "failure_category": "activity",
22412                    "exception_type": "TransientError"
22413                }),
22414            ),
22415            history_event(
22416                "ActivityStarted",
22417                json!({
22418                    "sequence": 1,
22419                    "activity_type": "flaky",
22420                    "activity_execution_id": "act-1",
22421                    "activity_attempt_id": "attempt-2",
22422                    "attempt_number": 2
22423                }),
22424            ),
22425            history_event(
22426                "ActivityCompleted",
22427                json!({
22428                    "sequence": 1,
22429                    "activity_type": "flaky",
22430                    "activity_execution_id": "act-1",
22431                    "activity_attempt_id": "attempt-2",
22432                    "attempt_number": 2,
22433                    "payload_codec": DEFAULT_CODEC,
22434                    "result": fixture_envelope(json!({"status":"recovered"}))
22435                }),
22436            ),
22437        ]
22438    }
22439
22440    fn retry_activity_options() -> ActivityOptions {
22441        ActivityOptions::new()
22442            .task_queue("critical-activities")
22443            .retry_policy(
22444                ActivityRetryPolicy::new(3)
22445                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
22446                    .non_retryable_error_type("PermanentError"),
22447            )
22448            .start_to_close_timeout(Duration::from_secs(30))
22449            .schedule_to_start_timeout(Duration::from_secs(5))
22450            .schedule_to_close_timeout(Duration::from_secs(90))
22451            .heartbeat_timeout(Duration::from_secs(10))
22452    }
22453
22454    #[test]
22455    fn fixed_avro_value_round_trips_json_values() {
22456        let value = json!({"greeting": "hello", "count": 3, "ok": true});
22457        let envelope = PayloadEnvelope::avro(&value).expect("encode");
22458        assert_eq!(envelope.codec, DEFAULT_CODEC);
22459        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
22460    }
22461
22462    #[tokio::test]
22463    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
22464        let client = Client::new("http://127.0.0.1:8080").expect("client");
22465        let mut worker = Worker::new(client, "rust-workers");
22466        worker.register_typed_workflow(
22467            "typed.contract.workflow",
22468            |_ctx, input: TypedContract| async move { Ok(input) },
22469        );
22470        worker.register_typed_activity(
22471            "typed.contract.activity",
22472            |_ctx, input: TypedContract| async move { Ok(input) },
22473        );
22474
22475        let expected = typed_contract();
22476        let arguments = AvroValue::Array(vec![
22477            AvroValue::from_serialize(&expected).expect("typed request")
22478        ]);
22479        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
22480        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
22481        workflow.arguments = Some(envelope.clone());
22482        let commands = worker
22483            .execute_workflow_task(workflow)
22484            .expect("typed workflow task");
22485        let workflow_result: TypedContract =
22486            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22487                .expect("workflow result envelope")
22488                .deserialize()
22489                .expect("workflow result type");
22490        assert_eq!(workflow_result, expected);
22491
22492        let activity = ActivityTask {
22493            task_id: "typed-contract-activity".to_string(),
22494            workflow_id: None,
22495            run_id: None,
22496            activity_execution_id: None,
22497            observability_context: None,
22498            dispatch_observability_context: None,
22499            observability_links: None,
22500            activity_attempt_id: Some("typed-contract-attempt".to_string()),
22501            attempt_id: None,
22502            activity_type: "typed.contract.activity".to_string(),
22503            payload_codec: DEFAULT_CODEC.to_string(),
22504            arguments: Some(envelope),
22505            attempt_number: 1,
22506            lease_owner: Some("rust-worker".to_string()),
22507        };
22508        let activity_result: TypedContract = worker
22509            .execute_activity_task(activity)
22510            .await
22511            .expect("typed activity task")
22512            .deserialize()
22513            .expect("activity result type");
22514        assert_eq!(activity_result, expected);
22515    }
22516
22517    #[test]
22518    fn typed_entry_mismatch_refuses_before_body_and_preserves_original_input() {
22519        let calls = Arc::new(AtomicUsize::new(0));
22520        let observed = Arc::clone(&calls);
22521        let client = Client::new("http://127.0.0.1:8080").expect("client");
22522        let mut worker = Worker::new(client.clone(), "rust-workers");
22523        worker.register_typed_workflow("entry.safe", move |_ctx, input: i64| {
22524            observed.fetch_add(1, Ordering::SeqCst);
22525            async move { Ok(input) }
22526        });
22527        let mut task = workflow_task("entry.safe", Vec::new(), DEFAULT_CODEC);
22528        task.arguments = Some(fixture_envelope(json!(["private-original-value"])));
22529        let original = task.clone();
22530        let error = worker
22531            .execute_workflow_task(task)
22532            .expect_err("incompatible entry must refuse the task, not fail the run");
22533        assert_eq!(calls.load(Ordering::SeqCst), 0);
22534        assert!(error
22535            .to_string()
22536            .contains("workflow_entry_arguments_mismatch:"));
22537        assert!(!error.to_string().contains("private-original-value"));
22538
22539        let mut compatible = Worker::new(client, "rust-workers");
22540        compatible
22541            .register_typed_workflow("entry.safe", |_ctx, input: String| async move { Ok(input) });
22542        let commands = compatible
22543            .execute_workflow_task(original)
22544            .expect("same recorded input");
22545        assert_eq!(commands[0]["type"], "complete_workflow");
22546        assert_eq!(
22547            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).unwrap(),
22548            json!("private-original-value")
22549        );
22550    }
22551
22552    #[test]
22553    fn typed_entry_replayed_mismatch_refuses_before_state_factory_and_body() {
22554        let factories = Arc::new(AtomicUsize::new(0));
22555        let observed = Arc::clone(&factories);
22556        let client = Client::new("http://127.0.0.1:8080").expect("client");
22557        let mut worker = Worker::new(client, "rust-workers");
22558        worker.register_typed_replayed_workflow(
22559            "entry.replayed",
22560            move || {
22561                observed.fetch_add(1, Ordering::SeqCst);
22562                ()
22563            },
22564            |_ctx, _input: i64, _state| async move {
22565                panic!("body must not start");
22566                #[allow(unreachable_code)]
22567                Ok(0_i64)
22568            },
22569        );
22570        let mut task = workflow_task("entry.replayed", Vec::new(), DEFAULT_CODEC);
22571        task.arguments = Some(fixture_envelope(json!(["private-replayed-value"])));
22572        let error = worker
22573            .execute_workflow_task(task)
22574            .expect_err("entry refusal");
22575        assert_eq!(factories.load(Ordering::SeqCst), 0);
22576        assert!(error
22577            .to_string()
22578            .contains("workflow_entry_arguments_mismatch:"));
22579        assert!(!error.to_string().contains("private-replayed-value"));
22580
22581        let replay = worker.workflows["entry.replayed"].replay.as_ref().unwrap();
22582        let Err(error) = replay(
22583            workflow_context(Vec::new()),
22584            AvroValue::Array(vec![AvroValue::String("private-replayed-value".into())]),
22585        ) else {
22586            panic!("query replay must refuse before creating application state");
22587        };
22588        assert_eq!(factories.load(Ordering::SeqCst), 0);
22589        assert!(!error.to_string().contains("private-replayed-value"));
22590    }
22591
22592    #[test]
22593    fn typed_entry_deserializes_once_before_entering_application_code() {
22594        static DECODES: AtomicUsize = AtomicUsize::new(0);
22595        struct Counted(i64);
22596        impl<'de> Deserialize<'de> for Counted {
22597            fn deserialize<D: Deserializer<'de>>(
22598                deserializer: D,
22599            ) -> std::result::Result<Self, D::Error> {
22600                DECODES.fetch_add(1, Ordering::SeqCst);
22601                i64::deserialize(deserializer).map(Self)
22602            }
22603        }
22604        DECODES.store(0, Ordering::SeqCst);
22605        let client = Client::new("http://127.0.0.1:8080").expect("client");
22606        let mut worker = Worker::new(client, "rust-workers");
22607        worker.register_typed_workflow(
22608            "entry.once",
22609            |_ctx, input: Counted| async move { Ok(input.0) },
22610        );
22611        let mut task = workflow_task("entry.once", Vec::new(), DEFAULT_CODEC);
22612        task.arguments = Some(fixture_envelope(json!([7])));
22613        let commands = worker.execute_workflow_task(task).expect("typed result");
22614        assert_eq!(commands[0]["type"], "complete_workflow");
22615        assert_eq!(DECODES.load(Ordering::SeqCst), 1);
22616    }
22617
22618    #[test]
22619    fn typed_entry_body_input_error_remains_a_business_failure() {
22620        let client = Client::new("http://127.0.0.1:8080").expect("client");
22621        let mut worker = Worker::new(client, "rust-workers");
22622        worker.register_typed_workflow("entry.body", |_ctx, _input: i64| async move {
22623            Err::<i64, _>(handler_type_error::<i64>(
22624                HandlerKind::Workflow,
22625                "entry.body",
22626                HandlerValueKind::Input,
22627                "deliberate body error",
22628            ))
22629        });
22630        let mut task = workflow_task("entry.body", Vec::new(), DEFAULT_CODEC);
22631        task.arguments = Some(fixture_envelope(json!([7])));
22632        let commands = worker
22633            .execute_workflow_task(task)
22634            .expect("business failure command");
22635        assert_eq!(commands[0]["type"], "fail_workflow");
22636        assert!(commands[0]["message"]
22637            .as_str()
22638            .unwrap()
22639            .contains("deliberate body error"));
22640    }
22641
22642    #[test]
22643    fn typed_entry_body_cannot_claim_the_adapter_refusal() {
22644        let client = Client::new("http://127.0.0.1:8080").expect("client");
22645        let mut worker = Worker::new(client, "rust-workers");
22646        worker.register_typed_workflow("entry.body.refusal", |_ctx, _input: i64| async move {
22647            Err::<i64, _>(handler_type_error::<i64>(
22648                HandlerKind::Workflow,
22649                "entry.body.refusal",
22650                HandlerValueKind::Input,
22651                "workflow_entry_arguments_mismatch: deliberate body error",
22652            ))
22653        });
22654        let mut task = workflow_task("entry.body.refusal", Vec::new(), DEFAULT_CODEC);
22655        task.arguments = Some(fixture_envelope(json!([7])));
22656        let commands = worker
22657            .execute_workflow_task(task)
22658            .expect("business failure");
22659        assert_eq!(commands[0]["type"], "fail_workflow");
22660    }
22661
22662    #[tokio::test]
22663    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
22664        let client = Client::new("http://127.0.0.1:8080").expect("client");
22665        let mut worker = Worker::new(client, "rust-workers");
22666        worker.register_typed_workflow(
22667            "typed.shape.workflow",
22668            |_ctx, input: TypedContract| async move { Ok(input) },
22669        );
22670        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
22671            Ok(f64::NAN)
22672        });
22673
22674        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
22675        workflow.arguments = Some(
22676            encode_typed_envelope(
22677                &AvroValue::Array(vec![
22678                    AvroValue::String("first".to_string()),
22679                    AvroValue::String("second".to_string()),
22680                ]),
22681                DEFAULT_CODEC,
22682            )
22683            .expect("malformed typed arguments"),
22684        );
22685        let error = worker
22686            .execute_workflow_task(workflow)
22687            .expect_err("entry shape mismatch refuses the task");
22688        let message = error.to_string();
22689        assert!(message.contains("workflow_entry_arguments_mismatch:"));
22690        assert!(message.contains("typed.shape.workflow"));
22691        assert!(message.contains(type_name::<TypedContract>()));
22692
22693        let activity = ActivityTask {
22694            task_id: "typed-unsupported-activity".to_string(),
22695            workflow_id: None,
22696            run_id: None,
22697            activity_execution_id: None,
22698            observability_context: None,
22699            dispatch_observability_context: None,
22700            observability_links: None,
22701            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
22702            attempt_id: None,
22703            activity_type: "typed.unsupported.activity".to_string(),
22704            payload_codec: DEFAULT_CODEC.to_string(),
22705            arguments: Some(
22706                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
22707                    .expect("unit arguments"),
22708            ),
22709            attempt_number: 1,
22710            lease_owner: Some("rust-worker".to_string()),
22711        };
22712        let Error::HandlerType {
22713            handler_kind,
22714            handler_name,
22715            value_kind,
22716            rust_type,
22717            message,
22718        } = worker
22719            .execute_activity_task(activity)
22720            .await
22721            .expect_err("non-finite handler output must fail")
22722        else {
22723            panic!("expected contextual handler type failure");
22724        };
22725        assert_eq!(handler_kind, HandlerKind::Activity);
22726        assert_eq!(handler_name, "typed.unsupported.activity");
22727        assert_eq!(value_kind, HandlerValueKind::Result);
22728        assert_eq!(rust_type, type_name::<f64>());
22729        assert!(message.contains("non_finite_float"));
22730    }
22731
22732    #[tokio::test]
22733    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
22734        #[derive(Clone, Default)]
22735        struct State {
22736            observed: Option<TypedContract>,
22737        }
22738
22739        let client = Client::new("http://127.0.0.1:8080").expect("client");
22740        let mut worker = Worker::new(client, "rust-workers");
22741        worker.register_typed_replayed_workflow(
22742            "typed.contract.replayed",
22743            State::default,
22744            |ctx, input: TypedContract, state| async move {
22745                let result: TypedContract =
22746                    ctx.activity_typed("typed.contract.activity", input).await?;
22747                state.update(|current| current.observed = Some(result.clone()))?;
22748                Ok(result)
22749            },
22750        );
22751        worker.register_replayed_query::<State, _, _>(
22752            "typed.contract.replayed",
22753            "observed",
22754            |_ctx, state, _args| async move {
22755                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
22756            },
22757        );
22758
22759        let expected = typed_contract();
22760        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
22761        let workflow_arguments =
22762            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
22763                .expect("workflow arguments");
22764        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
22765        let task = QueryTask {
22766            query_task_id: "typed-replay-query".to_string(),
22767            observability_context: None,
22768            dispatch_observability_context: None,
22769            observability_links: None,
22770            query_task_attempt: 1,
22771            lease_owner: Some("rust-worker".to_string()),
22772            workflow_id: Some("typed-replay".to_string()),
22773            run_id: Some("typed-replay-run".to_string()),
22774            workflow_type: "typed.contract.replayed".to_string(),
22775            query_name: "observed".to_string(),
22776            payload_codec: DEFAULT_CODEC.to_string(),
22777            workflow_arguments: Some(workflow_arguments),
22778            query_arguments: Some(
22779                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
22780                    .expect("query arguments"),
22781            ),
22782            history_events: vec![
22783                history_event(
22784                    "ActivityScheduled",
22785                    json!({
22786                        "sequence": 1,
22787                        "activity_type": "typed.contract.activity"
22788                    }),
22789                ),
22790                history_event(
22791                    "ActivityCompleted",
22792                    json!({
22793                        "sequence": 1,
22794                        "activity_type": "typed.contract.activity",
22795                        "payload_codec": DEFAULT_CODEC,
22796                        "result": result
22797                    }),
22798                ),
22799            ],
22800            history_export: None,
22801            run_status: Some("completed".to_string()),
22802        };
22803
22804        assert_eq!(
22805            worker
22806                .execute_query_task(task)
22807                .await
22808                .expect("typed replay query")
22809                .deserialize::<i64>()
22810                .expect("query result"),
22811            expected.signed
22812        );
22813    }
22814
22815    #[tokio::test]
22816    async fn update_context_preserves_workflow_input_and_committed_signals() {
22817        let client = Client::new("http://127.0.0.1:8080").expect("client");
22818        let mut worker = Worker::new(client, "rust-workers");
22819        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
22820        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
22821        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
22822        let expected_input = workflow_input.clone();
22823        let expected_signals = signal_arguments.clone();
22824        let handler = move |context: QueryContext, arguments: AvroValue| {
22825            let expected_input = expected_input.clone();
22826            let expected_signals = expected_signals.clone();
22827            async move {
22828                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
22829                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
22830                assert_eq!(context.workflow_input_avro_value(), &expected_input);
22831                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
22832                assert_eq!(
22833                    context.signals_avro_value("changed"),
22834                    vec![expected_signals.clone()]
22835                );
22836                assert_eq!(
22837                    context.signals("changed"),
22838                    vec![expected_signals
22839                        .into_iter()
22840                        .map(AvroValue::into_json)
22841                        .collect::<Result<Vec<_>>>()?]
22842                );
22843                assert_eq!(
22844                    context.signal_events()[0].id.as_deref(),
22845                    Some("signal-original")
22846                );
22847                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
22848                Ok(arguments)
22849            }
22850        };
22851        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
22852        worker.register_update_avro_value("snapshot", "inspect", handler);
22853        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
22854        let update_envelope =
22855            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
22856        let mut task = workflow_task(
22857            "snapshot",
22858            vec![
22859                history_event(
22860                    "SignalReceived",
22861                    json!({
22862                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
22863                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
22864                    }),
22865                ),
22866                history_event(
22867                    "UpdateAccepted",
22868                    json!({
22869                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
22870                    }),
22871                ),
22872            ],
22873            DEFAULT_CODEC,
22874        );
22875        task.arguments =
22876            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
22877        task.workflow_update_id = Some("update-original".into());
22878        task.update_name = Some("inspect".into());
22879        let query = QueryTask {
22880            query_task_id: "query-snapshot".into(),
22881            observability_context: None,
22882            dispatch_observability_context: None,
22883            observability_links: None,
22884            query_task_attempt: 1,
22885            lease_owner: None,
22886            workflow_id: task.workflow_id.clone(),
22887            run_id: task.run_id.clone(),
22888            workflow_type: task.workflow_type.clone(),
22889            query_name: "inspect".into(),
22890            payload_codec: DEFAULT_CODEC.into(),
22891            workflow_arguments: task.arguments.clone(),
22892            query_arguments: Some(update_envelope),
22893            history_events: task.history_events.clone(),
22894            history_export: None,
22895            run_status: Some("running".into()),
22896        };
22897        assert_eq!(
22898            worker
22899                .execute_query_task(query)
22900                .await
22901                .expect("query snapshot"),
22902            update_arguments
22903        );
22904        for _ in 0..2 {
22905            let commands = worker
22906                .execute_workflow_task(task.clone())
22907                .expect("cold update snapshot");
22908            assert_eq!(commands[0]["type"], "complete_update");
22909            assert_eq!(commands[0]["update_id"], "update-original");
22910            assert_eq!(
22911                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22912                    .expect("update result"),
22913                update_arguments
22914            );
22915        }
22916    }
22917
22918    #[test]
22919    fn committed_signal_snapshot_counts_identities_once() {
22920        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
22921        let received = history_event(
22922            "SignalReceived",
22923            json!({
22924                "signal_id": "signal-first", "workflow_command_id": "command-first",
22925                "signal_name": "changed", "arguments": arguments.clone(),
22926            }),
22927        );
22928        let applied = history_event(
22929            "SignalApplied",
22930            json!({
22931                "signal_id": "signal-first", "workflow_command_id": "command-first",
22932                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
22933            }),
22934        );
22935        let distinct = history_event(
22936            "SignalReceived",
22937            json!({
22938                "signal_id": "signal-second", "workflow_command_id": "command-second",
22939                "signal_name": "changed", "arguments": arguments,
22940            }),
22941        );
22942        let history = vec![received.clone(), applied.clone(), distinct];
22943        let signals =
22944            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
22945        assert_eq!(signals.len(), 2);
22946        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
22947        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
22948        assert_eq!(signals[0].workflow_sequence, Some(1));
22949        assert_eq!(signals[0].arguments, signals[1].arguments);
22950        let mut command_only = received.clone();
22951        command_only
22952            .payload
22953            .as_object_mut()
22954            .expect("payload")
22955            .remove("signal_id");
22956        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
22957            .expect("command identity");
22958        assert_eq!(signals.len(), 1);
22959        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
22960        let mut conflicting = applied;
22961        conflicting.payload["value"] =
22962            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
22963        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
22964    }
22965
22966    #[test]
22967    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
22968        for arguments in [
22969            vec![],
22970            vec![AvroValue::Array(vec![
22971                AvroValue::Long(1),
22972                AvroValue::Long(2),
22973            ])],
22974            vec![AvroValue::Bytes(vec![0, 255])],
22975            vec![AvroValue::Null],
22976            vec![AvroValue::Boolean(false)],
22977            vec![
22978                AvroValue::Long(1),
22979                AvroValue::Array(vec![AvroValue::Long(2)]),
22980            ],
22981        ] {
22982            let applied = match arguments.as_slice() {
22983                [] => AvroValue::Boolean(true),
22984                [value] => value.clone(),
22985                values => AvroValue::Array(values.to_vec()),
22986            };
22987            for applied in [applied, AvroValue::Array(arguments.clone())] {
22988                let events = vec![
22989                    history_event(
22990                        "SignalReceived",
22991                        json!({
22992                            "signal_id": "original", "signal_name": "changed",
22993                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
22994                        }),
22995                    ),
22996                    history_event(
22997                        "SignalApplied",
22998                        json!({
22999                            "signal_id": "original", "signal_name": "changed",
23000                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
23001                        }),
23002                    ),
23003                ];
23004                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
23005                    .expect("canonical signal snapshot");
23006                assert_eq!(signals.len(), 1);
23007                assert_eq!(signals[0].avro_arguments, arguments);
23008            }
23009        }
23010    }
23011
23012    #[tokio::test]
23013    async fn update_context_rejects_malformed_snapshot_before_handler() {
23014        let client = Client::new("http://127.0.0.1:8080").expect("client");
23015        let mut worker = Worker::new(client, "rust-workers");
23016        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
23017        let calls = Arc::new(AtomicUsize::new(0));
23018        let observed = Arc::clone(&calls);
23019        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
23020            observed.fetch_add(1, Ordering::SeqCst);
23021            async { Ok(Value::Null) }
23022        });
23023        let mut task = workflow_task(
23024            "snapshot",
23025            vec![history_event(
23026                "UpdateAccepted",
23027                json!({
23028                    "update_id": "update-original", "update_name": "inspect",
23029                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
23030                }),
23031            )],
23032            DEFAULT_CODEC,
23033        );
23034        task.workflow_update_id = Some("update-original".into());
23035        task.update_name = Some("inspect".into());
23036        let mut bad_input = task.clone();
23037        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
23038        assert!(worker.execute_workflow_task(bad_input).is_err());
23039        task.history_events.insert(0, history_event("SignalReceived", json!({
23040            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
23041        })));
23042        assert!(worker.execute_workflow_task(task).is_err());
23043        assert_eq!(calls.load(Ordering::SeqCst), 0);
23044    }
23045
23046    #[tokio::test]
23047    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
23048        let client = Client::new("http://127.0.0.1:8080").expect("client");
23049        let mut worker = Worker::new(client, "rust-workers");
23050        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
23051        worker
23052            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
23053        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
23054            Ok(input)
23055        });
23056        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
23057            Ok(input)
23058        });
23059        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
23060            Ok(AvroValue::Array(
23061                ctx.wait_signal_avro_value("changed").await?,
23062            ))
23063        });
23064
23065        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
23066        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
23067
23068        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
23069        workflow.arguments = Some(envelope.clone());
23070        let commands = worker
23071            .execute_workflow_task(workflow)
23072            .expect("typed workflow task");
23073        assert_eq!(commands[0]["type"], "complete_workflow");
23074        assert_eq!(
23075            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
23076                .expect("typed workflow result"),
23077            arguments
23078        );
23079
23080        let activity = ActivityTask {
23081            task_id: "activity-typed".to_string(),
23082            workflow_id: None,
23083            run_id: None,
23084            activity_execution_id: None,
23085            observability_context: None,
23086            dispatch_observability_context: None,
23087            observability_links: None,
23088            activity_attempt_id: Some("attempt-typed".to_string()),
23089            attempt_id: None,
23090            activity_type: "typed.activity".to_string(),
23091            payload_codec: DEFAULT_CODEC.to_string(),
23092            arguments: Some(envelope.clone()),
23093            attempt_number: 1,
23094            lease_owner: Some("rust-worker".to_string()),
23095        };
23096        assert_eq!(
23097            worker
23098                .execute_activity_task(activity)
23099                .await
23100                .expect("typed activity result"),
23101            arguments
23102        );
23103
23104        let query = QueryTask {
23105            query_task_id: "query-typed".to_string(),
23106            observability_context: None,
23107            dispatch_observability_context: None,
23108            observability_links: None,
23109            query_task_attempt: 1,
23110            lease_owner: Some("rust-worker".to_string()),
23111            workflow_id: Some("typed-1".to_string()),
23112            run_id: Some("run-typed".to_string()),
23113            workflow_type: "typed.echo".to_string(),
23114            query_name: "inspect".to_string(),
23115            payload_codec: DEFAULT_CODEC.to_string(),
23116            workflow_arguments: Some(
23117                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
23118                    .expect("workflow input"),
23119            ),
23120            query_arguments: Some(envelope.clone()),
23121            history_events: Vec::new(),
23122            history_export: None,
23123            run_status: Some("running".to_string()),
23124        };
23125        assert_eq!(
23126            worker
23127                .execute_query_task(query)
23128                .await
23129                .expect("typed query result"),
23130            arguments
23131        );
23132
23133        let mut update = workflow_task(
23134            "typed.echo",
23135            vec![history_event(
23136                "UpdateAccepted",
23137                json!({
23138                    "update_id": "update-typed",
23139                    "update_name": "replace",
23140                    "arguments": envelope.clone(),
23141                }),
23142            )],
23143            DEFAULT_CODEC,
23144        );
23145        update.workflow_update_id = Some("update-typed".to_string());
23146        update.update_name = Some("replace".to_string());
23147        let commands = worker
23148            .execute_workflow_task(update)
23149            .expect("typed update task");
23150        assert_eq!(commands[0]["type"], "complete_update");
23151        assert_eq!(
23152            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
23153                .expect("typed update result"),
23154            arguments
23155        );
23156
23157        let mut signal = workflow_task(
23158            "typed.signal",
23159            vec![history_event(
23160                "SignalReceived",
23161                json!({
23162                    "signal_id": "signal-typed",
23163                    "signal_name": "changed",
23164                    "arguments": envelope.clone(),
23165                }),
23166            )],
23167            DEFAULT_CODEC,
23168        );
23169        signal.workflow_signal_id = Some("signal-typed".to_string());
23170        signal.signal_name = Some("changed".to_string());
23171        signal.signal_arguments = Some(envelope);
23172        let commands = worker
23173            .execute_workflow_task(signal)
23174            .expect("typed signal resume");
23175        assert_eq!(
23176            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
23177                .expect("typed signal result"),
23178            arguments
23179        );
23180    }
23181
23182    #[tokio::test]
23183    async fn typed_helpers_never_parse_json_inspection_projection() {
23184        let collision_values = projection_collision_probe();
23185        let expected = AvroValue::Array(collision_values.clone());
23186        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
23187
23188        let activity_context = workflow_context_with_codec(
23189            vec![history_event(
23190                "ActivityCompleted",
23191                json!({
23192                    "sequence": 1,
23193                    "activity_type": "collision.activity",
23194                    "payload_codec": DEFAULT_CODEC,
23195                    "result": envelope.clone(),
23196                }),
23197            )],
23198            DEFAULT_CODEC,
23199        );
23200        assert_eq!(
23201            activity_context
23202                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
23203                .await
23204                .expect("typed activity collision result"),
23205            expected
23206        );
23207
23208        let signal_context = workflow_context_with_codec(
23209            vec![
23210                history_event(
23211                    "SignalWaitOpened",
23212                    json!({"sequence": 1, "signal_name": "collision"}),
23213                ),
23214                history_event(
23215                    "SignalApplied",
23216                    json!({
23217                        "sequence": 1,
23218                        "signal_name": "collision",
23219                        "payload_codec": DEFAULT_CODEC,
23220                        "value": envelope.clone(),
23221                    }),
23222                ),
23223            ],
23224            DEFAULT_CODEC,
23225        );
23226        assert_eq!(
23227            signal_context
23228                .wait_signal_avro_value("collision")
23229                .await
23230                .expect("typed signal collision arguments"),
23231            collision_values
23232        );
23233
23234        let child_context = workflow_context_with_codec(
23235            vec![
23236                history_event(
23237                    "ChildWorkflowScheduled",
23238                    json!({
23239                        "sequence": 1,
23240                        "child_workflow_instance_id": "collision-child",
23241                        "child_workflow_run_id": "collision-run",
23242                        "child_workflow_type": "collision.child",
23243                    }),
23244                ),
23245                history_event(
23246                    "ChildRunCompleted",
23247                    json!({
23248                        "sequence": 1,
23249                        "child_workflow_instance_id": "collision-child",
23250                        "child_workflow_run_id": "collision-run",
23251                        "child_workflow_type": "collision.child",
23252                        "payload_codec": DEFAULT_CODEC,
23253                        "result": envelope,
23254                    }),
23255                ),
23256            ],
23257            DEFAULT_CODEC,
23258        );
23259        let child = child_context
23260            .start_child_workflow_avro_value(
23261                "collision.child",
23262                ChildWorkflowOptions::new("collision-workers"),
23263                AvroValue::Array(Vec::new()),
23264            )
23265            .await
23266            .expect("typed child collision result");
23267        assert_eq!(child.result, expected);
23268    }
23269
23270    #[tokio::test]
23271    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
23272        let client = Client::new("http://127.0.0.1:8080").expect("client");
23273        let mut worker = Worker::new(client, "rust-workers");
23274        worker.register_replayed_workflow_avro_value(
23275            "typed.replayed",
23276            || (),
23277            |_ctx, input, _state| async move { Ok(input) },
23278        );
23279        worker.register_replayed_query_avro_value::<(), _, _>(
23280            "typed.replayed",
23281            "inspect",
23282            |ctx, _state, args| async move {
23283                let mut signals = ctx.signals_avro_value("collision");
23284                let signal = signals
23285                    .pop()
23286                    .map(AvroValue::Array)
23287                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
23288                Ok(AvroValue::Array(vec![
23289                    ctx.workflow_input_avro_value().clone(),
23290                    signal,
23291                    args,
23292                ]))
23293            },
23294        );
23295        let arguments = AvroValue::Array(projection_collision_probe());
23296        let signal_arguments =
23297            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
23298        let task = QueryTask {
23299            query_task_id: "query-typed-replay".to_string(),
23300            observability_context: None,
23301            dispatch_observability_context: None,
23302            observability_links: None,
23303            query_task_attempt: 1,
23304            lease_owner: Some("rust-worker".to_string()),
23305            workflow_id: Some("typed-replay".to_string()),
23306            run_id: Some("run-typed-replay".to_string()),
23307            workflow_type: "typed.replayed".to_string(),
23308            query_name: "inspect".to_string(),
23309            payload_codec: DEFAULT_CODEC.to_string(),
23310            workflow_arguments: Some(
23311                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
23312            ),
23313            query_arguments: Some(
23314                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
23315            ),
23316            history_events: vec![history_event(
23317                "SignalReceived",
23318                json!({
23319                    "signal_id": "collision-signal",
23320                    "signal_name": "collision",
23321                    "workflow_sequence": 1,
23322                    "payload_codec": DEFAULT_CODEC,
23323                    "arguments": signal_arguments,
23324                }),
23325            )],
23326            history_export: None,
23327            run_status: Some("completed".to_string()),
23328        };
23329
23330        assert_eq!(
23331            worker
23332                .execute_query_task(task)
23333                .await
23334                .expect("typed replay query"),
23335            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
23336        );
23337    }
23338
23339    #[test]
23340    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
23341        let value = BTreeMap::from([(1_i32, "integer key")]);
23342        let error = PayloadEnvelope::avro(&value)
23343            .expect_err("integer map keys must fail")
23344            .to_string();
23345
23346        assert!(error.contains("invalid_map_key"));
23347    }
23348
23349    #[test]
23350    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
23351        let envelope = PayloadEnvelope {
23352            codec: "json".to_string(),
23353            blob: r#"{"greeting":"hello"}"#.to_string(),
23354        };
23355
23356        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
23357        let diagnostic = error.to_string();
23358        assert!(diagnostic.contains("unsupported_payload_codec"));
23359        assert!(diagnostic.contains("codec=\"avro\""));
23360        assert!(diagnostic.contains("HTTP document transport"));
23361    }
23362
23363    #[test]
23364    fn untagged_json_payload_value_fails_closed() {
23365        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
23366            .expect_err("untagged JSON payload values must fail");
23367        let diagnostic = error.to_string();
23368        assert!(diagnostic.contains("unsupported_payload_codec"));
23369        assert!(diagnostic.contains("untagged durable payload"));
23370        assert!(diagnostic.contains("HTTP document transport"));
23371    }
23372
23373    #[test]
23374    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
23375        let envelope = PayloadEnvelope {
23376            codec: DEFAULT_CODEC.to_string(),
23377            blob: BASE64.encode([0x01]),
23378        };
23379
23380        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
23381        assert!(error.to_string().contains("invalid_payload_framing"));
23382    }
23383
23384    #[tokio::test]
23385    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
23386        let server = MockWorkerServer::start();
23387        let client = Client::builder(server.base_url())
23388            .timeout(Duration::from_secs(2))
23389            .build()
23390            .expect("client");
23391        let invalid_commands = [
23392            json!({
23393                "type": "complete_workflow",
23394                "result": {"codec": "json", "blob": null}
23395            }),
23396            json!({
23397                "type": "schedule_activity",
23398                "arguments": {"codec": "yaml", "blob": "ignored"}
23399            }),
23400            json!({
23401                "type": "start_child_workflow",
23402                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
23403            }),
23404            json!({"type": "continue_as_new", "arguments": []}),
23405            json!({"type": "complete_update"}),
23406            json!({"type": "record_side_effect", "result": null}),
23407            json!({
23408                "type": "start_service_operation",
23409                "payload_codec": DEFAULT_CODEC,
23410                "request_payload": "raw-avro-bytes"
23411            }),
23412        ];
23413
23414        for command in invalid_commands {
23415            let error = client
23416                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
23417                .await
23418                .expect_err("invalid durable payload must fail locally");
23419            let diagnostic = error.to_string();
23420            assert!(
23421                diagnostic.contains("unsupported_payload_codec")
23422                    || diagnostic.contains("invalid_payload_envelope")
23423                    || diagnostic.contains("untagged durable payload"),
23424                "unexpected validation diagnostic: {diagnostic}"
23425            );
23426        }
23427
23428        assert_eq!(
23429            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
23430            0,
23431            "invalid command payloads must not reach HTTP transport"
23432        );
23433    }
23434
23435    #[test]
23436    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
23437        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
23438        let commands = [
23439            json!({"type": "complete_workflow", "result": envelope.clone()}),
23440            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
23441            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
23442            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
23443            json!({"type": "complete_update", "result": envelope.clone()}),
23444            json!({"type": "record_side_effect", "result": envelope.clone()}),
23445            json!({
23446                "type": "start_service_operation",
23447                "payload_codec": DEFAULT_CODEC,
23448                "request_payload": envelope.clone()
23449            }),
23450            json!({
23451                "type": "complete_workflow",
23452                "result": envelope,
23453                "metadata": {
23454                    "codec": "json",
23455                    "payload_codec": "customer-codec",
23456                    "result": {"codec": "yaml", "blob": null}
23457                }
23458            }),
23459        ];
23460
23461        validate_workflow_task_commands(&commands)
23462            .expect("customer metadata must not become a protocol codec declaration");
23463    }
23464
23465    #[test]
23466    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
23467        assert_eq!(
23468            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
23469            AvroValue::Array(Vec::new())
23470        );
23471        assert_eq!(
23472            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
23473            AvroValue::Array(Vec::new())
23474        );
23475
23476        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
23477        signal.signal_name = Some("empty-signal".to_string());
23478        signal.signal_arguments = None;
23479        let decoded = decode_resume_signal(&signal)
23480            .expect("valid Avro signal")
23481            .expect("named signal resumes the workflow");
23482        assert!(decoded.arguments.is_empty());
23483    }
23484
23485    #[tokio::test]
23486    async fn malformed_task_level_codecs_become_pre_handler_failures() {
23487        let client = Client::new("http://127.0.0.1:8080").expect("client");
23488        let mut worker = Worker::new(client, "rust-workers");
23489        let handler_calls = Arc::new(AtomicUsize::new(0));
23490
23491        let calls = Arc::clone(&handler_calls);
23492        worker.register_workflow("codec.workflow", move |_ctx, _args| {
23493            calls.fetch_add(1, Ordering::SeqCst);
23494            async move { Ok(Value::Null) }
23495        });
23496        let calls = Arc::clone(&handler_calls);
23497        worker.register_activity("codec.activity", move |_ctx, _args| {
23498            calls.fetch_add(1, Ordering::SeqCst);
23499            async move { Ok(Value::Null) }
23500        });
23501        let calls = Arc::clone(&handler_calls);
23502        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
23503            calls.fetch_add(1, Ordering::SeqCst);
23504            async move { Ok(Value::Null) }
23505        });
23506
23507        let mut failures = Vec::new();
23508        for codec_case in [
23509            InvalidTaskPayloadCodec::Missing,
23510            InvalidTaskPayloadCodec::Null,
23511            InvalidTaskPayloadCodec::NonString,
23512        ] {
23513            let mut workflow = json!({
23514                "task_id": format!("workflow-{}", codec_case.label()),
23515                "workflow_type": "codec.workflow"
23516            });
23517            codec_case.apply(&mut workflow);
23518            match serde_json::from_value::<WorkflowTask>(workflow) {
23519                Ok(task) => match worker.execute_workflow_task(task) {
23520                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
23521                    outcome => failures.push(format!(
23522                        "workflow {} codec returned {outcome:?}",
23523                        codec_case.label()
23524                    )),
23525                },
23526                Err(error) => failures.push(format!(
23527                    "workflow {} codec failed transport deserialization: {error}",
23528                    codec_case.label()
23529                )),
23530            }
23531
23532            let mut activity = json!({
23533                "task_id": format!("activity-{}", codec_case.label()),
23534                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
23535                "activity_type": "codec.activity",
23536                "attempt_number": 1
23537            });
23538            codec_case.apply(&mut activity);
23539            match serde_json::from_value::<ActivityTask>(activity) {
23540                Ok(task) => match worker.execute_activity_task(task).await {
23541                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
23542                    outcome => failures.push(format!(
23543                        "activity {} codec returned {outcome:?}",
23544                        codec_case.label()
23545                    )),
23546                },
23547                Err(error) => failures.push(format!(
23548                    "activity {} codec failed transport deserialization: {error}",
23549                    codec_case.label()
23550                )),
23551            }
23552
23553            let mut query = json!({
23554                "query_task_id": format!("query-{}", codec_case.label()),
23555                "workflow_type": "codec.workflow",
23556                "query_name": "known"
23557            });
23558            codec_case.apply(&mut query);
23559            match serde_json::from_value::<QueryTask>(query) {
23560                Ok(task) => match worker.execute_query_task(task).await {
23561                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
23562                    outcome => failures.push(format!(
23563                        "query {} codec returned {outcome:?}",
23564                        codec_case.label()
23565                    )),
23566                },
23567                Err(error) => failures.push(format!(
23568                    "query {} codec failed transport deserialization: {error}",
23569                    codec_case.label()
23570                )),
23571            }
23572        }
23573
23574        assert!(failures.is_empty(), "{}", failures.join("\n"));
23575        assert_eq!(
23576            handler_calls.load(Ordering::SeqCst),
23577            0,
23578            "invalid task codecs must not invoke a handler"
23579        );
23580    }
23581
23582    #[tokio::test]
23583    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
23584        for codec_case in [
23585            InvalidTaskPayloadCodec::Missing,
23586            InvalidTaskPayloadCodec::Null,
23587            InvalidTaskPayloadCodec::NonString,
23588        ] {
23589            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
23590            let client = Client::builder(server.base_url())
23591                .timeout(Duration::from_secs(2))
23592                .build()
23593                .expect("client");
23594            let mut worker = Worker::new(client, "rust-workers")
23595                .worker_id("codec-worker")
23596                .poll_timeout(Duration::from_millis(10));
23597            let handler_calls = Arc::new(AtomicUsize::new(0));
23598
23599            let calls = Arc::clone(&handler_calls);
23600            worker.register_workflow("codec.workflow", move |_ctx, _args| {
23601                calls.fetch_add(1, Ordering::SeqCst);
23602                async move { Ok(Value::Null) }
23603            });
23604            let calls = Arc::clone(&handler_calls);
23605            worker.register_activity("codec.activity", move |_ctx, _args| {
23606                calls.fetch_add(1, Ordering::SeqCst);
23607                async move { Ok(Value::Null) }
23608            });
23609            let calls = Arc::clone(&handler_calls);
23610            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
23611                calls.fetch_add(1, Ordering::SeqCst);
23612                async move { Ok(Value::Null) }
23613            });
23614
23615            assert_eq!(
23616                worker.run_once().await.expect("invalid tasks are settled"),
23617                3,
23618                "all {} codec tasks must be handled",
23619                codec_case.label()
23620            );
23621            assert_eq!(
23622                handler_calls.load(Ordering::SeqCst),
23623                0,
23624                "{} task codecs must fail before every handler",
23625                codec_case.label()
23626            );
23627
23628            for path in [
23629                "/api/worker/workflow-tasks/codec-workflow/fail",
23630                "/api/worker/activity-tasks/codec-activity/fail",
23631                "/api/worker/query-tasks/codec-query/fail",
23632            ] {
23633                let body = server.request_body(path);
23634                assert!(
23635                    body["failure"]["message"]
23636                        .as_str()
23637                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
23638                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
23639                    codec_case.label()
23640                );
23641            }
23642            assert_eq!(
23643                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
23644                    ["reason"],
23645                "query_payload_decode_failed"
23646            );
23647            for path in [
23648                "/api/worker/workflow-tasks/codec-workflow/complete",
23649                "/api/worker/activity-tasks/codec-activity/complete",
23650                "/api/worker/query-tasks/codec-query/complete",
23651            ] {
23652                assert_eq!(
23653                    server.request_count(path),
23654                    0,
23655                    "invalid {} codec task reached {path}",
23656                    codec_case.label()
23657                );
23658            }
23659        }
23660    }
23661
23662    #[tokio::test]
23663    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
23664        let client = Client::new("http://127.0.0.1:8080").expect("client");
23665        let mut worker = Worker::new(client, "rust-workers");
23666        let handler_calls = Arc::new(AtomicUsize::new(0));
23667
23668        let calls = Arc::clone(&handler_calls);
23669        worker.register_workflow("codec.workflow", move |_ctx, _args| {
23670            calls.fetch_add(1, Ordering::SeqCst);
23671            async move { Ok(Value::Null) }
23672        });
23673        let calls = Arc::clone(&handler_calls);
23674        worker.register_activity("codec.activity", move |_ctx, _args| {
23675            calls.fetch_add(1, Ordering::SeqCst);
23676            async move { Ok(Value::Null) }
23677        });
23678        let calls = Arc::clone(&handler_calls);
23679        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
23680            calls.fetch_add(1, Ordering::SeqCst);
23681            async move { Ok(Value::Null) }
23682        });
23683        let calls = Arc::clone(&handler_calls);
23684        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
23685            calls.fetch_add(1, Ordering::SeqCst);
23686            async move { Ok(Value::Null) }
23687        });
23688
23689        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
23690        workflow.payload_codec = "json".to_string();
23691        workflow.arguments = None;
23692        let error = worker
23693            .execute_workflow_task(workflow)
23694            .expect_err("task codec must be checked before workflow invocation");
23695        assert!(error.to_string().contains("unsupported_payload_codec"));
23696
23697        let activity = ActivityTask {
23698            task_id: "activity-invalid-codec".to_string(),
23699            workflow_id: None,
23700            run_id: None,
23701            activity_execution_id: None,
23702            observability_context: None,
23703            dispatch_observability_context: None,
23704            observability_links: None,
23705            activity_attempt_id: None,
23706            attempt_id: None,
23707            activity_type: "codec.activity".to_string(),
23708            payload_codec: "unknown".to_string(),
23709            arguments: None,
23710            attempt_number: 1,
23711            lease_owner: None,
23712        };
23713        let error = worker
23714            .execute_activity_task(activity)
23715            .await
23716            .expect_err("task codec must be checked before activity invocation");
23717        assert!(error.to_string().contains("unsupported_payload_codec"));
23718
23719        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
23720        update.workflow_update_id = Some("update-invalid-codec".to_string());
23721        update.update_name = Some("known".to_string());
23722        update.history_events.push(history_event(
23723            "UpdateAccepted",
23724            json!({
23725                "update_id": "update-invalid-codec",
23726                "update_name": "known",
23727                "arguments": {"codec": "json", "blob": null}
23728            }),
23729        ));
23730        let error = worker
23731            .execute_workflow_task(update)
23732            .expect_err("nested update codec must be checked before handler lookup");
23733        assert!(error.to_string().contains("unsupported_payload_codec"));
23734
23735        let query: QueryTask = serde_json::from_value(json!({
23736            "query_task_id": "query-invalid-codec",
23737            "workflow_type": "codec.workflow",
23738            "query_name": "known",
23739            "payload_codec": DEFAULT_CODEC,
23740            "workflow_arguments": null,
23741            "query_arguments": null,
23742            "history_export": {
23743                "payloads": {"codec": DEFAULT_CODEC},
23744                "signals": [{
23745                    "name": "empty",
23746                    "payload_codec": "json",
23747                    "arguments": null
23748                }]
23749            }
23750        }))
23751        .expect("query task");
23752        let failure = worker
23753            .execute_query_task(query)
23754            .await
23755            .expect_err("exported signal codec must be checked before query invocation");
23756        assert_eq!(failure.reason, "query_payload_decode_failed");
23757        assert!(failure.message.contains("unsupported_payload_codec"));
23758
23759        let exported_history: QueryTask = serde_json::from_value(json!({
23760            "query_task_id": "query-invalid-history-codec",
23761            "workflow_type": "codec.workflow",
23762            "query_name": "known",
23763            "payload_codec": DEFAULT_CODEC,
23764            "history_export": {
23765                "payloads": {"codec": DEFAULT_CODEC},
23766                "history_events": [{
23767                    "type": "ActivityCompleted",
23768                    "payload": {"payload_codec": "unknown", "result": null}
23769                }]
23770            }
23771        }))
23772        .expect("query task");
23773        let failure = worker
23774            .execute_query_task(exported_history)
23775            .await
23776            .expect_err("exported history codec must be checked before query invocation");
23777        assert_eq!(failure.reason, "query_payload_decode_failed");
23778        assert!(failure.message.contains("unsupported_payload_codec"));
23779        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
23780
23781        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
23782        unknown_workflow.arguments = None;
23783        unknown_workflow.history_events.push(history_event(
23784            "SignalReceived",
23785            json!({
23786                "signal_name": "empty",
23787                "payload_codec": "json",
23788                "arguments": null
23789            }),
23790        ));
23791        let error = worker
23792            .execute_workflow_task(unknown_workflow)
23793            .expect_err("history codec must precede unknown workflow outcome");
23794        assert!(error.to_string().contains("unsupported_payload_codec"));
23795
23796        let unknown_activity = ActivityTask {
23797            task_id: "activity-unknown".to_string(),
23798            workflow_id: None,
23799            run_id: None,
23800            activity_execution_id: None,
23801            observability_context: None,
23802            dispatch_observability_context: None,
23803            observability_links: None,
23804            activity_attempt_id: None,
23805            attempt_id: None,
23806            activity_type: "missing".to_string(),
23807            payload_codec: "json".to_string(),
23808            arguments: None,
23809            attempt_number: 1,
23810            lease_owner: None,
23811        };
23812        let error = worker
23813            .execute_activity_task(unknown_activity)
23814            .await
23815            .expect_err("codec must precede unknown activity outcome");
23816        assert!(error.to_string().contains("unsupported_payload_codec"));
23817
23818        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
23819        unknown_update.payload_codec = "json".to_string();
23820        unknown_update.arguments = None;
23821        unknown_update.workflow_update_id = Some("update-unknown".to_string());
23822        unknown_update.update_name = Some("missing".to_string());
23823        let error = worker
23824            .execute_workflow_task(unknown_update)
23825            .expect_err("codec must precede fail_update shortcut");
23826        assert!(error.to_string().contains("unsupported_payload_codec"));
23827
23828        let unknown_query: QueryTask = serde_json::from_value(json!({
23829            "query_task_id": "query-unknown",
23830            "workflow_type": "missing",
23831            "query_name": "missing",
23832            "payload_codec": "json",
23833            "workflow_arguments": null,
23834            "query_arguments": null
23835        }))
23836        .expect("query task");
23837        let failure = worker
23838            .execute_query_task(unknown_query)
23839            .await
23840            .expect_err("codec must precede unknown query outcome");
23841        assert_eq!(failure.reason, "query_payload_decode_failed");
23842        assert!(failure.message.contains("unsupported_payload_codec"));
23843    }
23844
23845    #[tokio::test]
23846    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
23847        let client = Client::new("http://127.0.0.1:8080").expect("client");
23848        let worker = Worker::new(client, "rust-workers");
23849
23850        for event_type in ["SignalReceived", "SignalApplied"] {
23851            for (payload_field, codec) in [
23852                ("value", "json"),
23853                ("input", "unknown"),
23854                ("arguments", "json"),
23855            ] {
23856                let payload = json!({
23857                    "signal_name": "empty",
23858                    payload_field: {"codec": codec, "blob": null}
23859                });
23860                let workflow = workflow_task(
23861                    "missing",
23862                    vec![history_event(event_type, payload.clone())],
23863                    DEFAULT_CODEC,
23864                );
23865                let error = worker
23866                    .execute_workflow_task(workflow)
23867                    .expect_err("signal payload codec must precede unknown workflow outcome");
23868                assert!(
23869                    error.to_string().contains("unsupported_payload_codec"),
23870                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
23871                );
23872
23873                let query: QueryTask = serde_json::from_value(json!({
23874                    "query_task_id": format!("query-{event_type}-{payload_field}"),
23875                    "workflow_type": "missing",
23876                    "query_name": "missing",
23877                    "payload_codec": DEFAULT_CODEC,
23878                    "workflow_arguments": null,
23879                    "query_arguments": null,
23880                    "history_events": [{
23881                        "event_type": event_type,
23882                        "payload": payload
23883                    }]
23884                }))
23885                .expect("query task");
23886                let failure = worker
23887                    .execute_query_task(query)
23888                    .await
23889                    .expect_err("signal payload codec must precede unknown query outcome");
23890                assert_eq!(
23891                    failure.reason, "query_payload_decode_failed",
23892                    "{event_type}.{payload_field} returned an unrelated query outcome"
23893                );
23894                assert!(
23895                    failure.message.contains("unsupported_payload_codec"),
23896                    "{event_type}.{payload_field} returned an unrelated query error: {}",
23897                    failure.message
23898                );
23899            }
23900        }
23901    }
23902
23903    #[test]
23904    fn workflow_context_schedules_activity_until_completion_is_in_history() {
23905        let ctx = WorkflowContext {
23906            cancellation_scope_id: "root".into(),
23907            state: Arc::new(Mutex::new(
23908                WorkflowState::new_with_identity(
23909                    Vec::new(),
23910                    Some("wf-parent".to_string()),
23911                    Some("run-parent".to_string()),
23912                    "rust-workers".to_string(),
23913                    DEFAULT_CODEC.to_string(),
23914                    None,
23915                )
23916                .expect("workflow state"),
23917            )),
23918        };
23919
23920        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
23921        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23922        assert!(matches!(
23923            call.as_mut().poll(&mut task_context),
23924            Poll::Pending
23925        ));
23926
23927        let commands = ctx.take_commands().expect("commands");
23928        assert_eq!(commands[0]["type"], "schedule_activity");
23929        assert_eq!(commands[0]["activity_type"], "hello.activity");
23930    }
23931
23932    #[test]
23933    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
23934        let ctx = workflow_context(Vec::new());
23935        let options = ActivityOptions::new()
23936            .task_queue("payments")
23937            .retry_policy(
23938                ActivityRetryPolicy::new(4)
23939                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
23940                    .non_retryable_error_type("ValidationError"),
23941            )
23942            .start_to_close_timeout(Duration::from_secs(120))
23943            .schedule_to_start_timeout(Duration::from_secs(10))
23944            .schedule_to_close_timeout(Duration::from_secs(300))
23945            .heartbeat_timeout(Duration::from_secs(15));
23946        let mut call = Box::pin(ctx.activity_with_options(
23947            "charge-card",
23948            options,
23949            json!([{"order_id": "o-1"}]),
23950        ));
23951        let mut task_context = TaskContext::from_waker(noop_waker_ref());
23952
23953        assert!(matches!(
23954            call.as_mut().poll(&mut task_context),
23955            Poll::Pending
23956        ));
23957        assert!(matches!(
23958            call.as_mut().poll(&mut task_context),
23959            Poll::Pending
23960        ));
23961
23962        let commands = ctx.take_commands().expect("activity command");
23963        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
23964        assert_eq!(commands[0]["queue"], "payments");
23965        assert_eq!(
23966            commands[0]["retry_policy"],
23967            json!({
23968                "max_attempts": 4,
23969                "backoff_seconds": [1, 3, 9],
23970                "non_retryable_error_types": ["ValidationError"],
23971            })
23972        );
23973        assert_eq!(commands[0]["start_to_close_timeout"], 120);
23974        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
23975        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
23976        assert_eq!(commands[0]["heartbeat_timeout"], 15);
23977    }
23978
23979    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
23980        vec![
23981            history_event(
23982                "ActivityScheduled",
23983                json!({"sequence":1,"activity_type":"render",
23984                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
23985            ),
23986            history_event(
23987                "ActivityCompleted",
23988                json!({"sequence":1,"activity_type":"render",
23989                "payload_codec":DEFAULT_CODEC,
23990                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
23991            ),
23992        ]
23993    }
23994
23995    #[test]
23996    fn worker_session_activity_routes_to_session_queue_once() {
23997        let ctx = workflow_context(Vec::new());
23998        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
23999        let mut call = Box::pin(
24000            ctx.activity("render", json!([]))
24001                .in_worker_session(session.clone()),
24002        );
24003        let mut cx = TaskContext::from_waker(noop_waker_ref());
24004        assert!(call.as_mut().poll(&mut cx).is_pending());
24005        assert!(call.as_mut().poll(&mut cx).is_pending());
24006        let commands = ctx.take_commands().unwrap();
24007        assert_eq!(commands.len(), 1);
24008        assert_eq!(commands[0]["queue"], "gpu-workers");
24009        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
24010    }
24011
24012    #[tokio::test]
24013    async fn worker_session_cold_replay_uses_recorded_avro_result() {
24014        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
24015        for _replacement in 0..2 {
24016            let ctx = workflow_context(completed_worker_session_history(&session));
24017            let result: i64 = ctx
24018                .activity("render", json!([]))
24019                .in_worker_session(session.clone())
24020                .typed()
24021                .await
24022                .unwrap();
24023            assert_eq!(result, 42);
24024            assert!(ctx.take_commands().unwrap().is_empty());
24025        }
24026    }
24027
24028    #[test]
24029    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
24030        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
24031        for changed in [
24032            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
24033            Some(original.clone().ttl_seconds(60)),
24034            Some(original.clone().requirements(["gpu:l4"])),
24035            None,
24036        ] {
24037            let ctx = workflow_context(completed_worker_session_history(&original));
24038            let mut call = ctx.activity_with_options(
24039                "render",
24040                ActivityOptions::new().task_queue("gpu-workers"),
24041                json!([]),
24042            );
24043            if let Some(changed) = changed {
24044                call = call.in_worker_session(changed);
24045            }
24046            let mut call = Box::pin(call);
24047            let mut cx = TaskContext::from_waker(noop_waker_ref());
24048            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24049                call.as_mut().poll(&mut cx)
24050            else {
24051                panic!("changed session must fail replay");
24052            };
24053            assert_eq!(failure.reason, "activity_worker_session_mismatch");
24054            assert!(ctx.take_commands().unwrap().is_empty());
24055        }
24056    }
24057
24058    #[test]
24059    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
24060        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
24061        let ctx = workflow_context(Vec::new());
24062        let mut local = Box::pin(
24063            ctx.local_activity("render", json!([]))
24064                .in_worker_session(session.clone()),
24065        );
24066        let mut cx = TaskContext::from_waker(noop_waker_ref());
24067        assert!(matches!(
24068            local.as_mut().poll(&mut cx),
24069            Poll::Ready(Err(Error::WorkerLoop(_)))
24070        ));
24071        assert!(ctx.take_commands().unwrap().is_empty());
24072        let mut remote = Box::pin(
24073            ctx.activity_with_options(
24074                "render",
24075                ActivityOptions::new().task_queue("other"),
24076                json!([]),
24077            )
24078            .in_worker_session(session),
24079        );
24080        assert!(matches!(
24081            remote.as_mut().poll(&mut cx),
24082            Poll::Ready(Err(Error::WorkerLoop(_)))
24083        ));
24084        assert!(ctx.take_commands().unwrap().is_empty());
24085    }
24086
24087    #[test]
24088    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
24089        let ctx = workflow_context(Vec::new());
24090        let options = ActivityOptions::new().retry_policy(
24091            ActivityRetryPolicy::new(3)
24092                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
24093        );
24094        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
24095        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24096
24097        assert!(matches!(
24098            call.as_mut().poll(&mut task_context),
24099            Poll::Pending
24100        ));
24101        assert_eq!(
24102            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
24103            json!([1, 2])
24104        );
24105    }
24106
24107    #[test]
24108    fn activity_options_preserve_unused_explicit_backoff_entries() {
24109        for max_attempts in [1, 2, 10] {
24110            let ctx = workflow_context(Vec::new());
24111            let options =
24112                ActivityOptions::new()
24113                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
24114                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
24115                    ));
24116            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
24117            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24118            assert!(matches!(
24119                call.as_mut().poll(&mut task_context),
24120                Poll::Pending
24121            ));
24122            let commands = ctx.take_commands().expect("command");
24123            assert_eq!(commands.len(), 1);
24124            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
24125            assert_eq!(
24126                commands[0]["retry_policy"]["backoff_seconds"],
24127                json!([1, 2, 5, 10, 15, 30, 60, 120])
24128            );
24129        }
24130        let default_options = ActivityOptions::new().validate().expect("default options");
24131        let default_policy = current_activity_retry_snapshot(&default_options);
24132        assert_eq!(
24133            default_policy.max_attempts,
24134            RecordedSnapshotValue::Known(Some(1))
24135        );
24136        assert_eq!(
24137            default_policy.backoff_seconds,
24138            RecordedSnapshotValue::Known(Vec::new())
24139        );
24140    }
24141
24142    #[test]
24143    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
24144        let fixture: Value = serde_json::from_str(include_str!(
24145            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
24146        ))
24147        .expect("published PHP fixture");
24148        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
24149            .expect("unchanged published history");
24150        let matching = ActivityOptions::new().task_queue("default").retry_policy(
24151            ActivityRetryPolicy::new(1)
24152                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
24153        );
24154        let mut changed_tail = matching.clone();
24155        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
24156            [1, 2, 5, 10, 15, 30, 60, 121]
24157                .map(Duration::from_secs)
24158                .to_vec(),
24159        ));
24160        let mut changed_first = matching.clone();
24161        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
24162            [2, 2, 5, 10, 15, 30, 60, 120]
24163                .map(Duration::from_secs)
24164                .to_vec(),
24165        ));
24166        let mut changed_attempts = matching.clone();
24167        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
24168        let mut changed_types = matching.clone();
24169        changed_types
24170            .retry_policy
24171            .as_mut()
24172            .unwrap()
24173            .non_retryable_error_types = vec!["ChangedError".into()];
24174        let mut changed_start = matching.clone();
24175        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
24176        let mut changed_schedule_start = matching.clone();
24177        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
24178        let mut changed_schedule_close = matching.clone();
24179        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
24180        let mut changed_heartbeat = matching;
24181        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
24182        let unchanged_defaults = ActivityOptions::new().task_queue("default");
24183        for options in [
24184            changed_tail,
24185            changed_first,
24186            changed_attempts,
24187            changed_types,
24188            changed_start,
24189            changed_schedule_start,
24190            changed_schedule_close,
24191            changed_heartbeat,
24192            unchanged_defaults,
24193        ] {
24194            let ctx = workflow_context(history.clone());
24195            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
24196            assert!(!ctx.patched("frozen-zero").unwrap());
24197            ctx.deprecate_patch("frozen-zero").unwrap();
24198            let mut call =
24199                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
24200            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24201            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24202                call.as_mut().poll(&mut task_context)
24203            else {
24204                panic!("changed explicit policy must fail replay")
24205            };
24206            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
24207            assert_eq!(failure.sequence, Some(2));
24208            assert!(ctx.take_commands().unwrap().is_empty());
24209        }
24210    }
24211
24212    #[test]
24213    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
24214        let cases = [
24215            (
24216                ActivityOptions::new().task_queue("  "),
24217                ActivityOptionsErrorKind::EmptyTaskQueue,
24218            ),
24219            (
24220                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
24221                ActivityOptionsErrorKind::EmptyRetryPolicy,
24222            ),
24223            (
24224                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
24225                ActivityOptionsErrorKind::InvalidMaxAttempts,
24226            ),
24227            (
24228                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
24229                    max_attempts: None,
24230                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
24231                    non_retryable_error_types: Vec::new(),
24232                }),
24233                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
24234            ),
24235            (
24236                ActivityOptions::new().retry_policy(
24237                    ActivityRetryPolicy::new(2).exponential_backoff(
24238                        Duration::from_secs(1),
24239                        0,
24240                        None,
24241                    ),
24242                ),
24243                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
24244            ),
24245            (
24246                ActivityOptions::new()
24247                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
24248                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
24249            ),
24250            (
24251                ActivityOptions::new().retry_policy(
24252                    ActivityRetryPolicy::new(10_002).exponential_backoff(
24253                        Duration::from_secs(1),
24254                        1,
24255                        None,
24256                    ),
24257                ),
24258                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
24259            ),
24260            (
24261                ActivityOptions::new().retry_policy(
24262                    ActivityRetryPolicy::new(2)
24263                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
24264                ),
24265                ActivityOptionsErrorKind::BackoffOverflow,
24266            ),
24267        ];
24268
24269        for (options, expected_kind) in cases {
24270            let ctx = workflow_context(Vec::new());
24271            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
24272            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24273            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
24274                call.as_mut().poll(&mut task_context)
24275            else {
24276                panic!("expected typed activity validation error");
24277            };
24278            assert_eq!(error.kind, expected_kind);
24279            assert!(ctx.take_commands().expect("commands").is_empty());
24280        }
24281    }
24282
24283    #[test]
24284    fn activity_options_validate_positive_and_ordered_timeouts() {
24285        let zero_timeout_cases = [
24286            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
24287            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
24288            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
24289            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
24290        ];
24291        for options in zero_timeout_cases {
24292            assert_eq!(
24293                options.validate().expect_err("zero timeout").kind,
24294                ActivityOptionsErrorKind::TimeoutNotPositive
24295            );
24296        }
24297
24298        let ordering_cases = [
24299            ActivityOptions::new()
24300                .heartbeat_timeout(Duration::from_secs(11))
24301                .start_to_close_timeout(Duration::from_secs(10)),
24302            ActivityOptions::new()
24303                .start_to_close_timeout(Duration::from_secs(31))
24304                .schedule_to_close_timeout(Duration::from_secs(30)),
24305            ActivityOptions::new()
24306                .schedule_to_start_timeout(Duration::from_secs(31))
24307                .schedule_to_close_timeout(Duration::from_secs(30)),
24308        ];
24309        for options in ordering_cases {
24310            assert_eq!(
24311                options.validate().expect_err("timeout order").kind,
24312                ActivityOptionsErrorKind::TimeoutOrder
24313            );
24314        }
24315
24316        assert_eq!(
24317            ActivityOptions::new()
24318                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
24319                .validate()
24320                .expect_err("protocol integer overflow")
24321                .kind,
24322            ActivityOptionsErrorKind::TimeoutOverflow
24323        );
24324    }
24325
24326    #[test]
24327    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
24328        let ctx = workflow_context(completed_retry_activity_history());
24329        let mut call =
24330            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
24331        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24332
24333        assert!(matches!(
24334            call.as_mut().poll(&mut task_context),
24335            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
24336        ));
24337        assert!(ctx.take_commands().expect("commands").is_empty());
24338        ctx.ensure_history_consumed().expect("history consumed");
24339    }
24340
24341    #[test]
24342    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
24343        let mut options = retry_activity_options();
24344        options
24345            .retry_policy
24346            .as_mut()
24347            .expect("retry policy")
24348            .non_retryable_error_types
24349            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
24350
24351        let new_ctx = workflow_context(Vec::new());
24352        let mut new_call =
24353            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
24354        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24355        assert!(matches!(
24356            new_call.as_mut().poll(&mut task_context),
24357            Poll::Pending
24358        ));
24359        let commands = new_ctx.take_commands().expect("commands");
24360        assert_eq!(commands.len(), 1);
24361        assert_eq!(
24362            commands[0]["retry_policy"]["non_retryable_error_types"],
24363            json!(["PermanentError"])
24364        );
24365
24366        let replay_ctx = workflow_context(completed_retry_activity_history());
24367        let mut replay_call =
24368            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
24369        assert!(matches!(
24370            replay_call.as_mut().poll(&mut task_context),
24371            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
24372        ));
24373        assert!(replay_ctx.take_commands().expect("commands").is_empty());
24374        replay_ctx
24375            .ensure_history_consumed()
24376            .expect("history consumed");
24377    }
24378
24379    #[test]
24380    fn replayed_intermediate_retry_remains_pending_across_restarts() {
24381        let history = completed_retry_activity_history()
24382            .into_iter()
24383            .take(3)
24384            .collect::<Vec<_>>();
24385
24386        for _restart in 0..2 {
24387            let ctx = workflow_context(history.clone());
24388            let mut call =
24389                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
24390            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24391            assert!(matches!(
24392                call.as_mut().poll(&mut task_context),
24393                Poll::Pending
24394            ));
24395            assert!(ctx.take_commands().expect("commands").is_empty());
24396        }
24397    }
24398
24399    #[test]
24400    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
24401        let mut changed_queue = retry_activity_options();
24402        changed_queue.task_queue = Some("different-queue".to_string());
24403
24404        let mut changed_max_attempts = retry_activity_options();
24405        let retry_policy = changed_max_attempts
24406            .retry_policy
24407            .as_mut()
24408            .expect("retry policy");
24409        retry_policy.max_attempts = Some(4);
24410
24411        let mut changed_backoff = retry_activity_options();
24412        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
24413        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
24414            Duration::from_secs(3),
24415            Duration::from_secs(4),
24416        ]));
24417
24418        let mut changed_non_retryable_types = retry_activity_options();
24419        let retry_policy = changed_non_retryable_types
24420            .retry_policy
24421            .as_mut()
24422            .expect("retry policy");
24423        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
24424
24425        let mut changed_start_to_close = retry_activity_options();
24426        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
24427        let mut changed_schedule_to_start = retry_activity_options();
24428        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
24429        let mut changed_schedule_to_close = retry_activity_options();
24430        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
24431        let mut changed_heartbeat = retry_activity_options();
24432        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
24433
24434        let cases = [
24435            (changed_queue, "activity_task_queue_mismatch"),
24436            (changed_max_attempts, "activity_retry_policy_mismatch"),
24437            (changed_backoff, "activity_retry_policy_mismatch"),
24438            (
24439                changed_non_retryable_types,
24440                "activity_retry_policy_mismatch",
24441            ),
24442            (changed_start_to_close, "activity_retry_policy_mismatch"),
24443            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
24444            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
24445            (changed_heartbeat, "activity_retry_policy_mismatch"),
24446        ];
24447
24448        for (options, expected_reason) in cases {
24449            let ctx = workflow_context(completed_retry_activity_history());
24450            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
24451            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24452            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24453                call.as_mut().poll(&mut task_context)
24454            else {
24455                panic!("changed activity options must fail replay");
24456            };
24457            assert_eq!(failure.reason, expected_reason);
24458            assert_eq!(failure.sequence, Some(1));
24459            assert!(ctx.take_commands().expect("commands").is_empty());
24460        }
24461    }
24462
24463    #[test]
24464    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
24465        let cases = [
24466            (
24467                "execution_mode",
24468                json!("local"),
24469                "activity_execution_mode_mismatch",
24470            ),
24471            (
24472                "snapshot_version",
24473                json!(2),
24474                "activity_retry_policy_mismatch",
24475            ),
24476        ];
24477
24478        for (field, value, expected_reason) in cases {
24479            let mut history = completed_retry_activity_history();
24480            let activity = history[0].payload["activity"]
24481                .as_object_mut()
24482                .expect("activity snapshot");
24483            if field == "execution_mode" {
24484                activity.insert(field.to_string(), value);
24485            } else {
24486                activity["retry_policy"]
24487                    .as_object_mut()
24488                    .expect("retry snapshot")
24489                    .insert(field.to_string(), value);
24490            }
24491
24492            let ctx = workflow_context(history);
24493            let mut call =
24494                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
24495            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24496            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24497                call.as_mut().poll(&mut task_context)
24498            else {
24499                panic!("changed {field} must fail replay");
24500            };
24501            assert_eq!(failure.reason, expected_reason);
24502            assert_eq!(failure.sequence, Some(1));
24503            assert!(ctx.take_commands().expect("commands").is_empty());
24504        }
24505    }
24506
24507    #[test]
24508    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
24509        for (nested, field, value, terminal_only) in [
24510            (false, "execution_mode", json!("local"), false),
24511            (false, "local_activity", json!(true), false),
24512            (true, "local_activity", json!(true), false),
24513            (false, "local_activity", json!(true), true),
24514        ] {
24515            let mut history = completed_retry_activity_history();
24516            history[0]
24517                .payload
24518                .as_object_mut()
24519                .unwrap()
24520                .remove("activity");
24521            let event = if terminal_only {
24522                history.last_mut().unwrap()
24523            } else {
24524                &mut history[0]
24525            };
24526            if nested {
24527                event.payload["activity"] = json!({(field): value});
24528            } else {
24529                event.payload[field] = value;
24530            }
24531            let ctx = workflow_context(history);
24532            let mut call =
24533                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
24534            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24535            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24536                call.as_mut().poll(&mut task_context)
24537            else {
24538                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
24539            };
24540            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
24541            assert_eq!(failure.sequence, Some(1));
24542            assert!(ctx.take_commands().expect("commands").is_empty());
24543        }
24544    }
24545
24546    #[test]
24547    fn activity_history_rejects_conflicting_local_execution_markers() {
24548        let mut history = completed_retry_activity_history();
24549        history.last_mut().unwrap().payload["local_activity"] = json!(true);
24550        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
24551            .expect_err("remote schedule cannot become a local completion");
24552        assert!(
24553            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
24554            if reason == "activity_execution_mode_conflict")
24555        );
24556    }
24557
24558    #[test]
24559    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
24560        let mut history = completed_retry_activity_history();
24561        let activity = history[0].payload["activity"]
24562            .as_object_mut()
24563            .expect("activity snapshot");
24564        activity.remove("execution_mode");
24565        activity.remove("retry_policy");
24566
24567        let mut current = retry_activity_options();
24568        current.start_to_close_timeout = Some(Duration::from_secs(45));
24569        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
24570        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
24571        current.heartbeat_timeout = Some(Duration::from_secs(12));
24572
24573        let ctx = workflow_context(history);
24574        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
24575        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24576        assert!(matches!(
24577            call.as_mut().poll(&mut task_context),
24578            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
24579        ));
24580        assert!(ctx.take_commands().expect("commands").is_empty());
24581        ctx.ensure_history_consumed().expect("history consumed");
24582    }
24583
24584    #[test]
24585    fn terminal_activity_failed_after_start_returns_typed_failure() {
24586        let history = vec![
24587            history_event(
24588                "ActivityScheduled",
24589                json!({
24590                    "sequence": 1,
24591                    "activity_type": "flaky",
24592                    "activity_execution_id": "act-terminal",
24593                    "activity": {
24594                        "id": "act-terminal",
24595                        "sequence": 1,
24596                        "type": "flaky",
24597                        "queue": "critical-activities",
24598                        "retry_policy": {
24599                            "snapshot_version": 1,
24600                            "max_attempts": 3,
24601                            "backoff_seconds": [2, 4],
24602                            "non_retryable_error_types": ["PermanentError"]
24603                        }
24604                    }
24605                }),
24606            ),
24607            history_event(
24608                "ActivityStarted",
24609                json!({
24610                    "sequence": 1,
24611                    "activity_type": "flaky",
24612                    "activity_execution_id": "act-terminal",
24613                    "activity_attempt_id": "attempt-1",
24614                    "attempt_number": 1
24615                }),
24616            ),
24617            history_event(
24618                "ActivityFailed",
24619                json!({
24620                    "sequence": 1,
24621                    "activity_type": "flaky",
24622                    "activity_execution_id": "act-terminal",
24623                    "activity_attempt_id": "attempt-1",
24624                    "attempt_number": 1,
24625                    "failure_id": "failure-terminal",
24626                    "failure_category": "activity",
24627                    "exception_type": "PermanentError",
24628                    "message": "cannot retry",
24629                    "non_retryable": true
24630                }),
24631            ),
24632        ];
24633        let ctx = workflow_context(history);
24634        let mut call =
24635            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
24636        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24637
24638        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
24639            call.as_mut().poll(&mut task_context)
24640        else {
24641            panic!("terminal ActivityFailed must settle the activity future");
24642        };
24643        assert_eq!(failure.kind, ActivityFailureKind::Failed);
24644        assert_eq!(
24645            failure.activity_execution_id.as_deref(),
24646            Some("act-terminal")
24647        );
24648        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
24649        assert!(failure.non_retryable);
24650        assert!(ctx.take_commands().expect("commands").is_empty());
24651        ctx.ensure_history_consumed().expect("history consumed");
24652    }
24653
24654    #[test]
24655    fn activity_terminal_events_return_machine_readable_failures() {
24656        let cases = [
24657            (
24658                "ActivityFailed",
24659                json!({
24660                    "sequence": 1,
24661                    "activity_type": "charge-card",
24662                    "activity_execution_id": "act-1",
24663                    "activity_attempt_id": "attempt-2",
24664                    "attempt_number": 2,
24665                    "failure_id": "failure-1",
24666                    "failure_category": "activity",
24667                    "exception_type": "PaymentDeclined",
24668                    "exception_class": "payments.PaymentDeclined",
24669                    "message": "card declined",
24670                    "non_retryable": true
24671                }),
24672                ActivityFailureKind::Failed,
24673                "activity",
24674            ),
24675            (
24676                "ActivityCancelled",
24677                json!({
24678                    "sequence": 1,
24679                    "activity_type": "charge-card",
24680                    "activity_execution_id": "act-1",
24681                    "activity_attempt_id": "attempt-1"
24682                }),
24683                ActivityFailureKind::Cancelled,
24684                "cancelled",
24685            ),
24686        ];
24687
24688        for (event_type, payload, expected_kind, expected_reason) in cases {
24689            let ctx = workflow_context(vec![history_event(event_type, payload)]);
24690            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
24691            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24692            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
24693                call.as_mut().poll(&mut task_context)
24694            else {
24695                panic!("expected terminal activity failure");
24696            };
24697            assert_eq!(failure.kind, expected_kind);
24698            assert_eq!(failure.reason, expected_reason);
24699            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
24700            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
24701        }
24702    }
24703
24704    #[test]
24705    fn every_activity_timeout_class_is_typed() {
24706        for timeout_kind in [
24707            "start_to_close",
24708            "schedule_to_start",
24709            "schedule_to_close",
24710            "heartbeat",
24711        ] {
24712            let ctx = workflow_context(vec![history_event(
24713                "ActivityTimedOut",
24714                json!({
24715                    "sequence": 1,
24716                    "activity_type": "slow",
24717                    "activity_execution_id": "act-timeout",
24718                    "activity_attempt_id": "attempt-timeout",
24719                    "failure_category": "timeout",
24720                    "timeout_kind": timeout_kind,
24721                    "message": "deadline expired"
24722                }),
24723            )]);
24724            let mut call = Box::pin(ctx.activity("slow", json!([])));
24725            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24726            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
24727                call.as_mut().poll(&mut task_context)
24728            else {
24729                panic!("expected timeout failure");
24730            };
24731            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
24732            assert_eq!(failure.reason, timeout_kind);
24733            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
24734            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
24735        }
24736    }
24737
24738    #[test]
24739    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
24740        let ctx = workflow_context(Vec::new());
24741        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
24742        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24743
24744        assert!(matches!(
24745            sleep.as_mut().poll(&mut task_context),
24746            Poll::Pending
24747        ));
24748        assert!(matches!(
24749            sleep.as_mut().poll(&mut task_context),
24750            Poll::Pending
24751        ));
24752
24753        let commands = ctx.take_commands().expect("timer command");
24754        assert_eq!(
24755            commands,
24756            vec![json!({
24757                "type": "start_timer",
24758                "delay_seconds": 2,
24759            })]
24760        );
24761    }
24762
24763    #[test]
24764    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
24765        let history = vec![
24766            history_event(
24767                "TimerScheduled",
24768                json!({
24769                    "sequence": 1,
24770                    "timer_id": "timer-1",
24771                    "delay_seconds": 5,
24772                    "fire_at": "2026-07-11T12:00:05Z",
24773                }),
24774            ),
24775            history_event(
24776                "TimerFired",
24777                json!({
24778                    "sequence": 1,
24779                    "timer_id": "timer-1",
24780                    "delay_seconds": 5,
24781                    "fire_at": "2026-07-11T12:00:05Z",
24782                    "fired_at": "2026-07-11T12:00:05Z",
24783                }),
24784            ),
24785        ];
24786
24787        for _restart in 0..2 {
24788            let ctx = workflow_context(history.clone());
24789            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
24790            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24791            assert!(matches!(
24792                sleep.as_mut().poll(&mut task_context),
24793                Poll::Ready(Ok(()))
24794            ));
24795            assert!(ctx.take_commands().expect("commands").is_empty());
24796            ctx.ensure_history_consumed().expect("history consumed");
24797        }
24798    }
24799
24800    #[test]
24801    fn workflow_sleep_rejects_changed_delay_during_replay() {
24802        let ctx = workflow_context(vec![
24803            history_event(
24804                "TimerScheduled",
24805                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24806            ),
24807            history_event(
24808                "TimerFired",
24809                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
24810            ),
24811        ]);
24812        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
24813        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24814
24815        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
24816            sleep.as_mut().poll(&mut task_context)
24817        else {
24818            panic!("changed timer delay must be rejected");
24819        };
24820        assert_eq!(failure.reason, "timer_delay_mismatch");
24821        assert_eq!(failure.sequence, Some(1));
24822    }
24823
24824    #[test]
24825    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
24826        let ctx = workflow_context(Vec::new());
24827        let mut wait = Box::pin(
24828            ctx.wait_condition(
24829                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
24830                    .timeout(Duration::from_millis(60_001)),
24831                || Ok(false),
24832            ),
24833        );
24834        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24835
24836        assert!(matches!(
24837            wait.as_mut().poll(&mut task_context),
24838            Poll::Pending
24839        ));
24840        assert!(matches!(
24841            wait.as_mut().poll(&mut task_context),
24842            Poll::Pending
24843        ));
24844        assert_eq!(
24845            ctx.take_commands().expect("condition command"),
24846            vec![json!({
24847                "type": "open_condition_wait",
24848                "condition_wait_occurrence_id": "rust:condition-wait:0",
24849                "condition_key": "approval.ready",
24850                "condition_definition_fingerprint": "sha256:approval-v1",
24851                "timeout_seconds": 61,
24852            })]
24853        );
24854    }
24855
24856    #[test]
24857    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
24858        let ctx = workflow_context(Vec::new());
24859        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
24860        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24861        assert!(matches!(
24862            satisfied.as_mut().poll(&mut task_context),
24863            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24864        ));
24865
24866        let mut timed_out = Box::pin(wait_condition!(
24867            ctx,
24868            "no-wait",
24869            timeout: Duration::ZERO,
24870            || Ok(false),
24871        ));
24872        assert!(matches!(
24873            timed_out.as_mut().poll(&mut task_context),
24874            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
24875        ));
24876        assert!(ctx.take_commands().expect("commands").is_empty());
24877    }
24878
24879    #[test]
24880    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
24881        let signal_history = vec![
24882            history_event(
24883                "ConditionWaitOpened",
24884                json!({
24885                    "sequence": 4,
24886                    "condition_wait_id": "condition:4",
24887                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24888                    "condition_key": "approval",
24889                    "condition_definition_fingerprint": "sha256:approval-v1",
24890                    "timeout_seconds": 30,
24891                }),
24892            ),
24893            history_event(
24894                "SignalReceived",
24895                json!({
24896                    "workflow_sequence": 4,
24897                    "signal_name": "approve",
24898                    "arguments": fixture_envelope(json!(["Ada"])),
24899                }),
24900            ),
24901        ];
24902        for _worker_before_or_after_restart in 0..2 {
24903            let ctx = workflow_context(signal_history.clone());
24904            let predicate_ctx = ctx.clone();
24905            let mut wait = Box::pin(
24906                ctx.wait_condition(
24907                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
24908                        .timeout(Duration::from_secs(30)),
24909                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
24910                ),
24911            );
24912            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24913            assert!(matches!(
24914                wait.as_mut().poll(&mut task_context),
24915                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24916            ));
24917            assert!(ctx.take_commands().expect("commands").is_empty());
24918            ctx.ensure_history_consumed().expect("condition consumed");
24919        }
24920
24921        let update_history = vec![
24922            history_event(
24923                "ConditionWaitOpened",
24924                json!({
24925                    "sequence": 7,
24926                    "condition_wait_id": "condition:7",
24927                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24928                    "condition_key": "update-approval",
24929                    "condition_definition_fingerprint": "sha256:update-approval-v1",
24930                }),
24931            ),
24932            history_event(
24933                "UpdateApplied",
24934                json!({
24935                    "sequence": 7,
24936                    "update_id": "update-1",
24937                    "update_name": "approve",
24938                    "arguments": fixture_envelope(json!([true])),
24939                }),
24940            ),
24941        ];
24942        let ctx = workflow_context(update_history);
24943        let predicate_ctx = ctx.clone();
24944        let mut wait = Box::pin(ctx.wait_condition(
24945            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
24946            move || {
24947                Ok(predicate_ctx
24948                    .updates("approve")?
24949                    .first()
24950                    .and_then(|arguments| arguments.first())
24951                    .and_then(Value::as_bool)
24952                    == Some(true))
24953            },
24954        ));
24955        let mut task_context = TaskContext::from_waker(noop_waker_ref());
24956        assert!(matches!(
24957            wait.as_mut().poll(&mut task_context),
24958            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
24959        ));
24960        assert!(ctx.take_commands().expect("commands").is_empty());
24961        ctx.ensure_history_consumed().expect("condition consumed");
24962    }
24963
24964    #[test]
24965    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
24966        let open_history = vec![
24967            history_event(
24968                "ConditionWaitOpened",
24969                json!({
24970                    "sequence": 3,
24971                    "condition_wait_id": "condition:3",
24972                    "condition_wait_occurrence_id": "rust:condition-wait:0",
24973                    "condition_key": "two-votes",
24974                    "condition_definition_fingerprint": "sha256:two-votes-v1",
24975                    "timeout_seconds": 120,
24976                }),
24977            ),
24978            history_event(
24979                "SignalReceived",
24980                json!({
24981                    "workflow_sequence": 3,
24982                    "signal_name": "vote",
24983                    "arguments": fixture_envelope(json!(["first"])),
24984                }),
24985            ),
24986        ];
24987        for _worker_before_or_after_restart in 0..2 {
24988            let ctx = workflow_context(open_history.clone());
24989            let predicate_ctx = ctx.clone();
24990            let mut wait = Box::pin(
24991                ctx.wait_condition(
24992                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
24993                        .timeout(Duration::from_secs(120)),
24994                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
24995                ),
24996            );
24997            let mut task_context = TaskContext::from_waker(noop_waker_ref());
24998            assert!(matches!(
24999                wait.as_mut().poll(&mut task_context),
25000                Poll::Pending
25001            ));
25002            assert_eq!(
25003                ctx.take_commands().expect("reopened condition"),
25004                vec![json!({
25005                    "type": "open_condition_wait",
25006                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25007                    "condition_key": "two-votes",
25008                    "condition_definition_fingerprint": "sha256:two-votes-v1",
25009                    "timeout_seconds": 120,
25010                })]
25011            );
25012        }
25013
25014        let satisfied_ctx = workflow_context(vec![
25015            history_event(
25016                "ConditionWaitOpened",
25017                json!({
25018                    "sequence": 5,
25019                    "condition_wait_id": "condition:5",
25020                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25021                    "condition_key": "approval",
25022                    "condition_definition_fingerprint": "sha256:approval-v1",
25023                }),
25024            ),
25025            history_event(
25026                "ConditionWaitSatisfied",
25027                json!({
25028                    "sequence": 5,
25029                    "condition_wait_id": "condition:5",
25030                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25031                    "condition_key": "approval",
25032                    "condition_definition_fingerprint": "sha256:approval-v1",
25033                }),
25034            ),
25035        ]);
25036        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
25037            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
25038            || Ok(false),
25039        ));
25040        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25041        assert!(matches!(
25042            satisfied.as_mut().poll(&mut task_context),
25043            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
25044        ));
25045
25046        let timed_out_ctx = workflow_context(vec![
25047            history_event(
25048                "ConditionWaitOpened",
25049                json!({
25050                    "sequence": 8,
25051                    "condition_wait_id": "condition:8",
25052                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25053                    "condition_key": "approval-timeout",
25054                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
25055                    "timeout_seconds": 5,
25056                }),
25057            ),
25058            history_event(
25059                "TimerScheduled",
25060                json!({
25061                    "sequence": 9,
25062                    "timer_id": "condition-timer:9",
25063                    "timer_kind": "condition_timeout",
25064                    "condition_wait_id": "condition:8",
25065                    "delay_seconds": 5,
25066                }),
25067            ),
25068            history_event(
25069                "TimerFired",
25070                json!({
25071                    "sequence": 9,
25072                    "timer_id": "condition-timer:9",
25073                    "timer_kind": "condition_timeout",
25074                    "condition_wait_id": "condition:8",
25075                    "delay_seconds": 5,
25076                }),
25077            ),
25078        ]);
25079        let mut timed_out = Box::pin(
25080            timed_out_ctx.wait_condition(
25081                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
25082                    .timeout(Duration::from_secs(5)),
25083                || Ok(true),
25084            ),
25085        );
25086        assert!(matches!(
25087            timed_out.as_mut().poll(&mut task_context),
25088            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
25089        ));
25090    }
25091
25092    #[test]
25093    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
25094        let ctx = workflow_context(reopened_selection_condition_history());
25095        {
25096            let state = ctx.state.lock().unwrap();
25097            assert!(matches!(
25098                selection_member_recorded_command(&state, 2),
25099                Some(RecordedCommand::ConditionWait {
25100                    sequence: 3,
25101                    result: None,
25102                    ..
25103                })
25104            ));
25105        }
25106        let mut selected = Box::pin(ctx.select_keyed(vec![
25107            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
25108            (
25109                "votes",
25110                ParallelOperation::condition(
25111                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
25112                    || Ok(true),
25113                ),
25114            ),
25115        ]));
25116        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25117        assert!(selected.as_mut().poll(&mut task_context).is_pending());
25118        assert!(
25119            ctx.take_commands().unwrap().is_empty(),
25120            "true predicate must not reopen the recorded wait"
25121        );
25122        ctx.ensure_history_consumed()
25123            .expect("physical reopens are consumed while canonical selection is pending");
25124    }
25125
25126    #[test]
25127    fn reopened_selection_condition_replays_its_latest_physical_winner() {
25128        for (terminal_type, acknowledge_timeout) in [
25129            ("ConditionWaitSatisfied", false),
25130            ("ConditionWaitTimedOut", false),
25131            ("TimerFired", false),
25132            ("TimerFired", true),
25133        ] {
25134            let mut history = reopened_selection_condition_history();
25135            let original_identity = history[1].payload["condition_wait_id"].clone();
25136            let uses_timer = terminal_type == "TimerFired";
25137            let mut resolution_payload = history[3].payload.clone();
25138            if uses_timer {
25139                for event in &mut history[1..] {
25140                    event.payload["timeout_seconds"] = json!(3);
25141                }
25142                resolution_payload = history[3].payload.clone();
25143                resolution_payload["timer_kind"] = json!("condition_timeout");
25144                resolution_payload["timer_id"] = json!("condition-timeout-3");
25145                resolution_payload["delay_seconds"] = json!(3);
25146                history.push(history_event("TimerScheduled", resolution_payload.clone()));
25147            }
25148            let mut resolution = history_event(terminal_type, resolution_payload.clone());
25149            resolution
25150                .raw
25151                .insert("id".into(), json!("latest-condition-resolution"));
25152            history.push(resolution);
25153            history.push(history_event(
25154                "SelectionResolved",
25155                json!({
25156                    "selection_group_id": "select-calls:1:2",
25157                    "selection_group_base_sequence": 1,
25158                    "selection_group_size": 2,
25159                    "member_key": "votes",
25160                    "member_index": 1,
25161                    "member_base_sequence": 2,
25162                    "member_size": 1,
25163                    "operation_kind": "condition",
25164                    "operation_identity": original_identity,
25165                    "outcome": "completed",
25166                    "resolution_event_id": "latest-condition-resolution",
25167                    "resolution_event_type": terminal_type,
25168                }),
25169            ));
25170            if acknowledge_timeout {
25171                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
25172            }
25173            let ctx = workflow_context(history);
25174            let mut selected = Box::pin(ctx.select_keyed(vec![
25175                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
25176                (
25177                    "votes",
25178                    ParallelOperation::condition(
25179                        if uses_timer {
25180                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
25181                                .timeout(Duration::from_secs(3))
25182                        } else {
25183                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
25184                        },
25185                        || Ok(true),
25186                    ),
25187                ),
25188            ]));
25189            let mut task_context = TaskContext::from_waker(noop_waker_ref());
25190            match selected.as_mut().poll(&mut task_context) {
25191                Poll::Ready(Ok(result)) => {
25192                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
25193                    let expected = if terminal_type == "ConditionWaitSatisfied" {
25194                        ConditionWaitResult::Satisfied
25195                    } else {
25196                        ConditionWaitResult::TimedOut
25197                    };
25198                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
25199                }
25200                other => panic!("latest physical winner must replay: {other:?}"),
25201            }
25202            assert!(ctx.take_commands().unwrap().is_empty());
25203            ctx.ensure_history_consumed()
25204                .expect("winner history consumed");
25205        }
25206    }
25207
25208    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
25209        let fixture: Value = serde_json::from_str(include_str!(
25210            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
25211        ))
25212        .expect("grouped condition fixture");
25213        fixture["history"]
25214            .as_array()
25215            .unwrap()
25216            .iter()
25217            .map(|event| {
25218                let mut payload = event["payload"].clone();
25219                let index = payload["parallel_group_index"].as_u64().unwrap();
25220                payload["parallel_group_id"] = json!("select-calls:1:2");
25221                payload["parallel_group_mode"] = json!("select");
25222                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
25223                payload["selection_member_index"] = json!(index);
25224                payload["selection_member_base_sequence"] = json!(index + 1);
25225                payload["selection_member_size"] = json!(1);
25226                payload["selection_member_kind"] =
25227                    json!(if index == 0 { "timer" } else { "condition" });
25228                history_event(event["event_type"].as_str().unwrap(), payload)
25229            })
25230            .collect()
25231    }
25232
25233    fn grouped_wait(sequence: u64, base: u64, size: usize, index: usize) -> RecordedCommand {
25234        RecordedCommand::ConditionWait {
25235            sequence,
25236            occurrence_id: format!("rust:condition-wait:{base}-{index}"),
25237            condition_key: Some(format!("member-{index}")),
25238            predicate_identity: format!("sha256:member-{index}"),
25239            timeout_seconds: Some(300),
25240            result: None,
25241            parallel_group_path: Some(vec![parallel_group_entry(base, size, index, "condition")]),
25242        }
25243    }
25244
25245    fn order(commands: Vec<RecordedCommand>) -> Vec<u64> {
25246        group_condition_reopens_by_member(commands)
25247            .iter()
25248            .map(RecordedCommand::sequence)
25249            .collect()
25250    }
25251
25252    // #191: reorder only within a contiguous run of one group's condition
25253    // waits, member by member, keeping each member's own order.
25254    #[test]
25255    fn grouped_reopens_are_ordered_by_member_only_within_one_contiguous_group_run() {
25256        // Three members with unequal reopen counts: a1 b1 c1 a2 c2 a3.
25257        assert_eq!(
25258            order(vec![
25259                grouped_wait(1, 1, 3, 0),
25260                grouped_wait(2, 1, 3, 1),
25261                grouped_wait(3, 1, 3, 2),
25262                grouped_wait(4, 1, 3, 0),
25263                grouped_wait(5, 1, 3, 2),
25264                grouped_wait(6, 1, 3, 0),
25265            ]),
25266            vec![1, 4, 6, 2, 3, 5]
25267        );
25268
25269        // Another command between members ends the run: nothing moves across it.
25270        assert_eq!(
25271            order(vec![
25272                grouped_wait(1, 1, 2, 0),
25273                RecordedCommand::Timer {
25274                    sequence: 2,
25275                    delay_seconds: 5,
25276                    fired: false,
25277                    parallel_group_path: None,
25278                },
25279                grouped_wait(3, 1, 2, 1),
25280                grouped_wait(4, 1, 2, 0),
25281            ]),
25282            vec![1, 2, 3, 4]
25283        );
25284
25285        // A timer of the same group between condition members keeps its place
25286        // while each condition member's reopens join it (#194):
25287        // a1 t b1 a2 b2 -> a1 a2 t b1 b2.
25288        assert_eq!(
25289            order(vec![
25290                grouped_wait(1, 1, 3, 0),
25291                RecordedCommand::Timer {
25292                    sequence: 2,
25293                    delay_seconds: 5,
25294                    fired: false,
25295                    parallel_group_path: Some(vec![parallel_group_entry(1, 3, 1, "condition")]),
25296                },
25297                grouped_wait(3, 1, 3, 2),
25298                grouped_wait(4, 1, 3, 0),
25299                grouped_wait(5, 1, 3, 2),
25300            ]),
25301            vec![1, 4, 2, 3, 5]
25302        );
25303
25304        // Two different groups interleaved never merge into one run.
25305        assert_eq!(
25306            order(vec![
25307                grouped_wait(1, 1, 2, 0),
25308                grouped_wait(10, 10, 2, 0),
25309                grouped_wait(2, 1, 2, 1),
25310                grouped_wait(11, 10, 2, 1),
25311            ]),
25312            vec![1, 10, 2, 11]
25313        );
25314
25315        // Ungrouped waits and an already member-ordered run are unchanged.
25316        let ungrouped = |sequence| RecordedCommand::ConditionWait {
25317            sequence,
25318            occurrence_id: "rust:condition-wait:0".into(),
25319            condition_key: Some("approval".into()),
25320            predicate_identity: "sha256:approval".into(),
25321            timeout_seconds: Some(30),
25322            result: None,
25323            parallel_group_path: None,
25324        };
25325        assert_eq!(order(vec![ungrouped(1), ungrouped(2)]), vec![1, 2]);
25326        assert_eq!(
25327            order(vec![
25328                grouped_wait(1, 1, 2, 0),
25329                grouped_wait(3, 1, 2, 0),
25330                grouped_wait(2, 1, 2, 1),
25331            ]),
25332            vec![1, 3, 2]
25333        );
25334    }
25335
25336    // General's #193 review: after a one-sided grouped reopen, recorded commands
25337    // are consumed out of sequence order, so a new group must start after the
25338    // highest recorded sequence, not after the last consumed command.
25339    #[test]
25340    fn a_group_after_a_one_sided_grouped_reopen_starts_after_the_highest_sequence() {
25341        let signals = vec![
25342            approval_signal("vote", "v1", "2026-11-04T03:55:13.000000+00:00"),
25343            approval_signal("vote", "v2", "2026-11-04T03:55:30.000000+00:00"),
25344            approval_signal("approve", "a1", "2026-11-04T03:55:30.100000+00:00"),
25345        ];
25346        for select in [false, true] {
25347            let ctx = workflow_context(one_sided_grouped_reopen_history(signals.clone()));
25348            let workflow = {
25349                let ctx = ctx.clone();
25350                async move {
25351                    let votes = ctx.clone();
25352                    let approvals = ctx.clone();
25353                    ctx.parallel(vec![
25354                        ParallelOperation::condition(
25355                            ConditionWaitOptions::new("votes", "sha256:votes-v1")
25356                                .timeout(Duration::from_secs(300)),
25357                            move || Ok(votes.signals("vote")?.len() >= 2),
25358                        ),
25359                        ParallelOperation::condition(
25360                            ConditionWaitOptions::new("approvals", "sha256:approvals-v1")
25361                                .timeout(Duration::from_secs(300)),
25362                            move || Ok(approvals.signals("approve")?.len() >= 1),
25363                        ),
25364                    ])
25365                    .await?;
25366                    if select {
25367                        ctx.select_keyed(vec![
25368                            ("a", ParallelOperation::timer(Duration::from_secs(5))),
25369                            ("b", ParallelOperation::timer(Duration::from_secs(6))),
25370                        ])
25371                        .await
25372                        .map(|_| ())
25373                    } else {
25374                        ctx.parallel(vec![
25375                            ParallelOperation::timer(Duration::from_secs(5)),
25376                            ParallelOperation::timer(Duration::from_secs(6)),
25377                        ])
25378                        .await
25379                        .map(|_| ())
25380                    }
25381                }
25382            };
25383            let mut workflow = Box::pin(workflow);
25384            let mut task_context = TaskContext::from_waker(noop_waker_ref());
25385            assert!(matches!(
25386                workflow.as_mut().poll(&mut task_context),
25387                Poll::Pending
25388            ));
25389            let commands = ctx.take_commands().expect("commands");
25390            assert_eq!(commands.len(), 2, "select {select}: {commands:?}");
25391            for command in &commands {
25392                assert_eq!(command["type"], json!("start_timer"));
25393                assert_eq!(
25394                    command["parallel_group_base_sequence"],
25395                    json!(4),
25396                    "select {select}: {command}"
25397                );
25398            }
25399        }
25400    }
25401
25402    // #194: a timer member between two condition members. The Server reopens
25403    // both condition members (votes 1, timer 2, approvals 3, votes 4,
25404    // approvals 5); each member must still consume its own reopen.
25405    #[test]
25406    fn a_timer_between_grouped_condition_members_does_not_strand_their_reopens() {
25407        let group = |index: u64| {
25408            json!({
25409                "parallel_group_id": "parallel-calls:1:3",
25410                "parallel_group_kind": "mixed",
25411                "parallel_group_base_sequence": 1,
25412                "parallel_group_size": 3,
25413                "parallel_group_index": index,
25414            })
25415        };
25416        let member = |event_type: &str, sequence: u64, index: u64, key: &str, at: &str| {
25417            let mut payload = group(index);
25418            payload["sequence"] = json!(sequence);
25419            payload["condition_wait_id"] = json!(format!("condition:{sequence}"));
25420            payload["condition_wait_occurrence_id"] = json!(format!(
25421                "rust:condition-wait:{}",
25422                if index == 0 { 0 } else { 1 }
25423            ));
25424            payload["condition_key"] = json!(key);
25425            payload["condition_definition_fingerprint"] = json!(format!("sha256:{key}-v1"));
25426            payload["timeout_seconds"] = json!(300);
25427            timed_event(event_type, at, payload)
25428        };
25429        let timer = |event_type: &str, at: &str| {
25430            let mut payload = group(1);
25431            payload["sequence"] = json!(2);
25432            payload["timer_id"] = json!("timer-2");
25433            payload["delay_seconds"] = json!(5);
25434            timed_event(event_type, at, payload)
25435        };
25436        let history = vec![
25437            member(
25438                "ConditionWaitOpened",
25439                1,
25440                0,
25441                "votes",
25442                "2026-11-04T03:55:10.900000+00:00",
25443            ),
25444            timer("TimerScheduled", "2026-11-04T03:55:10.901000+00:00"),
25445            member(
25446                "ConditionWaitOpened",
25447                3,
25448                2,
25449                "approvals",
25450                "2026-11-04T03:55:10.902000+00:00",
25451            ),
25452            timer("TimerFired", "2026-11-04T03:55:15.901000+00:00"),
25453            approval_signal("vote", "v1", "2026-11-04T03:55:16.000000+00:00"),
25454            member(
25455                "ConditionWaitSatisfied",
25456                1,
25457                0,
25458                "votes",
25459                "2026-11-04T03:55:16.100000+00:00",
25460            ),
25461            member(
25462                "ConditionWaitOpened",
25463                4,
25464                0,
25465                "votes",
25466                "2026-11-04T03:55:16.101000+00:00",
25467            ),
25468            member(
25469                "ConditionWaitOpened",
25470                5,
25471                2,
25472                "approvals",
25473                "2026-11-04T03:55:16.102000+00:00",
25474            ),
25475            approval_signal("vote", "v2", "2026-11-04T03:55:30.000000+00:00"),
25476            approval_signal("approve", "a1", "2026-11-04T03:55:30.100000+00:00"),
25477        ];
25478        let ctx = workflow_context(history);
25479        let votes = ctx.clone();
25480        let approvals = ctx.clone();
25481        let mut group = Box::pin(ctx.parallel(vec![
25482            ParallelOperation::condition(
25483                ConditionWaitOptions::new("votes", "sha256:votes-v1")
25484                    .timeout(Duration::from_secs(300)),
25485                move || Ok(votes.signals("vote")?.len() >= 2),
25486            ),
25487            ParallelOperation::timer(Duration::from_secs(5)),
25488            ParallelOperation::condition(
25489                ConditionWaitOptions::new("approvals", "sha256:approvals-v1")
25490                    .timeout(Duration::from_secs(300)),
25491                move || Ok(approvals.signals("approve")?.len() >= 1),
25492            ),
25493        ]));
25494        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25495        let poll = group.as_mut().poll(&mut task_context);
25496        let Poll::Ready(Ok(results)) = poll else {
25497            panic!("the group must complete: {poll:?}");
25498        };
25499        assert_eq!(results.len(), 3);
25500        ctx.ensure_history_consumed()
25501            .expect("every member consumes its own reopen");
25502        assert!(ctx.take_commands().expect("commands").is_empty());
25503    }
25504
25505    // #191: the PHP Server 2.11.8 history for two condition members woken by
25506    // one signal. It satisfies only the resume task's member (seq 2) but
25507    // records a reopen of the other, still-open member (seq 3 after seq 1).
25508    fn two_member_condition_history(extra_signals: &[(&str, &str)]) -> Vec<HistoryEvent> {
25509        let member = |event_type: &str, seq: u64, index: u64, key: &str, at: &str| {
25510            let occurrence = format!("rust:condition-wait:{index}");
25511            timed_event(
25512                event_type,
25513                at,
25514                json!({
25515                    "sequence": seq,
25516                    "condition_wait_id": format!("condition:{seq}"),
25517                    "condition_wait_occurrence_id": occurrence,
25518                    "condition_key": key,
25519                    "condition_definition_fingerprint": format!("sha256:{key}-v1"),
25520                    "timeout_seconds": 300,
25521                    "parallel_group_id": "parallel-calls:1:2",
25522                    "parallel_group_kind": "condition",
25523                    "parallel_group_base_sequence": 1,
25524                    "parallel_group_size": 2,
25525                    "parallel_group_index": index,
25526                }),
25527            )
25528        };
25529        let mut history = vec![
25530            member(
25531                "ConditionWaitOpened",
25532                1,
25533                0,
25534                "votes",
25535                "2026-11-04T03:55:10.900000+00:00",
25536            ),
25537            member(
25538                "ConditionWaitOpened",
25539                2,
25540                1,
25541                "approvals",
25542                "2026-11-04T03:55:10.901000+00:00",
25543            ),
25544            approval_signal("vote", "v1", "2026-11-04T03:55:13.000000+00:00"),
25545            member(
25546                "ConditionWaitSatisfied",
25547                2,
25548                1,
25549                "approvals",
25550                "2026-11-04T03:55:13.100000+00:00",
25551            ),
25552            member(
25553                "ConditionWaitOpened",
25554                3,
25555                0,
25556                "votes",
25557                "2026-11-04T03:55:13.101000+00:00",
25558            ),
25559            member(
25560                "ConditionWaitOpened",
25561                4,
25562                1,
25563                "approvals",
25564                "2026-11-04T03:55:13.102000+00:00",
25565            ),
25566        ];
25567        for (index, (name, at)) in extra_signals.iter().enumerate() {
25568            history.push(approval_signal(name, &format!("x{index}"), at));
25569        }
25570        history
25571    }
25572
25573    fn poll_two_member_group(
25574        history: Vec<HistoryEvent>,
25575    ) -> (Poll<Result<Vec<ParallelResult>>>, Vec<Value>) {
25576        let ctx = workflow_context(history);
25577        let votes = ctx.clone();
25578        let approvals = ctx.clone();
25579        let mut group = Box::pin(ctx.parallel(vec![
25580            ParallelOperation::condition(
25581                ConditionWaitOptions::new("votes", "sha256:votes-v1")
25582                    .timeout(Duration::from_secs(300)),
25583                move || Ok(votes.signals("vote")?.len() >= 2),
25584            ),
25585            ParallelOperation::condition(
25586                ConditionWaitOptions::new("approvals", "sha256:approvals-v1")
25587                    .timeout(Duration::from_secs(300)),
25588                move || Ok(approvals.signals("approve")?.len() >= 1),
25589            ),
25590        ]));
25591        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25592        let poll = group.as_mut().poll(&mut task_context);
25593        if matches!(poll, Poll::Ready(Ok(_))) {
25594            // Interleaved reopens (votes 1, approvals 2, votes 3, approvals 4)
25595            // must all be consumed by their own members.
25596            ctx.ensure_history_consumed()
25597                .expect("every physical reopen is consumed");
25598        }
25599        (poll, ctx.take_commands().expect("commands"))
25600    }
25601
25602    #[test]
25603    fn two_grouped_condition_members_replay_the_servers_reopen_of_a_still_open_member() {
25604        // The task after the false wake decodes and keeps both members waiting.
25605        let (poll, _) = poll_two_member_group(two_member_condition_history(&[]));
25606        assert!(matches!(poll, Poll::Pending), "{poll:?}");
25607
25608        // A second vote and an approval satisfy both members: the group completes.
25609        let (poll, commands) = poll_two_member_group(two_member_condition_history(&[
25610            ("vote", "2026-11-04T03:55:30.000000+00:00"),
25611            ("approve", "2026-11-04T03:55:30.100000+00:00"),
25612        ]));
25613        let Poll::Ready(Ok(results)) = poll else {
25614            panic!("both satisfied members must complete the group: {poll:?}");
25615        };
25616        assert_eq!(
25617            results,
25618            vec![
25619                ParallelResult::Condition(ConditionWaitResult::Satisfied),
25620                ParallelResult::Condition(ConditionWaitResult::Satisfied),
25621            ]
25622        );
25623        assert!(commands.is_empty(), "{commands:?}");
25624    }
25625
25626    // #189: the PHP Server accepts a grouped reopen only with the authored
25627    // timeout, so a parallel or select member reopens with it, not with the
25628    // remaining time an ungrouped wait uses.
25629    #[test]
25630    fn grouped_condition_reopen_sends_the_authored_timeout() {
25631        let fixture: Value = serde_json::from_str(include_str!(
25632            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
25633        ))
25634        .expect("grouped condition fixture");
25635        let base = fixture["history"].as_array().expect("fixture history")[..2].to_vec();
25636        for mode in ["parallel", "select"] {
25637            let mut history = base
25638                .iter()
25639                .map(|event| {
25640                    let mut payload = event["payload"].clone();
25641                    if mode == "select" {
25642                        let index = payload["parallel_group_index"].as_u64().unwrap();
25643                        payload["parallel_group_id"] = json!("select-calls:1:2");
25644                        payload["parallel_group_mode"] = json!("select");
25645                        payload["selection_member_key"] =
25646                            json!(if index == 0 { "timer" } else { "votes" });
25647                        payload["selection_member_index"] = json!(index);
25648                        payload["selection_member_base_sequence"] = json!(index + 1);
25649                        payload["selection_member_size"] = json!(1);
25650                        payload["selection_member_kind"] =
25651                            json!(if index == 0 { "timer" } else { "condition" });
25652                    }
25653                    if event["event_type"] == "ConditionWaitOpened" {
25654                        payload["timeout_seconds"] = json!(300);
25655                    }
25656                    timed_event(
25657                        event["event_type"].as_str().unwrap(),
25658                        "2026-11-04T02:36:05.000000+00:00",
25659                        payload,
25660                    )
25661                })
25662                .collect::<Vec<_>>();
25663            history.push(approval_signal(
25664                "vote",
25665                "v1",
25666                "2026-11-04T02:36:17.000000+00:00",
25667            ));
25668            let ctx = workflow_context(history);
25669            let condition = ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
25670                .timeout(Duration::from_secs(300));
25671            let mut task_context = TaskContext::from_waker(noop_waker_ref());
25672            let poll = if mode == "parallel" {
25673                let mut group = Box::pin(ctx.parallel(vec![
25674                    ParallelOperation::timer(Duration::from_secs(300)),
25675                    ParallelOperation::condition(condition, || Ok(false)),
25676                ]));
25677                group
25678                    .as_mut()
25679                    .poll(&mut task_context)
25680                    .map(|result| result.map(|_| ()))
25681            } else {
25682                let mut group = Box::pin(ctx.select_keyed(vec![
25683                    ("timer", ParallelOperation::timer(Duration::from_secs(300))),
25684                    (
25685                        "votes",
25686                        ParallelOperation::condition(condition, || Ok(false)),
25687                    ),
25688                ]));
25689                group
25690                    .as_mut()
25691                    .poll(&mut task_context)
25692                    .map(|result| result.map(|_| ()))
25693            };
25694            assert!(matches!(poll, Poll::Pending), "{mode}: {poll:?}");
25695            let commands = ctx.take_commands().expect("commands");
25696            let reopens = commands
25697                .iter()
25698                .filter(|command| command["type"] == "open_condition_wait")
25699                .collect::<Vec<_>>();
25700            assert_eq!(reopens.len(), 1, "{mode}: {commands:?}");
25701            assert_eq!(
25702                reopens[0]["condition_wait_occurrence_id"],
25703                json!("rust:condition-wait:0"),
25704                "{mode}"
25705            );
25706            assert_eq!(reopens[0]["timeout_seconds"], json!(300), "{mode}");
25707        }
25708    }
25709
25710    // #187: a grouped reopen carries the remaining time, so the next task must
25711    // accept a smaller recorded timeout and still refuse a larger or missing one.
25712    #[test]
25713    fn grouped_condition_reopen_accepts_a_remaining_time_timeout() {
25714        let fixture: Value = serde_json::from_str(include_str!(
25715            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
25716        ))
25717        .expect("grouped condition fixture");
25718        let mut original = fixture["history"]
25719            .as_array()
25720            .expect("fixture history")
25721            .clone();
25722        for index in [1, 2, 3] {
25723            original[index]["payload"]["timeout_seconds"] = json!(30);
25724        }
25725        let decode = |events: &[Value]| {
25726            let history = events
25727                .iter()
25728                .map(|event| {
25729                    history_event(
25730                        event["event_type"].as_str().unwrap(),
25731                        event["payload"].clone(),
25732                    )
25733                })
25734                .collect::<Vec<_>>();
25735            recorded_commands(
25736                &history,
25737                DEFAULT_CODEC,
25738                WorkflowIdentity {
25739                    workflow_id: None,
25740                    run_id: None,
25741                },
25742            )
25743        };
25744        // The same history as select members, as reopened_selection_condition_history builds it.
25745        let selection = original
25746            .iter()
25747            .map(|event| {
25748                let mut event = event.clone();
25749                let payload = &mut event["payload"];
25750                let index = payload["parallel_group_index"].as_u64().unwrap();
25751                payload["parallel_group_id"] = json!("select-calls:1:2");
25752                payload["parallel_group_mode"] = json!("select");
25753                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
25754                payload["selection_member_index"] = json!(index);
25755                payload["selection_member_base_sequence"] = json!(index + 1);
25756                payload["selection_member_size"] = json!(1);
25757                payload["selection_member_kind"] =
25758                    json!(if index == 0 { "timer" } else { "condition" });
25759                event
25760            })
25761            .collect::<Vec<_>>();
25762        for (mode, history) in [("parallel", &original), ("select", &selection)] {
25763            assert!(
25764                decode(history).is_ok(),
25765                "{mode}: full-timeout reopen still replays"
25766            );
25767            for (reopen, accepted) in [
25768                (json!(18), true),
25769                (json!(0), true),
25770                (json!(31), false),
25771                (Value::Null, false),
25772            ] {
25773                let mut changed = history.clone();
25774                changed[3]["payload"]["timeout_seconds"] = reopen.clone();
25775                let result = decode(&changed);
25776                assert_eq!(
25777                    result.is_ok(),
25778                    accepted,
25779                    "{mode} reopen timeout {reopen}: {result:?}"
25780                );
25781                if let Err(Error::NonDeterministicReplay(failure)) = result {
25782                    assert_eq!(failure.reason, "condition_wait_group_reopen_mismatch");
25783                }
25784            }
25785        }
25786    }
25787
25788    #[test]
25789    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
25790        let fixture: Value = serde_json::from_str(include_str!(
25791            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
25792        ))
25793        .expect("grouped condition fixture");
25794        let original = fixture["history"].as_array().expect("fixture history");
25795        let decode = |events: &[Value]| {
25796            let history = events
25797                .iter()
25798                .map(|event| {
25799                    history_event(
25800                        event["event_type"].as_str().unwrap(),
25801                        event["payload"].clone(),
25802                    )
25803                })
25804                .collect::<Vec<_>>();
25805            recorded_commands(
25806                &history,
25807                DEFAULT_CODEC,
25808                WorkflowIdentity {
25809                    workflow_id: None,
25810                    run_id: None,
25811                },
25812            )
25813        };
25814        assert!(decode(original).is_ok());
25815        for field in [
25816            "condition_wait_occurrence_id",
25817            "condition_key",
25818            "condition_definition_fingerprint",
25819            "timeout_seconds",
25820            "parallel_group_id",
25821            "parallel_group_size",
25822            "parallel_group_index",
25823        ] {
25824            let mut changed = original.clone();
25825            changed[3]["payload"][field] = match field {
25826                "timeout_seconds" | "parallel_group_size" => json!(30),
25827                "parallel_group_index" => json!(0),
25828                _ => json!("changed"),
25829            };
25830            assert!(
25831                decode(&changed).is_err(),
25832                "reopen must reject changed {field}"
25833            );
25834        }
25835        // #191: the PHP Server records a grouped re-send of a still-open member
25836        // as a new physical open. A predecessor that was unresolved when the
25837        // reopen opened (never resolved, or resolved only later) is the same
25838        // logical member, decided by the state at that open.
25839        let mut unsettled = original.clone();
25840        unsettled.remove(2);
25841        assert!(
25842            decode(&unsettled).is_ok(),
25843            "an unresolved predecessor is a repeated open"
25844        );
25845        let mut late_resolution = original.clone();
25846        late_resolution.swap(2, 3);
25847        assert!(
25848            decode(&late_resolution).is_ok(),
25849            "a predecessor resolved after the reopen was still open when it opened"
25850        );
25851        let mut timed_out = original.clone();
25852        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
25853        assert!(decode(&timed_out).is_err(), "timeout is terminal");
25854    }
25855
25856    #[test]
25857    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
25858        let history = vec![
25859            history_event(
25860                "ConditionWaitOpened",
25861                json!({
25862                    "sequence": 3,
25863                    "condition_wait_id": "condition:3",
25864                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25865                    "condition_key": "two-votes",
25866                    "condition_definition_fingerprint": "sha256:two-votes-v1",
25867                }),
25868            ),
25869            history_event(
25870                "SignalReceived",
25871                json!({
25872                    "workflow_sequence": 3,
25873                    "signal_name": "vote",
25874                    "arguments": fixture_envelope(json!(["first"])),
25875                }),
25876            ),
25877            history_event(
25878                "ConditionWaitSatisfied",
25879                json!({
25880                    "sequence": 3,
25881                    "condition_wait_id": "condition:3",
25882                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25883                    "condition_key": "two-votes",
25884                    "condition_definition_fingerprint": "sha256:two-votes-v1",
25885                }),
25886            ),
25887            history_event(
25888                "ConditionWaitOpened",
25889                json!({
25890                    "sequence": 5,
25891                    "condition_wait_id": "condition:5",
25892                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25893                    "condition_key": "two-votes",
25894                    "condition_definition_fingerprint": "sha256:two-votes-v1",
25895                }),
25896            ),
25897            history_event(
25898                "SignalReceived",
25899                json!({
25900                    "workflow_sequence": 5,
25901                    "signal_name": "vote",
25902                    "arguments": fixture_envelope(json!(["second"])),
25903                }),
25904            ),
25905            history_event(
25906                "ConditionWaitSatisfied",
25907                json!({
25908                    "sequence": 5,
25909                    "condition_wait_id": "condition:5",
25910                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25911                    "condition_key": "two-votes",
25912                    "condition_definition_fingerprint": "sha256:two-votes-v1",
25913                }),
25914            ),
25915        ];
25916        for _cold_worker_or_restart in 0..2 {
25917            let ctx = workflow_context(history.clone());
25918            let predicate_ctx = ctx.clone();
25919            let mut wait = Box::pin(ctx.wait_condition(
25920                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
25921                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
25922            ));
25923            let mut task_context = TaskContext::from_waker(noop_waker_ref());
25924
25925            assert!(matches!(
25926                wait.as_mut().poll(&mut task_context),
25927                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
25928            ));
25929            assert!(ctx.take_commands().expect("commands").is_empty());
25930            ctx.ensure_history_consumed()
25931                .expect("every physical wait-open is consumed");
25932        }
25933    }
25934
25935    #[test]
25936    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
25937        let history = vec![
25938            history_event(
25939                "ConditionWaitOpened",
25940                json!({
25941                    "sequence": 3,
25942                    "condition_wait_id": "condition:3",
25943                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25944                    "condition_key": "approved",
25945                    "condition_definition_fingerprint": "sha256:approved-v1",
25946                }),
25947            ),
25948            history_event(
25949                "UpdateApplied",
25950                json!({
25951                    "sequence": 3,
25952                    "update_id": "update-1",
25953                    "update_name": "approve",
25954                    "arguments": fixture_envelope(json!([false])),
25955                }),
25956            ),
25957            history_event(
25958                "ConditionWaitOpened",
25959                json!({
25960                    "sequence": 5,
25961                    "condition_wait_id": "condition:5",
25962                    "condition_wait_occurrence_id": "rust:condition-wait:0",
25963                    "condition_key": "approved",
25964                    "condition_definition_fingerprint": "sha256:approved-v1",
25965                }),
25966            ),
25967            history_event(
25968                "UpdateApplied",
25969                json!({
25970                    "sequence": 5,
25971                    "update_id": "update-2",
25972                    "update_name": "approve",
25973                    "arguments": fixture_envelope(json!([true])),
25974                }),
25975            ),
25976        ];
25977
25978        for _cold_worker_or_restart in 0..2 {
25979            let ctx = workflow_context(history.clone());
25980            let predicate_ctx = ctx.clone();
25981            let mut wait = Box::pin(ctx.wait_condition(
25982                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
25983                move || {
25984                    Ok(predicate_ctx
25985                        .updates("approve")?
25986                        .last()
25987                        .and_then(|arguments| arguments.first())
25988                        .and_then(Value::as_bool)
25989                        == Some(true))
25990                },
25991            ));
25992            let mut task_context = TaskContext::from_waker(noop_waker_ref());
25993
25994            assert!(matches!(
25995                wait.as_mut().poll(&mut task_context),
25996                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
25997            ));
25998            assert!(ctx.take_commands().expect("commands").is_empty());
25999            ctx.ensure_history_consumed()
26000                .expect("every update-driven reopen is consumed");
26001        }
26002    }
26003
26004    #[test]
26005    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
26006        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
26007            ("shared", "sha256:first", "shared", "sha256:second"),
26008            ("first", "sha256:shared", "second", "sha256:shared"),
26009            ("shared", "sha256:shared", "shared", "sha256:shared"),
26010            ("first", "sha256:first", "second", "sha256:second"),
26011        ] {
26012            let history = vec![
26013                history_event(
26014                    "ConditionWaitOpened",
26015                    json!({
26016                        "sequence": 3,
26017                        "condition_wait_id": "condition:3",
26018                        "condition_wait_occurrence_id": "rust:condition-wait:0",
26019                        "condition_key": first_key,
26020                        "condition_definition_fingerprint": first_fingerprint,
26021                    }),
26022                ),
26023                history_event(
26024                    "ConditionWaitSatisfied",
26025                    json!({
26026                        "sequence": 3,
26027                        "condition_wait_id": "condition:3",
26028                        "condition_wait_occurrence_id": "rust:condition-wait:0",
26029                        "condition_key": first_key,
26030                        "condition_definition_fingerprint": first_fingerprint,
26031                    }),
26032                ),
26033                history_event(
26034                    "ConditionWaitOpened",
26035                    json!({
26036                        "sequence": 4,
26037                        "condition_wait_id": "condition:4",
26038                        "condition_wait_occurrence_id": "rust:condition-wait:1",
26039                        "condition_key": second_key,
26040                        "condition_definition_fingerprint": second_fingerprint,
26041                    }),
26042                ),
26043                history_event(
26044                    "ConditionWaitSatisfied",
26045                    json!({
26046                        "sequence": 4,
26047                        "condition_wait_id": "condition:4",
26048                        "condition_wait_occurrence_id": "rust:condition-wait:1",
26049                        "condition_key": second_key,
26050                        "condition_definition_fingerprint": second_fingerprint,
26051                    }),
26052                ),
26053            ];
26054            for _cold_worker_or_restart in 0..2 {
26055                let ctx = workflow_context(history.clone());
26056                let mut task_context = TaskContext::from_waker(noop_waker_ref());
26057                let mut first = Box::pin(ctx.wait_condition(
26058                    ConditionWaitOptions::new(first_key, first_fingerprint),
26059                    || Ok(false),
26060                ));
26061                assert!(matches!(
26062                    first.as_mut().poll(&mut task_context),
26063                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
26064                ));
26065
26066                let mut second = Box::pin(ctx.wait_condition(
26067                    ConditionWaitOptions::new(second_key, second_fingerprint),
26068                    || Ok(false),
26069                ));
26070                assert!(matches!(
26071                    second.as_mut().poll(&mut task_context),
26072                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
26073                ));
26074                assert!(ctx.take_commands().expect("commands").is_empty());
26075                ctx.ensure_history_consumed()
26076                    .expect("each authored wait consumes one occurrence");
26077            }
26078        }
26079    }
26080
26081    #[test]
26082    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
26083        fn worker() -> Worker {
26084            let client = Client::new("http://127.0.0.1:8080").expect("client");
26085            let mut worker = Worker::new(client, "rust-workers");
26086            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
26087                let mut outcomes = Vec::new();
26088                for _ in 0..2 {
26089                    outcomes.push(
26090                        ctx.wait_condition(
26091                            ConditionWaitOptions::new("shared", "sha256:shared"),
26092                            || Ok(false),
26093                        )
26094                        .await?,
26095                    );
26096                }
26097                Ok(json!(outcomes))
26098            });
26099            worker
26100        }
26101
26102        let task = workflow_task(
26103            "rust.condition-loop",
26104            vec![
26105                history_event(
26106                    "ConditionWaitOpened",
26107                    json!({
26108                        "sequence": 1,
26109                        "condition_wait_id": "condition:1",
26110                        "condition_wait_occurrence_id": "rust:condition-wait:0",
26111                        "condition_key": "shared",
26112                        "condition_definition_fingerprint": "sha256:shared",
26113                    }),
26114                ),
26115                history_event(
26116                    "ConditionWaitSatisfied",
26117                    json!({
26118                        "sequence": 1,
26119                        "condition_wait_id": "condition:1",
26120                        "condition_wait_occurrence_id": "rust:condition-wait:0",
26121                        "condition_key": "shared",
26122                        "condition_definition_fingerprint": "sha256:shared",
26123                    }),
26124                ),
26125                history_event(
26126                    "ConditionWaitOpened",
26127                    json!({
26128                        "sequence": 2,
26129                        "condition_wait_id": "condition:2",
26130                        "condition_wait_occurrence_id": "rust:condition-wait:1",
26131                        "condition_key": "shared",
26132                        "condition_definition_fingerprint": "sha256:shared",
26133                    }),
26134                ),
26135                history_event(
26136                    "ConditionWaitSatisfied",
26137                    json!({
26138                        "sequence": 2,
26139                        "condition_wait_id": "condition:2",
26140                        "condition_wait_occurrence_id": "rust:condition-wait:1",
26141                        "condition_key": "shared",
26142                        "condition_definition_fingerprint": "sha256:shared",
26143                    }),
26144                ),
26145            ],
26146            DEFAULT_CODEC,
26147        );
26148
26149        for _cold_worker_or_restart in 0..2 {
26150            let commands = worker()
26151                .execute_workflow_task(task.clone())
26152                .expect("adjacent loop waits replay deterministically");
26153            assert_eq!(commands.len(), 1);
26154            assert_eq!(commands[0]["type"], "complete_workflow");
26155            assert_eq!(
26156                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
26157                json!(["satisfied", "satisfied"])
26158            );
26159        }
26160    }
26161
26162    fn timed_event(event_type: &str, at: &str, payload: Value) -> HistoryEvent {
26163        let mut event = history_event(event_type, payload);
26164        event.raw.insert("timestamp".into(), json!(at));
26165        event
26166    }
26167
26168    fn approval_wait_open(sequence: u64, at: &str, timeout_seconds: u64) -> HistoryEvent {
26169        timed_event(
26170            "ConditionWaitOpened",
26171            at,
26172            json!({
26173                "sequence": sequence,
26174                "condition_wait_id": format!("condition:{sequence}"),
26175                "condition_wait_occurrence_id": "rust:condition-wait:0",
26176                "condition_key": "approval",
26177                "condition_definition_fingerprint": "sha256:approval-v1",
26178                "timeout_seconds": timeout_seconds,
26179            }),
26180        )
26181    }
26182
26183    fn approval_signal(name: &str, id: &str, at: &str) -> HistoryEvent {
26184        timed_event(
26185            "SignalReceived",
26186            at,
26187            json!({
26188                "signal_id": id,
26189                "workflow_command_id": format!("command-{id}"),
26190                "signal_name": name,
26191                "arguments": encode_value_envelope(&json!(["proposal-1"]), DEFAULT_CODEC)
26192                    .expect("signal input"),
26193            }),
26194        )
26195    }
26196
26197    fn poll_approval_wait(
26198        history: Vec<HistoryEvent>,
26199    ) -> (Poll<Result<ConditionWaitResult>>, Vec<Value>) {
26200        let ctx = workflow_context(history);
26201        let predicate_ctx = ctx.clone();
26202        let mut wait = Box::pin(
26203            ctx.wait_condition(
26204                ConditionWaitOptions::new("approval", "sha256:approval-v1")
26205                    .timeout(Duration::from_secs(300)),
26206                move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
26207            ),
26208        );
26209        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26210        let poll = wait.as_mut().poll(&mut task_context);
26211        (poll, ctx.take_commands().expect("commands"))
26212    }
26213
26214    fn approval_wait_open_at(
26215        sequence: u64,
26216        occurrence: u64,
26217        at: &str,
26218        timeout_seconds: u64,
26219    ) -> HistoryEvent {
26220        let mut event = approval_wait_open(sequence, at, timeout_seconds);
26221        event.payload["condition_wait_occurrence_id"] =
26222            json!(format!("rust:condition-wait:{occurrence}"));
26223        event
26224    }
26225
26226    fn approval_wait_timed_out(sequence: u64, at: &str) -> HistoryEvent {
26227        timed_event(
26228            "ConditionWaitTimedOut",
26229            at,
26230            json!({
26231                "sequence": sequence,
26232                "condition_wait_id": format!("condition:{sequence}"),
26233                "condition_wait_occurrence_id": "rust:condition-wait:0",
26234                "condition_key": "approval",
26235                "condition_definition_fingerprint": "sha256:approval-v1",
26236            }),
26237        )
26238    }
26239
26240    /// `if wait(300) { approved } else if wait(grace) { late } else { expired }`,
26241    /// both waits on the same key and predicate. Returns the outcome so far and
26242    /// any new commands.
26243    fn poll_grace_wait(
26244        history: Vec<HistoryEvent>,
26245        grace_seconds: u64,
26246    ) -> (Poll<Result<&'static str>>, Vec<Value>) {
26247        let ctx = workflow_context(history);
26248        let wait = |seconds| {
26249            let predicate_ctx = ctx.clone();
26250            ctx.wait_condition(
26251                ConditionWaitOptions::new("approval", "sha256:approval-v1")
26252                    .timeout(Duration::from_secs(seconds)),
26253                move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
26254            )
26255        };
26256        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26257        let mut first = Box::pin(wait(300));
26258        let poll = match first.as_mut().poll(&mut task_context) {
26259            Poll::Ready(Ok(ConditionWaitResult::Satisfied)) => Poll::Ready(Ok("approved")),
26260            Poll::Ready(Ok(ConditionWaitResult::TimedOut)) => {
26261                let mut grace = Box::pin(wait(grace_seconds));
26262                match grace.as_mut().poll(&mut task_context) {
26263                    Poll::Ready(Ok(ConditionWaitResult::Satisfied)) => Poll::Ready(Ok("late")),
26264                    Poll::Ready(Ok(ConditionWaitResult::TimedOut)) => Poll::Ready(Ok("expired")),
26265                    Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
26266                    Poll::Pending => Poll::Pending,
26267                }
26268            }
26269            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
26270            Poll::Pending => Poll::Pending,
26271        };
26272        (poll, ctx.take_commands().expect("commands"))
26273    }
26274
26275    fn decision_history(reopen: u64, orphan_fires_before_reopen: bool) -> Vec<HistoryEvent> {
26276        let wait = |seq: u64, at: &str, timeout: u64| {
26277            timed_event(
26278                "ConditionWaitOpened",
26279                at,
26280                json!({
26281                    "sequence": seq,
26282                    "condition_wait_id": format!("condition:{seq}"),
26283                    "condition_wait_occurrence_id": "rust:condition-wait:0",
26284                    "condition_key": "decision-1",
26285                    "condition_definition_fingerprint": "sha256:decision-v1",
26286                    "timeout_seconds": timeout,
26287                }),
26288            )
26289        };
26290        let timer = |kind: &str, seq: u64, at: &str, delay: u64| {
26291            timed_event(
26292                kind,
26293                at,
26294                json!({
26295                    "sequence": seq,
26296                    "timer_id": format!("condition-timer:{seq}"),
26297                    "timer_kind": "condition_timeout",
26298                    "condition_wait_id": format!("condition:{seq}"),
26299                    "delay_seconds": delay,
26300                }),
26301            )
26302        };
26303        let orphan_fire = timer("TimerFired", 1, "2026-11-04T04:12:36.956000+00:00", 300);
26304        let mut history = vec![
26305            wait(1, "2026-11-04T04:07:36.890000+00:00", 300),
26306            timer("TimerScheduled", 1, "2026-11-04T04:07:36.891000+00:00", 300),
26307        ];
26308        if orphan_fires_before_reopen {
26309            // Control: the first wait really timed out before the next open.
26310            history.push(orphan_fire.clone());
26311        }
26312        history.extend([
26313            wait(2, "2026-11-04T04:07:36.908000+00:00", 300),
26314            timer("TimerScheduled", 2, "2026-11-04T04:07:36.909000+00:00", 300),
26315            approval_signal("decision", "s1", "2026-11-04T04:09:36.979000+00:00"),
26316            timed_event(
26317                "ConditionWaitSatisfied",
26318                "2026-11-04T04:09:37.008000+00:00",
26319                json!({
26320                    "sequence": 2,
26321                    "condition_wait_id": "condition:2",
26322                    "condition_wait_occurrence_id": "rust:condition-wait:0",
26323                    "condition_key": "decision-1",
26324                    "condition_definition_fingerprint": "sha256:decision-v1",
26325                }),
26326            ),
26327            timer("TimerCancelled", 2, "2026-11-04T04:09:37.009000+00:00", 300),
26328            wait(3, "2026-11-04T04:09:37.010000+00:00", reopen),
26329            timer(
26330                "TimerScheduled",
26331                3,
26332                "2026-11-04T04:09:37.011000+00:00",
26333                reopen,
26334            ),
26335        ]);
26336        if !orphan_fires_before_reopen {
26337            history.push(orphan_fire);
26338        }
26339        history
26340    }
26341
26342    fn poll_decision_wait(
26343        history: Vec<HistoryEvent>,
26344    ) -> (Poll<Result<ConditionWaitResult>>, Vec<Value>) {
26345        let ctx = workflow_context(history);
26346        let mut wait = Box::pin(
26347            ctx.wait_condition(
26348                ConditionWaitOptions::new("decision-1", "sha256:decision-v1")
26349                    .timeout(Duration::from_secs(300)),
26350                || Ok(false),
26351            ),
26352        );
26353        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26354        let poll = wait.as_mut().poll(&mut task_context);
26355        (poll, ctx.take_commands().expect("commands"))
26356    }
26357
26358    // #192 (sdk-php#283 shape): a duplicate open left the first wait orphaned;
26359    // its timer firing later must not end the logical wait, because the next
26360    // same-occurrence wait opened while it was still open.
26361    #[test]
26362    fn an_orphaned_duplicate_wait_timing_out_later_does_not_end_the_logical_wait() {
26363        for reopen in [300, 180] {
26364            // Only the orphan's timer has fired: the chain continues, and the
26365            // deadline from the first open has passed, so it reopens with 0.
26366            let (poll, commands) = poll_decision_wait(decision_history(reopen, false));
26367            assert!(matches!(poll, Poll::Pending), "reopen {reopen}: {poll:?}");
26368            assert_eq!(commands.len(), 1, "reopen {reopen}: {commands:?}");
26369            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
26370            assert_eq!(commands[0]["timeout_seconds"], json!(0), "reopen {reopen}");
26371
26372            // The reopened wait's own timer fires as well: the logical wait
26373            // times out, as the workflow intended.
26374            let mut history = decision_history(reopen, false);
26375            history.push(timed_event(
26376                "TimerFired",
26377                "2026-11-04T04:12:37.216000+00:00",
26378                json!({
26379                    "sequence": 3,
26380                    "timer_id": "condition-timer:3",
26381                    "timer_kind": "condition_timeout",
26382                    "condition_wait_id": "condition:3",
26383                    "delay_seconds": reopen,
26384                }),
26385            ));
26386            let (poll, commands) = poll_decision_wait(history);
26387            assert!(
26388                matches!(poll, Poll::Ready(Ok(ConditionWaitResult::TimedOut))),
26389                "reopen {reopen}: {poll:?}"
26390            );
26391            assert!(commands.is_empty());
26392        }
26393
26394        // A genuine timeout before the next open still ends the wait: reopening
26395        // it is non-deterministic.
26396        let (poll, _) = poll_decision_wait(decision_history(300, true));
26397        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) = poll else {
26398            panic!("a reopen after a real timeout must fail replay: {poll:?}");
26399        };
26400        assert_eq!(failure.reason, "condition_wait_reopened_after_timeout");
26401        assert_eq!(failure.sequence, Some(2));
26402    }
26403
26404    // A separate wait after a timed-out one is its own logical wait: it
26405    // measures from its own open and never inherits the earlier deadline
26406    // (General's sdk-php#271 review vectors).
26407    #[test]
26408    fn a_wait_after_a_timed_out_wait_measures_from_its_own_open() {
26409        let timed_out_first = || {
26410            vec![
26411                approval_wait_open_at(1, 0, "2026-11-04T02:36:05.000000+00:00", 300),
26412                approval_wait_timed_out(1, "2026-11-04T02:41:05.000000+00:00"),
26413            ]
26414        };
26415        for (label, grace, signal, expected) in [
26416            ("grace wait, wrong signal", 60, "reject", 31),
26417            ("equal-timeout wait, wrong signal", 300, "reject", 271),
26418        ] {
26419            let mut history = timed_out_first();
26420            history.push(approval_wait_open_at(
26421                2,
26422                1,
26423                "2026-11-04T02:41:05.500000+00:00",
26424                grace,
26425            ));
26426            history.push(approval_signal(
26427                signal,
26428                "s1",
26429                "2026-11-04T02:41:35.000000+00:00",
26430            ));
26431            let (poll, commands) = poll_grace_wait(history, grace);
26432            assert!(matches!(poll, Poll::Pending), "{label}: {poll:?}");
26433            assert_eq!(commands.len(), 1, "{label}: {commands:?}");
26434            assert_eq!(
26435                commands[0]["condition_wait_occurrence_id"],
26436                json!("rust:condition-wait:1"),
26437                "{label}"
26438            );
26439            assert_eq!(commands[0]["timeout_seconds"], json!(expected), "{label}");
26440        }
26441
26442        let mut history = timed_out_first();
26443        history.push(approval_wait_open_at(
26444            2,
26445            1,
26446            "2026-11-04T02:41:05.500000+00:00",
26447            60,
26448        ));
26449        history.push(approval_signal(
26450            "approve",
26451            "a1",
26452            "2026-11-04T02:41:35.000000+00:00",
26453        ));
26454        let (poll, commands) = poll_grace_wait(history, 60);
26455        assert!(
26456            matches!(poll, Poll::Ready(Ok("late"))),
26457            "grace wait, approve: {poll:?}"
26458        );
26459        assert!(commands.is_empty());
26460    }
26461
26462    // The same vectors as sdk-php#271 (#187): a false wake satisfies the Server's
26463    // wait, and the reopen keeps the deadline of the first open.
26464    #[test]
26465    fn reopened_condition_wait_keeps_its_first_opening_deadline() {
26466        let opened = || approval_wait_open(1, "2026-11-04T02:36:05.295000+00:00", 300);
26467        let satisfied = || {
26468            timed_event(
26469                "ConditionWaitSatisfied",
26470                "2026-11-04T02:38:05.397000+00:00",
26471                json!({
26472                    "sequence": 1,
26473                    "condition_wait_id": "condition:1",
26474                    "condition_wait_occurrence_id": "rust:condition-wait:0",
26475                    "condition_key": "approval",
26476                    "condition_definition_fingerprint": "sha256:approval-v1",
26477                }),
26478            )
26479        };
26480        let reopened = |timeout| approval_wait_open(2, "2026-11-04T02:38:05.402000+00:00", timeout);
26481        let wrong = |id, at| approval_signal("reject", id, at);
26482        for (label, history, expected) in [
26483            (
26484                "first false wake",
26485                vec![opened(), wrong("w1", "2026-11-04T02:38:05.345000+00:00")],
26486                180,
26487            ),
26488            (
26489                "second false wake after a full-timeout reopen",
26490                vec![
26491                    opened(),
26492                    wrong("w1", "2026-11-04T02:38:05.345000+00:00"),
26493                    satisfied(),
26494                    reopened(300),
26495                    wrong("w2", "2026-11-04T02:40:05.000000+00:00"),
26496                ],
26497                61,
26498            ),
26499            (
26500                "second false wake after a remaining-time reopen",
26501                vec![
26502                    opened(),
26503                    wrong("w1", "2026-11-04T02:38:05.345000+00:00"),
26504                    satisfied(),
26505                    reopened(180),
26506                    wrong("w2", "2026-11-04T02:40:05.000000+00:00"),
26507                ],
26508                61,
26509            ),
26510            (
26511                "false wake after the deadline",
26512                vec![opened(), wrong("w1", "2026-11-04T02:41:06.000000+00:00")],
26513                0,
26514            ),
26515        ] {
26516            let (poll, commands) = poll_approval_wait(history);
26517            assert!(matches!(poll, Poll::Pending), "{label}: {poll:?}");
26518            assert_eq!(commands.len(), 1, "{label}: {commands:?}");
26519            assert_eq!(commands[0]["type"], json!("open_condition_wait"), "{label}");
26520            assert_eq!(commands[0]["condition_key"], json!("approval"), "{label}");
26521            assert_eq!(
26522                commands[0]["condition_wait_occurrence_id"],
26523                json!("rust:condition-wait:0"),
26524                "{label}"
26525            );
26526            assert_eq!(commands[0]["timeout_seconds"], json!(expected), "{label}");
26527        }
26528
26529        let (poll, commands) = poll_approval_wait(vec![
26530            opened(),
26531            wrong("w1", "2026-11-04T02:38:05.345000+00:00"),
26532            satisfied(),
26533            reopened(180),
26534            approval_signal("approve", "a1", "2026-11-04T02:39:00.000000+00:00"),
26535        ]);
26536        assert!(
26537            matches!(poll, Poll::Ready(Ok(ConditionWaitResult::Satisfied))),
26538            "a true wake after a remaining-time reopen completes: {poll:?}"
26539        );
26540        assert!(commands.is_empty());
26541
26542        // Without recorded times the authored timeout is kept, as before.
26543        let mut untimed = vec![opened(), wrong("w1", "2026-11-04T02:38:05.345000+00:00")];
26544        for event in &mut untimed {
26545            event.raw.remove("timestamp");
26546        }
26547        let (_, commands) = poll_approval_wait(untimed);
26548        assert_eq!(commands[0]["timeout_seconds"], json!(300));
26549    }
26550
26551    #[test]
26552    fn a_reopen_longer_than_the_authored_timeout_is_not_the_same_wait() {
26553        let history = vec![
26554            approval_wait_open(1, "2026-11-04T02:36:05.295000+00:00", 300),
26555            timed_event(
26556                "ConditionWaitSatisfied",
26557                "2026-11-04T02:38:05.397000+00:00",
26558                json!({
26559                    "sequence": 1,
26560                    "condition_wait_id": "condition:1",
26561                    "condition_wait_occurrence_id": "rust:condition-wait:0",
26562                    "condition_key": "approval",
26563                    "condition_definition_fingerprint": "sha256:approval-v1",
26564                }),
26565            ),
26566            approval_wait_open(2, "2026-11-04T02:38:05.402000+00:00", 301),
26567        ];
26568        let (poll, _) = poll_approval_wait(history);
26569        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) = poll else {
26570            panic!("a longer reopen must fail replay: {poll:?}");
26571        };
26572        assert_eq!(failure.reason, "condition_wait_timeout_mismatch");
26573        assert_eq!(failure.sequence, Some(2));
26574    }
26575
26576    #[test]
26577    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
26578        let history = vec![history_event(
26579            "ConditionWaitOpened",
26580            json!({
26581                "sequence": 12,
26582                "condition_wait_id": "condition:12",
26583                "condition_wait_occurrence_id": "rust:condition-wait:0",
26584                "condition_key": "approval",
26585                "condition_definition_fingerprint": "sha256:approval-v1",
26586                "timeout_seconds": 30,
26587            }),
26588        )];
26589        for (options, expected_reason) in [
26590            (
26591                ConditionWaitOptions::new("changed", "sha256:approval-v1")
26592                    .timeout(Duration::from_secs(30)),
26593                "condition_wait_key_mismatch",
26594            ),
26595            (
26596                ConditionWaitOptions::new("approval", "sha256:approval-v2")
26597                    .timeout(Duration::from_secs(30)),
26598                "condition_wait_predicate_mismatch",
26599            ),
26600            (
26601                ConditionWaitOptions::new("approval", "sha256:approval-v1")
26602                    .timeout(Duration::from_secs(29)),
26603                "condition_wait_timeout_mismatch",
26604            ),
26605        ] {
26606            let ctx = workflow_context(history.clone());
26607            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
26608            let mut task_context = TaskContext::from_waker(noop_waker_ref());
26609            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
26610                wait.as_mut().poll(&mut task_context)
26611            else {
26612                panic!("changed condition definition must fail replay");
26613            };
26614            assert_eq!(failure.reason, expected_reason);
26615            assert_eq!(failure.sequence, Some(12));
26616        }
26617    }
26618
26619    #[test]
26620    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
26621        let error = WorkflowState::new(
26622            vec![history_event(
26623                "ConditionWaitOpened",
26624                json!({
26625                    "sequence": 12,
26626                    "condition_wait_id": "condition:12",
26627                    "condition_wait_occurrence_id": "rust:condition-wait:0",
26628                    "condition_key": "approval",
26629                }),
26630            )],
26631            "rust-workers".to_string(),
26632            DEFAULT_CODEC.to_string(),
26633            None,
26634        )
26635        .expect_err("condition history without a predicate fingerprint must fail");
26636
26637        assert!(matches!(
26638            error,
26639            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
26640                if reason == "condition_wait_predicate_fingerprint_missing"
26641        ));
26642    }
26643
26644    #[test]
26645    fn condition_wait_history_requires_authored_occurrence_identity() {
26646        let error = WorkflowState::new(
26647            vec![history_event(
26648                "ConditionWaitOpened",
26649                json!({
26650                    "sequence": 12,
26651                    "condition_wait_id": "condition:12",
26652                    "condition_key": "approval",
26653                    "condition_definition_fingerprint": "sha256:approval-v1",
26654                }),
26655            )],
26656            "rust-workers".to_string(),
26657            DEFAULT_CODEC.to_string(),
26658            None,
26659        )
26660        .expect_err("condition history without occurrence identity must fail");
26661
26662        assert!(matches!(
26663            error,
26664            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
26665                if reason == "condition_wait_occurrence_id_missing"
26666        ));
26667    }
26668
26669    #[test]
26670    fn typed_search_attribute_updates_validate_emit_and_replay() {
26671        let update = SearchAttributeUpdate::new()
26672            .keyword("OrderStatus", " waiting ")
26673            .expect("keyword")
26674            .int("Attempt", 3)
26675            .expect("int")
26676            .bool("Escalated", false)
26677            .expect("bool")
26678            .keyword_list("Regions", ["us-east", "eu-west"])
26679            .expect("list")
26680            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
26681            .expect("datetime")
26682            .delete("LegacyStatus")
26683            .expect("delete");
26684        let ctx = workflow_context(Vec::new());
26685        ctx.upsert_search_attributes(update.clone())
26686            .expect("typed update");
26687        assert_eq!(
26688            ctx.take_commands().expect("search-attribute command"),
26689            vec![json!({
26690                "type": "upsert_search_attributes",
26691                "attributes": {
26692                    "Attempt": 3,
26693                    "Escalated": false,
26694                    "LegacyStatus": null,
26695                    "OrderStatus": "waiting",
26696                    "Regions": ["us-east", "eu-west"],
26697                    "UpdatedAt": "2026-08-22T04:00:00Z",
26698                },
26699                "attribute_types": {
26700                    "Attempt": "int",
26701                    "Escalated": "bool",
26702                    "OrderStatus": "keyword",
26703                    "Regions": "keyword_list",
26704                    "UpdatedAt": "datetime",
26705                },
26706            })]
26707        );
26708
26709        let replay = workflow_context(vec![history_event(
26710            "SearchAttributesUpserted",
26711            json!({
26712                "sequence": 6,
26713                "attributes": {
26714                    "Attempt": 3,
26715                    "Escalated": false,
26716                    "LegacyStatus": null,
26717                    "OrderStatus": "waiting",
26718                    "Regions": ["us-east", "eu-west"],
26719                    "UpdatedAt": "2026-08-22T04:00:00Z",
26720                },
26721                "attribute_types": {
26722                    "Attempt": "int",
26723                    "Escalated": "bool",
26724                    "OrderStatus": "keyword",
26725                    "Regions": "keyword_list",
26726                    "UpdatedAt": "datetime",
26727                },
26728                "merged": {},
26729            }),
26730        )]);
26731        replay
26732            .upsert_search_attributes(update)
26733            .expect("matching update replays");
26734        assert!(replay.take_commands().expect("commands").is_empty());
26735        replay.ensure_history_consumed().expect("history consumed");
26736
26737        let type_drift = workflow_context(vec![history_event(
26738            "SearchAttributesUpserted",
26739            json!({
26740                "sequence": 7,
26741                "attributes": {"OrderStatus": "waiting"},
26742                "attribute_types": {"OrderStatus": "keyword"},
26743                "merged": {"OrderStatus": "waiting"},
26744            }),
26745        )]);
26746        let error = type_drift
26747            .upsert_search_attributes(
26748                SearchAttributeUpdate::new()
26749                    .string("OrderStatus", "waiting")
26750                    .expect("string update"),
26751            )
26752            .expect_err("same JSON value with a changed type must fail replay");
26753        assert!(matches!(
26754            error,
26755            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
26756                if reason == "search_attribute_type_mismatch"
26757        ));
26758
26759        let malformed_types = WorkflowState::new(
26760            vec![history_event(
26761                "SearchAttributesUpserted",
26762                json!({
26763                    "sequence": 8,
26764                    "attributes": {"OrderStatus": "waiting"},
26765                    "attribute_types": {"OrderStatus": "unsupported"},
26766                    "merged": {"OrderStatus": "waiting"},
26767                }),
26768            )],
26769            "rust-workers".to_string(),
26770            DEFAULT_CODEC.to_string(),
26771            None,
26772        )
26773        .expect_err("unsupported search-attribute type metadata must fail");
26774        assert!(matches!(
26775            malformed_types,
26776            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
26777                if reason == "search_attribute_types_malformed"
26778        ));
26779
26780        assert!(matches!(
26781            SearchAttributeUpdate::new().keyword("bad key", "value"),
26782            Err(SearchAttributeUpdateError::InvalidKey(_))
26783        ));
26784        assert!(matches!(
26785            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
26786            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
26787        ));
26788        assert!(matches!(
26789            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
26790            Err(SearchAttributeUpdateError::ValueTooLong { .. })
26791        ));
26792        assert!(matches!(
26793            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
26794            Err(SearchAttributeUpdateError::InvalidDateTime(_))
26795        ));
26796        assert!(matches!(
26797            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
26798            Err(Error::InvalidSearchAttributeUpdate(
26799                SearchAttributeUpdateError::Empty
26800            ))
26801        ));
26802    }
26803
26804    #[test]
26805    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
26806        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
26807        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
26808
26809        assert!(SearchAttributeUpdate::new()
26810            .string("AsciiDescription", ascii)
26811            .is_ok());
26812        assert!(SearchAttributeUpdate::new()
26813            .string("Utf8Description", utf8)
26814            .is_ok());
26815        assert!(matches!(
26816            SearchAttributeUpdate::new().string(
26817                "TooLongDescription",
26818                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
26819            ),
26820            Err(SearchAttributeUpdateError::ValueTooLong {
26821                kind: "string",
26822                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
26823                ..
26824            })
26825        ));
26826    }
26827
26828    #[test]
26829    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
26830        let lone_fire = WorkflowState::new(
26831            vec![history_event(
26832                "TimerFired",
26833                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26834            )],
26835            "rust-workers".to_string(),
26836            DEFAULT_CODEC.to_string(),
26837            None,
26838        )
26839        .expect_err("TimerFired requires TimerScheduled");
26840        assert!(matches!(
26841            lone_fire,
26842            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
26843                if reason == "timer_schedule_missing_or_duplicate"
26844        ));
26845
26846        let wrong_identity = WorkflowState::new(
26847            vec![
26848                history_event(
26849                    "TimerScheduled",
26850                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26851                ),
26852                history_event(
26853                    "TimerFired",
26854                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
26855                ),
26856            ],
26857            "rust-workers".to_string(),
26858            DEFAULT_CODEC.to_string(),
26859            None,
26860        )
26861        .expect_err("fire must match scheduled timer identity");
26862        assert!(matches!(
26863            wrong_identity,
26864            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
26865                if reason == "timer_identity_mismatch"
26866        ));
26867
26868        let duplicate_fire = WorkflowState::new(
26869            vec![
26870                history_event(
26871                    "TimerScheduled",
26872                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26873                ),
26874                history_event(
26875                    "TimerFired",
26876                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26877                ),
26878                history_event(
26879                    "TimerFired",
26880                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26881                ),
26882            ],
26883            "rust-workers".to_string(),
26884            DEFAULT_CODEC.to_string(),
26885            None,
26886        )
26887        .expect_err("a durable timer cannot fire twice");
26888        assert!(matches!(
26889            duplicate_fire,
26890            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
26891                if reason == "duplicate_timer_fire"
26892        ));
26893
26894        let wrong_fired_delay = WorkflowState::new(
26895            vec![
26896                history_event(
26897                    "TimerScheduled",
26898                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26899                ),
26900                history_event(
26901                    "TimerFired",
26902                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
26903                ),
26904            ],
26905            "rust-workers".to_string(),
26906            DEFAULT_CODEC.to_string(),
26907            None,
26908        )
26909        .expect_err("timer schedule and fire delays must agree");
26910        assert!(matches!(
26911            wrong_fired_delay,
26912            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
26913                if reason == "timer_history_delay_mismatch"
26914        ));
26915    }
26916
26917    #[test]
26918    fn replay_rejects_activity_moved_before_recorded_timer() {
26919        let ctx = workflow_context(vec![
26920            history_event(
26921                "TimerScheduled",
26922                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26923            ),
26924            history_event(
26925                "TimerFired",
26926                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26927            ),
26928            history_event(
26929                "ActivityCompleted",
26930                json!({
26931                    "sequence": 2,
26932                    "activity_type": "after-timer",
26933                    "payload_codec": DEFAULT_CODEC,
26934                    "result": fixture_envelope(json!("done")),
26935                }),
26936            ),
26937        ]);
26938        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
26939        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26940
26941        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
26942            activity.as_mut().poll(&mut task_context)
26943        else {
26944            panic!("reordered durable command must be rejected");
26945        };
26946        assert_eq!(failure.reason, "recorded_command_mismatch");
26947        assert_eq!(failure.sequence, Some(1));
26948        assert_eq!(failure.expected.as_deref(), Some("timer"));
26949        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
26950    }
26951
26952    #[test]
26953    fn workflow_context_emits_a_typed_named_signal_wait() {
26954        let ctx = workflow_context(Vec::new());
26955        let mut signal = Box::pin(ctx.wait_signal("finish"));
26956        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26957
26958        assert!(matches!(
26959            signal.as_mut().poll(&mut task_context),
26960            Poll::Pending
26961        ));
26962        assert_eq!(
26963            ctx.take_commands().expect("signal-wait command"),
26964            vec![json!({
26965                "type": "open_signal_wait",
26966                "signal_name": "finish",
26967            })]
26968        );
26969    }
26970
26971    #[test]
26972    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
26973        let ctx = workflow_context(Vec::new());
26974        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
26975        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26976
26977        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
26978        else {
26979            panic!("runtime-reserved signal should be rejected");
26980        };
26981        assert!(message.contains("reserved by the workflow runtime"));
26982        assert!(ctx.take_commands().expect("commands").is_empty());
26983    }
26984
26985    #[tokio::test]
26986    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
26987        let client = Client::builder("http://127.0.0.1:9")
26988            .build()
26989            .expect("client");
26990        let error = client
26991            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
26992            .await
26993            .expect_err("runtime-reserved signal should be rejected before transport");
26994
26995        assert!(
26996            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
26997        );
26998    }
26999
27000    #[test]
27001    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
27002        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
27003            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
27004                value.to_string(),
27005            )]))
27006            .expect("message payload");
27007            json!({
27008                "schema": MESSAGE_STREAM_SCHEMA,
27009                "stream_name": "orders",
27010                "message_id": message_id,
27011                "position": position,
27012                "payload_envelope": payload,
27013            })
27014        }
27015
27016        fn opened(sequence: u64) -> HistoryEvent {
27017            history_event(
27018                "SignalWaitOpened",
27019                json!({
27020                    "sequence": sequence,
27021                    "signal_name": MESSAGE_STREAM_SIGNAL,
27022                }),
27023            )
27024        }
27025
27026        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
27027            history_event(
27028                "SignalApplied",
27029                json!({
27030                    "sequence": sequence,
27031                    "signal_name": MESSAGE_STREAM_SIGNAL,
27032                    "value": fixture_envelope(json!([delivery])),
27033                }),
27034            )
27035        }
27036
27037        fn received(delivery: Value) -> HistoryEvent {
27038            history_event(
27039                "SignalReceived",
27040                json!({
27041                    "signal_name": MESSAGE_STREAM_SIGNAL,
27042                    "arguments": fixture_envelope(json!([delivery])),
27043                    "payload_codec": DEFAULT_CODEC,
27044                }),
27045            )
27046        }
27047
27048        let client = Client::new("http://127.0.0.1:8080").expect("client");
27049        let mut worker = Worker::new(client, "rust-workers");
27050        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
27051            let messages = ctx.message_stream("orders")?.receive(2).await?;
27052            Ok(json!(messages
27053                .into_iter()
27054                .map(|message| message.message_id)
27055                .collect::<Vec<_>>()))
27056        });
27057
27058        let first = delivery("message-1", 1, "one");
27059        let second = delivery("message-2", 2, "two");
27060        let batch = worker
27061            .execute_workflow_task_decision(workflow_task(
27062                "rust.message-stream-batch",
27063                vec![
27064                    opened(1),
27065                    received(first.clone()),
27066                    applied(1, first.clone()),
27067                    received(first.clone()),
27068                    received(second),
27069                ],
27070                DEFAULT_CODEC,
27071            ))
27072            .expect("worker task consumes the available batch");
27073
27074        assert_eq!(batch.commands.len(), 1);
27075        assert_eq!(batch.commands[0]["type"], "complete_workflow");
27076        assert_eq!(
27077            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
27078                .expect("workflow result"),
27079            json!(["message-1", "message-2"])
27080        );
27081        assert_eq!(
27082            batch.message_stream_cursors,
27083            vec![json!({"stream_name": "orders", "through_position": 2})]
27084        );
27085        assert!(batch.message_stream_waits.is_empty());
27086
27087        let partial = worker
27088            .execute_workflow_task_decision(workflow_task(
27089                "rust.message-stream-batch",
27090                vec![opened(1), received(first.clone()), applied(1, first)],
27091                DEFAULT_CODEC,
27092            ))
27093            .expect("worker task returns without waiting for a missing second item");
27094        assert_eq!(partial.commands.len(), 1);
27095        assert_eq!(partial.commands[0]["type"], "complete_workflow");
27096        assert_eq!(
27097            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
27098                .expect("workflow result"),
27099            json!(["message-1"])
27100        );
27101        assert_eq!(
27102            partial.message_stream_cursors,
27103            vec![json!({"stream_name": "orders", "through_position": 1})]
27104        );
27105        assert!(partial.message_stream_waits.is_empty());
27106    }
27107
27108    #[test]
27109    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
27110        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
27111            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
27112                value.to_string(),
27113            )]))
27114            .expect("message payload");
27115            json!({
27116                "schema": MESSAGE_STREAM_SCHEMA,
27117                "stream_name": "orders",
27118                "message_id": message_id,
27119                "position": position,
27120                "payload_envelope": payload,
27121            })
27122        }
27123
27124        fn opened(sequence: u64) -> HistoryEvent {
27125            history_event(
27126                "SignalWaitOpened",
27127                json!({
27128                    "sequence": sequence,
27129                    "signal_name": MESSAGE_STREAM_SIGNAL,
27130                }),
27131            )
27132        }
27133
27134        fn received(delivery: Value) -> HistoryEvent {
27135            history_event(
27136                "SignalReceived",
27137                json!({
27138                    "signal_name": MESSAGE_STREAM_SIGNAL,
27139                    "arguments": fixture_envelope(json!([delivery])),
27140                    "payload_codec": DEFAULT_CODEC,
27141                }),
27142            )
27143        }
27144
27145        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
27146            history_event(
27147                "SignalApplied",
27148                json!({
27149                    "sequence": sequence,
27150                    "signal_name": MESSAGE_STREAM_SIGNAL,
27151                    "value": fixture_envelope(json!([delivery])),
27152                }),
27153            )
27154        }
27155
27156        let client = Client::new("http://127.0.0.1:8080").expect("client");
27157        let mut worker = Worker::new(client, "rust-workers");
27158        worker.register_workflow(
27159            "rust.message-stream-partial-batches",
27160            |ctx, _input| async move {
27161                let stream = ctx.message_stream("orders")?;
27162                let first = stream.receive(10).await?;
27163                let second = stream.receive(10).await?;
27164                Ok(json!([
27165                    first
27166                        .into_iter()
27167                        .map(|message| message.message_id)
27168                        .collect::<Vec<_>>(),
27169                    second
27170                        .into_iter()
27171                        .map(|message| message.message_id)
27172                        .collect::<Vec<_>>(),
27173                ]))
27174            },
27175        );
27176
27177        let first = delivery("message-1", 1, "one");
27178        let second = delivery("message-2", 2, "two");
27179        let decision = worker
27180            .execute_workflow_task_decision(workflow_task(
27181                "rust.message-stream-partial-batches",
27182                vec![
27183                    opened(1),
27184                    received(first.clone()),
27185                    applied(1, first),
27186                    opened(2),
27187                    received(second.clone()),
27188                    applied(2, second),
27189                ],
27190                DEFAULT_CODEC,
27191            ))
27192            .expect("cold replay preserves both authored receive boundaries");
27193
27194        assert_eq!(decision.commands.len(), 1);
27195        assert_eq!(decision.commands[0]["type"], "complete_workflow");
27196        assert_eq!(
27197            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
27198                .expect("workflow result"),
27199            json!([["message-1"], ["message-2"]])
27200        );
27201        assert_eq!(
27202            decision.message_stream_cursors,
27203            vec![json!({"stream_name": "orders", "through_position": 2})]
27204        );
27205        assert!(decision.message_stream_waits.is_empty());
27206    }
27207
27208    #[test]
27209    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
27210        let ctx = workflow_context(Vec::new());
27211        let stream = ctx.message_stream("orders").expect("message stream");
27212        let mut receive = Box::pin(stream.receive(10));
27213        let mut task_context = TaskContext::from_waker(noop_waker_ref());
27214
27215        assert!(matches!(
27216            receive.as_mut().poll(&mut task_context),
27217            Poll::Pending
27218        ));
27219        assert_eq!(
27220            ctx.take_commands().expect("message-stream wait command"),
27221            vec![json!({
27222                "type": "open_signal_wait",
27223                "signal_name": MESSAGE_STREAM_SIGNAL,
27224            })]
27225        );
27226        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
27227        assert!(cursors.is_empty());
27228        assert_eq!(
27229            waits,
27230            vec![json!({"stream_name": "orders", "after_position": 0})]
27231        );
27232    }
27233
27234    #[test]
27235    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
27236        let ctx = workflow_context(vec![history_event(
27237            "SignalReceived",
27238            json!({
27239                "signal_name": MESSAGE_STREAM_SIGNAL,
27240                "arguments": fixture_envelope(json!([{
27241                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
27242                    "stream_name": "orders",
27243                    "through_position": 2,
27244                }])),
27245                "payload_codec": DEFAULT_CODEC,
27246            }),
27247        )]);
27248        let stream = ctx.message_stream("orders").expect("message stream");
27249        let mut receive = Box::pin(stream.receive(10));
27250        let mut task_context = TaskContext::from_waker(noop_waker_ref());
27251
27252        assert!(matches!(
27253            receive.as_mut().poll(&mut task_context),
27254            Poll::Pending
27255        ));
27256        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
27257        assert_eq!(
27258            cursors,
27259            vec![json!({"stream_name": "orders", "through_position": 2})]
27260        );
27261        assert_eq!(
27262            waits,
27263            vec![json!({"stream_name": "orders", "after_position": 2})]
27264        );
27265    }
27266
27267    #[test]
27268    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
27269        let mut empty_map = BTreeMap::new();
27270        let mut nested = BTreeMap::new();
27271        nested.insert(
27272            "value".to_string(),
27273            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
27274        );
27275        let values = vec![
27276            AvroValue::Bytes(vec![0, 255]),
27277            AvroValue::Long(1),
27278            AvroValue::Double(1.0),
27279            AvroValue::Array(Vec::new()),
27280            AvroValue::Map(std::mem::take(&mut empty_map)),
27281            AvroValue::Map(nested),
27282        ];
27283        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
27284        let transport = vec![json!({
27285            "schema": MESSAGE_STREAM_SCHEMA,
27286            "stream_name": "orders",
27287            "message_id": "message-1",
27288            "position": 1,
27289            "payload_envelope": payload,
27290        })];
27291
27292        for _ in 0..2 {
27293            let Some(MessageStreamDelivery::Message(message)) =
27294                decode_message_stream_delivery(transport.clone()).expect("delivery")
27295            else {
27296                panic!("message delivery expected");
27297            };
27298            assert_eq!(message.arguments, values);
27299            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
27300            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
27301        }
27302    }
27303
27304    #[test]
27305    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
27306        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
27307            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
27308                value.to_string(),
27309            )]))
27310            .expect("message payload");
27311            json!({
27312                "schema": MESSAGE_STREAM_SCHEMA,
27313                "stream_name": "orders",
27314                "message_id": message_id,
27315                "position": position,
27316                "payload_envelope": payload,
27317            })
27318        }
27319
27320        fn opened(sequence: u64) -> HistoryEvent {
27321            history_event(
27322                "SignalWaitOpened",
27323                json!({
27324                    "sequence": sequence,
27325                    "signal_name": MESSAGE_STREAM_SIGNAL,
27326                }),
27327            )
27328        }
27329
27330        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
27331            history_event(
27332                "SignalApplied",
27333                json!({
27334                    "sequence": sequence,
27335                    "signal_name": MESSAGE_STREAM_SIGNAL,
27336                    "value": fixture_envelope(json!([delivery])),
27337                }),
27338            )
27339        }
27340
27341        fn worker() -> Worker {
27342            let client = Client::new("http://127.0.0.1:8080").expect("client");
27343            let mut worker = Worker::new(client, "rust-workers");
27344            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
27345                let stream = ctx.message_stream("orders")?;
27346                let first = stream.receive_one().await?;
27347                let second = stream.receive_one().await?;
27348                Ok(json!([first.message_id, second.message_id]))
27349            });
27350            worker
27351        }
27352
27353        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
27354            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
27355            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
27356            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
27357            task
27358        }
27359
27360        let waiting = worker()
27361            .execute_workflow_task_decision(workflow_task(
27362                "rust.message-stream",
27363                Vec::new(),
27364                DEFAULT_CODEC,
27365            ))
27366            .expect("first worker opens the stream wait");
27367        assert_eq!(
27368            waiting.commands,
27369            vec![json!({
27370                "type": "open_signal_wait",
27371                "signal_name": MESSAGE_STREAM_SIGNAL,
27372            })]
27373        );
27374        assert!(waiting.message_stream_cursors.is_empty());
27375        assert_eq!(
27376            waiting.message_stream_waits,
27377            vec![json!({"stream_name": "orders", "after_position": 0})]
27378        );
27379
27380        let first_delivery = delivery("message-1", 1, "one");
27381        let first_arrival = worker()
27382            .execute_workflow_task_decision(task_with_resume(
27383                vec![opened(1)],
27384                first_delivery.clone(),
27385            ))
27386            .expect("replacement worker consumes the first arrival");
27387        assert_eq!(
27388            first_arrival.commands,
27389            vec![json!({
27390                "type": "open_signal_wait",
27391                "signal_name": MESSAGE_STREAM_SIGNAL,
27392            })]
27393        );
27394        assert_eq!(
27395            first_arrival.message_stream_cursors,
27396            vec![json!({"stream_name": "orders", "through_position": 1})]
27397        );
27398        assert_eq!(
27399            first_arrival.message_stream_waits,
27400            vec![json!({"stream_name": "orders", "after_position": 1})]
27401        );
27402
27403        let second_delivery = delivery("message-2", 2, "two");
27404        let first_applied = applied(1, first_delivery);
27405        let completed = worker()
27406            .execute_workflow_task_decision(task_with_resume(
27407                vec![opened(1), first_applied.clone(), opened(2)],
27408                second_delivery.clone(),
27409            ))
27410            .expect("next replacement worker consumes the second arrival");
27411        assert_eq!(completed.commands.len(), 1);
27412        assert_eq!(completed.commands[0]["type"], "complete_workflow");
27413        assert_eq!(
27414            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
27415                .expect("workflow result"),
27416            json!(["message-1", "message-2"])
27417        );
27418        assert_eq!(
27419            completed.message_stream_cursors,
27420            vec![json!({"stream_name": "orders", "through_position": 2})]
27421        );
27422        assert!(completed.message_stream_waits.is_empty());
27423
27424        let replay_history = vec![
27425            opened(1),
27426            first_applied,
27427            opened(2),
27428            applied(2, second_delivery),
27429        ];
27430        for _cold_worker_or_restart in 0..2 {
27431            let replayed = worker()
27432                .execute_workflow_task_decision(workflow_task(
27433                    "rust.message-stream",
27434                    replay_history.clone(),
27435                    DEFAULT_CODEC,
27436                ))
27437                .expect("cold worker replays each logical message exactly once");
27438            assert_eq!(replayed.commands.len(), 1);
27439            assert_eq!(
27440                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
27441                    .expect("replayed workflow result"),
27442                json!(["message-1", "message-2"])
27443            );
27444            assert_eq!(
27445                replayed.message_stream_cursors,
27446                vec![json!({"stream_name": "orders", "through_position": 2})]
27447            );
27448            assert!(replayed.message_stream_waits.is_empty());
27449        }
27450    }
27451
27452    #[test]
27453    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
27454        assert!(!worker_protocol_supports_message_streams("1.14"));
27455        assert!(worker_protocol_supports_message_streams("1.15"));
27456        assert!(worker_protocol_supports_message_streams("1.16"));
27457        assert!(worker_protocol_supports_message_streams(
27458            WORKER_PROTOCOL_VERSION
27459        ));
27460        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
27461    }
27462
27463    #[test]
27464    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
27465        let ctx = workflow_context(vec![
27466            history_event(
27467                "ConditionWaitOpened",
27468                json!({
27469                    "sequence": 1,
27470                    "condition_wait_id": "condition:1",
27471                    "condition_wait_occurrence_id": "rust:condition-wait:0",
27472                    "condition_key": "signal:finish",
27473                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
27474                }),
27475            ),
27476            history_event(
27477                "ConditionWaitSatisfied",
27478                json!({
27479                    "sequence": 1,
27480                    "condition_wait_id": "condition:1",
27481                    "condition_wait_occurrence_id": "rust:condition-wait:0",
27482                    "condition_key": "signal:finish",
27483                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
27484                }),
27485            ),
27486            history_event(
27487                "SignalReceived",
27488                json!({"signal_name": "finish", "arguments": []}),
27489            ),
27490        ]);
27491        let mut signal = Box::pin(ctx.wait_signal("finish"));
27492        let mut task_context = TaskContext::from_waker(noop_waker_ref());
27493
27494        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
27495            signal.as_mut().poll(&mut task_context)
27496        else {
27497            panic!("condition history must not resolve as a typed signal wait");
27498        };
27499        assert_eq!(failure.reason, "recorded_command_mismatch");
27500        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
27501    }
27502
27503    #[test]
27504    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
27505        let signal_then_timer = vec![
27506            history_event(
27507                "SignalWaitOpened",
27508                json!({"sequence": 1, "signal_name": "go"}),
27509            ),
27510            history_event(
27511                "SignalApplied",
27512                json!({
27513                    "sequence": 1,
27514                    "signal_name": "go",
27515                    "value": fixture_envelope(json!(["now"])),
27516                }),
27517            ),
27518            history_event(
27519                "TimerScheduled",
27520                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
27521            ),
27522            history_event(
27523                "TimerFired",
27524                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
27525            ),
27526        ];
27527
27528        let ctx = workflow_context(signal_then_timer.clone());
27529        let mut signal = Box::pin(ctx.wait_signal("go"));
27530        let mut task_context = TaskContext::from_waker(noop_waker_ref());
27531        assert!(matches!(
27532            signal.as_mut().poll(&mut task_context),
27533            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
27534        ));
27535        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
27536        assert!(matches!(
27537            timer.as_mut().poll(&mut task_context),
27538            Poll::Ready(Ok(()))
27539        ));
27540        ctx.ensure_history_consumed()
27541            .expect("signal and timer history consumed in order");
27542
27543        let reordered = workflow_context(signal_then_timer);
27544        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
27545        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
27546            timer_first.as_mut().poll(&mut task_context)
27547        else {
27548            panic!("timer cannot consume signal-wait-first history");
27549        };
27550        assert_eq!(failure.reason, "recorded_command_mismatch");
27551        assert_eq!(failure.sequence, Some(1));
27552        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
27553
27554        let timer_then_signal = vec![
27555            history_event(
27556                "TimerScheduled",
27557                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
27558            ),
27559            history_event(
27560                "TimerFired",
27561                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
27562            ),
27563            history_event(
27564                "SignalWaitOpened",
27565                json!({"sequence": 2, "signal_name": "go"}),
27566            ),
27567            history_event(
27568                "SignalApplied",
27569                json!({
27570                    "sequence": 2,
27571                    "signal_name": "go",
27572                    "value": fixture_envelope(json!([])),
27573                }),
27574            ),
27575        ];
27576        let reordered = workflow_context(timer_then_signal);
27577        let mut signal_first = Box::pin(reordered.wait_signal("go"));
27578        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
27579            signal_first.as_mut().poll(&mut task_context)
27580        else {
27581            panic!("signal wait cannot consume timer-first history");
27582        };
27583        assert_eq!(failure.reason, "recorded_command_mismatch");
27584        assert_eq!(failure.sequence, Some(1));
27585        assert_eq!(failure.expected.as_deref(), Some("timer"));
27586    }
27587
27588    #[test]
27589    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
27590        let duplicate_timer = WorkflowState::new(
27591            vec![
27592                history_event(
27593                    "TimerScheduled",
27594                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
27595                ),
27596                history_event(
27597                    "TimerScheduled",
27598                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
27599                ),
27600            ],
27601            "rust-workers".to_string(),
27602            DEFAULT_CODEC.to_string(),
27603            None,
27604        )
27605        .expect_err("one workflow sequence cannot schedule two timers");
27606        assert!(matches!(
27607            duplicate_timer,
27608            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
27609                if reason == "timer_schedule_missing_or_duplicate"
27610        ));
27611
27612        let colliding_kinds = WorkflowState::new(
27613            vec![
27614                history_event(
27615                    "TimerScheduled",
27616                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
27617                ),
27618                history_event(
27619                    "ActivityCompleted",
27620                    json!({"sequence": 1, "activity_type": "same-sequence"}),
27621                ),
27622            ],
27623            "rust-workers".to_string(),
27624            DEFAULT_CODEC.to_string(),
27625            None,
27626        )
27627        .expect_err("one workflow sequence cannot identify two command kinds");
27628        assert!(matches!(
27629            colliding_kinds,
27630            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
27631                if reason == "durable_command_sequence_collision"
27632        ));
27633
27634        let duplicate_signal_wait = WorkflowState::new(
27635            vec![
27636                history_event(
27637                    "SignalWaitOpened",
27638                    json!({"sequence": 1, "signal_name": "go"}),
27639                ),
27640                history_event(
27641                    "SignalWaitOpened",
27642                    json!({"sequence": 1, "signal_name": "go"}),
27643                ),
27644            ],
27645            "rust-workers".to_string(),
27646            DEFAULT_CODEC.to_string(),
27647            None,
27648        )
27649        .expect_err("one workflow sequence cannot open two signal waits");
27650        assert!(matches!(
27651            duplicate_signal_wait,
27652            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
27653                if reason == "signal_wait_open_missing_or_duplicate"
27654        ));
27655    }
27656
27657    #[test]
27658    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
27659        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
27660            .expect("side-effect result");
27661        let ctx = workflow_context(vec![history_event(
27662            "SideEffectRecorded",
27663            json!({"sequence": 99, "result": result}),
27664        )]);
27665
27666        let replayed: Value = ctx
27667            .side_effect(|| panic!("recorded side effect must not run"))
27668            .expect("positive global workflow sequence is valid");
27669        assert_eq!(replayed, json!({"captured": true}));
27670        ctx.ensure_history_consumed().expect("history consumed");
27671    }
27672
27673    #[test]
27674    fn workflow_history_rejects_zero_and_descending_command_sequences() {
27675        let result =
27676            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
27677        let zero = WorkflowState::new(
27678            vec![history_event(
27679                "SideEffectRecorded",
27680                json!({"sequence": 0, "result": result.clone()}),
27681            )],
27682            "rust-workers".to_string(),
27683            DEFAULT_CODEC.to_string(),
27684            None,
27685        )
27686        .expect_err("durable command sequences must be positive");
27687        assert!(matches!(
27688            zero,
27689            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
27690                if reason == "durable_command_sequence_invalid"
27691        ));
27692
27693        let descending = WorkflowState::new(
27694            vec![
27695                history_event(
27696                    "SideEffectRecorded",
27697                    json!({"sequence": 3, "result": result}),
27698                ),
27699                history_event(
27700                    "VersionMarkerRecorded",
27701                    json!({
27702                        "sequence": 2,
27703                        "change_id": "descending-marker",
27704                        "version": 1,
27705                        "min_supported": 1,
27706                        "max_supported": 1,
27707                    }),
27708                ),
27709            ],
27710            "rust-workers".to_string(),
27711            DEFAULT_CODEC.to_string(),
27712            None,
27713        )
27714        .expect_err("new durable commands must remain strictly ordered");
27715        let Error::NonDeterministicReplay(failure) = descending else {
27716            panic!("expected typed replay failure");
27717        };
27718        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
27719        assert_eq!(failure.sequence, Some(2));
27720        assert_eq!(
27721            failure.expected.as_deref(),
27722            Some("workflow sequence greater than 3")
27723        );
27724        assert_eq!(failure.actual.as_deref(), Some("2"));
27725    }
27726
27727    #[test]
27728    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
27729        fn worker() -> Worker {
27730            let client = Client::new("http://127.0.0.1:8080").expect("client");
27731            let mut worker = Worker::new(client, "rust-workers");
27732            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
27733                ctx.wait_signal("finish").await?;
27734                let marker: String =
27735                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
27736                assert_eq!(marker, "after-finish");
27737                Ok(json!("finished"))
27738            });
27739            worker
27740        }
27741
27742        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
27743            .expect("side-effect result");
27744        let task = workflow_task(
27745            "rust.finish-after-gaps",
27746            vec![
27747                history_event(
27748                    "SignalWaitOpened",
27749                    json!({"sequence": 1, "signal_name": "finish"}),
27750                ),
27751                history_event(
27752                    "SignalReceived",
27753                    json!({
27754                        "signal_id": "increment-3",
27755                        "signal_name": "increment",
27756                        "workflow_sequence": 2,
27757                        "payload_codec": DEFAULT_CODEC,
27758                        "arguments": fixture_envelope(json!([3])),
27759                    }),
27760                ),
27761                history_event(
27762                    "SignalReceived",
27763                    json!({
27764                        "signal_id": "increment-5",
27765                        "signal_name": "increment",
27766                        "workflow_sequence": 3,
27767                        "payload_codec": DEFAULT_CODEC,
27768                        "arguments": fixture_envelope(json!([5])),
27769                    }),
27770                ),
27771                history_event(
27772                    "SignalReceived",
27773                    json!({
27774                        "signal_id": "finish",
27775                        "signal_name": "finish",
27776                        "workflow_sequence": 4,
27777                        "payload_codec": DEFAULT_CODEC,
27778                        "arguments": fixture_envelope(json!([])),
27779                    }),
27780                ),
27781                history_event(
27782                    "SignalApplied",
27783                    json!({
27784                        "sequence": 1,
27785                        "signal_id": "finish",
27786                        "signal_name": "finish",
27787                        "payload_codec": DEFAULT_CODEC,
27788                        "value": fixture_envelope(json!([])),
27789                    }),
27790                ),
27791                history_event(
27792                    "SideEffectRecorded",
27793                    json!({"sequence": 5, "result": marker}),
27794                ),
27795            ],
27796            DEFAULT_CODEC,
27797        );
27798
27799        for _original_or_cold_worker in 0..2 {
27800            let commands = worker()
27801                .execute_workflow_task(task.clone())
27802                .expect("signal gaps preserve deterministic replay");
27803            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
27804            assert_eq!(commands[0]["type"], "complete_workflow");
27805            assert_eq!(
27806                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
27807                json!("finished")
27808            );
27809        }
27810    }
27811
27812    #[test]
27813    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
27814        let ctx = workflow_context(Vec::new());
27815        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
27816        let mut task_context = TaskContext::from_waker(noop_waker_ref());
27817        assert!(matches!(
27818            sleep.as_mut().poll(&mut task_context),
27819            Poll::Ready(Err(Error::TimerDurationOverflow))
27820        ));
27821        assert!(ctx.take_commands().expect("commands").is_empty());
27822    }
27823
27824    #[test]
27825    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
27826        let entries = AvroValue::Map(BTreeMap::from([
27827            ("text".to_string(), AvroValue::String("same".to_string())),
27828            (
27829                "nested".to_string(),
27830                AvroValue::Map(BTreeMap::from([
27831                    ("beta".to_string(), AvroValue::Long(2)),
27832                    ("alpha".to_string(), AvroValue::Long(1)),
27833                ])),
27834            ),
27835            ("long".to_string(), AvroValue::Long(7)),
27836            ("double".to_string(), AvroValue::Double(7.0)),
27837            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
27838        ]));
27839        let ctx = workflow_context(Vec::new());
27840        ctx.upsert_memo(entries.clone()).expect("valid memo update");
27841        let commands = ctx.take_commands().expect("commands");
27842
27843        assert_eq!(commands.len(), 1);
27844        assert_eq!(commands[0]["type"], "upsert_memo");
27845        let server_entries = json!({
27846            "codec": "avro",
27847            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
27848        });
27849        assert_eq!(
27850            commands[0]["entries"]
27851                .as_object()
27852                .expect("entries envelope")
27853                .keys()
27854                .collect::<Vec<_>>(),
27855            vec!["blob", "codec"]
27856        );
27857        assert_eq!(commands[0]["entries"], server_entries);
27858        let wire_entries =
27859            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
27860        assert_eq!(wire_entries, entries);
27861
27862        let history = vec![history_event(
27863            "MemoUpserted",
27864            json!({
27865                "sequence": 1,
27866                "entries": server_entries.clone(),
27867                "merged": server_entries,
27868            }),
27869        )];
27870        let replay = workflow_context(history.clone());
27871        replay
27872            .upsert_memo(entries.clone())
27873            .expect("matching replay identity");
27874        assert!(replay.take_commands().expect("replay commands").is_empty());
27875
27876        let changed_types = AvroValue::Map(BTreeMap::from([
27877            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
27878            (
27879                "nested".to_string(),
27880                AvroValue::Map(BTreeMap::from([
27881                    ("alpha".to_string(), AvroValue::Long(1)),
27882                    ("beta".to_string(), AvroValue::Long(2)),
27883                ])),
27884            ),
27885            ("long".to_string(), AvroValue::Double(7.0)),
27886            ("double".to_string(), AvroValue::Long(7)),
27887            ("binary".to_string(), AvroValue::String("same".to_string())),
27888        ]));
27889        let error = workflow_context(history)
27890            .upsert_memo(changed_types)
27891            .expect_err("memo replay identity must preserve Avro value types");
27892        assert!(matches!(
27893            error,
27894            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
27895        ));
27896    }
27897
27898    #[test]
27899    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
27900        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
27901            .expect("memo envelope");
27902        let replay = workflow_context(vec![history_event(
27903            "MemoUpserted",
27904            json!({
27905                "sequence": 1,
27906                "entries": original.clone(),
27907                "merged": original
27908            }),
27909        )]);
27910        let error = replay
27911            .upsert_memo(json!({"stage": "changed"}))
27912            .expect_err("changed memo update must fail replay");
27913        assert!(matches!(
27914            error,
27915            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
27916        ));
27917
27918        let invalid = workflow_context(Vec::new())
27919            .upsert_memo(
27920                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
27921            )
27922            .expect_err("oversized key");
27923        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
27924    }
27925
27926    #[test]
27927    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
27928        let negative_zero = AvroValue::Map(BTreeMap::from([(
27929            "reading".to_string(),
27930            AvroValue::Double(-0.0),
27931        )]));
27932        let negative_zero_envelope =
27933            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
27934        let history = vec![history_event(
27935            "MemoUpserted",
27936            json!({
27937                "sequence": 1,
27938                "entries": negative_zero_envelope.clone(),
27939                "merged": negative_zero_envelope,
27940            }),
27941        )];
27942
27943        workflow_context(history.clone())
27944            .upsert_memo(negative_zero)
27945            .expect("matching negative-zero history identity");
27946
27947        let error = workflow_context(history)
27948            .upsert_memo(AvroValue::Map(BTreeMap::from([(
27949                "reading".to_string(),
27950                AvroValue::Double(0.0),
27951            )])))
27952            .expect_err("positive zero must not consume negative-zero memo history");
27953        assert!(matches!(
27954            error,
27955            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
27956        ));
27957    }
27958
27959    #[test]
27960    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
27961        let supported = json!({
27962            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
27963            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
27964        });
27965        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
27966        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
27967            "workflow_memo_updates": {"supported": false},
27968            "supported_workflow_task_commands": ["upsert_memo"]
27969        }))));
27970        assert!(commands_use_workflow_memo_updates(&[json!({
27971            "type": "upsert_memo",
27972            "entries": {"stage": "processing"}
27973        })]));
27974    }
27975
27976    #[test]
27977    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
27978        let client = Client::new("http://127.0.0.1:8080").expect("client");
27979        let mut worker = Worker::new(client, "rust-workers");
27980        worker.register_workflow("rust.timer", |ctx, _input| async move {
27981            ctx.sleep(Duration::from_secs(5)).await?;
27982            ctx.activity("after-timer", json!([])).await
27983        });
27984
27985        let task = |history_events| WorkflowTask {
27986            task_id: "wft-rust-timer-1".to_string(),
27987            observability_context: None,
27988            dispatch_observability_context: None,
27989            observability_links: None,
27990            workflow_command_id: None,
27991            workflow_id: Some("wf-rust-timer".to_string()),
27992            run_id: Some("run-rust-timer".to_string()),
27993            workflow_type: "rust.timer".to_string(),
27994            cancel_requested: false,
27995            payload_codec: DEFAULT_CODEC.to_string(),
27996            arguments: Some(
27997                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
27998            ),
27999            history_events,
28000            total_history_events: None,
28001            history_size_bytes: None,
28002            continue_as_new_recommended: None,
28003            history_budget_pressure: None,
28004            next_history_page_token: None,
28005            workflow_task_attempt: 1,
28006            workflow_signal_id: None,
28007            signal_name: None,
28008            signal_arguments: None,
28009            workflow_update_id: None,
28010            update_name: None,
28011            lease_owner: Some("rust-worker".to_string()),
28012        };
28013
28014        let initial = worker
28015            .execute_workflow_task(task(Vec::new()))
28016            .expect("initial timer task");
28017        assert_eq!(
28018            initial,
28019            vec![json!({"type": "start_timer", "delay_seconds": 5})]
28020        );
28021
28022        let activity_result =
28023            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
28024        let replayed = worker
28025            .execute_workflow_task(task(vec![
28026                history_event(
28027                    "TimerScheduled",
28028                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28029                ),
28030                history_event(
28031                    "TimerFired",
28032                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28033                ),
28034                history_event(
28035                    "ActivityCompleted",
28036                    json!({
28037                        "sequence": 2,
28038                        "activity_type": "after-timer",
28039                        "payload_codec": DEFAULT_CODEC,
28040                        "result": activity_result,
28041                    }),
28042                ),
28043            ]))
28044            .expect("replayed workflow task");
28045        assert_eq!(replayed.len(), 1);
28046        assert_eq!(replayed[0]["type"], "complete_workflow");
28047        assert_eq!(
28048            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
28049            json!("done")
28050        );
28051    }
28052
28053    #[test]
28054    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
28055        let client = Client::new("http://127.0.0.1:8080").expect("client");
28056        let mut worker = Worker::new(client, "rust-workers");
28057        worker.register_workflow("rust.continue", |ctx, _input| async move {
28058            ctx.continue_as_new_with_options(
28059                ContinueAsNewOptions::new()
28060                    .workflow_type("rust.next")
28061                    .task_queue("next-workers"),
28062                json!([2, {"cursor": "next"}]),
28063            )
28064        });
28065
28066        let commands = worker
28067            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
28068            .expect("continue-as-new command");
28069
28070        assert_eq!(commands.len(), 1);
28071        assert_eq!(commands[0]["type"], "continue_as_new");
28072        assert_eq!(commands[0]["workflow_type"], "rust.next");
28073        assert_eq!(commands[0]["queue"], "next-workers");
28074        assert_eq!(
28075            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
28076                .expect("continue-as-new arguments"),
28077            json!([2, {"cursor": "next"}])
28078        );
28079    }
28080
28081    #[test]
28082    fn continue_as_new_preserves_typed_arguments() {
28083        let client = Client::new("http://127.0.0.1:8080").expect("client");
28084        let mut worker = Worker::new(client, "rust-workers");
28085        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
28086            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
28087            unreachable!("continue-as-new returns a control-flow error")
28088        });
28089
28090        let commands = worker
28091            .execute_workflow_task(workflow_task(
28092                "rust.typed-continue",
28093                Vec::new(),
28094                DEFAULT_CODEC,
28095            ))
28096            .expect("typed continue-as-new command");
28097
28098        assert_eq!(commands[0]["type"], "continue_as_new");
28099        assert_eq!(
28100            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
28101                .expect("typed continue arguments"),
28102            AvroValue::Array(vec![typed_fidelity_probe()])
28103        );
28104    }
28105
28106    #[test]
28107    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
28108        let client = Client::new("http://127.0.0.1:8080").expect("client");
28109        let mut worker = Worker::new(client, "rust-workers");
28110        worker.register_workflow("rust.continue", |ctx, _input| async move {
28111            ctx.continue_as_new(json!([2]))
28112        });
28113        let task = workflow_task(
28114            "rust.continue",
28115            vec![history_event(
28116                "WorkflowContinuedAsNew",
28117                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
28118            )],
28119            DEFAULT_CODEC,
28120        );
28121
28122        for _worker_restart_or_redelivery in 0..2 {
28123            let commands = worker
28124                .execute_workflow_task(task.clone())
28125                .expect("recorded transition replays");
28126            assert!(
28127                commands.is_empty(),
28128                "replay must not emit another successor"
28129            );
28130        }
28131    }
28132
28133    #[test]
28134    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
28135        let ctx = workflow_context(Vec::new());
28136        let error = ctx
28137            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
28138            .expect_err("blank queue must be rejected");
28139
28140        let Error::InvalidContinueAsNewOptions(error) = error else {
28141            panic!("expected typed continue-as-new validation error");
28142        };
28143        assert_eq!(error.field, "task_queue");
28144        assert!(ctx.take_commands().expect("commands").is_empty());
28145    }
28146
28147    #[test]
28148    fn workflow_context_exposes_server_history_budget() {
28149        let client = Client::new("http://127.0.0.1:8080").expect("client");
28150        let mut worker = Worker::new(client, "rust-workers");
28151        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
28152            let budget = ctx.history_budget()?;
28153            Ok(json!({
28154                "events": budget.event_count,
28155                "bytes": budget.size_bytes,
28156                "recommended": budget.continue_as_new_recommended,
28157                "pressure": budget.pressure,
28158            }))
28159        });
28160        let task: WorkflowTask = serde_json::from_value(json!({
28161            "task_id": "task-history-budget",
28162            "workflow_type": "rust.history-budget",
28163            "payload_codec": DEFAULT_CODEC,
28164            "history_events": [],
28165            "total_history_events": 480,
28166            "history_size_bytes": 1_048_576,
28167            "continue_as_new_recommended": true,
28168            "history_budget_pressure": "continue_as_new_recommended",
28169        }))
28170        .expect("published workflow task");
28171
28172        let commands = worker
28173            .execute_workflow_task(task)
28174            .expect("history-budget workflow");
28175        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
28176        assert_eq!(result["events"], 480);
28177        assert_eq!(result["bytes"], 1_048_576);
28178        assert_eq!(result["recommended"], true);
28179        assert_eq!(result["pressure"], "continue_as_new_recommended");
28180    }
28181
28182    #[test]
28183    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
28184        let client = Client::new("http://127.0.0.1:8080").expect("client");
28185        let mut worker = Worker::new(client, "rust-workers");
28186        worker.register_workflow("rust.failing", |_ctx, _input| async move {
28187            Err(Error::Codec("rust_conformance_failure".to_string()))
28188        });
28189        let task = WorkflowTask {
28190            task_id: "wft-rust-failing-1".to_string(),
28191            observability_context: None,
28192            dispatch_observability_context: None,
28193            observability_links: None,
28194            workflow_command_id: None,
28195            workflow_id: Some("wf-rust-failing".to_string()),
28196            run_id: Some("run-rust-failing".to_string()),
28197            workflow_type: "rust.failing".to_string(),
28198            cancel_requested: false,
28199            payload_codec: DEFAULT_CODEC.to_string(),
28200            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
28201            history_events: Vec::new(),
28202            total_history_events: Some(0),
28203            history_size_bytes: None,
28204            continue_as_new_recommended: None,
28205            history_budget_pressure: None,
28206            next_history_page_token: None,
28207            workflow_task_attempt: 1,
28208            workflow_signal_id: None,
28209            signal_name: None,
28210            signal_arguments: None,
28211            workflow_update_id: None,
28212            update_name: None,
28213            lease_owner: Some("rust-worker".to_string()),
28214        };
28215
28216        let commands = worker
28217            .execute_workflow_task(task)
28218            .expect("handler failure becomes a workflow command");
28219
28220        assert_eq!(commands.len(), 1);
28221        assert_eq!(commands[0]["type"], "fail_workflow");
28222        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
28223        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
28224        assert_eq!(commands[0]["non_retryable"], false);
28225        assert_eq!(
28226            commands[0]["message"],
28227            "codec error: rust_conformance_failure"
28228        );
28229        assert_eq!(
28230            commands[0]["exception"]["message"],
28231            "codec error: rust_conformance_failure"
28232        );
28233    }
28234
28235    #[test]
28236    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
28237        let client = Client::new("http://127.0.0.1:8080").expect("client");
28238        let mut worker = Worker::new(client, "rust-workers");
28239        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
28240            let _: String = ctx.side_effect(|| "captured".to_string())?;
28241            Err(Error::WorkerLoop("application failure".to_string()))
28242        });
28243
28244        let commands = worker
28245            .execute_workflow_task(workflow_task(
28246                "rust.failing-after-side-effect",
28247                Vec::new(),
28248                DEFAULT_CODEC,
28249            ))
28250            .expect("ordinary failure remains a workflow decision");
28251
28252        assert_eq!(commands.len(), 2);
28253        assert_eq!(commands[0]["type"], "record_side_effect");
28254        assert_eq!(commands[1]["type"], "fail_workflow");
28255    }
28256
28257    #[test]
28258    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
28259        let client = Client::new("http://127.0.0.1:8080").expect("client");
28260        let mut worker = Worker::new(client, "rust-workers");
28261        worker.register_workflow("rust.redrive", |ctx, _input| async move {
28262            ctx.activity("greet", json!([])).await?;
28263            Ok(Value::Null)
28264        });
28265        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
28266            match ctx.activity("greet", json!([])).await {
28267                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
28268                result => result,
28269            }
28270        });
28271
28272        let failed = history_event(
28273            "ActivityFailed",
28274            json!({
28275                "sequence": 1,
28276                "activity_type": "greet",
28277                "activity_execution_id": "activity-1",
28278                "message": "failed"
28279            }),
28280        );
28281        let commands = worker
28282            .execute_workflow_task(workflow_task(
28283                "rust.redrive",
28284                vec![failed.clone()],
28285                DEFAULT_CODEC,
28286            ))
28287            .expect("recorded failure becomes a workflow command");
28288        assert_eq!(commands[0]["type"], "fail_workflow");
28289        assert_eq!(commands[0]["failed_step_sequence"], 1);
28290        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
28291
28292        let translated = worker
28293            .execute_workflow_task(workflow_task(
28294                "rust.redrive-translated",
28295                vec![failed],
28296                DEFAULT_CODEC,
28297            ))
28298            .expect("translated failure becomes a workflow command");
28299        assert_eq!(translated[0]["type"], "fail_workflow");
28300        assert!(translated[0].get("failed_step_sequence").is_none());
28301        assert!(translated[0].get("failed_activity_execution_id").is_none());
28302
28303        let without_identity = worker
28304            .execute_workflow_task(workflow_task(
28305                "rust.redrive",
28306                vec![history_event(
28307                    "ActivityFailed",
28308                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
28309                )],
28310                DEFAULT_CODEC,
28311            ))
28312            .expect("incomplete identity still fails the workflow");
28313        assert!(without_identity[0].get("failed_step_sequence").is_none());
28314
28315        let timed_out = worker
28316            .execute_workflow_task(workflow_task(
28317                "rust.redrive",
28318                vec![history_event(
28319                    "ActivityTimedOut",
28320                    json!({
28321                        "sequence": 1,
28322                        "activity_type": "greet",
28323                        "activity_execution_id": "activity-timeout",
28324                    }),
28325                )],
28326                DEFAULT_CODEC,
28327            ))
28328            .expect("timeout still fails the workflow");
28329        assert!(timed_out[0].get("failed_step_sequence").is_none());
28330    }
28331
28332    #[test]
28333    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
28334        let client = Client::new("http://127.0.0.1:8080").expect("client");
28335        let mut worker = Worker::new(client, "rust-workers");
28336        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
28337            let first = ctx.activity("first", json!([])).await?;
28338            let second = ctx.activity("second", json!([first.clone()])).await?;
28339            Ok(json!({"first": first, "second": second}))
28340        });
28341        let first = history_event(
28342            "ActivityCompleted",
28343            json!({
28344                "sequence": 1,
28345                "activity_type": "first",
28346                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
28347                "payload_codec": DEFAULT_CODEC,
28348                "reused_from_run_id": "failed-run",
28349                "reused_activity_execution_id": "original-first",
28350            }),
28351        );
28352
28353        let retry = worker
28354            .execute_workflow_task(workflow_task(
28355                "rust.redrive-successor",
28356                vec![first.clone()],
28357                DEFAULT_CODEC,
28358            ))
28359            .expect("reused result replays before failed step");
28360        assert_eq!(retry.len(), 1);
28361        assert_eq!(retry[0]["type"], "schedule_activity");
28362        assert_eq!(retry[0]["activity_type"], "second");
28363        assert_eq!(
28364            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
28365            json!(["recorded"]),
28366        );
28367
28368        let second = history_event(
28369            "ActivityCompleted",
28370            json!({
28371                "sequence": 2,
28372                "activity_type": "second",
28373                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
28374                "payload_codec": DEFAULT_CODEC,
28375            }),
28376        );
28377        let completed = worker
28378            .execute_workflow_task(workflow_task(
28379                "rust.redrive-successor",
28380                vec![first, second],
28381                DEFAULT_CODEC,
28382            ))
28383            .expect("retried step completes the successor");
28384        assert_eq!(completed.len(), 1);
28385        assert_eq!(completed[0]["type"], "complete_workflow");
28386        assert_eq!(
28387            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
28388            json!({"first": "recorded", "second": "retried"}),
28389        );
28390    }
28391
28392    #[test]
28393    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
28394        let client = Client::new("http://127.0.0.1:8080").expect("client");
28395        let mut worker = Worker::new(client, "rust-workers");
28396        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
28397            Err(Error::WorkerLoop("application failure".to_string()))
28398        });
28399        let result =
28400            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
28401
28402        let error = worker
28403            .execute_workflow_task(workflow_task(
28404                "rust.removed-side-effect",
28405                vec![history_event(
28406                    "SideEffectRecorded",
28407                    json!({"sequence": 1, "result": result}),
28408                )],
28409                DEFAULT_CODEC,
28410            ))
28411            .expect_err("removed committed history must not become fail_workflow");
28412
28413        let Error::NonDeterministicReplay(failure) = error else {
28414            panic!("expected typed replay failure");
28415        };
28416        assert_eq!(failure.reason, "recorded_commands_unconsumed");
28417        assert_eq!(failure.sequence, Some(1));
28418        assert_eq!(failure.expected.as_deref(), Some("side effect"));
28419    }
28420
28421    #[test]
28422    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
28423        let client = Client::new("http://127.0.0.1:8080").expect("client");
28424        let mut worker = Worker::new(client, "rust-workers");
28425        worker.register_workflow(
28426            "rust.side-effect-before-marker-error",
28427            |ctx, _input| async move {
28428                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
28429                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
28430                ctx.get_version("restart-safe", 2, 2)?;
28431                Ok(Value::Null)
28432            },
28433        );
28434
28435        let error = worker
28436            .execute_workflow_task(workflow_task(
28437                "rust.side-effect-before-marker-error",
28438                vec![history_event(
28439                    "VersionMarkerRecorded",
28440                    json!({
28441                        "sequence": 1,
28442                        "change_id": "restart-safe",
28443                        "version": 1,
28444                        "min_supported": 1,
28445                        "max_supported": 1,
28446                    }),
28447                )],
28448                DEFAULT_CODEC,
28449            ))
28450            .expect_err("replay error must return no queued workflow commands");
28451
28452        let Error::NonDeterministicReplay(failure) = error else {
28453            panic!("expected typed replay failure");
28454        };
28455        assert_eq!(failure.reason, "version_marker_incompatible_range");
28456        assert_eq!(failure.sequence, Some(1));
28457    }
28458
28459    #[test]
28460    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
28461        let client = Client::new("http://127.0.0.1:8080").expect("client");
28462        let mut worker = Worker::new(client, "rust-workers");
28463        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
28464            ctx.sleep(Duration::from_secs(5)).await?;
28465            Ok(json!({"status": "timer fired"}))
28466        });
28467
28468        let task = WorkflowTask {
28469            task_id: "wft-rust-timer-pending".to_string(),
28470            observability_context: None,
28471            dispatch_observability_context: None,
28472            observability_links: None,
28473            workflow_command_id: None,
28474            workflow_id: Some("wf-rust-timer".to_string()),
28475            run_id: Some("run-rust-timer".to_string()),
28476            workflow_type: "rust.timer.pending".to_string(),
28477            cancel_requested: false,
28478            payload_codec: DEFAULT_CODEC.to_string(),
28479            arguments: Some(
28480                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
28481            ),
28482            history_events: vec![history_event(
28483                "TimerScheduled",
28484                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28485            )],
28486            total_history_events: Some(1),
28487            history_size_bytes: None,
28488            continue_as_new_recommended: None,
28489            history_budget_pressure: None,
28490            next_history_page_token: None,
28491            workflow_task_attempt: 1,
28492            workflow_signal_id: None,
28493            signal_name: None,
28494            signal_arguments: None,
28495            workflow_update_id: None,
28496            update_name: None,
28497            lease_owner: Some("rust-worker".to_string()),
28498        };
28499
28500        for _redelivery_or_restart in 0..2 {
28501            let commands = worker
28502                .execute_workflow_task(task.clone())
28503                .expect("recorded timer remains pending");
28504            assert!(
28505                commands.is_empty(),
28506                "recorded timer must not be rescheduled"
28507            );
28508        }
28509    }
28510
28511    #[test]
28512    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
28513        let client = Client::new("http://127.0.0.1:8080").expect("client");
28514        let mut worker = Worker::new(client, "rust-workers");
28515        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
28516            Ok(json!({"status": "completed"}))
28517        });
28518        let task = WorkflowTask {
28519            task_id: "wft-rust-timer-removed".to_string(),
28520            observability_context: None,
28521            dispatch_observability_context: None,
28522            observability_links: None,
28523            workflow_command_id: None,
28524            workflow_id: Some("wf-rust-timer".to_string()),
28525            run_id: Some("run-rust-timer".to_string()),
28526            workflow_type: "rust.timer.removed".to_string(),
28527            cancel_requested: false,
28528            payload_codec: DEFAULT_CODEC.to_string(),
28529            arguments: Some(
28530                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
28531            ),
28532            history_events: vec![
28533                history_event(
28534                    "TimerScheduled",
28535                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28536                ),
28537                history_event(
28538                    "TimerFired",
28539                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28540                ),
28541            ],
28542            total_history_events: Some(2),
28543            history_size_bytes: None,
28544            continue_as_new_recommended: None,
28545            history_budget_pressure: None,
28546            next_history_page_token: None,
28547            workflow_task_attempt: 1,
28548            workflow_signal_id: None,
28549            signal_name: None,
28550            signal_arguments: None,
28551            workflow_update_id: None,
28552            update_name: None,
28553            lease_owner: Some("rust-worker".to_string()),
28554        };
28555
28556        let Error::NonDeterministicReplay(failure) = worker
28557            .execute_workflow_task(task)
28558            .expect_err("removed timer must fail replay")
28559        else {
28560            panic!("expected typed replay failure");
28561        };
28562        assert_eq!(failure.reason, "recorded_commands_unconsumed");
28563        assert_eq!(failure.sequence, Some(1));
28564    }
28565
28566    #[test]
28567    fn workflow_context_emits_explicit_child_workflow_contract() {
28568        let ctx = WorkflowContext {
28569            cancellation_scope_id: "root".into(),
28570            state: Arc::new(Mutex::new(
28571                WorkflowState::new_with_identity(
28572                    Vec::new(),
28573                    Some("wf-parent".to_string()),
28574                    Some("run-parent".to_string()),
28575                    "parent-workers".to_string(),
28576                    DEFAULT_CODEC.to_string(),
28577                    None,
28578                )
28579                .expect("workflow state"),
28580            )),
28581        };
28582        let options = ChildWorkflowOptions::new("python-workers")
28583            .parent_close_policy(ParentClosePolicy::RequestCancel)
28584            .retry_policy(ChildWorkflowRetryPolicy {
28585                max_attempts: Some(3),
28586                backoff_seconds: vec![1, 5],
28587                non_retryable_error_types: vec!["ValidationError".to_string()],
28588            })
28589            .execution_timeout_seconds(600)
28590            .run_timeout_seconds(120);
28591        let mut call = Box::pin(ctx.start_child_workflow(
28592            "python.fulfil-order",
28593            options,
28594            json!([{"order_id": "order-42"}]),
28595        ));
28596        let mut task_context = TaskContext::from_waker(noop_waker_ref());
28597
28598        assert!(matches!(
28599            call.as_mut().poll(&mut task_context),
28600            Poll::Pending
28601        ));
28602        let commands = ctx.take_commands().expect("commands");
28603        assert_eq!(commands.len(), 1);
28604        let command = &commands[0];
28605        assert_eq!(command["type"], "start_child_workflow");
28606        assert_eq!(command["workflow_type"], "python.fulfil-order");
28607        assert_eq!(command["queue"], "python-workers");
28608        assert_eq!(command["parent_close_policy"], "request_cancel");
28609        assert_eq!(command["retry_policy"]["max_attempts"], 3);
28610        assert_eq!(command["execution_timeout_seconds"], 600);
28611        assert_eq!(command["run_timeout_seconds"], 120);
28612        assert_eq!(
28613            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
28614            json!([{"order_id": "order-42"}])
28615        );
28616    }
28617
28618    fn child_parent_worker() -> Worker {
28619        let client = Client::new("http://127.0.0.1:8080").expect("client");
28620        let mut worker = Worker::new(client, "rust-parent-workers");
28621        worker.register_workflow("rust.parent", |ctx, _input| async move {
28622            let child = ctx
28623                .start_child_workflow(
28624                    "python.child",
28625                    ChildWorkflowOptions::new("python-child-workers")
28626                        .parent_close_policy(ParentClosePolicy::Terminate),
28627                    json!([{"codec_probe": [1, true, "rust"]}]),
28628                )
28629                .await?;
28630            Ok(json!({
28631                "parent_workflow_id": child.parent.workflow_id,
28632                "parent_run_id": child.parent.run_id,
28633                "child_workflow_id": child.child.workflow_id,
28634                "child_run_id": child.child.run_id,
28635                "child_workflow_type": child.child_workflow_type,
28636                "result": child.result,
28637            }))
28638        });
28639        worker
28640    }
28641
28642    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
28643        WorkflowTask {
28644            task_id: "wft-child-parent".to_string(),
28645            observability_context: None,
28646            dispatch_observability_context: None,
28647            observability_links: None,
28648            workflow_command_id: None,
28649            workflow_id: Some("wf-parent".to_string()),
28650            run_id: Some("run-parent".to_string()),
28651            workflow_type: "rust.parent".to_string(),
28652            cancel_requested: false,
28653            payload_codec: DEFAULT_CODEC.to_string(),
28654            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
28655            history_events: vec![
28656                HistoryEvent {
28657                    event_type: "ChildWorkflowScheduled".to_string(),
28658                    payload: json!({
28659                        "sequence": 1,
28660                        "child_call_id": "call-child",
28661                        "child_workflow_instance_id": "wf-child",
28662                        "child_workflow_run_id": "run-child",
28663                        "child_workflow_type": "python.child",
28664                        "parent_close_policy": "terminate",
28665                    }),
28666                    raw: HashMap::new(),
28667                },
28668                HistoryEvent {
28669                    event_type: event_type.to_string(),
28670                    payload,
28671                    raw: HashMap::new(),
28672                },
28673            ],
28674            total_history_events: Some(2),
28675            history_size_bytes: None,
28676            continue_as_new_recommended: None,
28677            history_budget_pressure: None,
28678            next_history_page_token: None,
28679            workflow_task_attempt: 1,
28680            workflow_signal_id: None,
28681            signal_name: None,
28682            signal_arguments: None,
28683            workflow_update_id: None,
28684            update_name: None,
28685            lease_owner: Some("rust-worker".to_string()),
28686        }
28687    }
28688
28689    #[test]
28690    fn committed_child_result_replays_without_starting_a_duplicate() {
28691        let worker = child_parent_worker();
28692        let task = child_parent_task(
28693            "ChildRunCompleted",
28694            json!({
28695                "sequence": 1,
28696                "child_call_id": "call-child",
28697                "child_workflow_instance_id": "wf-child",
28698                "child_workflow_run_id": "run-child",
28699                "child_workflow_type": "python.child",
28700                "payload_codec": DEFAULT_CODEC,
28701                "result": fixture_envelope(json!({"from":"python","ok":true})),
28702            }),
28703        );
28704
28705        for _restart in 0..2 {
28706            let commands = worker
28707                .execute_workflow_task(task.clone())
28708                .expect("replayed parent task");
28709            assert_eq!(commands.len(), 1);
28710            assert_eq!(commands[0]["type"], "complete_workflow");
28711            assert!(!commands
28712                .iter()
28713                .any(|command| command["type"] == "start_child_workflow"));
28714            let output =
28715                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
28716            assert_eq!(output["parent_workflow_id"], "wf-parent");
28717            assert_eq!(output["parent_run_id"], "run-parent");
28718            assert_eq!(output["child_workflow_id"], "wf-child");
28719            assert_eq!(output["child_run_id"], "run-child");
28720            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
28721        }
28722    }
28723
28724    #[test]
28725    fn typed_child_arguments_and_results_survive_replay() {
28726        let client = Client::new("http://127.0.0.1:8080").expect("client");
28727        let mut worker = Worker::new(client, "rust-parent-workers");
28728        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
28729            let child = ctx
28730                .start_child_workflow_avro_value(
28731                    "python.typed-child",
28732                    ChildWorkflowOptions::new("python-workers"),
28733                    AvroValue::Array(vec![typed_fidelity_probe()]),
28734                )
28735                .await?;
28736            Ok(child.result)
28737        });
28738
28739        let initial = worker
28740            .execute_workflow_task(workflow_task(
28741                "rust.typed-parent",
28742                Vec::new(),
28743                DEFAULT_CODEC,
28744            ))
28745            .expect("typed child start");
28746        assert_eq!(initial[0]["type"], "start_child_workflow");
28747        assert_eq!(
28748            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
28749                .expect("typed child arguments"),
28750            AvroValue::Array(vec![typed_fidelity_probe()])
28751        );
28752
28753        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
28754            .expect("typed child result");
28755        let task = workflow_task(
28756            "rust.typed-parent",
28757            vec![
28758                history_event(
28759                    "ChildWorkflowScheduled",
28760                    json!({
28761                        "sequence": 1,
28762                        "child_call_id": "call-typed",
28763                        "child_workflow_instance_id": "wf-child",
28764                        "child_workflow_run_id": "run-child",
28765                        "child_workflow_type": "python.typed-child",
28766                    }),
28767                ),
28768                history_event(
28769                    "ChildRunCompleted",
28770                    json!({
28771                        "sequence": 1,
28772                        "child_call_id": "call-typed",
28773                        "child_workflow_instance_id": "wf-child",
28774                        "child_workflow_run_id": "run-child",
28775                        "child_workflow_type": "python.typed-child",
28776                        "payload_codec": DEFAULT_CODEC,
28777                        "result": result,
28778                    }),
28779                ),
28780            ],
28781            DEFAULT_CODEC,
28782        );
28783
28784        let commands = worker
28785            .execute_workflow_task(task)
28786            .expect("typed child replay");
28787        assert_eq!(commands[0]["type"], "complete_workflow");
28788        assert_eq!(
28789            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
28790                .expect("typed parent result"),
28791            typed_fidelity_probe()
28792        );
28793    }
28794
28795    #[test]
28796    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
28797        let worker = child_parent_worker();
28798        let mut task = child_parent_task("unused", Value::Null);
28799        task.history_events.truncate(1);
28800        task.total_history_events = Some(1);
28801
28802        for _redelivery_or_restart in 0..2 {
28803            let commands = worker
28804                .execute_workflow_task(task.clone())
28805                .expect("recorded child remains pending");
28806            assert!(
28807                commands.is_empty(),
28808                "recorded pending child must not be started again"
28809            );
28810        }
28811    }
28812
28813    #[test]
28814    fn child_cancellation_becomes_stable_parent_failure_command() {
28815        let worker = child_parent_worker();
28816        let task = child_parent_task(
28817            "ChildRunCancelled",
28818            json!({
28819                "sequence": 1,
28820                "child_workflow_instance_id": "wf-child",
28821                "child_workflow_run_id": "run-child",
28822                "child_workflow_type": "python.child",
28823                "failure_id": "failure-child",
28824                "failure_category": "cancelled",
28825                "message": "cancelled by parent-close policy",
28826            }),
28827        );
28828
28829        let commands = worker
28830            .execute_workflow_task(task)
28831            .expect("parent settlement");
28832        assert_eq!(commands.len(), 1);
28833        assert_eq!(commands[0]["type"], "fail_workflow");
28834        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
28835        assert_eq!(
28836            commands[0]["exception"]["properties"]["reason"],
28837            "cancelled"
28838        );
28839        assert_eq!(
28840            commands[0]["exception"]["properties"]["child_workflow_run_id"],
28841            "run-child"
28842        );
28843    }
28844
28845    #[test]
28846    fn workflow_can_handle_typed_child_failure() {
28847        let client = Client::new("http://127.0.0.1:8080").expect("client");
28848        let mut worker = Worker::new(client, "rust-parent-workers");
28849        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
28850            match ctx
28851                .start_child_workflow(
28852                    "python.child",
28853                    ChildWorkflowOptions::new("python-child-workers"),
28854                    json!([]),
28855                )
28856                .await
28857            {
28858                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
28859                    "reason": failure.reason,
28860                    "failure_id": failure.failure_id,
28861                    "exception_class": failure.exception_class,
28862                    "child_run_id": failure.child_workflow_run_id,
28863                })),
28864                Err(error) => Err(error),
28865                Ok(_) => Err(Error::WorkerLoop(
28866                    "child unexpectedly succeeded".to_string(),
28867                )),
28868            }
28869        });
28870        let mut task = child_parent_task(
28871            "ChildRunFailed",
28872            json!({
28873                "sequence": 1,
28874                "child_workflow_instance_id": "wf-child",
28875                "child_workflow_run_id": "run-child",
28876                "child_workflow_type": "python.child",
28877                "failure_id": "failure-child",
28878                "failure_category": "child_workflow",
28879                "message": "payment rejected",
28880                "exception": {
28881                    "type": "PaymentRejected",
28882                    "class": "payments.PaymentRejected",
28883                    "message": "payment rejected"
28884                }
28885            }),
28886        );
28887        task.workflow_type = "rust.handled-parent".to_string();
28888        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
28889
28890        let commands = worker.execute_workflow_task(task).expect("handled failure");
28891        assert_eq!(commands[0]["type"], "complete_workflow");
28892        let output =
28893            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
28894        assert_eq!(output["reason"], "child_workflow");
28895        assert_eq!(output["failure_id"], "failure-child");
28896        assert_eq!(output["exception_class"], "payments.PaymentRejected");
28897        assert_eq!(output["child_run_id"], "run-child");
28898    }
28899
28900    #[test]
28901    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
28902        let client = Client::new("http://127.0.0.1:8080").expect("client");
28903        let mut worker = Worker::new(client, "rust-workers");
28904
28905        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
28906            let signal = ctx.wait_signal("start").await?;
28907            let name = signal
28908                .first()
28909                .and_then(|value| value.as_str())
28910                .unwrap_or("world");
28911            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
28912            Ok(json!({
28913                "greeting": greeting,
28914                "language": "rust"
28915            }))
28916        });
28917
28918        let signal_arguments =
28919            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
28920        let task = WorkflowTask {
28921            task_id: "wft-rust-signal-1".to_string(),
28922            observability_context: None,
28923            dispatch_observability_context: None,
28924            observability_links: None,
28925            workflow_command_id: None,
28926            workflow_id: Some("wf-rust-hello".to_string()),
28927            run_id: Some("run-rust-hello".to_string()),
28928            workflow_type: "rust.hello_workflow".to_string(),
28929            cancel_requested: false,
28930            payload_codec: DEFAULT_CODEC.to_string(),
28931            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
28932            history_events: vec![HistoryEvent {
28933                event_type: "SignalReceived".to_string(),
28934                payload: json!({
28935                    "signal_id": "sig-rust-1",
28936                    "signal_name": "start"
28937                }),
28938                raw: HashMap::new(),
28939            }],
28940            total_history_events: Some(1),
28941            history_size_bytes: None,
28942            continue_as_new_recommended: None,
28943            history_budget_pressure: None,
28944            next_history_page_token: None,
28945            workflow_task_attempt: 1,
28946            workflow_signal_id: Some("sig-rust-1".to_string()),
28947            signal_name: Some("start".to_string()),
28948            signal_arguments: Some(signal_arguments),
28949            workflow_update_id: None,
28950            update_name: None,
28951            lease_owner: Some("rust-worker".to_string()),
28952        };
28953
28954        let commands = worker.execute_workflow_task(task).expect("workflow task");
28955
28956        assert_eq!(commands.len(), 1);
28957        assert_eq!(commands[0]["type"], "schedule_activity");
28958        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
28959        assert_eq!(
28960            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
28961            json!(["Rust"])
28962        );
28963    }
28964
28965    #[test]
28966    fn workflow_task_appends_paginated_history_events() {
28967        let mut task = WorkflowTask {
28968            task_id: "wft-rust-pages-1".to_string(),
28969            observability_context: None,
28970            dispatch_observability_context: None,
28971            observability_links: None,
28972            workflow_command_id: None,
28973            workflow_id: Some("wf-rust-pages".to_string()),
28974            run_id: Some("run-rust-pages".to_string()),
28975            workflow_type: "rust.hello_workflow".to_string(),
28976            cancel_requested: false,
28977            payload_codec: DEFAULT_CODEC.to_string(),
28978            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
28979            history_events: vec![HistoryEvent {
28980                event_type: "WorkflowStarted".to_string(),
28981                payload: json!({}),
28982                raw: HashMap::new(),
28983            }],
28984            total_history_events: Some(3),
28985            history_size_bytes: None,
28986            continue_as_new_recommended: None,
28987            history_budget_pressure: None,
28988            next_history_page_token: Some("MQ==".to_string()),
28989            workflow_task_attempt: 1,
28990            workflow_signal_id: None,
28991            signal_name: None,
28992            signal_arguments: None,
28993            workflow_update_id: None,
28994            update_name: None,
28995            lease_owner: Some("rust-worker".to_string()),
28996        };
28997
28998        task.append_history_page(WorkflowTaskHistoryPage {
28999            history_events: vec![
29000                HistoryEvent {
29001                    event_type: "SignalReceived".to_string(),
29002                    payload: json!({
29003                        "signal_id": "sig-rust-1",
29004                        "signal_name": "start",
29005                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
29006                            .expect("signal arguments")
29007                    }),
29008                    raw: HashMap::new(),
29009                },
29010                HistoryEvent {
29011                    event_type: "MarkerRecorded".to_string(),
29012                    payload: json!({"sequence": 3}),
29013                    raw: HashMap::new(),
29014                },
29015            ],
29016            total_history_events: Some(3),
29017            next_history_page_token: None,
29018        });
29019
29020        assert_eq!(task.history_events.len(), 3);
29021        assert_eq!(task.total_history_events, Some(3));
29022        assert_eq!(task.next_history_page_token, None);
29023
29024        let signal = task
29025            .history_events
29026            .iter()
29027            .find(|event| event.event_type == "SignalReceived")
29028            .expect("signal event");
29029        assert_eq!(
29030            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
29031            vec![AvroValue::String("Rust".to_string())]
29032        );
29033    }
29034
29035    #[tokio::test]
29036    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
29037        let client = Client::new("http://127.0.0.1:8080").expect("client");
29038        let mut worker = Worker::new(client, "rust-workers");
29039        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29040        worker.register_query("counter", "current", |ctx, _args| async move {
29041            let mut count = 0_i64;
29042            for signal in ctx.signal_events() {
29043                let value = signal
29044                    .arguments
29045                    .first()
29046                    .and_then(Value::as_i64)
29047                    .unwrap_or_default();
29048                match signal.name.as_str() {
29049                    "increment" => count += value,
29050                    "set" => count = value,
29051                    _ => {}
29052                }
29053            }
29054            Ok(json!(count))
29055        });
29056
29057        let task = QueryTask {
29058            query_task_id: "query-rust-counter".to_string(),
29059            observability_context: None,
29060            dispatch_observability_context: None,
29061            observability_links: None,
29062            query_task_attempt: 1,
29063            lease_owner: Some("rust-worker".to_string()),
29064            workflow_id: Some("counter-1".to_string()),
29065            run_id: Some("run-counter-1".to_string()),
29066            workflow_type: "counter".to_string(),
29067            query_name: "current".to_string(),
29068            payload_codec: DEFAULT_CODEC.to_string(),
29069            workflow_arguments: Some(
29070                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
29071            ),
29072            query_arguments: Some(
29073                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
29074            ),
29075            history_events: vec![
29076                HistoryEvent {
29077                    event_type: "SignalReceived".to_string(),
29078                    payload: json!({
29079                        "signal_id": "php-signal-1",
29080                        "signal_name": "increment",
29081                        "workflow_sequence": 1,
29082                        "payload_codec": DEFAULT_CODEC,
29083                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
29084                    }),
29085                    raw: HashMap::new(),
29086                },
29087                HistoryEvent {
29088                    event_type: "SignalReceived".to_string(),
29089                    payload: json!({
29090                        "signal_id": "python-signal-2",
29091                        "signal_name": "increment",
29092                        "workflow_sequence": 2,
29093                        "payload_codec": DEFAULT_CODEC,
29094                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
29095                    }),
29096                    raw: HashMap::new(),
29097                },
29098                HistoryEvent {
29099                    event_type: "SignalReceived".to_string(),
29100                    payload: json!({
29101                        "signal_id": "rust-signal-3",
29102                        "signal_name": "set",
29103                        "workflow_sequence": 3,
29104                        "payload_codec": DEFAULT_CODEC,
29105                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
29106                    }),
29107                    raw: HashMap::new(),
29108                },
29109            ],
29110            history_export: None,
29111            run_status: Some("completed".to_string()),
29112        };
29113
29114        let result = worker.execute_query_task(task).await.expect("query result");
29115        assert_eq!(result.into_json().expect("query projection"), json!(0));
29116    }
29117
29118    #[tokio::test]
29119    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
29120        let worker = replay_counter_worker();
29121        let running_history = json!([
29122            {
29123                "type": "ActivityCompleted",
29124                "payload": {
29125                    "sequence": 1,
29126                    "activity_type": "load-counter",
29127                    "payload_codec": DEFAULT_CODEC,
29128                    "result": fixture_envelope(json!("loaded"))
29129                }
29130            },
29131            {
29132                "type": "SignalWaitOpened",
29133                "payload": {
29134                    "sequence": 3,
29135                    "signal_name": "increment"
29136                }
29137            },
29138            {
29139                "type": "SignalReceived",
29140                "payload": {
29141                    "signal_id": "signal-3",
29142                    "signal_name": "increment",
29143                    "workflow_sequence": 2,
29144                    "payload_codec": DEFAULT_CODEC,
29145                    "arguments": fixture_envelope(json!([3]))
29146                }
29147            },
29148            {
29149                "type": "SignalApplied",
29150                "payload": {
29151                    "sequence": 3,
29152                    "signal_id": "signal-3",
29153                    "signal_name": "increment",
29154                    "payload_codec": DEFAULT_CODEC,
29155                    "value": fixture_envelope(json!([3]))
29156                }
29157            }
29158        ]);
29159
29160        let running = worker
29161            .execute_query_task(replay_counter_query(
29162                "current",
29163                running_history.clone(),
29164                "running",
29165            ))
29166            .await
29167            .expect("running replay query");
29168        assert_eq!(
29169            running.clone().into_json().expect("query projection"),
29170            json!({"loaded": "loaded", "count": 3, "finished": false})
29171        );
29172
29173        let detached = worker
29174            .execute_query_task(replay_counter_query(
29175                "detached-mutation",
29176                running_history.clone(),
29177                "running",
29178            ))
29179            .await
29180            .expect("query mutates only its detached state clone");
29181        assert_eq!(detached.into_json().expect("query projection"), json!(999));
29182        let failed = worker
29183            .execute_query_task(replay_counter_query(
29184                "failed-mutation",
29185                running_history.clone(),
29186                "running",
29187            ))
29188            .await
29189            .expect_err("failed query");
29190        assert_eq!(failed.reason, "query_rejected");
29191        let unchanged = worker
29192            .execute_query_task(replay_counter_query("current", running_history, "running"))
29193            .await
29194            .expect("later query reconstructs unchanged state");
29195        assert_eq!(unchanged, running);
29196
29197        let restarted_worker = replay_counter_worker();
29198        let empty_arguments = fixture_envelope(json!([]));
29199        let loaded_result = fixture_envelope(json!("loaded"));
29200        let signal_three = fixture_blob(json!([3]));
29201        let signal_five = fixture_blob(json!([5]));
29202        let restarted_task: QueryTask = serde_json::from_value(json!({
29203            "query_task_id": "query-after-restart",
29204            "workflow_id": "counter-1",
29205            "run_id": "run-counter-1",
29206            "workflow_type": "replay-counter",
29207            "query_name": "current",
29208            "payload_codec": DEFAULT_CODEC,
29209            "workflow_arguments": empty_arguments.clone(),
29210            "query_arguments": empty_arguments,
29211            "history_events": [],
29212            "history_export": {
29213                "payloads": {"codec": DEFAULT_CODEC},
29214                "history_events": [
29215                    {
29216                        "type": "ActivityCompleted",
29217                        "payload": {
29218                            "sequence": 1,
29219                            "activity_type": "load-counter",
29220                            "payload_codec": DEFAULT_CODEC,
29221                            "result": null
29222                        }
29223                    },
29224                    {
29225                        "type": "SignalWaitOpened",
29226                        "payload": {
29227                            "sequence": 3,
29228                            "signal_name": "increment"
29229                        }
29230                    },
29231                    {
29232                        "type": "SignalReceived",
29233                        "payload": {
29234                            "signal_id": "signal-3",
29235                            "signal_name": "increment",
29236                            "workflow_sequence": 2
29237                        }
29238                    },
29239                    {
29240                        "type": "SignalApplied",
29241                        "payload": {
29242                            "sequence": 3,
29243                            "signal_id": "signal-3",
29244                            "signal_name": "increment"
29245                        }
29246                    },
29247                    {
29248                        "type": "SignalWaitOpened",
29249                        "payload": {
29250                            "sequence": 5,
29251                            "signal_name": "increment"
29252                        }
29253                    },
29254                    {
29255                        "type": "SignalReceived",
29256                        "payload": {
29257                            "signal_id": "signal-5",
29258                            "signal_name": "increment",
29259                            "workflow_sequence": 4
29260                        }
29261                    },
29262                    {
29263                        "type": "SignalApplied",
29264                        "payload": {
29265                            "sequence": 5,
29266                            "signal_id": "signal-5",
29267                            "signal_name": "increment"
29268                        }
29269                    }
29270                ],
29271                "activities": [{
29272                    "sequence": 1,
29273                    "activity_type": "load-counter",
29274                    "payload_codec": DEFAULT_CODEC,
29275                    "result": loaded_result
29276                }],
29277                "signals": [
29278                    {
29279                        "id": "signal-3",
29280                        "name": "increment",
29281                        "workflow_sequence": 2,
29282                        "payload_codec": DEFAULT_CODEC,
29283                        "arguments": signal_three
29284                    },
29285                    {
29286                        "id": "signal-5",
29287                        "name": "increment",
29288                        "workflow_sequence": 4,
29289                        "payload_codec": DEFAULT_CODEC,
29290                        "arguments": signal_five
29291                    }
29292                ]
29293            },
29294            "run_status": "completed"
29295        }))
29296        .expect("cold replay query task");
29297        let completed = restarted_worker
29298            .execute_query_task(restarted_task)
29299            .await
29300            .expect("completed cold replay query");
29301        assert_eq!(
29302            completed.into_json().expect("query projection"),
29303            json!({"loaded": "loaded", "count": 8, "finished": true})
29304        );
29305    }
29306
29307    #[tokio::test]
29308    async fn replayed_query_replay_failures_are_machine_readable() {
29309        let worker = replay_counter_worker();
29310        let task = replay_counter_query(
29311            "current",
29312            json!([{
29313                "type": "ActivityCompleted",
29314                "payload": {
29315                    "sequence": 1,
29316                    "payload_codec": DEFAULT_CODEC,
29317                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
29318                }
29319            }]),
29320            "running",
29321        );
29322        let failure = worker
29323            .execute_query_task(task)
29324            .await
29325            .expect_err("invalid replay history payload");
29326        assert_eq!(failure.reason, "query_payload_decode_failed");
29327        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
29328        assert!(failure.message.contains("invalid_payload_framing"));
29329    }
29330
29331    #[tokio::test]
29332    async fn query_task_restores_compact_history_from_export() {
29333        let client = Client::new("http://127.0.0.1:8080").expect("client");
29334        let mut worker = Worker::new(client, "rust-workers");
29335        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29336        worker.register_query("counter", "current", |ctx, _args| async move {
29337            Ok(json!(ctx.signals("increment")[0][0]))
29338        });
29339        let empty_arguments = fixture_envelope(json!([]));
29340        let exported_signal = fixture_blob(json!([9]));
29341        let task: QueryTask = serde_json::from_value(json!({
29342            "query_task_id": "query-export",
29343            "workflow_type": "counter",
29344            "query_name": "current",
29345            "payload_codec": DEFAULT_CODEC,
29346            "workflow_arguments": empty_arguments.clone(),
29347            "query_arguments": empty_arguments,
29348            "history_events": [],
29349            "history_export": {
29350                "payloads": {"codec": DEFAULT_CODEC},
29351                "history_events": [{
29352                    "type": "SignalReceived",
29353                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
29354                }],
29355                "signals": [{
29356                    "id": "signal-export",
29357                    "name": "increment",
29358                    "status": "applied",
29359                    "workflow_sequence": 1,
29360                    "payload_codec": DEFAULT_CODEC,
29361                    "arguments": exported_signal
29362                }]
29363            }
29364        }))
29365        .expect("query task");
29366
29367        let result = worker.execute_query_task(task).await.expect("query result");
29368        assert_eq!(result.into_json().expect("query projection"), json!(9));
29369    }
29370
29371    #[tokio::test]
29372    async fn query_task_failures_have_stable_reasons() {
29373        let client = Client::new("http://127.0.0.1:8080").expect("client");
29374        let mut worker = Worker::new(client, "rust-workers");
29375        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29376        worker.register_query(
29377            "counter",
29378            "current",
29379            |_ctx, _args| async move { Ok(json!(0)) },
29380        );
29381
29382        let base_task = QueryTask {
29383            query_task_id: "query-errors".to_string(),
29384            observability_context: None,
29385            dispatch_observability_context: None,
29386            observability_links: None,
29387            query_task_attempt: 1,
29388            lease_owner: None,
29389            workflow_id: Some("counter-errors".to_string()),
29390            run_id: Some("run-errors".to_string()),
29391            workflow_type: "counter".to_string(),
29392            query_name: "missing".to_string(),
29393            payload_codec: DEFAULT_CODEC.to_string(),
29394            workflow_arguments: Some(fixture_envelope(json!([]))),
29395            query_arguments: Some(fixture_envelope(json!([]))),
29396            history_events: Vec::new(),
29397            history_export: None,
29398            run_status: Some("running".to_string()),
29399        };
29400
29401        let unknown = worker
29402            .execute_query_task(base_task.clone())
29403            .await
29404            .expect_err("unknown query");
29405        assert_eq!(unknown.reason, "rejected_unknown_query");
29406
29407        let mut malformed = base_task;
29408        malformed.query_name = "current".to_string();
29409        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
29410        let malformed = worker
29411            .execute_query_task(malformed)
29412            .await
29413            .expect_err("malformed payload");
29414        assert_eq!(malformed.reason, "query_payload_decode_failed");
29415
29416        let client = Client::new("http://127.0.0.1:8080").expect("client");
29417        let mut unavailable_worker = Worker::new(client, "rust-workers");
29418        unavailable_worker
29419            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
29420        let empty_arguments = fixture_envelope(json!([]));
29421        let unavailable_task: QueryTask = serde_json::from_value(json!({
29422            "query_task_id": "query-unavailable",
29423            "workflow_type": "counter",
29424            "query_name": "current",
29425            "payload_codec": DEFAULT_CODEC,
29426            "workflow_arguments": empty_arguments.clone(),
29427            "query_arguments": empty_arguments
29428        }))
29429        .expect("query task");
29430        let unavailable = unavailable_worker
29431            .execute_query_task(unavailable_task)
29432            .await
29433            .expect_err("query handler unavailable");
29434        assert_eq!(unavailable.reason, "query_handler_unavailable");
29435    }
29436
29437    #[tokio::test]
29438    async fn client_query_decodes_result_and_typed_failure() {
29439        let server = MockWorkerServer::start();
29440        let client = Client::builder(server.base_url())
29441            .timeout(Duration::from_secs(2))
29442            .build()
29443            .expect("client");
29444
29445        let result = client
29446            .query_workflow("counter-1", "current", json!([]))
29447            .await
29448            .expect("query result");
29449        assert_eq!(result, json!({"count": 8}));
29450
29451        let error = client
29452            .query_workflow("counter-1", "missing", json!([]))
29453            .await
29454            .expect_err("unknown query");
29455        let Error::QueryFailed(failure) = error else {
29456            panic!("expected typed query failure");
29457        };
29458        assert_eq!(failure.status, 404);
29459        assert_eq!(failure.reason, "rejected_unknown_query");
29460    }
29461
29462    const KEYED_SIGNAL_PATH: &str = "/api/workflows/keyed-1/signal/approve";
29463    const KEYED_RUN_SIGNAL_PATH: &str = "/api/workflows/keyed-1/runs/run-keyed-1/signal/approve";
29464    const KEYED_UPDATE_PATH: &str = "/api/workflows/keyed-1/update/adjust";
29465
29466    #[cfg(feature = "telemetry")]
29467    #[tokio::test]
29468    async fn optional_observability_client_uses_actual_discovery_and_preserves_business_intent() {
29469        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
29470        static PHASE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
29471        PHASE.store(0, Ordering::SeqCst);
29472        use opentelemetry::{
29473            propagation::TextMapPropagator,
29474            trace::{FutureExt, TracerProvider},
29475        };
29476        use opentelemetry_sdk::propagation::TraceContextPropagator;
29477        struct Restore;
29478        impl Drop for Restore {
29479            fn drop(&mut self) {
29480                opentelemetry::global::set_text_map_propagator(
29481                    opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
29482                );
29483            }
29484        }
29485        let _restore = Restore;
29486        opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());
29487        let headers = HashMap::from([(
29488            "traceparent".to_string(),
29489            "00-12345678901234567890123456789012-1234567890123456-01".to_string(),
29490        )]);
29491        let parent = TraceContextPropagator::new().extract(&headers);
29492        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29493            request_override: Some(|path, body, _number| {
29494                if path == "/api/cluster/info" {
29495                    return Some(if PHASE.load(Ordering::SeqCst) == 2 {
29496                        ("503 Service Unavailable", "{}".into())
29497                    } else {
29498                        ("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
29499                            "supported": true, "schema": "durable-workflow.trace-context", "version": if PHASE.load(Ordering::SeqCst) == 0 {1} else {99},
29500                            "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
29501                            "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
29502                        }}}}).to_string())
29503                    });
29504                }
29505                let body: Value = serde_json::from_str(body).ok()?;
29506                Some(("200 OK", json!({"workflow_id": "order", "run_id": "run", "workflow_type": "orders",
29507                    "outcome": "accepted", "command_id": "command", "request_id": body["request_id"],
29508                    "result": "original"}).to_string()))
29509            }),
29510            ..MockWorkerBehavior::default()
29511        });
29512        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder().build();
29513        let client = Client::new(server.base_url()).unwrap().with_telemetry(
29514            telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test")),
29515        );
29516        let input = json!([{"observability_context": {"business": "preserved"}}]);
29517        async {
29518            client
29519                .start_workflow("orders", "orders", "order", &input)
29520                .await
29521                .unwrap();
29522            assert!(server
29523                .request_body("/api/workflows")
29524                .get("observability_context")
29525                .is_none());
29526            client.cluster_info().await.unwrap();
29527            client
29528                .start_workflow("orders", "orders", "order", &input)
29529                .await
29530                .unwrap();
29531            client
29532                .signal_workflow_with_request_id("order", "ready", &input, "signal-original")
29533                .await
29534                .unwrap();
29535            client
29536                .update_workflow("order", "status", &input, Some("update-original"))
29537                .await
29538                .unwrap();
29539            client
29540                .cancel_workflow("order", WorkflowCommandOptions::default())
29541                .await
29542                .unwrap();
29543            for path in [
29544                "/api/workflows",
29545                "/api/workflows/order/signal/ready",
29546                "/api/workflows/order/update/status",
29547                "/api/workflows/order/cancel",
29548            ] {
29549                let bodies = server.request_bodies(path);
29550                let body = bodies.last().unwrap();
29551                assert_eq!(
29552                    body["observability_context"]["carrier"]["traceparent"],
29553                    headers["traceparent"]
29554                );
29555                assert!(body["observability_context"]["carrier"]
29556                    .get("baggage")
29557                    .is_none());
29558            }
29559            let starts = server.request_bodies("/api/workflows");
29560            assert_eq!(
29561                decode_wire_value(&starts[1]["input"], DEFAULT_CODEC).unwrap(),
29562                input
29563            );
29564            assert_eq!(
29565                server.request_body("/api/workflows/order/signal/ready")["request_id"],
29566                "signal-original"
29567            );
29568            assert_eq!(
29569                server.request_body("/api/workflows/order/update/status")["request_id"],
29570                "update-original"
29571            );
29572            PHASE.store(1, Ordering::SeqCst);
29573            client.cluster_info().await.unwrap();
29574            client
29575                .start_workflow("orders", "orders", "order", &input)
29576                .await
29577                .unwrap();
29578            assert!(server
29579                .request_bodies("/api/workflows")
29580                .last()
29581                .unwrap()
29582                .get("observability_context")
29583                .is_none());
29584            PHASE.store(2, Ordering::SeqCst);
29585            assert!(client.cluster_info().await.is_err());
29586            let before = server.captured_paths().len();
29587            client
29588                .start_workflow("orders", "orders", "order", &input)
29589                .await
29590                .unwrap();
29591            assert_eq!(server.captured_paths().len(), before + 1);
29592            assert!(server
29593                .request_bodies("/api/workflows")
29594                .last()
29595                .unwrap()
29596                .get("observability_context")
29597                .is_none());
29598        }
29599        .with_context(parent)
29600        .await;
29601    }
29602
29603    #[cfg(feature = "telemetry")]
29604    fn observability_worker_server(
29605        path: &str,
29606        _body: &str,
29607        _: usize,
29608    ) -> Option<(&'static str, String)> {
29609        let context = json!({"schema": "durable-workflow.trace-context", "version": 1,
29610            "carrier": {"traceparent": "00-12345678901234567890123456789012-1234567890123456-01",
29611                        "baggage": "credential=private"}});
29612        let link_context = json!({"schema": "durable-workflow.trace-context", "version": 1,
29613            "carrier": {"traceparent": "00-abcdef78901234567890123456789012-abcdef7890123456-01"}});
29614        if path == "/api/cluster/info" {
29615            return Some(("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
29616                "supported": true, "schema": "durable-workflow.trace-context", "version": 1,
29617                "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
29618                "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
29619            }}}}).to_string()));
29620        }
29621        if path.ends_with("/complete") {
29622            return Some(("200 OK", json!({"recorded": true}).to_string()));
29623        }
29624        let task_id = match path {
29625            "/api/worker/workflow-tasks/poll" => "workflow-task",
29626            "/api/worker/activity-tasks/poll" => "activity-task",
29627            "/api/worker/query-tasks/poll" => "query-task",
29628            _ => return None,
29629        };
29630        let input = encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap();
29631        let mut task = json!({"task_id": task_id, "query_task_id": task_id,
29632        "workflow_id": "workflow", "run_id": "run", "workflow_type": "wire.workflow",
29633        "activity_type": "wire.activity", "activity_execution_id": "activity",
29634        "activity_attempt_id": "attempt", "attempt_number": 3, "workflow_task_attempt": 1,
29635        "query_task_attempt": 1, "query_name": "state", "lease_owner": "test-worker",
29636        "namespace": "shipping", "task_queue": "shipping", "lease_expires_at": "2099-01-01T00:00:00Z",
29637        "payload_codec": DEFAULT_CODEC, "arguments": input, "workflow_arguments": input,
29638        "query_arguments": input, "history_events": [], "observability_context": context,
29639        "dispatch_observability_context": {"schema": "durable-workflow.queue-trace", "version": 1,
29640            "task_id": task_id, "context": link_context},
29641        "observability_links": {"schema": "durable-workflow.trace-links", "version": 1,
29642            "task_id": task_id, "run_id": "run", "namespace": "shipping", "links": [
29643                {"kind": "command", "command_id": "accepted-command", "context": link_context},
29644                {"kind": "child_outcome", "workflow_link_id": "link", "child_run_id": "child",
29645                 "child_task_id": null, "event_id": "terminal", "sequence": 7,
29646                 "event_type": "WorkflowCancelled", "context": link_context}
29647            ]}});
29648        if task_id == "workflow-task" {
29649            task["arguments"] = encode_value_envelope(
29650                &json!([{"observability_context": {"business": "preserved"}}]),
29651                DEFAULT_CODEC,
29652            )
29653            .unwrap();
29654        }
29655        Some((
29656            "200 OK",
29657            json!({"task": task, "poll_status": "leased"}).to_string(),
29658        ))
29659    }
29660
29661    #[cfg(feature = "telemetry")]
29662    #[tokio::test]
29663    async fn observability_polled_tasks_recover_parent_links_and_capture_the_actual_child_producer()
29664    {
29665        use opentelemetry::trace::TracerProvider;
29666        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
29667        opentelemetry::global::set_text_map_propagator(
29668            opentelemetry_sdk::propagation::TraceContextPropagator::new(),
29669        );
29670        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
29671        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
29672            .with_simple_exporter(exporter.clone())
29673            .build();
29674        let telemetry = telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test"));
29675        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29676            request_override: Some(observability_worker_server),
29677            ..MockWorkerBehavior::default()
29678        });
29679        let client = Client::builder(server.base_url())
29680            .namespace("shipping")
29681            .build()
29682            .unwrap();
29683        client.cluster_info().await.unwrap();
29684        let mut worker = Worker::new(client, "shipping")
29685            .worker_id("test-worker")
29686            .telemetry(telemetry);
29687        worker.register_workflow("wire.workflow", |ctx, input| async move {
29688            assert_eq!(telemetry::current_log_context()["workflow_run_id"], "run");
29689            assert_eq!(
29690                input,
29691                json!([{"observability_context": {"business": "preserved"}}])
29692            );
29693            ctx.start_child_workflow("child", ChildWorkflowOptions::new("child-workers"), input)
29694                .await?;
29695            Ok(Value::Null)
29696        });
29697        worker.register_activity("wire.activity", |_, _| async {
29698            let fields = telemetry::current_log_context();
29699            assert_eq!(fields["workflow_run_id"], "run");
29700            assert_eq!(fields["activity_id"], "activity");
29701            assert_eq!(fields["activity_attempt_id"], "attempt");
29702            assert_eq!(fields["activity_attempt_number"], "3");
29703            Ok(json!("original-result"))
29704        });
29705        worker.register_query("wire.workflow", "state", |_, _| async {
29706            assert_eq!(telemetry::current_log_context()["task_id"], "query-task");
29707            Ok(json!("original-query"))
29708        });
29709        assert_eq!(worker.run_once().await.unwrap(), 3);
29710        let spans = exporter.get_finished_spans().unwrap();
29711        assert_eq!(spans.len(), 4);
29712        let origin_trace = "12345678901234567890123456789012";
29713        for span in spans
29714            .iter()
29715            .filter(|span| span.name.as_ref() != "durable.activity.attempt")
29716        {
29717            assert_eq!(span.span_context.trace_id().to_string(), origin_trace);
29718            assert_eq!(span.parent_span_id.to_string(), "1234567890123456");
29719            assert_eq!(span.links.len(), 3);
29720            assert!(!format!("{:?}", span.attributes).contains("credential"));
29721        }
29722        let task = spans
29723            .iter()
29724            .find(|span| span.name.as_ref() == "durable.workflow.task")
29725            .unwrap();
29726        let body = server.request_body("/api/worker/workflow-tasks/workflow-task/complete");
29727        assert_eq!(body["commands"][0]["type"], "start_child_workflow");
29728        let parent = body["commands"][0]["observability_context"]["carrier"]["traceparent"]
29729            .as_str()
29730            .unwrap();
29731        assert_eq!(&parent[36..52], task.span_context.span_id().to_string());
29732        assert!(telemetry::current_log_context().is_empty());
29733        opentelemetry::global::set_text_map_propagator(
29734            opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
29735        );
29736    }
29737
29738    #[cfg(feature = "telemetry")]
29739    #[tokio::test]
29740    async fn observability_never_enters_a_query_with_a_refused_original_claim() {
29741        use opentelemetry::trace::TracerProvider;
29742        static REFUSAL: AtomicUsize = AtomicUsize::new(0);
29743        fn refused_query(path: &str, body: &str, count: usize) -> Option<(&'static str, String)> {
29744            let (status, reply) = observability_worker_server(path, body, count)?;
29745            if path != "/api/worker/query-tasks/poll" {
29746                return Some((status, reply));
29747            }
29748            let mut reply: Value = serde_json::from_str(&reply).unwrap();
29749            match REFUSAL.load(Ordering::SeqCst) {
29750                0 => reply["task"]["lease_owner"] = json!("other-worker"),
29751                1 => reply["task"]["query_task_attempt"] = json!(0),
29752                _ => reply["task"]["lease_expires_at"] = json!("2000-01-01T00:00:00Z"),
29753            }
29754            Some((status, reply.to_string()))
29755        }
29756        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
29757        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
29758            .with_simple_exporter(exporter.clone())
29759            .build();
29760        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
29761            request_override: Some(refused_query),
29762            ..MockWorkerBehavior::default()
29763        });
29764        let client = Client::builder(server.base_url())
29765            .namespace("shipping")
29766            .build()
29767            .unwrap();
29768        client.cluster_info().await.unwrap();
29769        let mut worker = Worker::new(client, "shipping")
29770            .worker_id("test-worker")
29771            .telemetry(telemetry::ExecutionTelemetry::from_tracer(
29772                provider.tracer("test"),
29773            ));
29774        let calls = Arc::new(AtomicUsize::new(0));
29775        let query_calls = calls.clone();
29776        worker.register_query("wire.workflow", "state", move |_, _| {
29777            query_calls.fetch_add(1, Ordering::SeqCst);
29778            async { Ok(Value::Null) }
29779        });
29780        for refusal in 0..3 {
29781            REFUSAL.store(refusal, Ordering::SeqCst);
29782            assert!(matches!(
29783                worker.poll_query_once().await.unwrap(),
29784                ManagedPollOutcome::Handled
29785            ));
29786            assert_eq!(calls.load(Ordering::SeqCst), 0);
29787            assert!(exporter.get_finished_spans().unwrap().is_empty());
29788            assert!(telemetry::current_log_context().is_empty());
29789        }
29790        assert!(!server
29791            .captured_paths()
29792            .iter()
29793            .any(|path| path.ends_with("/complete") || path.ends_with("/fail")));
29794    }
29795
29796    fn keyed_command_request(path: &str, body: &str) -> Option<Value> {
29797        if path != KEYED_SIGNAL_PATH && path != KEYED_RUN_SIGNAL_PATH && path != KEYED_UPDATE_PATH {
29798            return None;
29799        }
29800        serde_json::from_str(body).ok()
29801    }
29802
29803    /// A #216 Server: echoes the key with `retained` and `intent_verified`.
29804    fn keyed_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
29805        let request = keyed_command_request(path, body)?;
29806        let mut receipt = json!({
29807            "outcome": "accepted",
29808            "command_status": "accepted",
29809            "command_id": "cmd-keyed-1",
29810            "request_id": request["request_id"],
29811            "retained": false,
29812            "intent_verified": true,
29813        });
29814        if path == KEYED_UPDATE_PATH {
29815            receipt["update_id"] = json!("upd-keyed-1");
29816            receipt["result_envelope"] =
29817                encode_typed_envelope(&AvroValue::Long(42), DEFAULT_CODEC).expect("result");
29818        }
29819        Some(("202 Accepted", receipt.to_string()))
29820    }
29821
29822    /// A Server released before #216: accepts the body field but echoes nothing.
29823    fn legacy_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
29824        keyed_command_request(path, body)?;
29825        Some((
29826            "202 Accepted",
29827            r#"{"outcome":"accepted","command_status":"accepted","command_id":"cmd-legacy"}"#
29828                .to_string(),
29829        ))
29830    }
29831
29832    fn retained_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
29833        let request = keyed_command_request(path, body)?;
29834        Some((
29835            "202 Accepted",
29836            json!({
29837                "outcome": "accepted",
29838                "command_status": "accepted",
29839                "command_id": "cmd-first",
29840                "request_id": request["request_id"],
29841                "retained": true,
29842                "intent_verified": true,
29843            })
29844            .to_string(),
29845        ))
29846    }
29847
29848    fn conflicting_command_server(
29849        path: &str,
29850        body: &str,
29851        _: usize,
29852    ) -> Option<(&'static str, String)> {
29853        let request = keyed_command_request(path, body)?;
29854        let retained_type = if path == KEYED_UPDATE_PATH {
29855            "update"
29856        } else {
29857            "signal"
29858        };
29859        Some((
29860            "409 Conflict",
29861            json!({
29862                "reason": "request_id_conflict",
29863                "message": format!("request id is retained for a different {retained_type} intent"),
29864                "request_id": request["request_id"],
29865                "retained_command_id": "cmd-retained-1",
29866                "retained_command_type": retained_type,
29867                "retained_outcome": "accepted",
29868                "conflict": ["arguments", "target"],
29869                "control_plane": {"operation": retained_type},
29870            })
29871            .to_string(),
29872        ))
29873    }
29874
29875    /// A native Server 3.9.0 (server#934): the original intent is `["ok"]` on
29876    /// the instance. Its retry gets the retained receipt, and any other input or
29877    /// run target is refused exactly as native refuses it, without echoing the key.
29878    fn native_command_key_server(
29879        path: &str,
29880        body: &str,
29881        _: usize,
29882    ) -> Option<(&'static str, String)> {
29883        let request = keyed_command_request(path, body)?;
29884        let original = encode_typed_envelope(
29885            &normalize_avro_arguments(AvroValue::from_serialize(&json!(["ok"])).expect("input")),
29886            DEFAULT_CODEC,
29887        )
29888        .expect("envelope");
29889        let command_type = if path == KEYED_UPDATE_PATH {
29890            "update"
29891        } else {
29892            "signal"
29893        };
29894        if path == KEYED_RUN_SIGNAL_PATH || request["input"] != original {
29895            let part = if path == KEYED_RUN_SIGNAL_PATH {
29896                "target_or_arguments"
29897            } else {
29898                "arguments"
29899            };
29900            return Some((
29901                "409 Conflict",
29902                json!({
29903                    "workflow_id": "keyed-1",
29904                    "reason": "request_id_conflict",
29905                    "outcome": "rejected_request_id_conflict",
29906                    "command_status": "rejected",
29907                    "rejection_reason": "request_id_conflict",
29908                    "message": format!("The request_id was already used for a different {command_type} command on workflow [keyed-1]. Use a new request_id for a different command."),
29909                    "intent_verified": true,
29910                    "retained": true,
29911                    "retained_command_id": "cmd-native-1",
29912                    "retained_outcome": "signal_received",
29913                    "conflict": [part],
29914                })
29915                .to_string(),
29916            ));
29917        }
29918        let mut receipt = json!({
29919            "workflow_id": "keyed-1",
29920            "run_id": "run-keyed-1",
29921            "command_id": "cmd-native-1",
29922            "command_status": "accepted",
29923            "outcome": "signal_received",
29924            "retained": true,
29925            "intent_verified": true,
29926        });
29927        if path == KEYED_UPDATE_PATH {
29928            receipt["update_id"] = json!("upd-native-1");
29929            receipt["result_envelope"] =
29930                encode_typed_envelope(&AvroValue::Long(7), DEFAULT_CODEC).expect("result");
29931        }
29932        Some(("200 OK", receipt.to_string()))
29933    }
29934
29935    fn closed_run_command_server(
29936        path: &str,
29937        body: &str,
29938        _: usize,
29939    ) -> Option<(&'static str, String)> {
29940        let request = keyed_command_request(path, body)?;
29941        Some((
29942            "409 Conflict",
29943            json!({
29944                "reason": "run_not_active",
29945                "message": "run is closed",
29946                "request_id": request["request_id"],
29947            })
29948            .to_string(),
29949        ))
29950    }
29951
29952    fn drop_first_keyed_signal(path: &str, request_number: usize) -> bool {
29953        path == KEYED_SIGNAL_PATH && request_number == 1
29954    }
29955
29956    fn keyed_client(server: &MockWorkerServer) -> Client {
29957        Client::builder(server.base_url())
29958            .timeout(Duration::from_secs(2))
29959            .build()
29960            .expect("client")
29961    }
29962
29963    fn keyed_handle(client: &Client) -> WorkflowHandle {
29964        WorkflowHandle {
29965            client: client.clone(),
29966            workflow_id: "keyed-1".to_string(),
29967            run_id: Some("run-keyed-1".to_string()),
29968            workflow_type: "keyed".to_string(),
29969        }
29970    }
29971
29972    fn assert_generated_request_id(request_id: &str, prefix: &str) {
29973        let suffix = request_id
29974            .strip_prefix(prefix)
29975            .unwrap_or_else(|| panic!("{request_id:?} does not start with {prefix:?}"));
29976        assert_eq!(suffix.len(), 32, "uuid4 simple hex suffix: {request_id:?}");
29977        assert!(
29978            suffix
29979                .bytes()
29980                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()),
29981            "lowercase hex suffix: {request_id:?}"
29982        );
29983        assert!(request_id.len() <= MAX_REQUEST_ID_CHARACTERS);
29984    }
29985
29986    fn assert_key_sent_only_in_body(server: &MockWorkerServer, path: &str) {
29987        let headers = server.request_headers(path);
29988        assert!(!headers.is_empty(), "no request captured for {path}");
29989        for headers in headers {
29990            let header_names: Vec<String> = headers
29991                .lines()
29992                .skip(1)
29993                .filter_map(|line| line.split_once(':'))
29994                .map(|(name, _)| name.trim().to_ascii_lowercase())
29995                .collect();
29996            assert!(
29997                !header_names.iter().any(|name| name == "x-request-id"),
29998                "the caller command key is a body field, never an X-Request-Id header: {headers}"
29999            );
30000        }
30001    }
30002
30003    #[tokio::test]
30004    async fn signal_without_key_sends_a_generated_sdk_rust_signal_key_and_returns_it() {
30005        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30006            request_override: Some(legacy_command_server),
30007            ..MockWorkerBehavior::default()
30008        });
30009        let client = keyed_client(&server);
30010
30011        let receipt = client
30012            .signal_workflow("keyed-1", "approve", json!(["ok"]))
30013            .await
30014            .expect("signal receipt");
30015
30016        let sent = server.request_body(KEYED_SIGNAL_PATH);
30017        let request_id = sent["request_id"].as_str().expect("generated request_id");
30018        assert_generated_request_id(request_id, "sdk-rust-signal-");
30019        assert_eq!(
30020            receipt,
30021            json!({
30022                "outcome": "accepted",
30023                "command_status": "accepted",
30024                "command_id": "cmd-legacy",
30025                "request_id": request_id,
30026            }),
30027            "the sent key is added when an older Server omits it"
30028        );
30029        assert_key_sent_only_in_body(&server, KEYED_SIGNAL_PATH);
30030
30031        let receipt = keyed_handle(&client)
30032            .signal_selected_run("approve", json!(["ok"]))
30033            .await
30034            .expect("selected-run signal receipt");
30035        let run_sent = server.request_body(KEYED_RUN_SIGNAL_PATH);
30036        let run_request_id = run_sent["request_id"]
30037            .as_str()
30038            .expect("generated request_id");
30039        assert_generated_request_id(run_request_id, "sdk-rust-signal-");
30040        assert_eq!(receipt["request_id"], run_request_id);
30041        assert_ne!(
30042            run_request_id, request_id,
30043            "each logical call gets its own key"
30044        );
30045        assert_key_sent_only_in_body(&server, KEYED_RUN_SIGNAL_PATH);
30046    }
30047
30048    #[tokio::test]
30049    async fn update_without_key_sends_a_generated_sdk_rust_update_key() {
30050        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30051            request_override: Some(keyed_command_server),
30052            ..MockWorkerBehavior::default()
30053        });
30054        let client = keyed_client(&server);
30055
30056        let result = client
30057            .update_workflow("keyed-1", "adjust", json!([1]), None)
30058            .await
30059            .expect("update result");
30060        assert_eq!(
30061            result,
30062            json!(42),
30063            "the decoded update result is returned unchanged"
30064        );
30065        let typed = client
30066            .update_workflow_avro_value("keyed-1", "adjust", json!([1]), None)
30067            .await
30068            .expect("typed update result");
30069        assert_eq!(typed, AvroValue::Long(42));
30070        keyed_handle(&client)
30071            .update("adjust", json!([1]), None)
30072            .await
30073            .expect("handle update result");
30074
30075        let bodies = server.request_bodies(KEYED_UPDATE_PATH);
30076        assert_eq!(bodies.len(), 3);
30077        for body in &bodies {
30078            assert_generated_request_id(
30079                body["request_id"].as_str().expect("generated request_id"),
30080                "sdk-rust-update-",
30081            );
30082            assert_eq!(body["wait_for"], "completed");
30083        }
30084        assert_ne!(bodies[0]["request_id"], bodies[1]["request_id"]);
30085        assert_ne!(bodies[1]["request_id"], bodies[2]["request_id"]);
30086        assert_key_sent_only_in_body(&server, KEYED_UPDATE_PATH);
30087    }
30088
30089    fn segment_server(path: &str, _: &str, _: usize) -> Option<(&'static str, String)> {
30090        if path.contains("/update/") {
30091            return Some((
30092                "200 OK",
30093                json!({"update_id": "upd-1", "update_status": "completed",
30094                    "result_envelope": encode_typed_envelope(&AvroValue::Long(1), DEFAULT_CODEC).ok()})
30095                .to_string(),
30096            ));
30097        }
30098        path.starts_with("/api/workflows/").then(|| {
30099            (
30100                "200 OK",
30101                json!({"workflow_id": "x", "run_id": "run-1", "status": "running"}).to_string(),
30102            )
30103        })
30104    }
30105
30106    #[tokio::test]
30107    async fn describe_and_update_keep_each_identifier_in_one_encoded_segment() {
30108        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30109            request_override: Some(segment_server),
30110            ..MockWorkerBehavior::default()
30111        });
30112        let client = keyed_client(&server);
30113
30114        client
30115            .describe_workflow("orders/2026?x#y")
30116            .await
30117            .expect("describe");
30118        assert_eq!(
30119            server.method_for("/api/workflows/orders%2F2026%3Fx%23y"),
30120            Some("GET".to_string()),
30121            "the workflow id stays one segment: {:?}",
30122            server.captured_paths()
30123        );
30124        client
30125            .update_workflow("order 1/a", "re/name", json!([1]), Some("key-1"))
30126            .await
30127            .expect("update");
30128        assert_eq!(
30129            server.request_body("/api/workflows/order%201%2Fa/update/re%2Fname")["request_id"],
30130            "key-1"
30131        );
30132    }
30133
30134    #[tokio::test]
30135    async fn dot_segment_and_empty_identifiers_are_refused_before_any_request() {
30136        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30137            request_override: Some(segment_server),
30138            ..MockWorkerBehavior::default()
30139        });
30140        let client = keyed_client(&server);
30141
30142        for workflow_id in ["", ".", ".."] {
30143            let error = client
30144                .describe_workflow(workflow_id)
30145                .await
30146                .expect_err("a dot segment would describe another route");
30147            assert!(
30148                matches!(
30149                    error,
30150                    Error::InvalidPathSegment {
30151                        field: "workflow_id"
30152                    }
30153                ),
30154                "{workflow_id:?}: {error:?}"
30155            );
30156            let error = client
30157                .update_workflow(workflow_id, "adjust", json!([1]), None)
30158                .await
30159                .expect_err("a dot segment would update another route");
30160            assert!(
30161                matches!(
30162                    error,
30163                    Error::InvalidPathSegment {
30164                        field: "workflow_id"
30165                    }
30166                ),
30167                "{workflow_id:?}: {error:?}"
30168            );
30169        }
30170        for update_name in ["", ".", ".."] {
30171            let error = client
30172                .update_workflow("order-1", update_name, json!([1]), None)
30173                .await
30174                .expect_err("a dot segment update name is refused");
30175            assert!(
30176                matches!(
30177                    error,
30178                    Error::InvalidPathSegment {
30179                        field: "update_name"
30180                    }
30181                ),
30182                "{update_name:?}: {error:?}"
30183            );
30184        }
30185        assert!(
30186            server.captured_paths().is_empty(),
30187            "nothing was sent: {:?}",
30188            server.captured_paths()
30189        );
30190    }
30191
30192    #[tokio::test]
30193    async fn explicit_command_keys_are_sent_verbatim_as_the_request_id_body_field() {
30194        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30195            request_override: Some(keyed_command_server),
30196            ..MockWorkerBehavior::default()
30197        });
30198        let client = keyed_client(&server);
30199        let handle = keyed_handle(&client);
30200
30201        let receipt = client
30202            .signal_workflow_with_request_id(
30203                "keyed-1",
30204                "approve",
30205                json!(["ok"]),
30206                "Order-42/approve",
30207            )
30208            .await
30209            .expect("signal receipt");
30210        assert_eq!(receipt["request_id"], "Order-42/approve");
30211        assert_eq!(receipt["retained"], false);
30212        assert_eq!(receipt["intent_verified"], true);
30213        handle
30214            .signal_with_request_id("approve", json!(["ok"]), "handle-signal-key")
30215            .await
30216            .expect("handle signal receipt");
30217        client
30218            .signal_workflow_run_with_request_id(
30219                "keyed-1",
30220                "run-keyed-1",
30221                "approve",
30222                json!(["ok"]),
30223                "run-signal-key",
30224            )
30225            .await
30226            .expect("selected-run signal receipt");
30227        handle
30228            .signal_selected_run_with_request_id("approve", json!(["ok"]), "handle-run-signal-key")
30229            .await
30230            .expect("handle selected-run signal receipt");
30231        let result = client
30232            .update_workflow("keyed-1", "adjust", json!([1]), Some("update-key"))
30233            .await
30234            .expect("update result");
30235        assert_eq!(result, json!(42));
30236        handle
30237            .update("adjust", json!([1]), Some("handle-update-key"))
30238            .await
30239            .expect("handle update result");
30240        handle
30241            .update_avro_value("adjust", json!([1]), Some("handle-typed-update-key"))
30242            .await
30243            .expect("handle typed update result");
30244
30245        let signal_keys: Vec<Value> = server
30246            .request_bodies(KEYED_SIGNAL_PATH)
30247            .into_iter()
30248            .map(|body| body["request_id"].clone())
30249            .collect();
30250        assert_eq!(
30251            signal_keys,
30252            [json!("Order-42/approve"), json!("handle-signal-key")]
30253        );
30254        let run_signal_keys: Vec<Value> = server
30255            .request_bodies(KEYED_RUN_SIGNAL_PATH)
30256            .into_iter()
30257            .map(|body| body["request_id"].clone())
30258            .collect();
30259        assert_eq!(
30260            run_signal_keys,
30261            [json!("run-signal-key"), json!("handle-run-signal-key")]
30262        );
30263        let update_keys: Vec<Value> = server
30264            .request_bodies(KEYED_UPDATE_PATH)
30265            .into_iter()
30266            .map(|body| body["request_id"].clone())
30267            .collect();
30268        assert_eq!(
30269            update_keys,
30270            [
30271                json!("update-key"),
30272                json!("handle-update-key"),
30273                json!("handle-typed-update-key")
30274            ]
30275        );
30276        for path in [KEYED_SIGNAL_PATH, KEYED_RUN_SIGNAL_PATH, KEYED_UPDATE_PATH] {
30277            assert_key_sent_only_in_body(&server, path);
30278        }
30279    }
30280
30281    #[tokio::test]
30282    async fn retained_receipts_are_returned_unchanged() {
30283        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30284            request_override: Some(retained_command_server),
30285            ..MockWorkerBehavior::default()
30286        });
30287        let client = keyed_client(&server);
30288
30289        let receipt = client
30290            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "retry-key")
30291            .await
30292            .expect("retained receipt");
30293
30294        assert_eq!(
30295            receipt,
30296            json!({
30297                "outcome": "accepted",
30298                "command_status": "accepted",
30299                "command_id": "cmd-first",
30300                "request_id": "retry-key",
30301                "retained": true,
30302                "intent_verified": true,
30303            })
30304        );
30305    }
30306
30307    #[tokio::test]
30308    async fn request_id_conflict_refusal_keeps_error_http_and_classifies_the_sent_key() {
30309        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30310            request_override: Some(conflicting_command_server),
30311            ..MockWorkerBehavior::default()
30312        });
30313        let client = keyed_client(&server);
30314
30315        let error = client
30316            .signal_workflow_with_request_id(
30317                "keyed-1",
30318                "approve",
30319                json!(["changed"]),
30320                "Order-42/approve",
30321            )
30322            .await
30323            .expect_err("different intent under a retained key");
30324        assert!(
30325            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT),
30326            "existing Error::Http matching keeps working: {error:?}"
30327        );
30328        assert!(error.is_request_id_conflict());
30329        assert_eq!(error.request_id().as_deref(), Some("Order-42/approve"));
30330        let conflict = error.request_id_conflict().expect("conflict details");
30331        assert_eq!(conflict.status, 409);
30332        assert_eq!(conflict.request_id, "Order-42/approve");
30333        assert_eq!(
30334            conflict.message,
30335            "request id is retained for a different signal intent"
30336        );
30337        assert_eq!(
30338            conflict.retained_command_id.as_deref(),
30339            Some("cmd-retained-1")
30340        );
30341        assert_eq!(conflict.retained_command_type.as_deref(), Some("signal"));
30342        assert_eq!(conflict.retained_outcome.as_deref(), Some("accepted"));
30343        assert_eq!(conflict.conflict, ["arguments", "target"]);
30344        assert_eq!(conflict.body["control_plane"]["operation"], "signal");
30345
30346        let error = client
30347            .update_workflow("keyed-1", "adjust", json!([2]), None)
30348            .await
30349            .expect_err("different intent under a retained generated key");
30350        let sent = server.request_body(KEYED_UPDATE_PATH);
30351        assert_eq!(
30352            error.request_id(),
30353            sent["request_id"].as_str().map(str::to_string)
30354        );
30355        assert_eq!(
30356            error
30357                .request_id_conflict()
30358                .expect("conflict details")
30359                .retained_command_type
30360                .as_deref(),
30361            Some("update")
30362        );
30363    }
30364
30365    #[tokio::test]
30366    async fn native_request_id_conflict_is_typed_carries_the_sent_key_and_is_sent_once() {
30367        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30368            request_override: Some(native_command_key_server),
30369            ..MockWorkerBehavior::default()
30370        });
30371        let client = keyed_client(&server);
30372
30373        let error = client
30374            .signal_workflow_with_request_id("keyed-1", "approve", json!(["changed"]), "approve-1")
30375            .await
30376            .expect_err("changed arguments under a retained key");
30377        assert!(
30378            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT),
30379            "{error:?}"
30380        );
30381        assert!(error.is_request_id_conflict());
30382        assert_eq!(error.request_id().as_deref(), Some("approve-1"));
30383        let conflict = error.request_id_conflict().expect("conflict details");
30384        assert_eq!(conflict.status, 409);
30385        assert_eq!(conflict.request_id, "approve-1");
30386        assert_eq!(
30387            conflict.retained_command_id.as_deref(),
30388            Some("cmd-native-1")
30389        );
30390        assert_eq!(conflict.retained_command_type, None);
30391        assert_eq!(
30392            conflict.retained_outcome.as_deref(),
30393            Some("signal_received")
30394        );
30395        assert_eq!(conflict.conflict, ["arguments"]);
30396        assert_eq!(conflict.body["outcome"], "rejected_request_id_conflict");
30397        assert_eq!(
30398            server.request_bodies(KEYED_SIGNAL_PATH).len(),
30399            1,
30400            "never resent"
30401        );
30402
30403        let error = client
30404            .signal_workflow_run_with_request_id(
30405                "keyed-1",
30406                "run-keyed-1",
30407                "approve",
30408                json!(["ok"]),
30409                "approve-1",
30410            )
30411            .await
30412            .expect_err("another run target under a retained key");
30413        let conflict = error.request_id_conflict().expect("conflict details");
30414        assert_eq!(conflict.conflict, ["target_or_arguments"]);
30415        assert_eq!(conflict.request_id, "approve-1");
30416        assert_eq!(server.request_bodies(KEYED_RUN_SIGNAL_PATH).len(), 1);
30417
30418        let error = client
30419            .update_workflow("keyed-1", "adjust", json!(["changed"]), None)
30420            .await
30421            .expect_err("changed update under a retained generated key");
30422        let sent = server.request_body(KEYED_UPDATE_PATH);
30423        let conflict = error.request_id_conflict().expect("conflict details");
30424        assert_eq!(
30425            Some(conflict.request_id.as_str()),
30426            sent["request_id"].as_str()
30427        );
30428        assert_eq!(error.request_id().as_deref(), sent["request_id"].as_str());
30429        assert_eq!(conflict.conflict, ["arguments"]);
30430        assert_eq!(
30431            server.request_bodies(KEYED_UPDATE_PATH).len(),
30432            1,
30433            "never resent"
30434        );
30435    }
30436
30437    #[tokio::test]
30438    async fn native_identical_retry_returns_the_original_receipt() {
30439        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30440            request_override: Some(native_command_key_server),
30441            ..MockWorkerBehavior::default()
30442        });
30443        let client = keyed_client(&server);
30444
30445        let receipt = client
30446            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "approve-1")
30447            .await
30448            .expect("retained signal receipt");
30449        assert_eq!(receipt["command_id"], "cmd-native-1");
30450        assert_eq!(receipt["retained"], true);
30451        assert_eq!(receipt["intent_verified"], true);
30452        assert_eq!(receipt["request_id"], "approve-1");
30453
30454        let result = client
30455            .update_workflow("keyed-1", "adjust", json!(["ok"]), Some("adjust-1"))
30456            .await
30457            .expect("retained update result");
30458        assert_eq!(result, json!(7));
30459    }
30460
30461    #[tokio::test]
30462    async fn older_server_without_command_keys_is_unchanged() {
30463        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30464            request_override: Some(legacy_command_server),
30465            ..MockWorkerBehavior::default()
30466        });
30467        let client = keyed_client(&server);
30468
30469        // Before native 3.9.0 the same key with other input is admitted again.
30470        for input in [json!(["ok"]), json!(["changed"])] {
30471            let receipt = client
30472                .signal_workflow_with_request_id("keyed-1", "approve", input, "approve-1")
30473                .await
30474                .expect("legacy receipt");
30475            assert_eq!(receipt["request_id"], "approve-1");
30476            assert_eq!(receipt.get("retained"), None);
30477        }
30478        assert_eq!(server.request_bodies(KEYED_SIGNAL_PATH).len(), 2);
30479    }
30480
30481    #[test]
30482    fn a_sent_key_is_added_only_to_conflicts_that_do_not_echo_one() {
30483        let conflict = Error::Http {
30484            status: reqwest::StatusCode::CONFLICT,
30485            body: r#"{"reason":"request_id_conflict","retained_command_id":"cmd-1","conflict":["name"]}"#
30486                .to_string(),
30487        }
30488        .with_sent_request_id("sent");
30489        assert_eq!(conflict.request_id().as_deref(), Some("sent"));
30490
30491        let echoed = Error::Http {
30492            status: reqwest::StatusCode::CONFLICT,
30493            body: r#"{"reason":"request_id_conflict","request_id":"echoed"}"#.to_string(),
30494        }
30495        .with_sent_request_id("sent");
30496        assert_eq!(echoed.request_id().as_deref(), Some("echoed"));
30497
30498        let other = r#"{"reason":"run_not_active"}"#;
30499        let refused = Error::Http {
30500            status: reqwest::StatusCode::CONFLICT,
30501            body: other.to_string(),
30502        }
30503        .with_sent_request_id("sent");
30504        assert!(matches!(refused, Error::Http { ref body, .. } if body == other));
30505        assert!(matches!(
30506            Error::Timeout.with_sent_request_id("sent"),
30507            Error::Timeout
30508        ));
30509    }
30510
30511    #[tokio::test]
30512    async fn other_refusals_echoing_the_key_are_not_request_id_conflicts() {
30513        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30514            request_override: Some(closed_run_command_server),
30515            ..MockWorkerBehavior::default()
30516        });
30517        let client = keyed_client(&server);
30518
30519        let error = client
30520            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "closed-key")
30521            .await
30522            .expect_err("closed run");
30523
30524        assert!(matches!(error, Error::Http { status, .. } if status.as_u16() == 409));
30525        assert!(!error.is_request_id_conflict());
30526        assert_eq!(error.request_id_conflict(), None);
30527        assert_eq!(error.request_id().as_deref(), Some("closed-key"));
30528    }
30529
30530    #[tokio::test]
30531    async fn transport_failure_keeps_error_transport_and_the_held_key_retries_identically() {
30532        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30533            request_override: Some(keyed_command_server),
30534            drop_request: Some(drop_first_keyed_signal),
30535            ..MockWorkerBehavior::default()
30536        });
30537        let client = keyed_client(&server);
30538        let request_id = Client::generate_signal_request_id();
30539
30540        let error = client
30541            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
30542            .await
30543            .expect_err("connection closed before any response");
30544        assert!(
30545            matches!(error, Error::Transport(_)),
30546            "the transport variant is unchanged: {error:?}"
30547        );
30548        assert_eq!(
30549            error.request_id(),
30550            None,
30551            "nothing was echoed; the application holds the key it chose"
30552        );
30553
30554        let receipt = client
30555            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
30556            .await
30557            .expect("manual retry with the same key");
30558        assert_eq!(receipt["request_id"], request_id);
30559        let bodies = server.request_bodies(KEYED_SIGNAL_PATH);
30560        assert_eq!(bodies.len(), 2, "one attempt per call, no automatic retry");
30561        assert_eq!(
30562            bodies[0], bodies[1],
30563            "the retry resends the identical key and input"
30564        );
30565        assert_eq!(bodies[0]["request_id"], request_id);
30566    }
30567
30568    #[tokio::test]
30569    async fn invalid_command_keys_are_refused_before_sending() {
30570        let server = MockWorkerServer::start();
30571        let client = keyed_client(&server);
30572        let too_long = "k".repeat(MAX_REQUEST_ID_CHARACTERS + 1);
30573
30574        for request_id in ["", too_long.as_str()] {
30575            let error = client
30576                .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), request_id)
30577                .await
30578                .expect_err("invalid signal key");
30579            assert!(
30580                matches!(error, Error::Codec(ref message) if message.contains("1 to 255 Unicode characters")),
30581                "{error:?}"
30582            );
30583            let error = client
30584                .update_workflow("keyed-1", "adjust", json!([1]), Some(request_id))
30585                .await
30586                .expect_err("invalid update key");
30587            assert!(matches!(error, Error::Codec(_)), "{error:?}");
30588        }
30589        assert!(server.captured_paths().is_empty(), "nothing was sent");
30590
30591        let longest = "k".repeat(MAX_REQUEST_ID_CHARACTERS);
30592        let _ = client
30593            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &longest)
30594            .await;
30595        assert_eq!(
30596            server.request_body(KEYED_SIGNAL_PATH)["request_id"],
30597            longest
30598        );
30599    }
30600
30601    #[test]
30602    fn generated_command_keys_are_distinct_and_well_formed() {
30603        let signal = Client::generate_signal_request_id();
30604        let update = Client::generate_update_request_id();
30605        assert_generated_request_id(&signal, "sdk-rust-signal-");
30606        assert_generated_request_id(&update, "sdk-rust-update-");
30607        assert_ne!(Client::generate_signal_request_id(), signal);
30608        assert!(validate_request_id(&signal).is_ok());
30609    }
30610
30611    #[test]
30612    fn command_keys_preserve_the_published_server_unicode_character_limit() {
30613        assert!(validate_request_id(&"é".repeat(255)).is_ok());
30614        assert!(validate_request_id(&"😀".repeat(255)).is_ok());
30615        assert!(validate_request_id(&"é".repeat(256)).is_err());
30616    }
30617
30618    #[test]
30619    fn request_id_accessors_read_only_echoed_refusal_bodies() {
30620        let conflict = Error::Http {
30621            status: reqwest::StatusCode::CONFLICT,
30622            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(),
30623        };
30624        assert!(conflict.is_request_id_conflict());
30625        assert_eq!(conflict.request_id().as_deref(), Some("k1"));
30626        let details = conflict.request_id_conflict().expect("conflict details");
30627        assert_eq!(details.conflict, ["name"]);
30628        assert_eq!(
30629            details.message,
30630            "request id is retained for a different command intent"
30631        );
30632
30633        let echoed = Error::Http {
30634            status: reqwest::StatusCode::CONFLICT,
30635            body: r#"{"reason":"run_not_active","request_id":"k2"}"#.to_string(),
30636        };
30637        assert!(!echoed.is_request_id_conflict());
30638        assert_eq!(echoed.request_id().as_deref(), Some("k2"));
30639
30640        let blank = Error::Http {
30641            status: reqwest::StatusCode::UNPROCESSABLE_ENTITY,
30642            body: r#"{"request_id":""}"#.to_string(),
30643        };
30644        assert_eq!(blank.request_id(), None);
30645        let text = Error::Http {
30646            status: reqwest::StatusCode::BAD_GATEWAY,
30647            body: "upstream unavailable".to_string(),
30648        };
30649        assert_eq!(text.request_id(), None);
30650        assert!(!text.is_request_id_conflict());
30651
30652        let rejection = Error::WorkflowCommandRejected(WorkflowCommandRejection {
30653            command: WorkflowCommandKind::Cancel,
30654            status: 409,
30655            reason: "request_id_conflict".to_string(),
30656            message: "retained".to_string(),
30657            workflow_id: "wf".to_string(),
30658            run_id: None,
30659            target_scope: None,
30660            body: json!({"reason": "request_id_conflict", "request_id": "k3", "conflict": []}),
30661        });
30662        assert!(rejection.is_request_id_conflict());
30663        assert_eq!(rejection.request_id().as_deref(), Some("k3"));
30664
30665        assert_eq!(Error::Timeout.request_id(), None);
30666        assert!(!Error::Codec("local".to_string()).is_request_id_conflict());
30667    }
30668
30669    #[tokio::test]
30670    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
30671        let server = MockWorkerServer::start();
30672        let client = Client::builder(server.base_url())
30673            .timeout(Duration::from_secs(2))
30674            .build()
30675            .expect("client");
30676        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
30677
30678        client
30679            .start_workflow(
30680                "typed.echo",
30681                "rust-workers",
30682                "typed-start",
30683                arguments.clone(),
30684            )
30685            .await
30686            .expect("typed workflow start");
30687        assert_eq!(
30688            decode_wire_avro_value(
30689                &server.request_body("/api/workflows")["input"],
30690                DEFAULT_CODEC,
30691            )
30692            .expect("typed start input"),
30693            arguments
30694        );
30695
30696        client
30697            .signal_workflow("typed-1", "changed", arguments.clone())
30698            .await
30699            .expect("typed signal");
30700        assert_eq!(
30701            decode_wire_avro_value(
30702                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
30703                DEFAULT_CODEC,
30704            )
30705            .expect("typed signal input"),
30706            arguments
30707        );
30708
30709        assert_eq!(
30710            client
30711                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
30712                .await
30713                .expect("typed query"),
30714            typed_fidelity_probe()
30715        );
30716        assert_eq!(
30717            decode_wire_avro_value(
30718                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
30719                DEFAULT_CODEC,
30720            )
30721            .expect("typed query input"),
30722            arguments
30723        );
30724
30725        assert_eq!(
30726            client
30727                .update_workflow_avro_value(
30728                    "typed-1",
30729                    "replace",
30730                    arguments.clone(),
30731                    Some("typed-request"),
30732                )
30733                .await
30734                .expect("typed update"),
30735            typed_fidelity_probe()
30736        );
30737        let update = server.request_body("/api/workflows/typed-1/update/replace");
30738        assert_eq!(update["request_id"], "typed-request");
30739        assert_eq!(
30740            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
30741            arguments
30742        );
30743
30744        let handle = WorkflowHandle {
30745            client: client.clone(),
30746            workflow_id: "typed-1".to_string(),
30747            run_id: Some("run-typed-1".to_string()),
30748            workflow_type: "typed.echo".to_string(),
30749        };
30750        assert_eq!(
30751            handle
30752                .result_avro_value(WorkflowResultOptions::default())
30753                .await
30754                .expect("typed workflow result"),
30755            typed_fidelity_probe()
30756        );
30757
30758        client
30759            .complete_activity_task(
30760                "activity-typed",
30761                "attempt-typed",
30762                "rust-worker",
30763                typed_fidelity_probe(),
30764                DEFAULT_CODEC,
30765            )
30766            .await
30767            .expect("typed activity completion");
30768        assert_eq!(
30769            decode_wire_avro_value(
30770                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
30771                    ["result"],
30772                DEFAULT_CODEC,
30773            )
30774            .expect("typed activity result"),
30775            typed_fidelity_probe()
30776        );
30777        client
30778            .fail_activity_task(
30779                "activity-typed",
30780                "attempt-typed",
30781                "rust-worker",
30782                "typed failure",
30783                true,
30784            )
30785            .await
30786            .expect("activity failure");
30787    }
30788
30789    #[tokio::test]
30790    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
30791        let server = MockWorkerServer::start();
30792        let client = Client::builder(server.base_url())
30793            .timeout(Duration::from_secs(2))
30794            .build()
30795            .expect("client");
30796
30797        let options = WorkflowCommandOptions::new()
30798            .reason("cleanup requested")
30799            .request_id("cancel-17");
30800        let cancelled = client
30801            .cancel_workflow("wf-lifecycle", options)
30802            .await
30803            .expect("instance cancellation");
30804        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
30805        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
30806        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
30807        assert_eq!(
30808            server.request_body("/api/workflows/wf-lifecycle/cancel"),
30809            json!({"reason":"cleanup requested","request_id":"cancel-17"})
30810        );
30811
30812        let terminated = client
30813            .terminate_workflow(
30814                "wf-lifecycle",
30815                WorkflowCommandOptions::new().reason("forced stop"),
30816            )
30817            .await
30818            .expect("instance termination");
30819        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
30820        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
30821
30822        client
30823            .cancel_workflow_run(
30824                "wf-lifecycle",
30825                "run-current",
30826                WorkflowCommandOptions::default(),
30827            )
30828            .await
30829            .expect("selected run cancellation");
30830        client
30831            .terminate_workflow_run(
30832                "wf-lifecycle",
30833                "run-current",
30834                WorkflowCommandOptions::default(),
30835            )
30836            .await
30837            .expect("selected run termination");
30838
30839        for (command, error) in [
30840            (
30841                WorkflowCommandKind::Cancel,
30842                client
30843                    .cancel_workflow_run(
30844                        "wf-lifecycle",
30845                        "run-stale",
30846                        WorkflowCommandOptions::default(),
30847                    )
30848                    .await
30849                    .expect_err("stale cancellation must be rejected"),
30850            ),
30851            (
30852                WorkflowCommandKind::Terminate,
30853                client
30854                    .terminate_workflow_run(
30855                        "wf-lifecycle",
30856                        "run-stale",
30857                        WorkflowCommandOptions::default(),
30858                    )
30859                    .await
30860                    .expect_err("stale termination must be rejected"),
30861            ),
30862        ] {
30863            let Error::WorkflowCommandRejected(rejection) = error else {
30864                panic!("expected typed command rejection");
30865            };
30866            assert_eq!(rejection.command, command);
30867            assert_eq!(rejection.status, 409);
30868            assert_eq!(rejection.reason, "historical_run_command_rejected");
30869            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
30870            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
30871        }
30872    }
30873
30874    #[tokio::test]
30875    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
30876        let server = MockWorkerServer::start();
30877        let client = Client::builder(server.base_url())
30878            .timeout(Duration::from_secs(2))
30879            .build()
30880            .expect("client");
30881
30882        let result = client
30883            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
30884            .await
30885            .expect("redrive accepted");
30886        assert_eq!(result.workflow_id, "wf-lifecycle");
30887        assert_eq!(result.source_run_id, "run-failed");
30888        assert_eq!(result.run_id, "run-successor");
30889        assert_eq!(result.resume_step_sequence, 2);
30890        assert_eq!(
30891            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
30892            json!({"request_id":"retry-1"})
30893        );
30894
30895        let repeated = client
30896            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
30897            .await
30898            .expect("idempotent redrive response accepted");
30899        assert_eq!(repeated.run_id, "run-successor");
30900
30901        let error = client
30902            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
30903            .await
30904            .expect_err("completed run must be rejected");
30905        let Error::Http { status, body } = error else {
30906            panic!("expected HTTP redrive rejection");
30907        };
30908        assert_eq!(status.as_u16(), 409);
30909        assert!(body.contains("run_not_failed"));
30910        assert_eq!(
30911            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
30912            json!({})
30913        );
30914
30915        let handle = WorkflowHandle {
30916            client: client.clone(),
30917            workflow_id: "wf-lifecycle".to_string(),
30918            run_id: Some("run-failed".to_string()),
30919            workflow_type: "test".to_string(),
30920        };
30921        assert_eq!(
30922            handle.redrive(None).await.expect("handle redrive").run_id,
30923            "run-successor"
30924        );
30925        let missing_run = WorkflowHandle {
30926            run_id: None,
30927            ..handle
30928        };
30929        assert!(matches!(
30930            missing_run.redrive(None).await,
30931            Err(Error::Codec(_))
30932        ));
30933    }
30934
30935    #[tokio::test]
30936    async fn workflow_start_options_send_server_enforced_deadlines() {
30937        let server = MockWorkerServer::start();
30938        let client = Client::builder(server.base_url())
30939            .timeout(Duration::from_secs(2))
30940            .build()
30941            .expect("client");
30942
30943        let handle = client
30944            .start_workflow_with_options(
30945                "rust.timeout",
30946                "rust-timeouts",
30947                "wf-start-options",
30948                WorkflowStartOptions::new()
30949                    .execution_timeout_seconds(30)
30950                    .run_timeout_seconds(1),
30951                json!([]),
30952            )
30953            .await
30954            .expect("workflow start");
30955
30956        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
30957        let body = server.request_body("/api/workflows");
30958        assert_eq!(body["execution_timeout_seconds"], 30);
30959        assert_eq!(body["run_timeout_seconds"], 1);
30960
30961        let invalid = client
30962            .start_workflow_with_options(
30963                "rust.timeout",
30964                "rust-timeouts",
30965                "wf-invalid-options",
30966                WorkflowStartOptions::new()
30967                    .execution_timeout_seconds(1)
30968                    .run_timeout_seconds(2),
30969                json!([]),
30970            )
30971            .await
30972            .expect_err("invalid deadline ordering");
30973        assert!(invalid
30974            .to_string()
30975            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
30976    }
30977
30978    async fn terminal_error(client: &Client, workflow_id: &str, run_id: Option<&str>) -> Error {
30979        WorkflowHandle {
30980            client: client.clone(),
30981            workflow_id: workflow_id.to_string(),
30982            run_id: run_id.map(str::to_string),
30983            workflow_type: "terminal".to_string(),
30984        }
30985        .result(WorkflowResultOptions {
30986            poll_interval: Duration::ZERO,
30987            timeout: Duration::from_secs(1),
30988        })
30989        .await
30990        .expect_err("terminal outcome")
30991    }
30992
30993    #[tokio::test]
30994    async fn workflow_result_fills_missing_terminal_detail_from_history() {
30995        let server = MockWorkerServer::start();
30996        let client = Client::builder(server.base_url())
30997            .timeout(Duration::from_secs(2))
30998            .build()
30999            .expect("client");
31000
31001        let Error::WorkflowFailed(failed) = terminal_error(&client, "wf-native-failed", None).await
31002        else {
31003            panic!("expected WorkflowFailed");
31004        };
31005        assert_eq!(failed.run_id.as_deref(), Some("run-native-failed"));
31006        assert_eq!(failed.reason, "failed");
31007        assert_eq!(failed.exception_type.as_deref(), Some("ActivityFailed"));
31008        assert_eq!(
31009            failed.exception_class.as_deref(),
31010            Some("durable_workflow::ActivityFailure")
31011        );
31012        assert_eq!(
31013            failed.message.as_deref(),
31014            Some("activity failed (activity): rejected bob")
31015        );
31016        assert_eq!(failed.non_retryable, Some(true));
31017        assert_eq!(failed.failure_category.as_deref(), Some("application"));
31018        assert_eq!(failed.failure_id.as_deref(), Some("failure-native"));
31019        assert_eq!(
31020            failed.exception.as_ref().and_then(|e| e.get("type")),
31021            Some(&json!("ActivityFailed"))
31022        );
31023
31024        // The same detail is filled for an explicitly selected run.
31025        let Error::WorkflowFailed(selected) =
31026            terminal_error(&client, "wf-native-failed", Some("run-native-failed")).await
31027        else {
31028            panic!("expected WorkflowFailed");
31029        };
31030        assert_eq!(selected.exception_type.as_deref(), Some("ActivityFailed"));
31031
31032        let Error::WorkflowTimedOut(timed_out) =
31033            terminal_error(&client, "wf-native-timed-out", None).await
31034        else {
31035            panic!("expected WorkflowTimedOut");
31036        };
31037        assert_eq!(timed_out.reason, "execution_timeout");
31038        assert_eq!(timed_out.failure_category.as_deref(), Some("timeout"));
31039        assert_eq!(
31040            timed_out.message.as_deref(),
31041            Some("Workflow execution deadline expired.")
31042        );
31043
31044        let Error::WorkflowFailed(paged) = terminal_error(&client, "wf-native-paged", None).await
31045        else {
31046            panic!("expected WorkflowFailed");
31047        };
31048        assert_eq!(paged.exception_type.as_deref(), Some("PagedFailure"));
31049        assert_eq!(paged.message.as_deref(), Some("found on page two"));
31050
31051        // An unavailable history keeps the describe-only outcome.
31052        let Error::WorkflowFailed(bare) =
31053            terminal_error(&client, "wf-native-no-history", None).await
31054        else {
31055            panic!("expected WorkflowFailed");
31056        };
31057        assert_eq!(bare.reason, "failed");
31058        assert_eq!(bare.exception_type, None);
31059        assert_eq!(bare.message, None);
31060        assert_eq!(
31061            server
31062                .method_for(
31063                    "/api/workflows/wf-native-no-history/runs/run-native-no-history/history"
31064                )
31065                .as_deref(),
31066            Some("GET")
31067        );
31068
31069        // A complete description, and a non-failure terminal state, never read history.
31070        let Error::WorkflowFailed(complete) =
31071            terminal_error(&client, "wf-failed", Some("run-failed")).await
31072        else {
31073            panic!("expected WorkflowFailed");
31074        };
31075        assert_eq!(complete.exception_type.as_deref(), Some("PaymentError"));
31076        assert!(matches!(
31077            terminal_error(&client, "wf-cancelled", None).await,
31078            Error::WorkflowCancelled(_)
31079        ));
31080        assert!(matches!(
31081            terminal_error(&client, "wf-timed-out", None).await,
31082            Error::WorkflowTimedOut(_)
31083        ));
31084        for path in [
31085            "/api/workflows/wf-failed/runs/run-failed/history",
31086            "/api/workflows/wf-cancelled/runs/run-cancelled/history",
31087            "/api/workflows/wf-timed-out/runs/run-timed-out/history",
31088        ] {
31089            assert_eq!(server.method_for(path), None, "{path} must not be read");
31090        }
31091    }
31092
31093    #[tokio::test]
31094    async fn workflow_result_returns_each_typed_terminal_outcome() {
31095        let server = MockWorkerServer::start();
31096        let client = Client::builder(server.base_url())
31097            .timeout(Duration::from_secs(2))
31098            .build()
31099            .expect("client");
31100        let options = WorkflowResultOptions {
31101            poll_interval: Duration::ZERO,
31102            timeout: Duration::from_secs(1),
31103        };
31104
31105        let failed = WorkflowHandle {
31106            client: client.clone(),
31107            workflow_id: "wf-failed".to_string(),
31108            run_id: Some("run-failed".to_string()),
31109            workflow_type: "failure".to_string(),
31110        }
31111        .result(options)
31112        .await
31113        .expect_err("failed outcome");
31114        let Error::WorkflowFailed(failure) = failed else {
31115            panic!("expected WorkflowFailed");
31116        };
31117        assert_eq!(failure.workflow_id, "wf-failed");
31118        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
31119        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
31120        assert_eq!(failure.failure_category.as_deref(), Some("application"));
31121        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
31122        assert_eq!(
31123            failure.exception_class.as_deref(),
31124            Some("billing::PaymentError")
31125        );
31126        assert_eq!(failure.non_retryable, Some(true));
31127
31128        for (workflow_id, expected_kind, expected_reason) in [
31129            (
31130                "wf-cancelled",
31131                WorkflowTerminalKind::Cancelled,
31132                "cleanup requested",
31133            ),
31134            (
31135                "wf-terminated",
31136                WorkflowTerminalKind::Terminated,
31137                "forced stop",
31138            ),
31139            (
31140                "wf-timed-out",
31141                WorkflowTerminalKind::TimedOut,
31142                "run_timeout",
31143            ),
31144        ] {
31145            let error = WorkflowHandle {
31146                client: client.clone(),
31147                workflow_id: workflow_id.to_string(),
31148                run_id: None,
31149                workflow_type: "terminal".to_string(),
31150            }
31151            .result(options)
31152            .await
31153            .expect_err("typed terminal outcome");
31154            let outcome = match error {
31155                Error::WorkflowCancelled(outcome) => outcome,
31156                Error::WorkflowTerminated(outcome) => outcome,
31157                Error::WorkflowTimedOut(outcome) => outcome,
31158                other => panic!("unexpected terminal error: {other}"),
31159            };
31160            assert_eq!(outcome.kind, expected_kind);
31161            assert_eq!(outcome.workflow_id, workflow_id);
31162            assert_eq!(outcome.reason, expected_reason);
31163        }
31164
31165        let wait_timeout = WorkflowHandle {
31166            client,
31167            workflow_id: "wf-waiting".to_string(),
31168            run_id: Some("run-waiting".to_string()),
31169            workflow_type: "waiting".to_string(),
31170        }
31171        .result(WorkflowResultOptions {
31172            poll_interval: Duration::ZERO,
31173            timeout: Duration::ZERO,
31174        })
31175        .await
31176        .expect_err("client wait timeout");
31177        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
31178            panic!("expected typed client timeout");
31179        };
31180        assert_eq!(timeout.reason, "result_wait_timeout");
31181        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
31182        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
31183    }
31184
31185    #[tokio::test]
31186    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
31187        let server = MockWorkerServer::start();
31188        let client = Client::builder(server.base_url())
31189            .timeout(Duration::from_secs(2))
31190            .build()
31191            .expect("client");
31192
31193        let handle = WorkflowHandle {
31194            client,
31195            workflow_id: "wf-selected".to_string(),
31196            run_id: Some("run-selected".to_string()),
31197            workflow_type: "selected".to_string(),
31198        };
31199        let options = WorkflowResultOptions {
31200            poll_interval: Duration::ZERO,
31201            timeout: Duration::from_secs(1),
31202        };
31203
31204        let current = handle
31205            .result(options)
31206            .await
31207            .expect("instance result follows the current run");
31208        assert_eq!(current, json!("current run output"));
31209
31210        let error = handle
31211            .result_selected_run(options)
31212            .await
31213            .expect_err("the selected run is cancelled even though the current run completed");
31214
31215        let Error::WorkflowCancelled(outcome) = error else {
31216            panic!("expected selected run cancellation");
31217        };
31218        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
31219        assert_eq!(outcome.reason, "selected run cancelled");
31220        assert_eq!(
31221            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
31222            1
31223        );
31224        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
31225    }
31226
31227    #[tokio::test]
31228    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
31229        let server = MockWorkerServer::draining_polls();
31230        let client = Client::builder(server.base_url())
31231            .timeout(Duration::from_secs(2))
31232            .build()
31233            .expect("client");
31234
31235        let workflow = client
31236            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
31237            .await
31238            .expect("workflow drain response");
31239        let activity = client
31240            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
31241            .await
31242            .expect("activity drain response");
31243        let query = client
31244            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
31245            .await
31246            .expect("query drain response");
31247
31248        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
31249            assert_eq!(
31250                outcome,
31251                WorkerPollOutcome::Stop {
31252                    poll_status: Some("draining".to_string()),
31253                    reason: Some("worker_draining".to_string()),
31254                }
31255            );
31256        }
31257
31258        assert!(client
31259            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
31260            .await
31261            .expect("compatibility poll")
31262            .is_none());
31263    }
31264
31265    #[tokio::test]
31266    async fn managed_worker_honors_drain_stop_for_every_task_family() {
31267        let server = MockWorkerServer::draining_polls();
31268        let client = Client::builder(server.base_url())
31269            .timeout(Duration::from_secs(2))
31270            .build()
31271            .expect("client");
31272
31273        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
31274            .worker_id("draining-workflow-worker")
31275            .poll_timeout(Duration::ZERO);
31276        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
31277        workflow_worker
31278            .run()
31279            .await
31280            .expect("workflow drain is a clean stop");
31281
31282        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
31283            .worker_id("draining-activity-worker")
31284            .poll_timeout(Duration::ZERO);
31285        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
31286        activity_worker
31287            .run()
31288            .await
31289            .expect("activity drain is a clean stop");
31290
31291        let mut query_worker = Worker::new(client, "rust-workers")
31292            .worker_id("draining-query-worker")
31293            .poll_timeout(Duration::ZERO);
31294        query_worker.register_query("counter", "current", |_ctx, _args| async {
31295            Ok(Value::Null)
31296        });
31297        query_worker
31298            .run()
31299            .await
31300            .expect("query drain is a clean stop");
31301    }
31302
31303    #[tokio::test]
31304    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
31305        let server = MockWorkerServer::start();
31306        let client = Client::builder(server.base_url())
31307            .timeout(Duration::from_secs(2))
31308            .build()
31309            .expect("client");
31310
31311        let details: Value = serde_json::from_str(include_str!(
31312            "../tests/fixtures/activity-heartbeat-progress.json"
31313        ))
31314        .expect("heartbeat progress fixture");
31315        // Every individual field fits Server's progress contract, while the
31316        // obsolete encoded envelope exceeded its 191-character string limit.
31317        assert!(
31318            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
31319                .unwrap()["blob"]
31320                .as_str()
31321                .unwrap()
31322                .len()
31323                > 191
31324        );
31325        let heartbeat = client
31326            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
31327            .await
31328            .expect("cancellation heartbeat");
31329        assert!(heartbeat.cancel_requested);
31330        assert!(heartbeat.should_stop());
31331        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
31332        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
31333        let heartbeat_body =
31334            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
31335        assert_eq!(heartbeat_body["details"], details);
31336        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
31337        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
31338
31339        let error = client
31340            .complete_activity_task(
31341                "activity-cancel",
31342                "attempt-cancel",
31343                "rust-worker",
31344                json!({"late":true}),
31345                DEFAULT_CODEC,
31346            )
31347            .await
31348            .expect_err("late completion must be refused");
31349        assert!(activity_task_rejection_is_final(&error));
31350        let Error::ActivityTaskRejected(rejection) = error else {
31351            panic!("expected typed activity rejection");
31352        };
31353        assert_eq!(rejection.status, 409);
31354        assert_eq!(rejection.reason, "run_cancelled");
31355        assert!(rejection.cancel_requested);
31356        assert_eq!(rejection.can_continue, Some(false));
31357    }
31358
31359    #[tokio::test]
31360    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
31361        let server = MockWorkerServer::cancelled_activity();
31362        let client = Client::builder(server.base_url())
31363            .timeout(Duration::from_secs(2))
31364            .build()
31365            .expect("client");
31366        let cancellation_observed = Arc::new(AtomicBool::new(false));
31367        let observed = Arc::clone(&cancellation_observed);
31368        let mut worker = Worker::new(client.clone(), "rust-workers")
31369            .worker_id("rust-cancel-worker")
31370            .poll_timeout(Duration::from_millis(10));
31371        worker.register_activity("cancel-aware", move |ctx, _args| {
31372            let observed = Arc::clone(&observed);
31373            async move {
31374                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
31375                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
31376                Ok(json!({"late":"completion"}))
31377            }
31378        });
31379
31380        assert_eq!(
31381            worker.run_once().await.expect("cancelled attempt handled"),
31382            1
31383        );
31384        assert!(cancellation_observed.load(Ordering::SeqCst));
31385        assert_eq!(
31386            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
31387            1
31388        );
31389
31390        let mut restarted = Worker::new(client, "rust-workers")
31391            .worker_id("rust-cancel-worker-restarted")
31392            .poll_timeout(Duration::from_millis(10));
31393        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
31394        assert_eq!(
31395            restarted
31396                .run_once()
31397                .await
31398                .expect("replacement worker continues polling"),
31399            0
31400        );
31401    }
31402
31403    #[tokio::test]
31404    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
31405        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"}"#;
31406        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
31407        let client = Client::builder(server.base_url())
31408            .timeout(Duration::from_secs(2))
31409            .build()
31410            .expect("client");
31411
31412        let direct_error = client
31413            .complete_workflow_task(
31414                "workflow-timeout-task",
31415                "timeout-worker",
31416                3,
31417                vec![json!({
31418                    "type": "complete_workflow",
31419                    "result": fixture_envelope(Value::Null)
31420                })],
31421            )
31422            .await
31423            .expect_err("the low-level client preserves the completion rejection");
31424        let Error::Http { status, body } = direct_error else {
31425            panic!("expected the original HTTP completion rejection");
31426        };
31427        assert_eq!(status, reqwest::StatusCode::CONFLICT);
31428        assert_eq!(
31429            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
31430            "run_timed_out"
31431        );
31432
31433        let mut worker = Worker::new(client, "rust-workers")
31434            .worker_id("timeout-worker")
31435            .poll_timeout(Duration::from_millis(10));
31436        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
31437            Ok(json!({"late": "result"}))
31438        });
31439
31440        assert_eq!(
31441            worker
31442                .run_once()
31443                .await
31444                .expect("authoritative selected-run timeout settles the tick"),
31445            1
31446        );
31447        assert_eq!(
31448            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
31449            2,
31450            "both the direct client proof and managed worker must see the rejection"
31451        );
31452    }
31453
31454    #[tokio::test]
31455    async fn managed_worker_absorbs_selected_run_terminal_timeout_failure_races() {
31456        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"}"#;
31457        for (surface, decision) in workflow_timeout_failure_decisions() {
31458            let server = MockWorkerServer::workflow_completion("409 Conflict", response);
31459            let client = Client::builder(server.base_url())
31460                .timeout(Duration::from_secs(2))
31461                .build()
31462                .expect("client");
31463            let error = client
31464                .fail_workflow_task(
31465                    "workflow-timeout-task",
31466                    "timeout-worker",
31467                    3,
31468                    "fixture failure",
31469                )
31470                .await
31471                .expect_err("low-level failure reporting preserves the HTTP refusal");
31472            assert!(
31473                matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT)
31474            );
31475
31476            let worker = Worker::new(client, "rust-workers");
31477            assert_eq!(
31478                worker
31479                    .settle_workflow_task_decision(
31480                        "workflow-timeout-task",
31481                        "timeout-worker",
31482                        3,
31483                        Some("run-selected-timeout"),
31484                        decision,
31485                        false,
31486                        None,
31487                    )
31488                    .await
31489                    .expect(surface),
31490                ManagedPollOutcome::Handled,
31491            );
31492            assert_eq!(
31493                server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/fail"),
31494                2
31495            );
31496        }
31497    }
31498
31499    fn workflow_timeout_failure_decisions() -> [(&'static str, Result<WorkflowTaskDecision>); 4] {
31500        [
31501            (
31502                "history wait",
31503                Ok(WorkflowTaskDecision::without_message_streams(vec![])),
31504            ),
31505            (
31506                "unsupported memo",
31507                Ok(WorkflowTaskDecision::without_message_streams(vec![
31508                    json!({"type":"upsert_memo"}),
31509                ])),
31510            ),
31511            (
31512                "ordinary failure",
31513                Err(Error::WorkerLoop("fixture failure".into())),
31514            ),
31515            (
31516                "entry argument mismatch",
31517                Err(handler_type_error::<bool>(
31518                    HandlerKind::Workflow,
31519                    "timeout.workflow",
31520                    HandlerValueKind::Input,
31521                    "fixture mismatch",
31522                )),
31523            ),
31524        ]
31525    }
31526
31527    #[tokio::test]
31528    async fn managed_worker_preserves_nonmatching_timeout_failure_refusals() {
31529        let valid = json!({"task_id":"workflow-timeout-task","workflow_task_attempt":3,
31530            "outcome":"completed","recorded":false,"run_id":"run-selected-timeout",
31531            "run_status":"failed","created_task_ids":[],"reason":"run_timed_out"});
31532        let mut cases = vec![
31533            ("malformed JSON", "409 Conflict", "{broken".to_owned()),
31534            ("wrong status", "403 Forbidden", valid.to_string()),
31535            (
31536                "authentication failure",
31537                "401 Unauthorized",
31538                valid.to_string(),
31539            ),
31540            (
31541                "validation failure",
31542                "422 Unprocessable Entity",
31543                valid.to_string(),
31544            ),
31545            (
31546                "server failure",
31547                "503 Service Unavailable",
31548                valid.to_string(),
31549            ),
31550        ];
31551        for (field, value) in [
31552            ("task_id", json!("another-task")),
31553            ("workflow_task_attempt", json!(4)),
31554            ("run_id", json!("another-run")),
31555            ("run_status", json!("waiting")),
31556            ("recorded", json!(true)),
31557            ("reason", json!("lease_expired")),
31558            ("run_id", Value::Null),
31559            ("workflow_task_attempt", Value::Null),
31560        ] {
31561            let mut body = valid.clone();
31562            body[field] = value;
31563            cases.push((field, "409 Conflict", body.to_string()));
31564        }
31565        for (name, status, response) in cases {
31566            // The mock response callback has a static lifetime, so retain each
31567            // bounded response for the duration of this test process.
31568            let response = Box::leak(response.into_boxed_str());
31569            for (surface, decision) in workflow_timeout_failure_decisions() {
31570                let server = MockWorkerServer::workflow_completion(status, response);
31571                let client = Client::builder(server.base_url())
31572                    .timeout(Duration::from_secs(2))
31573                    .build()
31574                    .expect("client");
31575                let worker = Worker::new(client, "rust-workers");
31576                let error = worker
31577                    .settle_workflow_task_decision(
31578                        "workflow-timeout-task",
31579                        "timeout-worker",
31580                        3,
31581                        Some("run-selected-timeout"),
31582                        decision,
31583                        false,
31584                        None,
31585                    )
31586                    .await
31587                    .expect_err(&format!("{surface}: {name} must remain an error"));
31588                assert!(
31589                    matches!(error, Error::Http { .. }),
31590                    "{surface}: {name}: {error}"
31591                );
31592            }
31593        }
31594    }
31595
31596    // durable-workflow/.github#228: native Server 3.6.0 refuses a completion
31597    // over its aggregate limit with a typed 413.
31598    fn completion_size_refusal(
31599        path: &str,
31600        _body: &str,
31601        request: usize,
31602    ) -> Option<(&'static str, String)> {
31603        let typed = json!({"message":"Workflow task completion exceeds the maximum allowed size of 33554432 bytes. Each command's arguments may be up to 2097152 bytes; offload larger payloads or split the work across workflow tasks.",
31604            "reason":"payload_too_large","limit":33_554_432,"limit_kind":"workflow_task_completion_bytes",
31605            "protocol_version":"1.20","server_capabilities":{}});
31606        let recorded = json!({"outcome":"completed","recorded":true}).to_string();
31607        match (path, request) {
31608            ("/api/worker/workflow-tasks/typed-413/complete", 1)
31609            | ("/api/worker/workflow-tasks/typed-413-unrecorded/complete", 1) => {
31610                Some(("413 Payload Too Large", typed.to_string()))
31611            }
31612            ("/api/worker/workflow-tasks/typed-413/complete", _) => Some(("200 OK", recorded)),
31613            ("/api/worker/workflow-tasks/typed-413-unrecorded/complete", _) => Some((
31614                "500 Internal Server Error",
31615                json!({"message":"fixture"}).to_string(),
31616            )),
31617            ("/api/worker/workflow-tasks/plain-413/complete", _) => Some((
31618                "413 Payload Too Large",
31619                json!({"message":"Request payload exceeds the maximum allowed size of 2097152 bytes.",
31620                    "reason":"payload_too_large","limit":2_097_152}).to_string(),
31621            )),
31622            ("/api/worker/workflow-tasks/other-kind-413/complete", _) => {
31623                let mut other = typed.clone();
31624                other["limit_kind"] = json!("payload_size_bytes");
31625                Some(("413 Payload Too Large", other.to_string()))
31626            }
31627            ("/api/worker/workflow-tasks/server-503/complete", _) => Some((
31628                "503 Service Unavailable",
31629                json!({"message":"fixture"}).to_string(),
31630            )),
31631            _ => None,
31632        }
31633    }
31634
31635    fn fan_out_commands() -> Vec<Value> {
31636        (0..10)
31637            .map(|index| {
31638                json!({"type":"schedule_activity","activity_type":"fan.out",
31639                    "arguments":fixture_envelope(json!([index, "x".repeat(1024)]))})
31640            })
31641            .collect()
31642    }
31643
31644    fn completion_size_worker() -> (MockWorkerServer, Worker) {
31645        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31646            request_override: Some(completion_size_refusal),
31647            ..MockWorkerBehavior::default()
31648        });
31649        let client = Client::builder(server.base_url())
31650            .timeout(Duration::from_secs(2))
31651            .build()
31652            .expect("client");
31653        (server, Worker::new(client, "rust-workers"))
31654    }
31655
31656    #[tokio::test]
31657    async fn typed_completion_size_refusal_is_a_typed_error_and_is_not_resent() {
31658        let (server, worker) = completion_size_worker();
31659        let error = worker
31660            .client
31661            .complete_workflow_task("typed-413", "fan-worker", 2, fan_out_commands())
31662            .await
31663            .expect_err("the typed 413 is an error");
31664        let path = "/api/worker/workflow-tasks/typed-413/complete";
31665        let sent = server.request_bodies(path);
31666        assert_eq!(sent.len(), 1, "the oversized completion is sent once");
31667        let Error::WorkflowTaskCompletionTooLarge(refusal) = &error else {
31668            panic!("expected a typed completion size refusal, got {error:?}");
31669        };
31670        assert_eq!(refusal.status, 413);
31671        assert_eq!(refusal.limit_kind, "workflow_task_completion_bytes");
31672        assert_eq!(refusal.limit, Some(33_554_432));
31673        assert_eq!(refusal.size, sent[0].to_string().len() as u64);
31674        assert!(refusal
31675            .message
31676            .starts_with("Workflow task completion exceeds"));
31677        let text = error.to_string();
31678        assert!(
31679            text.starts_with("Structural limit exceeded: workflow_task_completion_bytes:"),
31680            "{text}"
31681        );
31682        assert!(
31683            text.contains(&format!("is {} bytes", refusal.size)),
31684            "{text}"
31685        );
31686        assert!(text.contains("server limit of 33554432 bytes"), "{text}");
31687        assert!(text.contains("child workflows"), "{text}");
31688        assert!(!worker_operation_is_retryable(&error));
31689    }
31690
31691    #[tokio::test]
31692    async fn managed_worker_fails_the_run_once_on_a_typed_completion_size_refusal() {
31693        let (server, worker) = completion_size_worker();
31694        let outcome = worker
31695            .settle_workflow_task_decision(
31696                "typed-413",
31697                "fan-worker",
31698                2,
31699                Some("fan-run"),
31700                Ok(WorkflowTaskDecision::without_message_streams(
31701                    fan_out_commands(),
31702                )),
31703                false,
31704                None,
31705            )
31706            .await
31707            .expect("the structural-limit failure settles the task");
31708        assert!(matches!(outcome, ManagedPollOutcome::Handled));
31709        let sent = server.request_bodies("/api/worker/workflow-tasks/typed-413/complete");
31710        assert_eq!(sent.len(), 2, "one oversized completion, then one failure");
31711        assert_eq!(sent[0]["commands"].as_array().unwrap().len(), 10);
31712        let size = sent[0].to_string().len();
31713        assert_eq!(sent[1]["lease_owner"], "fan-worker");
31714        assert_eq!(sent[1]["workflow_task_attempt"], 2);
31715        let commands = sent[1]["commands"].as_array().unwrap();
31716        assert_eq!(commands.len(), 1, "the oversized commands are not resent");
31717        let failure = &commands[0];
31718        assert_eq!(failure["type"], "fail_workflow");
31719        assert_eq!(failure["non_retryable"], true);
31720        assert_eq!(failure["exception_type"], "StructuralLimitExceeded");
31721        let message = failure["message"].as_str().unwrap();
31722        assert!(
31723            message.starts_with("Structural limit exceeded: workflow_task_completion_bytes:"),
31724            "{message}"
31725        );
31726        assert!(message.contains(&format!("is {size} bytes")), "{message}");
31727        assert!(message.contains("33554432 bytes"), "{message}");
31728        let properties = &failure["exception"]["properties"];
31729        assert_eq!(
31730            properties["structural_limit_kind"],
31731            "workflow_task_completion_bytes"
31732        );
31733        assert_eq!(properties["structural_limit_value"], size);
31734        assert_eq!(properties["structural_limit_configured"], 33_554_432);
31735        // The Server's free-text message is not recorded with the failure.
31736        assert!(properties.get("server_message").is_none(), "{properties}");
31737        assert_eq!(
31738            server.request_count("/api/worker/workflow-tasks/typed-413/fail"),
31739            0,
31740            "a failed task would be retried into the same refusal"
31741        );
31742    }
31743
31744    #[tokio::test]
31745    async fn managed_worker_keeps_the_typed_refusal_when_the_failure_is_not_recorded() {
31746        let (server, worker) = completion_size_worker();
31747        let error = worker
31748            .settle_workflow_task_decision(
31749                "typed-413-unrecorded",
31750                "fan-worker",
31751                2,
31752                Some("fan-run"),
31753                Ok(WorkflowTaskDecision::without_message_streams(
31754                    fan_out_commands(),
31755                )),
31756                false,
31757                None,
31758            )
31759            .await
31760            .expect_err("an unrecorded failure stays an error");
31761        assert!(
31762            matches!(error, Error::WorkflowTaskCompletionTooLarge(_)),
31763            "{error:?}"
31764        );
31765        let sent =
31766            server.request_bodies("/api/worker/workflow-tasks/typed-413-unrecorded/complete");
31767        assert_eq!(sent.len(), 2, "no resend and no retry loop");
31768        assert_eq!(sent[1]["commands"][0]["type"], "fail_workflow");
31769    }
31770
31771    #[tokio::test]
31772    async fn managed_worker_leaves_other_413_and_5xx_completion_refusals_unchanged() {
31773        for (task, status) in [
31774            ("plain-413", reqwest::StatusCode::PAYLOAD_TOO_LARGE),
31775            ("other-kind-413", reqwest::StatusCode::PAYLOAD_TOO_LARGE),
31776            ("server-503", reqwest::StatusCode::SERVICE_UNAVAILABLE),
31777        ] {
31778            let (server, worker) = completion_size_worker();
31779            let error = worker
31780                .settle_workflow_task_decision(
31781                    task,
31782                    "fan-worker",
31783                    2,
31784                    Some("fan-run"),
31785                    Ok(WorkflowTaskDecision::without_message_streams(
31786                        fan_out_commands(),
31787                    )),
31788                    false,
31789                    None,
31790                )
31791                .await
31792                .expect_err("the refusal remains an error");
31793            assert!(
31794                matches!(&error, Error::Http { status: observed, .. } if *observed == status),
31795                "{task}: {error:?}"
31796            );
31797            let sent =
31798                server.request_bodies(&format!("/api/worker/workflow-tasks/{task}/complete"));
31799            assert_eq!(sent.len(), 1, "{task}");
31800            assert_eq!(sent[0]["commands"].as_array().unwrap().len(), 10, "{task}");
31801        }
31802    }
31803
31804    #[tokio::test]
31805    async fn managed_worker_polls_unrelated_work_after_history_wait_timeout() {
31806        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31807            request_override: Some(history_wait_timeout_then_unrelated_work),
31808            ..MockWorkerBehavior::default()
31809        });
31810        let client = Client::builder(server.base_url())
31811            .timeout(Duration::from_secs(2))
31812            .build()
31813            .expect("client");
31814        let executed = Arc::new(AtomicBool::new(false));
31815        let observed = Arc::clone(&executed);
31816        let mut worker = Worker::new(client, "rust-workers")
31817            .worker_id("timeout-worker")
31818            .poll_timeout(Duration::from_millis(10));
31819        worker.register_workflow("timeout.workflow", |ctx, _input| async move {
31820            ctx.sleep(Duration::from_secs(5)).await?;
31821            Ok(Value::Null)
31822        });
31823        worker.register_workflow("unrelated.workflow", move |_ctx, _input| {
31824            let observed = Arc::clone(&observed);
31825            async move {
31826                observed.store(true, Ordering::SeqCst);
31827                Ok(Value::Null)
31828            }
31829        });
31830        assert_eq!(
31831            worker
31832                .run_once()
31833                .await
31834                .expect("terminal history-wait timeout settles the tick"),
31835            1
31836        );
31837        assert_eq!(
31838            worker
31839                .run_once()
31840                .await
31841                .expect("same worker processes an unrelated workflow"),
31842            1
31843        );
31844        assert!(executed.load(Ordering::SeqCst));
31845        assert_eq!(
31846            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/fail"),
31847            1
31848        );
31849        assert_eq!(
31850            server.request_count("/api/worker/workflow-tasks/unrelated-task/complete"),
31851            1
31852        );
31853    }
31854
31855    fn history_wait_timeout_then_unrelated_work(
31856        path: &str,
31857        _body: &str,
31858        request: usize,
31859    ) -> Option<(&'static str, String)> {
31860        if path == "/api/worker/workflow-tasks/poll" && request <= 2 {
31861            let waiting = request == 1;
31862            let task = json!({"task_id":if waiting {"workflow-timeout-task"} else {"unrelated-task"},
31863                "workflow_id":if waiting {"reused-workflow-id"} else {"unrelated-workflow"},
31864                "run_id":if waiting {"run-selected-timeout"} else {"unrelated-run"},
31865                "workflow_type":if waiting {"timeout.workflow"} else {"unrelated.workflow"},
31866                "payload_codec":"avro","arguments":fixture_envelope(json!([])),
31867                "history_events":if waiting {vec![json!({"event_type":"TimerScheduled","payload":{"sequence":1,"timer_id":"timer-1","delay_seconds":5}})]} else {vec![]},
31868                "workflow_task_attempt":3,"lease_owner":"timeout-worker"});
31869            return Some(("200 OK", json!({"task":task}).to_string()));
31870        }
31871        match path {
31872            "/api/worker/workflow-tasks/workflow-timeout-task/fail" => Some(("409 Conflict",
31873                json!({"task_id":"workflow-timeout-task","workflow_task_attempt":3,"outcome":"completed",
31874                    "recorded":false,"run_id":"run-selected-timeout","run_status":"failed",
31875                    "created_task_ids":[],"reason":"run_timed_out"}).to_string())),
31876            "/api/worker/workflow-tasks/unrelated-task/complete" => Some(("200 OK", json!({"outcome":"completed","recorded":true}).to_string())),
31877            _ => None,
31878        }
31879    }
31880
31881    #[tokio::test]
31882    async fn managed_worker_settles_matching_task_not_leased_receipt_and_keeps_polling() {
31883        // Published PHP Server 2.11.8 answered a completion after cancellation
31884        // with this receipt; the 4.10.2 managed worker exited on it (#157).
31885        let response = r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"outcome":"completed","recorded":false,"run_id":"run-selected-timeout","run_status":null,"created_task_ids":[],"reason":"task_not_leased"}"#;
31886        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
31887        let client = Client::builder(server.base_url())
31888            .timeout(Duration::from_secs(2))
31889            .build()
31890            .expect("client");
31891
31892        let direct_error = client
31893            .complete_workflow_task(
31894                "workflow-timeout-task",
31895                "timeout-worker",
31896                3,
31897                vec![json!({"type": "complete_workflow", "result": fixture_envelope(Value::Null)})],
31898            )
31899            .await
31900            .expect_err("the low-level client preserves the completion rejection");
31901        assert!(
31902            matches!(direct_error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT)
31903        );
31904
31905        let mut worker = Worker::new(client, "rust-workers")
31906            .worker_id("timeout-worker")
31907            .poll_timeout(Duration::from_millis(10));
31908        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
31909            Ok(json!({"late": "result"}))
31910        });
31911        assert_eq!(
31912            worker
31913                .run_once()
31914                .await
31915                .expect("a matching task_not_leased receipt settles the tick"),
31916            1
31917        );
31918        assert_eq!(
31919            worker
31920                .run_once()
31921                .await
31922                .expect("the managed worker keeps polling"),
31923            0
31924        );
31925    }
31926
31927    #[tokio::test]
31928    async fn managed_worker_keeps_nearby_task_not_leased_conflicts_as_errors() {
31929        for (name, response) in [
31930            (
31931                "recorded",
31932                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","reason":"task_not_leased"}"#,
31933            ),
31934            (
31935                "recorded missing",
31936                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"run_id":"run-selected-timeout","reason":"task_not_leased"}"#,
31937            ),
31938            (
31939                "different task",
31940                r#"{"task_id":"other-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","reason":"task_not_leased"}"#,
31941            ),
31942            (
31943                "different attempt",
31944                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","reason":"task_not_leased"}"#,
31945            ),
31946            (
31947                "different run",
31948                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-other","reason":"task_not_leased"}"#,
31949            ),
31950            (
31951                "other reason",
31952                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","reason":"lease_owner_mismatch"}"#,
31953            ),
31954        ] {
31955            let server = MockWorkerServer::workflow_completion("409 Conflict", response);
31956            let client = Client::builder(server.base_url())
31957                .timeout(Duration::from_secs(2))
31958                .build()
31959                .expect("client");
31960            let mut worker = Worker::new(client, "rust-workers")
31961                .worker_id("timeout-worker")
31962                .poll_timeout(Duration::from_millis(10));
31963            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
31964                Ok(json!({"late": "result"}))
31965            });
31966            let error = worker
31967                .run_once()
31968                .await
31969                .expect_err(&format!("{name} must remain an error"));
31970            assert!(
31971                matches!(error, Error::Http { .. }),
31972                "{name}: unexpected error {error}"
31973            );
31974        }
31975    }
31976
31977    /// Native Server's full not-recorded `run_closed` receipt (server#994) for
31978    /// the mock's selected task, after the run closed by another path. The
31979    /// guard's body and the receipt fields follow Server PR #999; the
31980    /// capability manifest is elided.
31981    fn run_closed_receipt(close: &str) -> Value {
31982        let (run_status, stop_reason, closed_reason, task_status, cancel_requested) = match close {
31983            "completed" => (
31984                "completed",
31985                "run_completed",
31986                "completed",
31987                "completed",
31988                false,
31989            ),
31990            "failed" => ("failed", "run_failed", "failed", "failed", false),
31991            "timed_out" => ("failed", "run_failed", "timed_out", "completed", false),
31992            "cancelled" => ("cancelled", "run_cancelled", "cancelled", "cancelled", true),
31993            "terminated" => (
31994                "terminated",
31995                "run_terminated",
31996                "terminated",
31997                "cancelled",
31998                true,
31999            ),
32000            other => panic!("unknown close {other}"),
32001        };
32002        json!({"task_id":"workflow-timeout-task","workflow_task_attempt":3,
32003            "error":"Workflow run is already closed.","reason":"run_closed","protocol_version":"1.20",
32004            "server_capabilities":{},"stop_reason":stop_reason,"cancel_requested":cancel_requested,
32005            "can_continue":false,"run_status":run_status,"run_closed_reason":closed_reason,
32006            "run_closed_at":"2026-11-03T12:00:00.000000Z","task_status":task_status,
32007            "lease_owner":"timeout-worker","lease_expires_at":null,
32008            "recorded":false,"run_id":"run-selected-timeout"})
32009    }
32010
32011    /// Every request except task polls and the read-only capability probe:
32012    /// the reports and any retry, lease or other state-changing call.
32013    fn state_requests(server: &MockWorkerServer) -> Vec<String> {
32014        server
32015            .captured_paths()
32016            .into_iter()
32017            .filter(|path| !path.ends_with("/poll") && path != "/api/cluster/info")
32018            .collect()
32019    }
32020
32021    const RUN_CLOSED_CLOSES: [&str; 5] = [
32022        "completed",
32023        "failed",
32024        "timed_out",
32025        "cancelled",
32026        "terminated",
32027    ];
32028
32029    fn assert_original_http_error(
32030        error: Error,
32031        status: reqwest::StatusCode,
32032        response: &str,
32033        context: &str,
32034    ) {
32035        let Error::Http {
32036            status: actual,
32037            body,
32038        } = error
32039        else {
32040            panic!("{context}: expected the original HTTP error, got {error}");
32041        };
32042        assert_eq!(actual, status, "{context}");
32043        assert_eq!(body, response, "{context}: the response body is unchanged");
32044    }
32045
32046    #[tokio::test]
32047    async fn managed_worker_settles_exact_run_closed_receipts_without_advancing_state() {
32048        let complete = "/api/worker/workflow-tasks/workflow-timeout-task/complete";
32049        let fail = "/api/worker/workflow-tasks/workflow-timeout-task/fail";
32050        for close in RUN_CLOSED_CLOSES {
32051            let response: &'static str =
32052                Box::leak(run_closed_receipt(close).to_string().into_boxed_str());
32053
32054            // Direct client calls keep the original HTTP error.
32055            let server = MockWorkerServer::workflow_completion("409 Conflict", response);
32056            let client = Client::builder(server.base_url())
32057                .timeout(Duration::from_secs(2))
32058                .build()
32059                .expect("client");
32060            let error = client
32061                .complete_workflow_task(
32062                    "workflow-timeout-task",
32063                    "timeout-worker",
32064                    3,
32065                    vec![json!({"type": "complete_workflow", "result": fixture_envelope(Value::Null)})],
32066                )
32067                .await
32068                .expect_err("the low-level client preserves the completion refusal");
32069            assert_original_http_error(error, reqwest::StatusCode::CONFLICT, response, close);
32070            let error = client
32071                .fail_workflow_task(
32072                    "workflow-timeout-task",
32073                    "timeout-worker",
32074                    3,
32075                    "fixture failure",
32076                )
32077                .await
32078                .expect_err("the low-level client preserves the failure refusal");
32079            assert_original_http_error(error, reqwest::StatusCode::CONFLICT, response, close);
32080
32081            // The managed completion settles with exactly one report and no
32082            // further request for the task: no retry, failure report, lease
32083            // renewal or other state change.
32084            let server = MockWorkerServer::workflow_completion("409 Conflict", response);
32085            let client = Client::builder(server.base_url())
32086                .timeout(Duration::from_secs(2))
32087                .build()
32088                .expect("client");
32089            let mut worker = Worker::new(client, "rust-workers")
32090                .worker_id("timeout-worker")
32091                .poll_timeout(Duration::from_millis(10));
32092            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
32093                Ok(json!({"late": "result"}))
32094            });
32095            assert_eq!(
32096                worker.run_once().await.unwrap_or_else(|error| panic!(
32097                    "{close}: an exact run_closed receipt settles the tick: {error}"
32098                )),
32099                1
32100            );
32101            assert_eq!(
32102                state_requests(&server),
32103                vec![complete.to_owned()],
32104                "{close}"
32105            );
32106
32107            // Every managed failure report settles the same way.
32108            for (surface, decision) in workflow_timeout_failure_decisions() {
32109                let server = MockWorkerServer::workflow_completion("409 Conflict", response);
32110                let client = Client::builder(server.base_url())
32111                    .timeout(Duration::from_secs(2))
32112                    .build()
32113                    .expect("client");
32114                let worker = Worker::new(client, "rust-workers");
32115                assert_eq!(
32116                    worker
32117                        .settle_workflow_task_decision(
32118                            "workflow-timeout-task",
32119                            "timeout-worker",
32120                            3,
32121                            Some("run-selected-timeout"),
32122                            decision,
32123                            false,
32124                            None,
32125                        )
32126                        .await
32127                        .unwrap_or_else(|error| panic!("{close} {surface}: {error}")),
32128                    ManagedPollOutcome::Handled,
32129                );
32130                assert_eq!(
32131                    server.captured_paths(),
32132                    vec![fail.to_owned()],
32133                    "{close} {surface}"
32134                );
32135            }
32136        }
32137    }
32138
32139    #[tokio::test]
32140    async fn managed_worker_keeps_polling_after_a_cancel_during_report_race() {
32141        // Native 3.0.4 answered a completion that raced a cancellation with
32142        // 409 run_closed, and the managed 4.11.1 worker exited (#170). With
32143        // server#994's full receipt the same worker settles and keeps going.
32144        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32145            request_override: Some(cancelled_during_report_then_unrelated_work),
32146            ..MockWorkerBehavior::default()
32147        });
32148        let client = Client::builder(server.base_url())
32149            .timeout(Duration::from_secs(2))
32150            .build()
32151            .expect("client");
32152        let executed = Arc::new(AtomicBool::new(false));
32153        let observed = Arc::clone(&executed);
32154        let mut worker = Worker::new(client, "rust-workers")
32155            .worker_id("timeout-worker")
32156            .poll_timeout(Duration::from_millis(10));
32157        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
32158            Ok(json!({"late": "result"}))
32159        });
32160        worker.register_workflow("unrelated.workflow", move |_ctx, _input| {
32161            let observed = Arc::clone(&observed);
32162            async move {
32163                observed.store(true, Ordering::SeqCst);
32164                Ok(Value::Null)
32165            }
32166        });
32167        assert_eq!(
32168            worker
32169                .run_once()
32170                .await
32171                .expect("the cancelled run's exact receipt settles the tick"),
32172            1
32173        );
32174        assert_eq!(
32175            worker
32176                .run_once()
32177                .await
32178                .expect("the same worker processes a later workflow task"),
32179            1
32180        );
32181        assert!(executed.load(Ordering::SeqCst));
32182        assert_eq!(
32183            state_requests(&server),
32184            vec![
32185                "/api/worker/workflow-tasks/workflow-timeout-task/complete".to_owned(),
32186                "/api/worker/workflow-tasks/unrelated-task/complete".to_owned(),
32187            ],
32188            "one report for the closed run, then the later task's completion"
32189        );
32190    }
32191
32192    fn cancelled_during_report_then_unrelated_work(
32193        path: &str,
32194        _body: &str,
32195        request: usize,
32196    ) -> Option<(&'static str, String)> {
32197        if path == "/api/worker/workflow-tasks/poll" && request <= 2 {
32198            let raced = request == 1;
32199            let task = json!({"task_id":if raced {"workflow-timeout-task"} else {"unrelated-task"},
32200                "workflow_id":if raced {"reused-workflow-id"} else {"unrelated-workflow"},
32201                "run_id":if raced {"run-selected-timeout"} else {"unrelated-run"},
32202                "workflow_type":if raced {"timeout.workflow"} else {"unrelated.workflow"},
32203                "payload_codec":"avro","arguments":fixture_envelope(json!([])),
32204                "history_events":[],"workflow_task_attempt":3,"lease_owner":"timeout-worker"});
32205            return Some(("200 OK", json!({"task":task}).to_string()));
32206        }
32207        match path {
32208            // The run was cancelled while the completion was in flight.
32209            "/api/worker/workflow-tasks/workflow-timeout-task/complete" => {
32210                Some(("409 Conflict", run_closed_receipt("cancelled").to_string()))
32211            }
32212            "/api/worker/workflow-tasks/unrelated-task/complete" => Some((
32213                "200 OK",
32214                json!({"outcome":"completed","recorded":true}).to_string(),
32215            )),
32216            _ => None,
32217        }
32218    }
32219
32220    #[tokio::test]
32221    async fn managed_worker_keeps_inexact_run_closed_refusals_fatal() {
32222        let valid = run_closed_receipt("cancelled");
32223        let mut cases: Vec<(String, &'static str, String)> = Vec::new();
32224        for (field, value) in [
32225            ("recorded", None),
32226            ("recorded", Some(json!(true))),
32227            ("recorded", Some(json!("false"))),
32228            ("recorded", Some(Value::Null)),
32229            ("task_id", None),
32230            ("task_id", Some(json!("other-task"))),
32231            ("workflow_task_attempt", None),
32232            ("workflow_task_attempt", Some(json!(4))),
32233            ("workflow_task_attempt", Some(json!("3"))),
32234            ("run_id", None),
32235            ("run_id", Some(json!("run-other"))),
32236            ("run_id", Some(Value::Null)),
32237            ("run_status", None),
32238            ("run_status", Some(json!("running"))),
32239            ("run_status", Some(json!("waiting"))),
32240            ("run_status", Some(json!("completed"))),
32241            ("stop_reason", None),
32242            ("stop_reason", Some(json!("run_terminated"))),
32243            ("can_continue", None),
32244            ("can_continue", Some(json!(true))),
32245            ("reason", None),
32246            ("reason", Some(json!("lease_owner_mismatch"))),
32247            ("reason", Some(json!("lease_expired"))),
32248            ("reason", Some(json!("workflow_task_attempt_mismatch"))),
32249            ("reason", Some(json!("conflicting_completion"))),
32250        ] {
32251            let mut body = valid.clone();
32252            let name = match value {
32253                Some(value) => {
32254                    let name = format!("{field}={value}");
32255                    body[field] = value;
32256                    name
32257                }
32258                None => {
32259                    body.as_object_mut().expect("receipt object").remove(field);
32260                    format!("{field} absent")
32261                }
32262            };
32263            cases.push((name, "409 Conflict", body.to_string()));
32264        }
32265        for status in [
32266            "403 Forbidden",
32267            "410 Gone",
32268            "422 Unprocessable Entity",
32269            "503 Service Unavailable",
32270        ] {
32271            cases.push((format!("HTTP {status}"), status, valid.to_string()));
32272        }
32273        cases.push(("malformed JSON".into(), "409 Conflict", "{broken".into()));
32274        // Native 3.0.4's guard body (#170) for the same task and attempt: it
32275        // lacks `recorded` and `run_id`, so it stays fatal.
32276        cases.push((
32277            "native 3.0.4 body".into(),
32278            "409 Conflict",
32279            json!({"task_id":"workflow-timeout-task","workflow_task_attempt":3,
32280                "error":"Workflow run is already closed.","reason":"run_closed","protocol_version":"1.20",
32281                "server_capabilities":{},"stop_reason":"run_cancelled","cancel_requested":true,
32282                "can_continue":false,"run_status":"cancelled","run_closed_reason":"cancelled",
32283                "task_status":"cancelled","lease_owner":"timeout-worker"})
32284            .to_string(),
32285        ));
32286        // A receipt that carries no closed-run state is not inferred terminal.
32287        cases.push((
32288            "receipt without run state".into(),
32289            "409 Conflict",
32290            json!({"reason":"run_closed","message":"run_closed","protocol_version":"1.20",
32291                "server_capabilities":{},"task_id":"workflow-timeout-task","workflow_task_attempt":3,
32292                "recorded":false,"run_id":"run-selected-timeout","task_status":"leased"})
32293            .to_string(),
32294        ));
32295
32296        for (name, status, response) in cases {
32297            let response: &'static str = Box::leak(response.into_boxed_str());
32298            let expected_status =
32299                reqwest::StatusCode::from_u16(status[..3].parse().expect("status code"))
32300                    .expect("status");
32301
32302            let server = MockWorkerServer::workflow_completion(status, response);
32303            let client = Client::builder(server.base_url())
32304                .timeout(Duration::from_secs(2))
32305                .build()
32306                .expect("client");
32307            let mut worker = Worker::new(client, "rust-workers")
32308                .worker_id("timeout-worker")
32309                .poll_timeout(Duration::from_millis(10));
32310            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
32311                Ok(json!({"late": "result"}))
32312            });
32313            let error = worker
32314                .run_once()
32315                .await
32316                .expect_err(&format!("{name} must remain an error"));
32317            assert_original_http_error(error, expected_status, response, &name);
32318            if expected_status == reqwest::StatusCode::CONFLICT {
32319                assert_eq!(
32320                    server
32321                        .request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
32322                    1,
32323                    "{name}: a refused report is not retried"
32324                );
32325            }
32326
32327            for (surface, decision) in workflow_timeout_failure_decisions() {
32328                let server = MockWorkerServer::workflow_completion(status, response);
32329                let client = Client::builder(server.base_url())
32330                    .timeout(Duration::from_secs(2))
32331                    .build()
32332                    .expect("client");
32333                let worker = Worker::new(client, "rust-workers");
32334                let error = worker
32335                    .settle_workflow_task_decision(
32336                        "workflow-timeout-task",
32337                        "timeout-worker",
32338                        3,
32339                        Some("run-selected-timeout"),
32340                        decision,
32341                        false,
32342                        None,
32343                    )
32344                    .await
32345                    .expect_err(&format!("{surface}: {name} must remain an error"));
32346                assert_original_http_error(
32347                    error,
32348                    expected_status,
32349                    response,
32350                    &format!("{surface}: {name}"),
32351                );
32352            }
32353        }
32354    }
32355
32356    #[tokio::test]
32357    async fn managed_worker_requires_the_selected_run_for_run_closed_receipts() {
32358        // Without the task's own run there is nothing to match.
32359        let response: &'static str =
32360            Box::leak(run_closed_receipt("cancelled").to_string().into_boxed_str());
32361        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
32362        let client = Client::builder(server.base_url())
32363            .timeout(Duration::from_secs(2))
32364            .build()
32365            .expect("client");
32366        let worker = Worker::new(client, "rust-workers");
32367        let error = worker
32368            .settle_workflow_task_decision(
32369                "workflow-timeout-task",
32370                "timeout-worker",
32371                3,
32372                None,
32373                Err(Error::WorkerLoop("fixture failure".into())),
32374                false,
32375                None,
32376            )
32377            .await
32378            .expect_err("a task without a run never settles");
32379        assert_original_http_error(error, reqwest::StatusCode::CONFLICT, response, "no run");
32380    }
32381
32382    #[tokio::test]
32383    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
32384        for (name, status, response) in [
32385            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
32386            (
32387                "command was recorded",
32388                "409 Conflict",
32389                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
32390            ),
32391            (
32392                "lease conflict",
32393                "409 Conflict",
32394                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
32395            ),
32396            (
32397                "nonterminal run",
32398                "409 Conflict",
32399                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
32400            ),
32401            (
32402                "different selected run",
32403                "409 Conflict",
32404                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"}"#,
32405            ),
32406            (
32407                "different task attempt",
32408                "409 Conflict",
32409                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
32410            ),
32411            (
32412                "authentication failure",
32413                "401 Unauthorized",
32414                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
32415            ),
32416            (
32417                "authorization failure",
32418                "403 Forbidden",
32419                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
32420            ),
32421            (
32422                "protocol failure",
32423                "400 Bad Request",
32424                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
32425            ),
32426            (
32427                "malformed command",
32428                "422 Unprocessable Entity",
32429                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
32430            ),
32431            (
32432                "transient server failure",
32433                "503 Service Unavailable",
32434                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
32435            ),
32436        ] {
32437            let server = MockWorkerServer::workflow_completion(status, response);
32438            let client = Client::builder(server.base_url())
32439                .timeout(Duration::from_secs(2))
32440                .build()
32441                .expect("client");
32442            let mut worker = Worker::new(client, "rust-workers")
32443                .worker_id("timeout-worker")
32444                .poll_timeout(Duration::from_millis(10));
32445            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
32446                Ok(json!({"late": "result"}))
32447            });
32448
32449            let error = worker
32450                .run_once()
32451                .await
32452                .expect_err(&format!("{name} must remain an error"));
32453            assert!(
32454                matches!(error, Error::Http { .. } | Error::Protocol(_)),
32455                "{name} returned an unexpected error variant: {error}"
32456            );
32457        }
32458    }
32459
32460    #[tokio::test]
32461    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
32462        let server = MockWorkerServer::start();
32463        let client = Client::builder(server.base_url())
32464            .worker_token(Some("worker-secret".to_string()))
32465            .namespace("orders")
32466            .timeout(Duration::from_secs(2))
32467            .build()
32468            .expect("client");
32469        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
32470
32471        let result = client
32472            .deregister_worker_registration("worker/α space")
32473            .await
32474            .expect("deregister worker registration");
32475
32476        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
32477        assert_eq!(
32478            server.worker_protocol_for(path).as_deref(),
32479            Some(WORKER_PROTOCOL_VERSION)
32480        );
32481        assert_eq!(server.control_protocol_for(path), None);
32482        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
32483        assert_eq!(
32484            server.authorization_for(path).as_deref(),
32485            Some("Bearer worker-secret")
32486        );
32487        assert_eq!(
32488            result,
32489            WorkerDeregistrationEnvelope {
32490                worker_id: "deregistered-worker".to_string(),
32491                outcome: "deregistered".to_string(),
32492                recovered_workflow_task_count: 2,
32493            }
32494        );
32495    }
32496
32497    #[tokio::test]
32498    async fn low_level_registration_rejects_update_validators_before_transport() {
32499        let server = MockWorkerServer::start();
32500        let client = Client::builder(server.base_url())
32501            .timeout(Duration::from_secs(2))
32502            .build()
32503            .expect("client");
32504
32505        for update_validators in [json!(["approve"]), json!("approve")] {
32506            let error = client
32507                .register_worker_with_command_contracts(
32508                    "validator-claiming-worker",
32509                    "rust-workers",
32510                    vec!["orders".to_string()],
32511                    vec![],
32512                    1,
32513                    1,
32514                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
32515                    json!({
32516                        "orders": {
32517                            "queries": ["current"],
32518                            "updates": ["approve"],
32519                            "update_validators": update_validators,
32520                        },
32521                    }),
32522                )
32523                .await
32524                .expect_err("unsupported validator claims must fail before registration");
32525
32526            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
32527                panic!("expected typed unsupported-validator failure");
32528            };
32529            assert_eq!(workflow_type, "orders");
32530        }
32531        assert_eq!(server.request_count("/api/worker/register"), 0);
32532    }
32533
32534    #[tokio::test]
32535    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
32536        let server = MockWorkerServer::start();
32537        let client = Client::builder(server.base_url())
32538            .timeout(Duration::from_secs(2))
32539            .build()
32540            .expect("client");
32541        let mut worker = Worker::new(client, "rust-workers");
32542        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
32543        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
32544        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
32545        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
32546        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
32547        worker
32548            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
32549            .expect("declare workflow signals");
32550
32551        worker.register().await.expect("register handler contracts");
32552
32553        let declaration =
32554            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
32555        let expected_contracts = json!([
32556            {
32557                "name": "a-avro",
32558                "parameters": [{
32559                    "name": "args", "position": 0, "required": false,
32560                    "variadic": true, "type": null, "allows_null": true,
32561                    "default_available": false, "default": null,
32562                }],
32563            },
32564            {
32565                "name": "z-json",
32566                "parameters": [{
32567                    "name": "args", "position": 0, "required": false,
32568                    "variadic": true, "type": null, "allows_null": true,
32569                    "default_available": false, "default": null,
32570                }],
32571            },
32572        ]);
32573        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
32574        assert_eq!(declaration["query_contracts"], expected_contracts);
32575        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
32576        assert_eq!(declaration["update_contracts"], expected_contracts);
32577        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
32578        assert_eq!(declaration["signal_contracts"], expected_contracts);
32579        assert_eq!(declaration["update_validators"], json!([]));
32580    }
32581
32582    #[tokio::test]
32583    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
32584        let server = MockWorkerServer::start();
32585        let client = Client::new(server.base_url()).expect("client");
32586        let mut worker = Worker::new(client, "rust-workers");
32587        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
32588        assert!(worker
32589            .declare_workflow_signals("missing", &["finish"])
32590            .is_err());
32591        worker
32592            .declare_workflow_signals("orders", &["finish"])
32593            .unwrap();
32594        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
32595            assert!(worker.declare_workflow_signals("orders", names).is_err());
32596        }
32597        worker.register().await.unwrap();
32598        assert_eq!(
32599            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
32600                ["signals"],
32601            json!(["finish"])
32602        );
32603        worker.declare_workflow_signals("orders", &[]).unwrap();
32604        worker.register().await.unwrap();
32605        let registrations = server.request_bodies("/api/worker/register");
32606        assert_eq!(
32607            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
32608            json!([])
32609        );
32610        assert_eq!(
32611            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
32612            json!([])
32613        );
32614    }
32615
32616    #[tokio::test]
32617    async fn low_level_registration_preserves_query_and_update_contracts() {
32618        let server = MockWorkerServer::start();
32619        let client = Client::builder(server.base_url())
32620            .timeout(Duration::from_secs(2))
32621            .build()
32622            .expect("client");
32623        let contracts = json!({
32624            "orders": {
32625                "queries": ["current"],
32626                "updates": ["approve"],
32627                "update_validators": [],
32628            },
32629            "payments": {
32630                "queries": ["status"],
32631                "updates": ["capture"],
32632            },
32633        });
32634
32635        client
32636            .register_worker_with_command_contracts(
32637                "command-worker",
32638                "rust-workers",
32639                vec!["orders".to_string(), "payments".to_string()],
32640                vec![],
32641                1,
32642                1,
32643                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
32644                contracts.clone(),
32645            )
32646            .await
32647            .expect("query and update contracts must remain supported");
32648
32649        assert_eq!(
32650            server.request_body("/api/worker/register")["workflow_command_contracts"],
32651            contracts
32652        );
32653        assert!(server
32654            .request_body("/api/worker/register")
32655            .get("workflow_definition_fingerprints")
32656            .is_none());
32657    }
32658
32659    #[tokio::test]
32660    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
32661        let server = MockWorkerServer::start();
32662        let client = Client::builder(server.base_url())
32663            .timeout(Duration::from_secs(2))
32664            .build()
32665            .expect("client");
32666        let mut worker = Worker::new(client.clone(), "rust-workers");
32667        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
32668
32669        assert!(worker
32670            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
32671            .is_err());
32672        assert!(worker
32673            .set_workflow_definition_sources("orders", &[])
32674            .is_err());
32675        worker
32676            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
32677            .expect("embed workflow source");
32678        worker.register().await.expect("register worker");
32679        let first = server.request_bodies("/api/worker/register")[0]
32680            ["workflow_definition_fingerprints"]["orders"]
32681            .as_str()
32682            .expect("source-backed fingerprint")
32683            .to_string();
32684        assert!(first.starts_with("sha256:"));
32685
32686        worker
32687            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
32688            .expect("change embedded helper source");
32689        worker.register().await.expect("register changed source");
32690        let changed = server.request_bodies("/api/worker/register")[1]
32691            ["workflow_definition_fingerprints"]["orders"]
32692            .as_str()
32693            .expect("changed fingerprint")
32694            .to_string();
32695        assert_ne!(first, changed);
32696
32697        let mut replacement =
32698            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
32699        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
32700        replacement
32701            .register()
32702            .await
32703            .expect("register replacement handler");
32704        assert_eq!(
32705            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
32706            json!({})
32707        );
32708    }
32709
32710    #[tokio::test]
32711    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
32712        let server = MockWorkerServer::start();
32713        let control_only = Client::builder(server.base_url())
32714            .control_token(Some("control-secret".to_string()))
32715            .build()
32716            .expect("control client");
32717
32718        let error = control_only
32719            .register_worker("worker", "queue", vec![], vec![], 1, 1)
32720            .await
32721            .expect_err("control token must not authorize a worker request");
32722        assert!(matches!(
32723            error,
32724            Error::MissingRoleCredentials { role: "worker", .. }
32725        ));
32726        assert_eq!(server.request_count("/api/worker/register"), 0);
32727
32728        let worker_only = Client::builder(server.base_url())
32729            .worker_token(Some("worker-secret".to_string()))
32730            .build()
32731            .expect("worker client");
32732        let error = worker_only
32733            .health()
32734            .await
32735            .expect_err("worker token must not authorize a control request");
32736        assert!(matches!(
32737            error,
32738            Error::MissingRoleCredentials {
32739                role: "control",
32740                ..
32741            }
32742        ));
32743        assert_eq!(server.request_count("/api/health"), 0);
32744    }
32745
32746    #[tokio::test]
32747    async fn shared_token_supports_worker_and_control_planes() {
32748        let server = MockWorkerServer::start();
32749        let client = Client::builder(server.base_url())
32750            .token(Some("shared-secret".to_string()))
32751            .build()
32752            .expect("client");
32753
32754        client.health().await.expect("control request");
32755        client
32756            .register_worker("worker", "queue", vec![], vec![], 1, 1)
32757            .await
32758            .expect("worker request");
32759
32760        assert_eq!(
32761            server.authorization_for("/api/health").as_deref(),
32762            Some("Bearer shared-secret")
32763        );
32764        assert_eq!(
32765            server.control_protocol_for("/api/health").as_deref(),
32766            Some(CONTROL_PLANE_VERSION)
32767        );
32768        assert_eq!(
32769            server.authorization_for("/api/worker/register").as_deref(),
32770            Some("Bearer shared-secret")
32771        );
32772        assert_eq!(
32773            server
32774                .worker_protocol_for("/api/worker/register")
32775                .as_deref(),
32776            Some(WORKER_PROTOCOL_VERSION)
32777        );
32778    }
32779
32780    #[tokio::test]
32781    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
32782        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
32783        let server = MockWorkerServer::start();
32784        let client = Client::builder(server.base_url())
32785            .timeout(Duration::from_secs(2))
32786            .build()
32787            .expect("client");
32788
32789        client
32790            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
32791            .await
32792            .expect("register");
32793        client
32794            .heartbeat_worker("capture-worker", 1, 1)
32795            .await
32796            .expect("heartbeat");
32797        client
32798            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
32799            .await
32800            .expect("workflow poll");
32801        client
32802            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
32803            .await
32804            .expect("activity poll");
32805
32806        for path in [
32807            "/api/worker/register",
32808            "/api/worker/heartbeat",
32809            "/api/worker/workflow-tasks/poll",
32810            "/api/worker/activity-tasks/poll",
32811        ] {
32812            assert_eq!(
32813                server.worker_protocol_for(path).as_deref(),
32814                Some(WORKER_PROTOCOL_VERSION),
32815                "unexpected protocol for {path}"
32816            );
32817        }
32818
32819        assert_eq!(
32820            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
32821            1
32822        );
32823        assert_eq!(
32824            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
32825            500
32826        );
32827        assert_eq!(
32828            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
32829            1
32830        );
32831        assert!(
32832            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
32833                .as_str()
32834                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
32835        );
32836        assert!(
32837            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
32838                .as_str()
32839                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
32840        );
32841        let registration = server.request_body("/api/worker/register");
32842        for optional in [
32843            "cooperative_cancellation",
32844            "local_activities",
32845            "worker_sessions",
32846            "sticky_execution",
32847        ] {
32848            assert!(!registration["capabilities"]
32849                .as_array()
32850                .is_some_and(|capabilities| capabilities
32851                    .iter()
32852                    .any(|capability| capability.as_str() == Some(optional))));
32853        }
32854    }
32855
32856    #[tokio::test]
32857    async fn explicit_previous_worker_protocol_preserves_headers() {
32858        let server = MockWorkerServer::start();
32859        let client = Client::builder(server.base_url())
32860            .worker_protocol_version(WorkerProtocolVersion::V119)
32861            .timeout(Duration::from_secs(2))
32862            .build()
32863            .expect("client");
32864        client
32865            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
32866            .await
32867            .expect("register");
32868        client
32869            .heartbeat_worker("legacy-worker", 1, 1)
32870            .await
32871            .expect("heartbeat");
32872        client
32873            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
32874            .await
32875            .expect("workflow poll");
32876        client
32877            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
32878            .await
32879            .expect("activity poll");
32880        client
32881            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
32882            .await
32883            .expect("query poll");
32884        client
32885            .deregister_worker_registration("legacy-worker")
32886            .await
32887            .expect("deregister");
32888        for path in [
32889            "/api/worker/register",
32890            "/api/worker/heartbeat",
32891            "/api/worker/workflow-tasks/poll",
32892            "/api/worker/activity-tasks/poll",
32893            "/api/worker/query-tasks/poll",
32894            "/api/worker/registrations/legacy-worker",
32895        ] {
32896            assert_eq!(
32897                server.worker_protocol_for(path).as_deref(),
32898                Some("1.19"),
32899                "{path}"
32900            );
32901            assert_eq!(server.control_protocol_for(path), None, "{path}");
32902        }
32903    }
32904
32905    #[tokio::test]
32906    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
32907        let server = MockWorkerServer::start();
32908        let client = Client::builder(server.base_url())
32909            .worker_protocol_version(WorkerProtocolVersion::V119)
32910            .timeout(Duration::from_secs(2))
32911            .build()
32912            .expect("client");
32913        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
32914        let error = worker
32915            .register()
32916            .await
32917            .expect_err("legacy cooperation must be refused");
32918        assert!(matches!(
32919            error,
32920            Error::CooperativeCancellationUnavailable(_)
32921        ));
32922        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
32923    }
32924
32925    #[tokio::test]
32926    async fn query_task_endpoints_send_the_selected_worker_protocol() {
32927        let server = MockWorkerServer::start();
32928        let client = Client::builder(server.base_url())
32929            .timeout(Duration::from_secs(2))
32930            .build()
32931            .expect("client");
32932
32933        client
32934            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
32935            .await
32936            .expect("query poll");
32937        client
32938            .complete_query_task(
32939                "query-capture",
32940                "capture-worker",
32941                1,
32942                json!(8),
32943                DEFAULT_CODEC,
32944            )
32945            .await
32946            .expect("query complete");
32947        client
32948            .fail_query_task(
32949                "query-capture",
32950                "capture-worker",
32951                1,
32952                "failed",
32953                "query_rejected",
32954                "QueryFailed",
32955            )
32956            .await
32957            .expect("query fail");
32958
32959        for path in [
32960            "/api/worker/query-tasks/poll",
32961            "/api/worker/query-tasks/query-capture/complete",
32962            "/api/worker/query-tasks/query-capture/fail",
32963        ] {
32964            assert_eq!(
32965                server.worker_protocol_for(path).as_deref(),
32966                Some(WORKER_PROTOCOL_VERSION),
32967                "unexpected protocol for {path}"
32968            );
32969        }
32970
32971        assert_eq!(
32972            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
32973            1
32974        );
32975        assert!(
32976            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
32977                .as_str()
32978                .is_some_and(|id| id.starts_with("rust-query-poll-"))
32979        );
32980    }
32981
32982    #[tokio::test]
32983    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
32984        let server = MockWorkerServer::transient_worker_failures();
32985        let client = Client::builder(server.base_url())
32986            .timeout(Duration::from_secs(2))
32987            .build()
32988            .expect("client");
32989
32990        client
32991            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
32992            .await
32993            .expect("workflow poll retry");
32994        client
32995            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
32996            .await
32997            .expect("activity poll retry");
32998        client
32999            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
33000            .await
33001            .expect("query poll retry");
33002
33003        for path in [
33004            "/api/worker/workflow-tasks/poll",
33005            "/api/worker/activity-tasks/poll",
33006            "/api/worker/query-tasks/poll",
33007        ] {
33008            let bodies = server.request_bodies(path);
33009            assert_eq!(bodies.len(), 2, "{path} must be retried once");
33010            assert_eq!(
33011                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
33012                "{path} must preserve the request binding across retry"
33013            );
33014        }
33015    }
33016
33017    #[tokio::test]
33018    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
33019        let server = MockWorkerServer::consecutive_poll_failures(2);
33020        let client = Client::builder(server.base_url())
33021            .timeout(Duration::from_secs(2))
33022            .build()
33023            .expect("client");
33024        let mut worker = Worker::new(client, "capture")
33025            .worker_id("capture-worker")
33026            .poll_timeout(Duration::from_millis(10))
33027            .retry_policy(WorkerRetryPolicy {
33028                max_retries: 2,
33029                initial_backoff: Duration::from_millis(1),
33030                max_backoff: Duration::from_millis(1),
33031            });
33032        worker.register_workflow(
33033            "capture.workflow",
33034            |_ctx, _input| async move { Ok(Value::Null) },
33035        );
33036        worker.register_activity(
33037            "capture.activity",
33038            |_ctx, _input| async move { Ok(Value::Null) },
33039        );
33040        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
33041            Ok(Value::Null)
33042        });
33043
33044        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
33045
33046        for path in [
33047            "/api/worker/workflow-tasks/poll",
33048            "/api/worker/activity-tasks/poll",
33049            "/api/worker/query-tasks/poll",
33050        ] {
33051            let bodies = server.request_bodies(path);
33052            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
33053            assert!(
33054                bodies
33055                    .iter()
33056                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
33057                "{path} must preserve one request binding across every retry"
33058            );
33059        }
33060    }
33061
33062    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
33063        let reason = if unavailable {
33064            "storage_admission_unavailable"
33065        } else {
33066            "storage_pressure"
33067        };
33068        let mut body = json!({
33069            "reason": reason,
33070            "storage_state": if unavailable { "fenced" } else { "draining" },
33071            "retryable": true,
33072            "retry_after_seconds": 1,
33073        });
33074        if !mid_poll {
33075            body["request_admitted"] = json!(false);
33076        }
33077        if let Some(id) = poll_id {
33078            body["task"] = Value::Null;
33079            body["poll_status"] = json!(reason);
33080            body["poll_request_id"] = json!(id);
33081            body["retry_same_poll_request_id"] = json!(true);
33082            body["claim_admitted"] = json!(false);
33083        }
33084        body
33085    }
33086
33087    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
33088        let operation = match path {
33089            "/api/worker/register" => "register_worker",
33090            "/api/worker/heartbeat" => "heartbeat_worker",
33091            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
33092            "/api/worker/activity-tasks/poll" => "poll_activity_task",
33093            "/api/worker/query-tasks/poll" => "poll_query_task",
33094            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
33095            _ => return None,
33096        };
33097        let request: Value = serde_json::from_str(request).ok()?;
33098        let mut response = json!({
33099            "reason": "backend_unavailable",
33100            "operation": operation,
33101            "outcome": "unknown",
33102            "retryable": true,
33103            "retry_after_seconds": 1,
33104            "worker_id": request["worker_id"],
33105            "task_queue": request.get("task_queue"),
33106        });
33107        if path.ends_with("/poll") {
33108            response["task"] = Value::Null;
33109            response["poll_status"] = json!("backend_unavailable");
33110            response["poll_request_id"] = request["poll_request_id"].clone();
33111            response["retry_same_poll_request_id"] = json!(true);
33112        }
33113        Some(response)
33114    }
33115
33116    fn backend_retry_override(
33117        path: &str,
33118        request: &str,
33119        number: usize,
33120    ) -> Option<(&'static str, String)> {
33121        if number > 8 {
33122            return None;
33123        }
33124        Some((
33125            "503 Service Unavailable",
33126            backend_refusal(path, request)?.to_string(),
33127        ))
33128    }
33129
33130    fn backend_unavailable_override(
33131        path: &str,
33132        request: &str,
33133        _number: usize,
33134    ) -> Option<(&'static str, String)> {
33135        Some((
33136            "503 Service Unavailable",
33137            backend_refusal(path, request)?.to_string(),
33138        ))
33139    }
33140
33141    fn storage_worker(server: &MockWorkerServer) -> Worker {
33142        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
33143            .worker_id("storage-worker")
33144            .retry_policy(WorkerRetryPolicy {
33145                max_retries: 1,
33146                initial_backoff: Duration::from_millis(1),
33147                max_backoff: Duration::from_millis(1),
33148            })
33149    }
33150
33151    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
33152        let requests = server.requests.lock().expect("requests");
33153        let bodies: Vec<_> = requests
33154            .iter()
33155            .filter(|request| request.path == path)
33156            .map(|request| &request.body)
33157            .collect();
33158        assert_eq!(bodies.len(), count, "{path}");
33159        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
33160    }
33161
33162    #[test]
33163    fn backend_recovery_requires_the_explicit_worker_contract() {
33164        for (path, operation) in [
33165            ("/worker/register", "register_worker"),
33166            ("/worker/heartbeat", "heartbeat_worker"),
33167            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
33168            ("/worker/activity-tasks/poll", "poll_activity_task"),
33169            ("/worker/query-tasks/poll", "poll_query_task"),
33170            (
33171                "/worker/update-validation-tasks/poll",
33172                "poll_update_validation_task",
33173            ),
33174        ] {
33175            let poll_id = path.ends_with("/poll").then_some("same-poll");
33176            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
33177            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
33178                .expect("worker operation");
33179            assert_eq!(body["operation"], operation);
33180            let error = Error::Http {
33181                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33182                body: body.to_string(),
33183            };
33184            assert_eq!(
33185                worker_backend_unavailable_retry_after(&error, path, poll_id),
33186                Some(Duration::from_secs(1))
33187            );
33188            assert!(!worker_operation_is_retryable(&error));
33189            for (field, value) in [
33190                ("operation", json!("wrong_operation")),
33191                ("outcome", json!("completed")),
33192                ("retryable", json!(false)),
33193                ("retry_after_seconds", json!(0)),
33194                ("worker_id", json!("")),
33195            ] {
33196                let mut invalid = body.clone();
33197                invalid[field] = value;
33198                let error = Error::Http {
33199                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33200                    body: invalid.to_string(),
33201                };
33202                assert!(
33203                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
33204                    "{path}: {field}"
33205                );
33206                assert!(!worker_operation_is_retryable(&error));
33207            }
33208            if let Some(poll_id) = poll_id {
33209                for (field, value) in [
33210                    ("poll_request_id", json!("wrong-poll")),
33211                    ("poll_status", json!("empty")),
33212                    ("task", json!({"task_id":"claimed"})),
33213                    ("retry_same_poll_request_id", json!(false)),
33214                ] {
33215                    let mut invalid = body.clone();
33216                    invalid[field] = value;
33217                    let error = Error::Http {
33218                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33219                        body: invalid.to_string(),
33220                    };
33221                    assert!(
33222                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
33223                            .is_none(),
33224                        "{path}: {field}"
33225                    );
33226                }
33227            }
33228            let error = Error::Http {
33229                status: reqwest::StatusCode::UNAUTHORIZED,
33230                body: body.to_string(),
33231            };
33232            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
33233            assert!(!worker_operation_is_retryable(&error));
33234        }
33235    }
33236
33237    #[tokio::test]
33238    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
33239        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33240            request_override: Some(backend_retry_override),
33241            ..MockWorkerBehavior::default()
33242        });
33243        let mut worker =
33244            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
33245        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
33246        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
33247        worker.register_query("backend.workflow", "state", |_, _| async {
33248            Ok(Value::Null)
33249        });
33250        worker.register().await.expect("registration recovery");
33251        worker
33252            .client
33253            .heartbeat_worker("storage-worker", 1, 1)
33254            .await
33255            .expect("heartbeat recovery");
33256        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
33257        for path in [
33258            "/api/worker/register",
33259            "/api/worker/heartbeat",
33260            "/api/worker/workflow-tasks/poll",
33261            "/api/worker/activity-tasks/poll",
33262            "/api/worker/query-tasks/poll",
33263        ] {
33264            assert_identical_requests(&server, path, 9);
33265        }
33266    }
33267
33268    #[tokio::test]
33269    async fn backend_recovery_wait_stops_with_worker() {
33270        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33271            request_override: Some(backend_unavailable_override),
33272            ..MockWorkerBehavior::default()
33273        });
33274        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
33275            max_retries: 1,
33276            initial_backoff: Duration::from_secs(2),
33277            max_backoff: Duration::from_secs(2),
33278        });
33279        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
33280        let started = tokio::time::Instant::now();
33281        let _ = tokio::time::timeout(
33282            Duration::from_secs(1),
33283            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
33284        )
33285        .await
33286        .expect("shutdown interrupts backend wait");
33287        assert!(started.elapsed() < Duration::from_secs(1));
33288        assert!(server.request_count("/api/worker/register") >= 1);
33289    }
33290
33291    #[test]
33292    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
33293        for unavailable in [false, true] {
33294            for mid_poll in [false, true] {
33295                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
33296                let error = Error::Http {
33297                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33298                    body: body.to_string(),
33299                };
33300                assert_eq!(
33301                    worker_storage_admission_retry_after(&error, Some("same-poll")),
33302                    Some(Duration::from_secs(1))
33303                );
33304                assert!(
33305                    !worker_operation_is_retryable(&error),
33306                    "storage is not a bounded generic retry"
33307                );
33308                for (field, value) in [
33309                    ("poll_request_id", json!("wrong-poll")),
33310                    ("task", json!({"task_id":"claimed"})),
33311                    ("retryable", json!(false)),
33312                    ("retry_after_seconds", json!(0)),
33313                    ("retry_after_seconds", json!(true)),
33314                    ("retry_after_seconds", json!(1.0)),
33315                    ("storage_state", json!("normal")),
33316                    ("poll_status", json!("empty")),
33317                    ("claim_admitted", json!(true)),
33318                    ("retry_same_poll_request_id", json!(false)),
33319                    ("request_admitted", json!(true)),
33320                ] {
33321                    let mut invalid = body.clone();
33322                    invalid[field] = value;
33323                    let error = Error::Http {
33324                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33325                        body: invalid.to_string(),
33326                    };
33327                    assert!(
33328                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
33329                        "{field}"
33330                    );
33331                }
33332            }
33333        }
33334        let body = storage_refusal(None, false, false);
33335        let error = Error::Http {
33336            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33337            body: body.to_string(),
33338        };
33339        assert!(worker_storage_admission_retry_after(&error, None).is_some());
33340        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
33341        let error = Error::Http {
33342            status: reqwest::StatusCode::FORBIDDEN,
33343            body: body.to_string(),
33344        };
33345        assert!(worker_storage_admission_retry_after(&error, None).is_none());
33346        let body = storage_refusal(None, false, true);
33347        let error = Error::Http {
33348            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33349            body: body.to_string(),
33350        };
33351        assert!(worker_storage_admission_retry_after(&error, None).is_none());
33352    }
33353
33354    #[tokio::test]
33355    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
33356        for unavailable in [false, true] {
33357            for mid_poll in [false, true] {
33358                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33359                    poll_failures_per_path: 1,
33360                    storage_refusals: 7,
33361                    storage_path: Some("/poll"),
33362                    storage_unavailable: unavailable,
33363                    storage_mid_poll: mid_poll,
33364                    ..MockWorkerBehavior::default()
33365                });
33366                let mut worker = storage_worker(&server);
33367                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
33368                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
33369                for path in [
33370                    "/api/worker/workflow-tasks/poll",
33371                    "/api/worker/activity-tasks/poll",
33372                    "/api/worker/query-tasks/poll",
33373                ] {
33374                    assert_identical_requests(&server, path, 9);
33375                }
33376            }
33377        }
33378    }
33379
33380    #[tokio::test]
33381    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
33382        struct CountedBody(Arc<AtomicUsize>);
33383        impl Serialize for CountedBody {
33384            fn serialize<S: Serializer>(
33385                &self,
33386                serializer: S,
33387            ) -> std::result::Result<S::Ok, S::Error> {
33388                let count = self.0.fetch_add(1, Ordering::SeqCst);
33389                json!({"serialization":count,"lease_owner":"worker","attempt":7})
33390                    .serialize(serializer)
33391            }
33392        }
33393        for path in [
33394            "/api/worker/register",
33395            "/api/worker/heartbeat",
33396            "/api/worker/workflow-tasks/storage-task/complete",
33397            "/api/worker/workflow-tasks/storage-task/fail",
33398            "/api/worker/activity-tasks/storage-task/complete",
33399            "/api/worker/activity-tasks/storage-task/fail",
33400            "/api/worker/activity-tasks/storage-task/heartbeat",
33401            "/api/worker/query-tasks/storage-task/complete",
33402            "/api/worker/query-tasks/storage-task/fail",
33403        ] {
33404            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33405                storage_refusals: 7,
33406                storage_path: Some(path),
33407                ..MockWorkerBehavior::default()
33408            });
33409            let worker =
33410                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
33411            let calls = Arc::new(AtomicUsize::new(0));
33412            let _: Value = worker
33413                .client
33414                .request_json(
33415                    reqwest::Method::POST,
33416                    &path[4..],
33417                    RequestProtocol::DefaultWorker,
33418                    Some(&CountedBody(Arc::clone(&calls))),
33419                )
33420                .await
33421                .expect("prepared request recovery");
33422            assert_eq!(calls.load(Ordering::SeqCst), 1);
33423            assert_identical_requests(&server, path, 8);
33424        }
33425        for worker_scope in [false, true] {
33426            let path = if worker_scope {
33427                "/api/health"
33428            } else {
33429                "/api/worker/register"
33430            };
33431            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33432                storage_refusals: usize::MAX,
33433                storage_path: Some(path),
33434                ..MockWorkerBehavior::default()
33435            });
33436            let worker = storage_worker(&server);
33437            let client = worker.client.clone();
33438            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
33439            let error = if worker_scope {
33440                worker
33441                    .client
33442                    .health()
33443                    .await
33444                    .expect_err("control plane is not retried")
33445            } else {
33446                client
33447                    .request_json::<Value, Value>(
33448                        reqwest::Method::POST,
33449                        "/worker/register",
33450                        RequestProtocol::DefaultWorker,
33451                        Some(&json!({})),
33452                    )
33453                    .await
33454                    .expect_err("direct client is not retried")
33455            };
33456            assert!(worker_storage_admission_body(&error).is_some());
33457            assert_eq!(server.request_count(path), 1);
33458        }
33459    }
33460
33461    #[tokio::test]
33462    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
33463        for fail in [false, true] {
33464            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33465                storage_activity: true,
33466                storage_refusals: 7,
33467                storage_path: Some("/storage-activity/"),
33468                ..MockWorkerBehavior::default()
33469            });
33470            let mut worker = storage_worker(&server);
33471            let calls = Arc::new(AtomicUsize::new(0));
33472            let observed = Arc::clone(&calls);
33473            worker.register_activity("storage.activity", move |ctx, _| {
33474                let calls = Arc::clone(&observed);
33475                async move {
33476                    calls.fetch_add(1, Ordering::SeqCst);
33477                    ctx.heartbeat(json!({"step":2})).await?;
33478                    if fail {
33479                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
33480                    } else {
33481                        Ok(json!({"receipt":true}))
33482                    }
33483                }
33484            });
33485            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
33486            assert_eq!(calls.load(Ordering::SeqCst), 1);
33487            assert_identical_requests(
33488                &server,
33489                "/api/worker/activity-tasks/storage-activity/heartbeat",
33490                8,
33491            );
33492            let suffix = if fail { "fail" } else { "complete" };
33493            assert_identical_requests(
33494                &server,
33495                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
33496                8,
33497            );
33498            let other = if fail { "complete" } else { "fail" };
33499            assert_eq!(
33500                server.request_count(&format!(
33501                    "/api/worker/activity-tasks/storage-activity/{other}"
33502                )),
33503                0
33504            );
33505        }
33506    }
33507
33508    #[tokio::test]
33509    async fn storage_waits_are_interruptible_without_false_activity_failure() {
33510        for path in [
33511            "/api/worker/register",
33512            "/api/worker/heartbeat",
33513            "/api/worker/activity-tasks/poll",
33514            "/api/worker/activity-tasks/storage-activity/heartbeat",
33515            "/api/worker/activity-tasks/storage-activity/complete",
33516        ] {
33517            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33518                storage_activity: true,
33519                storage_refusals: usize::MAX,
33520                storage_path: Some(path),
33521                ..MockWorkerBehavior::default()
33522            });
33523            let mut worker = storage_worker(&server)
33524                .max_concurrent_workflow_tasks(1)
33525                .max_concurrent_activity_tasks(1)
33526                .retry_policy(WorkerRetryPolicy::default());
33527            worker.register_activity("storage.activity", |ctx, _| async move {
33528                ctx.heartbeat(json!({"step":2})).await?;
33529                Ok(json!({"receipt":true}))
33530            });
33531            let shutdown = async {
33532                while server.request_count(path) == 0 {
33533                    tokio::time::sleep(Duration::from_millis(1)).await;
33534                }
33535            };
33536            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
33537                .await
33538                .expect("shutdown interrupts admission");
33539            assert!(
33540                result.is_err(),
33541                "a refused operation must not appear acknowledged: {path}, {result:?}"
33542            );
33543            assert_eq!(server.request_count(path), 1);
33544            assert_eq!(
33545                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
33546                0
33547            );
33548            assert_eq!(
33549                server.request_count("/api/worker/registrations/mock-worker"),
33550                usize::from(!path.ends_with("/register"))
33551            );
33552        }
33553    }
33554
33555    #[tokio::test]
33556    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
33557        for fail in [false, true] {
33558            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33559                storage_query: true,
33560                storage_refusals: 7,
33561                storage_path: Some("/storage-query/"),
33562                ..MockWorkerBehavior::default()
33563            });
33564            let mut worker = storage_worker(&server);
33565            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
33566            let calls = Arc::new(AtomicUsize::new(0));
33567            let observed = Arc::clone(&calls);
33568            worker.register_query("storage.workflow", "state", move |_, _| {
33569                let calls = Arc::clone(&observed);
33570                async move {
33571                    calls.fetch_add(1, Ordering::SeqCst);
33572                    if fail {
33573                        Err(Error::WorkerLoop("intentional query failure".to_string()))
33574                    } else {
33575                        Ok(json!({"state":"waiting"}))
33576                    }
33577                }
33578            });
33579            assert_eq!(worker.run_once().await.expect("query settled"), 1);
33580            assert_eq!(calls.load(Ordering::SeqCst), 1);
33581            let suffix = if fail { "fail" } else { "complete" };
33582            assert_identical_requests(
33583                &server,
33584                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
33585                8,
33586            );
33587            let other = if fail { "complete" } else { "fail" };
33588            assert_eq!(
33589                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
33590                0
33591            );
33592        }
33593    }
33594
33595    #[tokio::test]
33596    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
33597        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33598            storage_refusals: 7,
33599            storage_path: Some("/poll"),
33600            unauthorized_polls: true,
33601            ..MockWorkerBehavior::default()
33602        });
33603        let error = storage_worker(&server)
33604            .run_once()
33605            .await
33606            .expect_err("auth remains terminal");
33607        assert!(matches!(
33608            error,
33609            Error::Http {
33610                status: reqwest::StatusCode::UNAUTHORIZED,
33611                ..
33612            }
33613        ));
33614        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
33615
33616        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33617            storage_refusals: 7,
33618            storage_path: Some("/activity-cancel/complete"),
33619            ..MockWorkerBehavior::default()
33620        });
33621        let worker =
33622            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
33623        let error = worker
33624            .client
33625            .complete_activity_task(
33626                "activity-cancel",
33627                "attempt-cancel",
33628                "worker",
33629                json!({}),
33630                DEFAULT_CODEC,
33631            )
33632            .await
33633            .expect_err("cancellation remains terminal");
33634        assert!(activity_task_rejection_is_final(&error));
33635        assert_identical_requests(
33636            &server,
33637            "/api/worker/activity-tasks/activity-cancel/complete",
33638            8,
33639        );
33640
33641        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33642            storage_refusals: usize::MAX,
33643            storage_path: Some("/poll"),
33644            storage_wrong_poll_id: true,
33645            ..MockWorkerBehavior::default()
33646        });
33647        assert!(storage_worker(&server).run_once().await.is_err());
33648        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
33649    }
33650
33651    #[tokio::test]
33652    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
33653        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33654            storage_refusals: usize::MAX,
33655            storage_path: Some("/poll"),
33656            ..MockWorkerBehavior::default()
33657        });
33658        let mut worker = storage_worker(&server)
33659            .max_concurrent_workflow_tasks(1)
33660            .max_concurrent_activity_tasks(1)
33661            .retry_policy(WorkerRetryPolicy::default());
33662        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
33663        let run = tokio::spawn(async move { worker.run().await });
33664        tokio::time::timeout(Duration::from_secs(2), async {
33665            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
33666                tokio::time::sleep(Duration::from_millis(1)).await;
33667            }
33668        })
33669        .await
33670        .expect("poll started");
33671        run.abort();
33672        assert!(run.await.expect_err("cancelled run").is_cancelled());
33673        tokio::time::sleep(Duration::from_millis(250)).await;
33674        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
33675    }
33676
33677    #[tokio::test]
33678    async fn query_protocol_rejection_from_older_server_is_typed() {
33679        let server = MockWorkerServer::reject_query_protocol();
33680        let client = Client::builder(server.base_url())
33681            .timeout(Duration::from_secs(2))
33682            .build()
33683            .expect("client");
33684
33685        let error = client
33686            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
33687            .await
33688            .expect_err("server below query protocol floor must reject");
33689        let Error::Protocol(failure) = error else {
33690            panic!("expected typed protocol failure");
33691        };
33692
33693        assert_eq!(failure.status, 400);
33694        assert_eq!(failure.reason, "unsupported_protocol_version");
33695        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
33696        assert_eq!(
33697            failure.requested_version.as_deref(),
33698            Some(WORKER_PROTOCOL_VERSION)
33699        );
33700        assert_eq!(
33701            server
33702                .worker_protocol_for("/api/worker/query-tasks/poll")
33703                .as_deref(),
33704            Some(WORKER_PROTOCOL_VERSION)
33705        );
33706    }
33707
33708    #[tokio::test]
33709    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
33710        let server = MockWorkerServer::reject_query_protocol();
33711        let client = Client::builder(server.base_url())
33712            .timeout(Duration::from_secs(2))
33713            .build()
33714            .expect("client");
33715        let mut worker = Worker::new(client, "rust-workers")
33716            .worker_id("baseline-worker")
33717            .poll_timeout(Duration::from_millis(10));
33718
33719        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
33720            Ok(Value::Null)
33721        });
33722
33723        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
33724        assert_eq!(
33725            server
33726                .worker_protocol_for("/api/worker/workflow-tasks/poll")
33727                .as_deref(),
33728            Some(WORKER_PROTOCOL_VERSION)
33729        );
33730        assert_eq!(
33731            server.worker_protocol_for("/api/worker/query-tasks/poll"),
33732            None,
33733            "a worker without query handlers must not use the query-task endpoint"
33734        );
33735    }
33736
33737    #[tokio::test]
33738    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
33739        let server = MockWorkerServer::reject_query_completion();
33740        let client = Client::builder(server.base_url())
33741            .timeout(Duration::from_secs(2))
33742            .build()
33743            .expect("client");
33744
33745        let error = client
33746            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
33747            .await
33748            .expect_err("expired completion must be rejected");
33749        let Error::QueryFailed(failure) = error else {
33750            panic!("expected typed query failure");
33751        };
33752        assert_eq!(failure.status, 409);
33753        assert_eq!(failure.reason, "query_task_timed_out");
33754
33755        let mut worker = Worker::new(client, "rust-workers")
33756            .worker_id("late-worker")
33757            .poll_timeout(Duration::from_millis(10));
33758        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
33759        worker.register_query(
33760            "counter",
33761            "current",
33762            |_ctx, _args| async move { Ok(json!(8)) },
33763        );
33764
33765        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
33766        assert_eq!(
33767            worker
33768                .run_once()
33769                .await
33770                .expect("worker continues after late completion"),
33771            0
33772        );
33773        assert_eq!(
33774            server.request_count("/api/worker/query-tasks/query-late/complete"),
33775            2
33776        );
33777        assert_eq!(
33778            server.request_count("/api/worker/query-tasks/query-late/fail"),
33779            0,
33780            "a server completion rejection must not be reported as an encoding failure"
33781        );
33782    }
33783
33784    #[tokio::test]
33785    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
33786        let server = MockWorkerServer::start();
33787        let client = Client::builder(server.base_url())
33788            .timeout(Duration::from_secs(2))
33789            .build()
33790            .expect("client");
33791        let mut worker = Worker::new(client, "rust-workers")
33792            .worker_id("joined-worker")
33793            .poll_timeout(Duration::from_millis(10));
33794        worker.register_workflow(
33795            "joined.workflow",
33796            |_ctx, _input| async move { Ok(Value::Null) },
33797        );
33798        worker.register_activity(
33799            "joined.activity",
33800            |_ctx, _input| async move { Ok(Value::Null) },
33801        );
33802        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
33803            Ok(Value::Null)
33804        });
33805
33806        worker
33807            .run_until(tokio::time::sleep(Duration::from_millis(20)))
33808            .await
33809            .expect("normal shutdown");
33810
33811        let deregistration_path = "/api/worker/registrations/mock-worker";
33812        assert_eq!(server.request_count(deregistration_path), 1);
33813        for poll_path in [
33814            "/api/worker/workflow-tasks/poll",
33815            "/api/worker/activity-tasks/poll",
33816            "/api/worker/query-tasks/poll",
33817        ] {
33818            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
33819        }
33820        assert_eq!(
33821            server.captured_paths().last().map(String::as_str),
33822            Some(deregistration_path),
33823            "deregistration must start only after every poller has joined"
33824        );
33825    }
33826
33827    #[tokio::test]
33828    async fn registration_failure_does_not_deregister() {
33829        let server = MockWorkerServer::rejected_registration();
33830        let client = Client::builder(server.base_url())
33831            .timeout(Duration::from_secs(2))
33832            .build()
33833            .expect("client");
33834        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
33835
33836        let error = worker
33837            .run_until(async {})
33838            .await
33839            .expect_err("registration must fail");
33840        assert!(matches!(
33841            error,
33842            Error::Http {
33843                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
33844                ..
33845            }
33846        ));
33847        assert!(server
33848            .captured_paths()
33849            .iter()
33850            .all(|path| !path.starts_with("/api/worker/registrations/")));
33851    }
33852
33853    #[tokio::test]
33854    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
33855        let server = MockWorkerServer::rejected_registration_protocol();
33856        let client = Client::builder(server.base_url())
33857            .timeout(Duration::from_secs(2))
33858            .build()
33859            .expect("client");
33860        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
33861
33862        let error = worker
33863            .run_until(async {})
33864            .await
33865            .expect_err("a protocol 1.16 server must reject this worker");
33866        let Error::Protocol(failure) = error else {
33867            panic!("expected typed protocol rejection");
33868        };
33869        assert_eq!(failure.reason, "unsupported_protocol_version");
33870        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
33871        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
33872        assert_eq!(
33873            server
33874                .worker_protocol_for("/api/worker/register")
33875                .as_deref(),
33876            Some(WORKER_PROTOCOL_VERSION)
33877        );
33878    }
33879
33880    #[tokio::test]
33881    async fn declined_registration_does_not_deregister() {
33882        let server = MockWorkerServer::declined_registration();
33883        let client = Client::builder(server.base_url())
33884            .timeout(Duration::from_secs(2))
33885            .build()
33886            .expect("client");
33887        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
33888
33889        let error = worker
33890            .run_until(async {})
33891            .await
33892            .expect_err("declined registration must fail");
33893        assert!(matches!(error, Error::WorkerLoop(_)));
33894        assert!(error.to_string().contains("was not accepted"));
33895        assert!(server
33896            .captured_paths()
33897            .iter()
33898            .all(|path| !path.starts_with("/api/worker/registrations/")));
33899    }
33900
33901    #[tokio::test]
33902    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
33903        let server = MockWorkerServer::rejected_deregistration();
33904        let client = Client::builder(server.base_url())
33905            .timeout(Duration::from_secs(2))
33906            .build()
33907            .expect("client");
33908        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
33909
33910        let error = worker
33911            .run_until(async {})
33912            .await
33913            .expect_err("deregistration must fail");
33914        assert!(matches!(
33915            error,
33916            Error::Http {
33917                status: reqwest::StatusCode::FORBIDDEN,
33918                ..
33919            }
33920        ));
33921        assert_eq!(
33922            server.request_count("/api/worker/registrations/mock-worker"),
33923            1
33924        );
33925    }
33926
33927    #[tokio::test]
33928    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
33929        let server = MockWorkerServer::rejected_deregistration_protocol();
33930        let client = Client::builder(server.base_url())
33931            .timeout(Duration::from_secs(2))
33932            .build()
33933            .expect("client");
33934        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
33935
33936        let error = worker
33937            .run_until(async {})
33938            .await
33939            .expect_err("protocol rejection must fail shutdown");
33940        let Error::Protocol(failure) = error else {
33941            panic!("expected typed protocol failure");
33942        };
33943        assert_eq!(failure.reason, "unsupported_protocol_version");
33944        assert_eq!(
33945            failure.requested_version.as_deref(),
33946            Some(WORKER_PROTOCOL_VERSION)
33947        );
33948        assert_eq!(
33949            server.request_count("/api/worker/registrations/mock-worker"),
33950            1
33951        );
33952    }
33953
33954    #[tokio::test]
33955    async fn primary_poller_error_retains_deregistration_failure_context() {
33956        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
33957        let client = Client::builder(server.base_url())
33958            .timeout(Duration::from_secs(2))
33959            .build()
33960            .expect("client");
33961        let mut worker = Worker::new(client, "rust-workers")
33962            .worker_id("combined-failure")
33963            .poll_timeout(Duration::from_millis(10));
33964        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
33965            Ok(Value::Null)
33966        });
33967
33968        let error = worker
33969            .run()
33970            .await
33971            .expect_err("worker and cleanup must fail");
33972        let summary = error.to_string();
33973        assert!(summary.contains("authentication_failed"));
33974        assert!(summary.contains("worker cannot deregister"));
33975        let Error::WorkerShutdown {
33976            primary,
33977            deregistration,
33978        } = error
33979        else {
33980            panic!("expected combined worker shutdown error");
33981        };
33982        assert!(matches!(
33983            *primary,
33984            Error::Http {
33985                status: reqwest::StatusCode::UNAUTHORIZED,
33986                ..
33987            }
33988        ));
33989        assert!(matches!(
33990            *deregistration,
33991            Error::Http {
33992                status: reqwest::StatusCode::FORBIDDEN,
33993                ..
33994            }
33995        ));
33996        assert_eq!(
33997            server.request_count("/api/worker/registrations/mock-worker"),
33998            1
33999        );
34000    }
34001
34002    #[tokio::test]
34003    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
34004        let server = MockWorkerServer::start();
34005        let client = Client::builder(server.base_url())
34006            .timeout(Duration::from_secs(2))
34007            .build()
34008            .expect("client");
34009        let mut worker = Worker::new(client, "rust-workers")
34010            .worker_id("activity-only-worker")
34011            .poll_timeout(Duration::from_millis(10));
34012
34013        worker.register_activity(
34014            "activity.only",
34015            |_ctx, _args| async move { Ok(Value::Null) },
34016        );
34017
34018        worker.run_until(async {}).await.expect("run worker");
34019    }
34020
34021    #[tokio::test]
34022    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
34023        let server = MockWorkerServer::start();
34024        let client = Client::builder(server.base_url())
34025            .timeout(Duration::from_secs(2))
34026            .build()
34027            .expect("client");
34028        let mut worker = Worker::new(client, "rust-workers")
34029            .worker_id("workflow-only-worker")
34030            .poll_timeout(Duration::from_millis(10));
34031
34032        worker.register_workflow(
34033            "workflow.only",
34034            |_ctx, _input| async move { Ok(Value::Null) },
34035        );
34036
34037        worker.run_until(async {}).await.expect("run worker");
34038    }
34039
34040    #[tokio::test]
34041    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
34042        let server = MockWorkerServer::start();
34043        let client = Client::builder(server.base_url())
34044            .timeout(Duration::from_secs(2))
34045            .build()
34046            .expect("client");
34047        let observations = Arc::new(Mutex::new(Vec::new()));
34048        let observed = Arc::clone(&observations);
34049        let mut worker = Worker::new(client, "rust-workers")
34050            .worker_id("observed-heartbeat-worker")
34051            .poll_timeout(Duration::from_millis(10))
34052            .on_worker_heartbeat(move |observation| {
34053                observed
34054                    .lock()
34055                    .expect("heartbeat observations")
34056                    .push(observation.clone());
34057            });
34058
34059        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
34060            Ok(Value::Null)
34061        });
34062        let acknowledged = Arc::clone(&observations);
34063        worker
34064            .run_until(async move {
34065                tokio::time::timeout(Duration::from_secs(2), async move {
34066                    loop {
34067                        if !acknowledged
34068                            .lock()
34069                            .expect("heartbeat observations")
34070                            .is_empty()
34071                        {
34072                            break;
34073                        }
34074                        tokio::time::sleep(Duration::from_millis(1)).await;
34075                    }
34076                })
34077                .await
34078                .expect("heartbeat acknowledgement within timeout");
34079            })
34080            .await
34081            .expect("run worker");
34082
34083        let observations = observations.lock().expect("heartbeat observations");
34084        let first = observations.first().expect("heartbeat acknowledgement");
34085        assert_eq!(first.worker_id, "observed-heartbeat-worker");
34086        assert_eq!(first.task_queue, "rust-workers");
34087        assert!(first.acknowledged_at_unix_millis > 0);
34088        assert_eq!(first.acknowledgement, json!({}));
34089    }
34090
34091    #[tokio::test]
34092    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
34093        let server = MockWorkerServer::delayed_heartbeat_worker();
34094        let client = Client::builder(server.base_url())
34095            .timeout(Duration::from_secs(3))
34096            .build()
34097            .expect("client");
34098        let observations = Arc::new(Mutex::new(Vec::new()));
34099        let observed = Arc::clone(&observations);
34100        let mut worker = Worker::new(client, "rust-snapshot-workers")
34101            .max_concurrent_workflow_tasks(1)
34102            .max_concurrent_activity_tasks(1)
34103            .worker_id("rust-snapshot-worker")
34104            .poll_timeout(Duration::from_millis(10))
34105            .on_worker_heartbeat(move |observation| {
34106                observed
34107                    .lock()
34108                    .expect("heartbeat observations")
34109                    .push(observation.clone());
34110            });
34111
34112        worker.register_workflow("snapshot", |ctx, _input| async move {
34113            ctx.wait_signal("finish").await?;
34114            Ok(json!({"status": "finished"}))
34115        });
34116        worker.register_query("snapshot", "current", |ctx, _args| async move {
34117            Ok(json!(ctx
34118                .signals("increment")
34119                .iter()
34120                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
34121                .sum::<i64>()))
34122        });
34123        worker.register_activity("cancel-aware", |_ctx, _args| async move {
34124            Ok(json!({"late": "completion"}))
34125        });
34126
34127        worker
34128            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
34129            .await
34130            .expect("delayed heartbeat must allow a clean worker shutdown");
34131
34132        let observations = observations.lock().expect("heartbeat observations");
34133        assert!(
34134            observations.len() >= 3,
34135            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
34136        );
34137        assert!(
34138            observations.windows(2).all(|pair| {
34139                pair[1].acknowledged_at_unix_millis
34140                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
34141                    >= 850
34142            }),
34143            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
34144        );
34145        drop(observations);
34146
34147        let heartbeat_times = server.request_times("/api/worker/heartbeat");
34148        let delayed_request_at = *heartbeat_times
34149            .get(1)
34150            .expect("intentionally delayed heartbeat request");
34151        let delay_window_start = delayed_request_at + Duration::from_millis(100);
34152        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
34153        for path in [
34154            "/api/worker/workflow-tasks/poll",
34155            "/api/worker/activity-tasks/poll",
34156            "/api/worker/query-tasks/poll",
34157        ] {
34158            assert!(
34159                server
34160                    .request_times(path)
34161                    .iter()
34162                    .any(|received_at| *received_at >= delay_window_start
34163                        && *received_at <= delay_window_end),
34164                "{path} must keep polling while a heartbeat acknowledgement is delayed"
34165            );
34166        }
34167        assert!(
34168            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
34169            "workflow work must be settled"
34170        );
34171        assert!(
34172            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
34173            "activity work must be settled"
34174        );
34175        assert!(
34176            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
34177            "query work must be settled"
34178        );
34179    }
34180
34181    #[tokio::test]
34182    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
34183        let server = MockWorkerServer::heartbeat_retry_worker();
34184        let client = Client::builder(server.base_url())
34185            .timeout(Duration::from_secs(2))
34186            .build()
34187            .expect("client");
34188        let observations = Arc::new(Mutex::new(Vec::new()));
34189        let observed = Arc::clone(&observations);
34190        let worker = Worker::new(client, "rust-workers")
34191            .worker_id("heartbeat-retry-worker")
34192            .retry_policy(WorkerRetryPolicy {
34193                max_retries: 1,
34194                initial_backoff: Duration::from_millis(300),
34195                max_backoff: Duration::from_millis(300),
34196            })
34197            .on_worker_heartbeat(move |observation| {
34198                observed
34199                    .lock()
34200                    .expect("heartbeat observations")
34201                    .push(observation.clone());
34202            });
34203
34204        worker
34205            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
34206            .await
34207            .expect("retryable heartbeat failure must remain bounded and recover");
34208
34209        let observations = observations.lock().expect("heartbeat observations");
34210        assert!(observations.len() >= 3, "heartbeat retry must recover");
34211        assert!(
34212            observations.windows(2).all(|pair| {
34213                pair[1]
34214                    .acknowledged_at_unix_millis
34215                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
34216                    >= 850
34217            }),
34218            "a successful retry must start a fresh advertised cadence: {observations:?}"
34219        );
34220        assert_eq!(
34221            server.request_count("/api/worker/heartbeat"),
34222            observations.len() + 1,
34223            "one retryable failure must add exactly one bounded request"
34224        );
34225    }
34226
34227    #[tokio::test]
34228    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
34229        let server = MockWorkerServer::waiting_query_worker();
34230        let client = Client::builder(server.base_url())
34231            .timeout(Duration::from_secs(2))
34232            .build()
34233            .expect("client");
34234        let observations = Arc::new(Mutex::new(Vec::new()));
34235        let observed = Arc::clone(&observations);
34236        let mut worker = Worker::new(client, "rust-snapshot-workers")
34237            .worker_id("rust-snapshot-worker")
34238            .poll_timeout(Duration::from_millis(10))
34239            .on_worker_heartbeat(move |observation| {
34240                observed
34241                    .lock()
34242                    .expect("heartbeat observations")
34243                    .push(observation.clone());
34244            });
34245
34246        worker.register_workflow("snapshot", |ctx, _input| async move {
34247            ctx.wait_signal("finish").await?;
34248            Ok(json!({"status": "finished"}))
34249        });
34250        worker.register_query("snapshot", "current", |ctx, _args| async move {
34251            let current = ctx
34252                .signals("increment")
34253                .iter()
34254                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
34255                .sum::<i64>();
34256            Ok(json!(current))
34257        });
34258        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
34259        worker
34260            .declare_workflow_signals("snapshot", &["finish"])
34261            .expect("declare finish signal");
34262
34263        worker
34264            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
34265            .await
34266            .expect("pending workflow and query poller must remain live until shutdown");
34267
34268        assert!(
34269            observations.lock().expect("heartbeat observations").len() >= 4,
34270            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
34271        );
34272        assert!(
34273            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
34274            "workflow polling must continue after empty replay acknowledgements"
34275        );
34276        assert!(
34277            server.request_count("/api/worker/query-tasks/poll") >= 2,
34278            "query polling must continue after serving the current query"
34279        );
34280        assert_eq!(
34281            server.request_body("/api/worker/register")["capabilities"],
34282            json!([
34283                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
34284                "workflow_entry_arguments_validation",
34285                DURABLE_SELECTION_CAPABILITY,
34286                MEMO_UPSERTS_CAPABILITY,
34287                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
34288                QUERY_TASKS_CAPABILITY,
34289                WORKFLOW_UPDATES_CAPABILITY,
34290                MESSAGE_STREAMS_CAPABILITY
34291            ])
34292        );
34293        assert_eq!(
34294            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
34295            json!({
34296                "queries": ["current"],
34297                "query_contracts": [{
34298                    "name": "current",
34299                    "parameters": [{
34300                        "name": "args", "position": 0, "required": false,
34301                        "variadic": true, "type": null, "allows_null": true,
34302                        "default_available": false, "default": null,
34303                    }],
34304                }],
34305                "signals": ["finish"],
34306                "signal_contracts": [{
34307                    "name": "finish",
34308                    "parameters": [{
34309                        "name": "args", "position": 0, "required": false,
34310                        "variadic": true, "type": null, "allows_null": true,
34311                        "default_available": false, "default": null,
34312                    }],
34313                }],
34314                "updates": ["replace"],
34315                "update_contracts": [{
34316                    "name": "replace",
34317                    "parameters": [{
34318                        "name": "args", "position": 0, "required": false,
34319                        "variadic": true, "type": null, "allows_null": true,
34320                        "default_available": false, "default": null,
34321                    }],
34322                }],
34323                "update_validators": [],
34324            })
34325        );
34326
34327        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
34328        assert_eq!(
34329            opened["commands"],
34330            json!([{
34331                "type": "open_signal_wait",
34332                "signal_name": "finish",
34333            }])
34334        );
34335
34336        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
34337            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
34338            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
34339            let failure = server.request_body(&fail_path);
34340            assert_eq!(
34341                failure["failure"]["type"],
34342                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
34343            );
34344            assert_eq!(server.request_count(&completion_path), 0);
34345        }
34346
34347        let query_completion =
34348            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
34349        assert_eq!(query_completion["result"], json!(8));
34350
34351        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
34352        assert_eq!(
34353            server.request_count(terminal_path),
34354            1,
34355            "the matching signal must settle the workflow exactly once"
34356        );
34357        let terminal = server.request_body(terminal_path);
34358        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
34359        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
34360        assert_eq!(
34361            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
34362                .expect("terminal workflow result"),
34363            json!({"status": "finished"})
34364        );
34365    }
34366
34367    #[tokio::test]
34368    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
34369        let server = MockWorkerServer::transient_worker_failures();
34370        let client = Client::builder(server.base_url())
34371            .timeout(Duration::from_secs(2))
34372            .build()
34373            .expect("client");
34374        let mut worker = Worker::new(client, "rust-workers")
34375            .max_concurrent_workflow_tasks(1)
34376            .max_concurrent_activity_tasks(1)
34377            .worker_id("retry-worker")
34378            .poll_timeout(Duration::from_millis(10))
34379            .retry_policy(WorkerRetryPolicy {
34380                max_retries: 2,
34381                initial_backoff: Duration::from_millis(1),
34382                max_backoff: Duration::from_millis(1),
34383            });
34384        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
34385        worker.register_activity(
34386            "counter.activity",
34387            |_ctx, _input| async move { Ok(Value::Null) },
34388        );
34389        worker.register_query(
34390            "counter",
34391            "current",
34392            |_ctx, _args| async move { Ok(json!(8)) },
34393        );
34394
34395        worker
34396            .run_until(tokio::time::sleep(Duration::from_millis(75)))
34397            .await
34398            .expect("transient failures must not stop the worker");
34399
34400        for path in [
34401            "/api/worker/heartbeat",
34402            "/api/worker/workflow-tasks/poll",
34403            "/api/worker/activity-tasks/poll",
34404            "/api/worker/query-tasks/poll",
34405        ] {
34406            assert!(
34407                server.request_count(path) >= 2,
34408                "{path} must continue after its transient failure"
34409            );
34410        }
34411    }
34412
34413    #[tokio::test]
34414    async fn worker_continues_after_long_poll_capacity_backpressure() {
34415        let server = MockWorkerServer::capacity_limited_activity_poll();
34416        let client = Client::builder(server.base_url())
34417            .timeout(Duration::from_secs(2))
34418            .build()
34419            .expect("client");
34420        let mut worker = Worker::new(client, "rust-workers")
34421            .worker_id("capacity-worker")
34422            .poll_timeout(Duration::from_millis(10))
34423            .retry_policy(WorkerRetryPolicy {
34424                max_retries: 0,
34425                initial_backoff: Duration::from_millis(1),
34426                max_backoff: Duration::from_millis(1),
34427            });
34428        worker.register_activity("capacity.activity", |_ctx, _input| async move {
34429            Ok(json!({"handled": true}))
34430        });
34431
34432        worker
34433            .run_until(tokio::time::sleep(Duration::from_millis(50)))
34434            .await
34435            .expect("capacity backpressure must not stop the worker");
34436
34437        assert!(
34438            server.request_count("/api/worker/activity-tasks/poll") >= 2,
34439            "the activity poller must continue after capacity backpressure"
34440        );
34441        assert_eq!(
34442            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
34443            1,
34444            "the worker must complete work returned after capacity recovers"
34445        );
34446    }
34447
34448    #[test]
34449    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
34450        let capacity = Error::Http {
34451            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
34452            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
34453        };
34454        assert_eq!(
34455            worker_poll_capacity_retry_after(&capacity),
34456            Some(Duration::from_secs(3))
34457        );
34458
34459        let rejected_capacity = Error::Http {
34460            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
34461            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
34462        };
34463        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
34464        assert!(!worker_operation_is_retryable(&rejected_capacity));
34465
34466        let ordinary_rate_limit = Error::Http {
34467            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
34468            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
34469                .to_string(),
34470        };
34471        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
34472        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
34473    }
34474
34475    #[tokio::test]
34476    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
34477        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
34478            poll_failures_per_path: 8,
34479            heartbeat_failures: 8,
34480            ..MockWorkerBehavior::default()
34481        });
34482        let client = Client::builder(server.base_url())
34483            .timeout(Duration::from_secs(2))
34484            .build()
34485            .expect("client");
34486        let acknowledgements = Arc::new(AtomicUsize::new(0));
34487        let observed = Arc::clone(&acknowledgements);
34488        let mut worker = Worker::new(client, "rust-workers")
34489            .max_concurrent_workflow_tasks(1)
34490            .max_concurrent_activity_tasks(1)
34491            .recover_transient_outages(true)
34492            .poll_timeout(Duration::from_millis(10))
34493            .retry_policy(WorkerRetryPolicy {
34494                max_retries: 2,
34495                initial_backoff: Duration::from_millis(2),
34496                max_backoff: Duration::from_millis(5),
34497            })
34498            .on_worker_heartbeat(move |_| {
34499                observed.fetch_add(1, Ordering::SeqCst);
34500            });
34501        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
34502        worker.register_activity(
34503            "counter.activity",
34504            |_ctx, _input| async move { Ok(Value::Null) },
34505        );
34506        worker.register_query("counter", "current", |_ctx, _args| async move {
34507            Ok(Value::Null)
34508        });
34509
34510        worker
34511            .run_until(tokio::time::sleep(Duration::from_millis(500)))
34512            .await
34513            .expect("a recoverable outage must not stop the service worker");
34514
34515        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
34516        assert_eq!(server.request_count("/api/worker/heartbeat"), 9);
34517        for path in [
34518            "/api/worker/workflow-tasks/poll",
34519            "/api/worker/activity-tasks/poll",
34520            "/api/worker/query-tasks/poll",
34521        ] {
34522            let bodies = server.request_bodies(path);
34523            assert!(bodies.len() >= 10, "{path} must resume after recovery");
34524            let first = &bodies[0]["poll_request_id"];
34525            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
34526            for body in &bodies[..9] {
34527                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
34528            }
34529            assert_ne!(&bodies[9]["poll_request_id"], first);
34530            let times = server.request_times(path);
34531            for pair in times[..9].windows(2) {
34532                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
34533            }
34534        }
34535    }
34536
34537    #[tokio::test]
34538    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
34539        for heartbeat_outage in [false, true] {
34540            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
34541                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
34542                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
34543                ..MockWorkerBehavior::default()
34544            });
34545            let client = Client::builder(server.base_url()).build().expect("client");
34546            let mut worker = Worker::new(client, "rust-workers")
34547                .max_concurrent_workflow_tasks(1)
34548                .max_concurrent_activity_tasks(1)
34549                .recover_transient_outages(true)
34550                .retry_policy(WorkerRetryPolicy {
34551                    max_retries: 1,
34552                    initial_backoff: Duration::from_secs(5),
34553                    max_backoff: Duration::from_secs(5),
34554                });
34555            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
34556            let started = Instant::now();
34557            worker
34558                .run_until(tokio::time::sleep(Duration::from_millis(200)))
34559                .await
34560                .expect("shutdown during an outage is a normal stop");
34561            assert!(started.elapsed() < Duration::from_secs(1));
34562            let path = if heartbeat_outage {
34563                "/api/worker/heartbeat"
34564            } else {
34565                "/api/worker/workflow-tasks/poll"
34566            };
34567            assert_eq!(server.request_count(path), 1);
34568            assert_eq!(
34569                server.request_count("/api/worker/registrations/mock-worker"),
34570                1
34571            );
34572        }
34573    }
34574
34575    #[tokio::test]
34576    async fn worker_outage_recovery_keeps_run_once_bounded() {
34577        let server = MockWorkerServer::unavailable_polls();
34578        let client = Client::builder(server.base_url()).build().expect("client");
34579        let mut worker = Worker::new(client, "rust-workers")
34580            .recover_transient_outages(true)
34581            .retry_policy(WorkerRetryPolicy {
34582                max_retries: 2,
34583                initial_backoff: Duration::from_millis(1),
34584                max_backoff: Duration::from_millis(1),
34585            });
34586        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
34587        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
34588        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
34589    }
34590
34591    #[tokio::test]
34592    async fn worker_outage_recovery_respects_disabled_retries() {
34593        let server = MockWorkerServer::unavailable_polls();
34594        let client = Client::builder(server.base_url()).build().expect("client");
34595        let mut worker = Worker::new(client, "rust-workers")
34596            .max_concurrent_workflow_tasks(1)
34597            .max_concurrent_activity_tasks(1)
34598            .recover_transient_outages(true)
34599            .retry_policy(WorkerRetryPolicy {
34600                max_retries: 0,
34601                ..WorkerRetryPolicy::default()
34602            });
34603        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
34604        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
34605        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
34606    }
34607
34608    #[tokio::test]
34609    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
34610        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
34611            heartbeat_failures: usize::MAX,
34612            unauthorized_polls: true,
34613            ..MockWorkerBehavior::default()
34614        });
34615        let client = Client::builder(server.base_url()).build().expect("client");
34616        let mut worker = Worker::new(client, "rust-workers")
34617            .max_concurrent_workflow_tasks(1)
34618            .max_concurrent_activity_tasks(1)
34619            .recover_transient_outages(true)
34620            .retry_policy(WorkerRetryPolicy {
34621                max_retries: 1,
34622                initial_backoff: Duration::from_secs(5),
34623                max_backoff: Duration::from_secs(5),
34624            });
34625        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
34626        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
34627            .await
34628            .expect("fatal poll errors must interrupt heartbeat recovery")
34629            .expect_err("authentication failure is terminal");
34630        assert!(
34631            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
34632        );
34633        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
34634    }
34635
34636    #[tokio::test]
34637    async fn worker_bounds_transport_retries() {
34638        let server = MockWorkerServer::unavailable_polls();
34639        let client = Client::builder(server.base_url())
34640            .timeout(Duration::from_secs(2))
34641            .build()
34642            .expect("client");
34643        let mut worker = Worker::new(client, "rust-workers")
34644            .max_concurrent_workflow_tasks(1)
34645            .max_concurrent_activity_tasks(1)
34646            .worker_id("bounded-retry-worker")
34647            .poll_timeout(Duration::from_millis(10))
34648            .retry_policy(WorkerRetryPolicy {
34649                max_retries: 2,
34650                initial_backoff: Duration::from_millis(1),
34651                max_backoff: Duration::from_millis(1),
34652            });
34653        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
34654
34655        let error = worker.run().await.expect_err("retry bound must terminate");
34656        assert!(matches!(error, Error::Transport(_)));
34657        assert_eq!(
34658            server.request_count("/api/worker/workflow-tasks/poll"),
34659            3,
34660            "one initial request plus exactly two retries"
34661        );
34662    }
34663
34664    #[tokio::test]
34665    async fn worker_retry_policy_can_disable_poll_retries() {
34666        let server = MockWorkerServer::unavailable_polls();
34667        let client = Client::builder(server.base_url())
34668            .timeout(Duration::from_secs(2))
34669            .build()
34670            .expect("client");
34671        let mut worker = Worker::new(client, "rust-workers")
34672            .worker_id("no-retry-worker")
34673            .poll_timeout(Duration::from_millis(10))
34674            .retry_policy(WorkerRetryPolicy {
34675                max_retries: 0,
34676                initial_backoff: Duration::from_millis(1),
34677                max_backoff: Duration::from_millis(1),
34678            });
34679        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
34680
34681        let error = worker
34682            .run_once()
34683            .await
34684            .expect_err("disabled retries must return the first transport failure");
34685        assert!(matches!(error, Error::Transport(_)));
34686        assert_eq!(
34687            server.request_count("/api/worker/workflow-tasks/poll"),
34688            1,
34689            "max_retries=0 must send only the initial request"
34690        );
34691    }
34692
34693    #[tokio::test]
34694    async fn worker_does_not_retry_authentication_failures() {
34695        let server = MockWorkerServer::unauthorized_polls();
34696        let client = Client::builder(server.base_url())
34697            .timeout(Duration::from_secs(2))
34698            .build()
34699            .expect("client");
34700        let mut worker = Worker::new(client, "rust-workers")
34701            .max_concurrent_workflow_tasks(1)
34702            .max_concurrent_activity_tasks(1)
34703            .worker_id("unauthorized-worker")
34704            .recover_transient_outages(true)
34705            .poll_timeout(Duration::from_millis(10));
34706        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
34707
34708        let error = worker
34709            .run()
34710            .await
34711            .expect_err("authentication must terminate");
34712        let Error::Http { status, body } = error else {
34713            panic!("expected stable HTTP authentication error");
34714        };
34715        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
34716        assert!(body.contains("authentication_failed"));
34717        assert_eq!(
34718            server.request_count("/api/worker/workflow-tasks/poll"),
34719            1,
34720            "authentication failures must not be retried"
34721        );
34722    }
34723
34724    #[test]
34725    fn duplicate_registration_keeps_the_original_workflow() {
34726        let client = Client::new("http://127.0.0.1:9").expect("client");
34727        let mut worker = Worker::new(client, "registration-tests");
34728        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
34729        let original = Arc::clone(&worker.workflows["same"].execute);
34730        worker
34731            .set_workflow_definition_sources("same", &["first workflow source"])
34732            .expect("source identity");
34733        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
34734        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
34735        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
34736        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
34737    }
34738
34739    #[test]
34740    fn duplicate_registration_keeps_the_original_activity() {
34741        let client = Client::new("http://127.0.0.1:9").expect("client");
34742        let mut worker = Worker::new(client, "registration-tests");
34743        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
34744        let original = Arc::clone(&worker.activities["same"]);
34745        worker.register_activity_avro_value("same", |_ctx, _input| async {
34746            Ok(AvroValue::String("second".into()))
34747        });
34748        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
34749    }
34750
34751    #[test]
34752    fn duplicate_registration_keeps_original_query_and_update_handlers() {
34753        let client = Client::new("http://127.0.0.1:9").expect("client");
34754        let mut worker = Worker::new(client, "registration-tests");
34755        worker.register_query("orders", "same", |_ctx, _input| async {
34756            Ok(json!("first"))
34757        });
34758        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
34759            panic!("snapshot query");
34760        };
34761        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
34762            Ok(json!("second"))
34763        });
34764        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
34765            panic!("duplicate replaced the query adapter");
34766        };
34767        assert!(Arc::ptr_eq(&original, retained));
34768        worker.register_update("orders", "same", |_ctx, _input| async {
34769            Ok(json!("first"))
34770        });
34771        let original = Arc::clone(&worker.updates["orders"]["same"]);
34772        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
34773            Ok(AvroValue::Null)
34774        });
34775        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
34776    }
34777
34778    #[tokio::test]
34779    async fn duplicate_registration_fails_before_server_contact() {
34780        let server = MockWorkerServer::start();
34781        let client = Client::builder(server.base_url()).build().expect("client");
34782        let mut worker =
34783            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
34784        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
34785        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
34786        let error = worker
34787            .run_once()
34788            .await
34789            .expect_err("ambiguous worker must not poll");
34790        assert!(
34791            error.to_string().contains("duplicate_registration"),
34792            "{error}"
34793        );
34794        assert!(server.requests.lock().expect("requests").is_empty());
34795    }
34796
34797    #[derive(Clone, Debug)]
34798    struct CapturedRequest {
34799        headers: String,
34800        method: String,
34801        path: String,
34802        authorization: Option<String>,
34803        namespace: Option<String>,
34804        worker_protocol: Option<String>,
34805        control_protocol: Option<String>,
34806        body: String,
34807        received_at: Instant,
34808    }
34809
34810    struct MockWorkerServer {
34811        addr: SocketAddr,
34812        stop: Arc<AtomicBool>,
34813        requests: Arc<Mutex<Vec<CapturedRequest>>>,
34814        thread: Option<thread::JoinHandle<()>>,
34815    }
34816
34817    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
34818
34819    #[derive(Clone, Copy, Default)]
34820    struct MockWorkerBehavior {
34821        response_override: Option<fn(&str) -> Option<(&'static str, String)>>,
34822        request_override: Option<RequestOverride>,
34823        /// Close the connection after reading the request, without any response.
34824        drop_request: Option<fn(&str, usize) -> bool>,
34825        storage_refusals: usize,
34826        storage_path: Option<&'static str>,
34827        storage_unavailable: bool,
34828        storage_mid_poll: bool,
34829        storage_activity: bool,
34830        storage_query: bool,
34831        storage_wrong_poll_id: bool,
34832        reject_query_protocol: bool,
34833        reject_query_completion: bool,
34834        waiting_query_worker: bool,
34835        decline_registration: bool,
34836        complete_named_signal: bool,
34837        poll_failures_per_path: usize,
34838        long_poll_capacity_responses_per_path: usize,
34839        heartbeat_failures: usize,
34840        heartbeat_failure_request: Option<usize>,
34841        delayed_heartbeat_request: Option<usize>,
34842        heartbeat_response_delay: Duration,
34843        concurrent_requests: bool,
34844        unauthorized_polls: bool,
34845        reject_registration: bool,
34846        reject_registration_protocol: bool,
34847        reject_deregistration: bool,
34848        reject_deregistration_protocol: bool,
34849        cancelled_activity: bool,
34850        draining_polls: bool,
34851        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
34852        workflow_completion_status: Option<&'static str>,
34853        workflow_completion_body: Option<&'static str>,
34854    }
34855
34856    impl MockWorkerServer {
34857        fn start() -> Self {
34858            Self::start_with_behavior(MockWorkerBehavior::default())
34859        }
34860
34861        fn reject_query_protocol() -> Self {
34862            Self::start_with_behavior(MockWorkerBehavior {
34863                reject_query_protocol: true,
34864                ..MockWorkerBehavior::default()
34865            })
34866        }
34867
34868        fn reject_query_completion() -> Self {
34869            Self::start_with_behavior(MockWorkerBehavior {
34870                reject_query_completion: true,
34871                ..MockWorkerBehavior::default()
34872            })
34873        }
34874
34875        fn waiting_query_worker() -> Self {
34876            Self::start_with_behavior(MockWorkerBehavior {
34877                waiting_query_worker: true,
34878                complete_named_signal: true,
34879                ..MockWorkerBehavior::default()
34880            })
34881        }
34882
34883        fn transient_worker_failures() -> Self {
34884            Self::start_with_behavior(MockWorkerBehavior {
34885                poll_failures_per_path: 1,
34886                heartbeat_failures: 1,
34887                ..MockWorkerBehavior::default()
34888            })
34889        }
34890
34891        fn consecutive_poll_failures(count: usize) -> Self {
34892            Self::start_with_behavior(MockWorkerBehavior {
34893                poll_failures_per_path: count,
34894                ..MockWorkerBehavior::default()
34895            })
34896        }
34897
34898        fn capacity_limited_activity_poll() -> Self {
34899            Self::start_with_behavior(MockWorkerBehavior {
34900                long_poll_capacity_responses_per_path: 1,
34901                ..MockWorkerBehavior::default()
34902            })
34903        }
34904
34905        fn delayed_heartbeat_worker() -> Self {
34906            Self::start_with_behavior(MockWorkerBehavior {
34907                waiting_query_worker: true,
34908                delayed_heartbeat_request: Some(2),
34909                heartbeat_response_delay: Duration::from_millis(1_500),
34910                concurrent_requests: true,
34911                cancelled_activity: true,
34912                ..MockWorkerBehavior::default()
34913            })
34914        }
34915
34916        fn heartbeat_retry_worker() -> Self {
34917            Self::start_with_behavior(MockWorkerBehavior {
34918                waiting_query_worker: true,
34919                heartbeat_failure_request: Some(2),
34920                concurrent_requests: true,
34921                ..MockWorkerBehavior::default()
34922            })
34923        }
34924
34925        fn unavailable_polls() -> Self {
34926            Self::start_with_behavior(MockWorkerBehavior {
34927                poll_failures_per_path: usize::MAX,
34928                ..MockWorkerBehavior::default()
34929            })
34930        }
34931
34932        fn unauthorized_polls() -> Self {
34933            Self::start_with_behavior(MockWorkerBehavior {
34934                unauthorized_polls: true,
34935                ..MockWorkerBehavior::default()
34936            })
34937        }
34938
34939        fn rejected_registration() -> Self {
34940            Self::start_with_behavior(MockWorkerBehavior {
34941                reject_registration: true,
34942                ..MockWorkerBehavior::default()
34943            })
34944        }
34945
34946        fn rejected_registration_protocol() -> Self {
34947            Self::start_with_behavior(MockWorkerBehavior {
34948                reject_registration_protocol: true,
34949                ..MockWorkerBehavior::default()
34950            })
34951        }
34952
34953        fn declined_registration() -> Self {
34954            Self::start_with_behavior(MockWorkerBehavior {
34955                decline_registration: true,
34956                ..MockWorkerBehavior::default()
34957            })
34958        }
34959
34960        fn rejected_deregistration() -> Self {
34961            Self::start_with_behavior(MockWorkerBehavior {
34962                reject_deregistration: true,
34963                ..MockWorkerBehavior::default()
34964            })
34965        }
34966
34967        fn rejected_deregistration_protocol() -> Self {
34968            Self::start_with_behavior(MockWorkerBehavior {
34969                reject_deregistration_protocol: true,
34970                ..MockWorkerBehavior::default()
34971            })
34972        }
34973
34974        fn unauthorized_polls_and_rejected_deregistration() -> Self {
34975            Self::start_with_behavior(MockWorkerBehavior {
34976                unauthorized_polls: true,
34977                reject_deregistration: true,
34978                ..MockWorkerBehavior::default()
34979            })
34980        }
34981
34982        fn cancelled_activity() -> Self {
34983            Self::start_with_behavior(MockWorkerBehavior {
34984                cancelled_activity: true,
34985                ..MockWorkerBehavior::default()
34986            })
34987        }
34988
34989        fn draining_polls() -> Self {
34990            Self::start_with_behavior(MockWorkerBehavior {
34991                draining_polls: true,
34992                ..MockWorkerBehavior::default()
34993            })
34994        }
34995
34996        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
34997            Self::start_with_behavior(MockWorkerBehavior {
34998                invalid_task_payload_codec: Some(codec),
34999                ..MockWorkerBehavior::default()
35000            })
35001        }
35002
35003        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
35004            Self::start_with_behavior(MockWorkerBehavior {
35005                workflow_completion_status: Some(status),
35006                workflow_completion_body: Some(body),
35007                ..MockWorkerBehavior::default()
35008            })
35009        }
35010
35011        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
35012            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
35013            listener
35014                .set_nonblocking(true)
35015                .expect("configure mock listener");
35016            let addr = listener.local_addr().expect("mock server address");
35017            let stop = Arc::new(AtomicBool::new(false));
35018            let server_stop = Arc::clone(&stop);
35019            let requests = Arc::new(Mutex::new(Vec::new()));
35020            let server_requests = Arc::clone(&requests);
35021            let thread = thread::spawn(move || {
35022                let mut request_threads = Vec::new();
35023                while !server_stop.load(Ordering::SeqCst) {
35024                    match listener.accept() {
35025                        Ok((mut stream, _)) => {
35026                            // macOS/BSD accepted sockets inherit the listener's O_NONBLOCK.
35027                            let _ = stream.set_nonblocking(false);
35028                            let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
35029                            if behavior.concurrent_requests {
35030                                let requests = Arc::clone(&server_requests);
35031                                request_threads.push(thread::spawn(move || {
35032                                    handle_mock_worker_request(&mut stream, &requests, behavior)
35033                                }));
35034                            } else {
35035                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
35036                            }
35037                        }
35038                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
35039                            let mut index = 0;
35040                            while index < request_threads.len() {
35041                                if request_threads[index].is_finished() {
35042                                    request_threads
35043                                        .swap_remove(index)
35044                                        .join()
35045                                        .expect("join mock request");
35046                                } else {
35047                                    index += 1;
35048                                }
35049                            }
35050                            thread::sleep(Duration::from_millis(5));
35051                        }
35052                        Err(_) => break,
35053                    }
35054                }
35055                for request_thread in request_threads {
35056                    request_thread.join().expect("join mock request");
35057                }
35058            });
35059
35060            Self {
35061                addr,
35062                stop,
35063                requests,
35064                thread: Some(thread),
35065            }
35066        }
35067
35068        fn base_url(&self) -> String {
35069            format!("http://{}", self.addr)
35070        }
35071
35072        fn worker_protocol_for(&self, path: &str) -> Option<String> {
35073            self.requests
35074                .lock()
35075                .expect("captured requests")
35076                .iter()
35077                .find(|request| request.path == path)
35078                .and_then(|request| request.worker_protocol.clone())
35079        }
35080
35081        fn control_protocol_for(&self, path: &str) -> Option<String> {
35082            self.requests
35083                .lock()
35084                .expect("captured requests")
35085                .iter()
35086                .find(|request| request.path == path)
35087                .and_then(|request| request.control_protocol.clone())
35088        }
35089
35090        fn method_for(&self, path: &str) -> Option<String> {
35091            self.requests
35092                .lock()
35093                .expect("captured requests")
35094                .iter()
35095                .find(|request| request.path == path)
35096                .map(|request| request.method.clone())
35097        }
35098
35099        fn authorization_for(&self, path: &str) -> Option<String> {
35100            self.requests
35101                .lock()
35102                .expect("captured requests")
35103                .iter()
35104                .find(|request| request.path == path)
35105                .and_then(|request| request.authorization.clone())
35106        }
35107
35108        fn namespace_for(&self, path: &str) -> Option<String> {
35109            self.requests
35110                .lock()
35111                .expect("captured requests")
35112                .iter()
35113                .find(|request| request.path == path)
35114                .and_then(|request| request.namespace.clone())
35115        }
35116
35117        fn request_count(&self, path: &str) -> usize {
35118            self.requests
35119                .lock()
35120                .expect("captured requests")
35121                .iter()
35122                .filter(|request| request.path == path)
35123                .count()
35124        }
35125
35126        fn captured_paths(&self) -> Vec<String> {
35127            self.requests
35128                .lock()
35129                .expect("captured requests")
35130                .iter()
35131                .map(|request| request.path.clone())
35132                .collect()
35133        }
35134
35135        fn request_times(&self, path: &str) -> Vec<Instant> {
35136            self.requests
35137                .lock()
35138                .expect("captured requests")
35139                .iter()
35140                .filter(|request| request.path == path)
35141                .map(|request| request.received_at)
35142                .collect()
35143        }
35144
35145        fn request_body(&self, path: &str) -> Value {
35146            let requests = self.requests.lock().expect("captured requests");
35147            let body = &requests
35148                .iter()
35149                .find(|request| request.path == path)
35150                .unwrap_or_else(|| panic!("missing request for {path}"))
35151                .body;
35152            serde_json::from_str(body).unwrap_or_else(|error| {
35153                panic!("invalid JSON request body for {path}: {error}: {body:?}")
35154            })
35155        }
35156
35157        fn request_bodies(&self, path: &str) -> Vec<Value> {
35158            self.requests
35159                .lock()
35160                .expect("captured requests")
35161                .iter()
35162                .filter(|request| request.path == path)
35163                .map(|request| {
35164                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
35165                        panic!(
35166                            "invalid JSON request body for {path}: {error}: {:?}",
35167                            request.body
35168                        )
35169                    })
35170                })
35171                .collect()
35172        }
35173
35174        fn request_headers(&self, path: &str) -> Vec<String> {
35175            self.requests
35176                .lock()
35177                .expect("captured requests")
35178                .iter()
35179                .filter(|request| request.path == path)
35180                .map(|request| request.headers.clone())
35181                .collect()
35182        }
35183    }
35184
35185    impl Drop for MockWorkerServer {
35186        fn drop(&mut self) {
35187            self.stop.store(true, Ordering::SeqCst);
35188            let _ = TcpStream::connect(self.addr);
35189
35190            if let Some(thread) = self.thread.take() {
35191                thread.join().expect("join mock server");
35192            }
35193        }
35194    }
35195
35196    #[test]
35197    fn closed_mock_connection_is_not_a_worker_request() {
35198        let listener = TcpListener::bind("127.0.0.1:0").expect("bind closed connection control");
35199        let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
35200        let (mut stream, _) = listener.accept().unwrap();
35201        drop(client);
35202        let requests = Arc::new(Mutex::new(Vec::new()));
35203        handle_mock_worker_request(
35204            &mut stream,
35205            &requests,
35206            MockWorkerBehavior {
35207                request_override: Some(|_, _, _| {
35208                    panic!("closed connection cannot invoke an HTTP handler")
35209                }),
35210                ..MockWorkerBehavior::default()
35211            },
35212        );
35213        assert!(requests.lock().unwrap().is_empty());
35214    }
35215
35216    fn handle_mock_worker_request(
35217        stream: &mut TcpStream,
35218        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
35219        behavior: MockWorkerBehavior,
35220    ) {
35221        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
35222        let mut buffer = [0_u8; 8192];
35223        let mut request = Vec::new();
35224
35225        loop {
35226            match stream.read(&mut buffer) {
35227                Ok(0) => break,
35228                Ok(read) => {
35229                    request.extend_from_slice(&buffer[..read]);
35230                    if mock_request_is_complete(&request) {
35231                        break;
35232                    }
35233                }
35234                Err(error)
35235                    if matches!(
35236                        error.kind(),
35237                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
35238                    ) =>
35239                {
35240                    break;
35241                }
35242                Err(_) => return,
35243            }
35244        }
35245
35246        if !mock_request_is_complete(&request) {
35247            return;
35248        }
35249
35250        let request = String::from_utf8_lossy(&request);
35251        let body = request
35252            .split_once("\r\n\r\n")
35253            .map(|(_, body)| body)
35254            .unwrap_or_default();
35255        let path = request
35256            .lines()
35257            .next()
35258            .and_then(|line| line.split_whitespace().nth(1))
35259            .unwrap_or_default();
35260        let method = request
35261            .lines()
35262            .next()
35263            .and_then(|line| line.split_whitespace().next())
35264            .unwrap_or_default();
35265        let authorization = request.lines().find_map(|line| {
35266            let (name, value) = line.split_once(':')?;
35267            name.eq_ignore_ascii_case("Authorization")
35268                .then(|| value.trim().to_string())
35269        });
35270        let namespace = request.lines().find_map(|line| {
35271            let (name, value) = line.split_once(':')?;
35272            name.eq_ignore_ascii_case("X-Namespace")
35273                .then(|| value.trim().to_string())
35274        });
35275        let worker_protocol = request.lines().find_map(|line| {
35276            let (name, value) = line.split_once(':')?;
35277            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
35278                .then(|| value.trim().to_string())
35279        });
35280        let control_protocol = request.lines().find_map(|line| {
35281            let (name, value) = line.split_once(':')?;
35282            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
35283                .then(|| value.trim().to_string())
35284        });
35285        let request_number = {
35286            let mut requests = requests.lock().expect("captured requests");
35287            requests.push(CapturedRequest {
35288                headers: request
35289                    .split_once("\r\n\r\n")
35290                    .map_or("", |(headers, _)| headers)
35291                    .to_owned(),
35292                method: method.to_string(),
35293                path: path.to_string(),
35294                authorization,
35295                namespace,
35296                worker_protocol: worker_protocol.clone(),
35297                control_protocol,
35298                body: body.to_string(),
35299                received_at: Instant::now(),
35300            });
35301            requests
35302                .iter()
35303                .filter(|request| request.path == path)
35304                .count()
35305        };
35306
35307        if behavior
35308            .drop_request
35309            .is_some_and(|dropped| dropped(path, request_number))
35310        {
35311            return;
35312        }
35313        if let Some(response) = behavior
35314            .request_override
35315            .and_then(|handler| handler(path, body, request_number))
35316        {
35317            write_mock_response(stream, response.0, &response.1);
35318            return;
35319        }
35320        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
35321            write_mock_response(stream, response.0, &response.1);
35322            return;
35323        }
35324        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
35325            return;
35326        }
35327        let pressure_path = behavior
35328            .storage_path
35329            .is_some_and(|part| path.contains(part));
35330        let prior_failures = if path.ends_with("/poll") {
35331            behavior.poll_failures_per_path
35332        } else {
35333            0
35334        };
35335        if pressure_path
35336            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
35337        {
35338            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
35339            let poll_id = path
35340                .ends_with("/poll")
35341                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
35342            let mut refusal = storage_refusal(
35343                poll_id,
35344                behavior.storage_unavailable,
35345                behavior.storage_mid_poll,
35346            );
35347            if behavior.storage_wrong_poll_id {
35348                refusal["poll_request_id"] = json!("wrong-poll");
35349            }
35350            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
35351            return;
35352        }
35353        if path.contains("/storage-task/")
35354            || path.contains("/storage-activity/")
35355            || path.contains("/storage-query/")
35356        {
35357            write_mock_response(stream, "200 OK", "{}");
35358            return;
35359        }
35360        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
35361            write_mock_response(stream, "200 OK", &json!({"task":{
35362                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
35363                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
35364                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
35365                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
35366                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
35367            }}).to_string());
35368            return;
35369        }
35370        if behavior.storage_activity
35371            && path == "/api/worker/activity-tasks/poll"
35372            && request_number == 1
35373        {
35374            write_mock_response(stream, "200 OK", &json!({"task":{
35375                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
35376                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
35377                "attempt_number":7, "lease_owner":"storage-worker"
35378            }}).to_string());
35379            return;
35380        }
35381
35382        if path == "/api/worker/register" {
35383            if behavior.reject_registration_protocol {
35384                write_mock_response(
35385                    stream,
35386                    "400 Bad Request",
35387                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
35388                );
35389                return;
35390            }
35391            if behavior.reject_registration {
35392                write_mock_response(
35393                    stream,
35394                    "503 Service Unavailable",
35395                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
35396                );
35397                return;
35398            }
35399        }
35400
35401        if path.starts_with("/api/worker/registrations/") {
35402            if behavior.reject_deregistration_protocol {
35403                write_mock_response(
35404                    stream,
35405                    "400 Bad Request",
35406                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
35407                );
35408            } else if behavior.reject_deregistration {
35409                write_mock_response(
35410                    stream,
35411                    "403 Forbidden",
35412                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
35413                );
35414            } else {
35415                write_mock_response(
35416                    stream,
35417                    "200 OK",
35418                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
35419                );
35420            }
35421            return;
35422        }
35423
35424        let is_poll = matches!(
35425            path,
35426            "/api/worker/workflow-tasks/poll"
35427                | "/api/worker/activity-tasks/poll"
35428                | "/api/worker/query-tasks/poll"
35429        );
35430        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
35431            write_mock_response(
35432                stream,
35433                "429 Too Many Requests",
35434                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
35435            );
35436            return;
35437        }
35438        if is_poll && request_number <= behavior.poll_failures_per_path {
35439            return;
35440        }
35441        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
35442            return;
35443        }
35444        if path == "/api/worker/heartbeat"
35445            && behavior.heartbeat_failure_request == Some(request_number)
35446        {
35447            return;
35448        }
35449        if path == "/api/worker/heartbeat"
35450            && behavior.delayed_heartbeat_request == Some(request_number)
35451        {
35452            thread::sleep(behavior.heartbeat_response_delay);
35453        }
35454        if behavior.unauthorized_polls && is_poll {
35455            write_mock_response(
35456                stream,
35457                "401 Unauthorized",
35458                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
35459            );
35460            return;
35461        }
35462        if behavior.draining_polls && is_poll {
35463            write_mock_response(
35464                stream,
35465                "409 Conflict",
35466                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
35467            );
35468            return;
35469        }
35470
35471        if let Some(codec_case) = behavior.invalid_task_payload_codec {
35472            if is_poll && request_number == 1 {
35473                let mut task = match path {
35474                    "/api/worker/workflow-tasks/poll" => json!({
35475                        "task_id": "codec-workflow",
35476                        "workflow_type": "codec.workflow",
35477                        "payload_codec": DEFAULT_CODEC,
35478                        "workflow_task_attempt": 1,
35479                        "lease_owner": "codec-worker"
35480                    }),
35481                    "/api/worker/activity-tasks/poll" => json!({
35482                        "task_id": "codec-activity",
35483                        "activity_attempt_id": "codec-activity-attempt",
35484                        "activity_type": "codec.activity",
35485                        "payload_codec": DEFAULT_CODEC,
35486                        "attempt_number": 1,
35487                        "lease_owner": "codec-worker"
35488                    }),
35489                    "/api/worker/query-tasks/poll" => json!({
35490                        "query_task_id": "codec-query",
35491                        "query_task_attempt": 1,
35492                        "workflow_type": "codec.workflow",
35493                        "query_name": "known",
35494                        "payload_codec": DEFAULT_CODEC,
35495                        "lease_owner": "codec-worker"
35496                    }),
35497                    _ => unreachable!("is_poll limits task codec probe paths"),
35498                };
35499                codec_case.apply(&mut task);
35500                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
35501                return;
35502            }
35503
35504            if matches!(
35505                path,
35506                "/api/worker/workflow-tasks/codec-workflow/fail"
35507                    | "/api/worker/activity-tasks/codec-activity/fail"
35508                    | "/api/worker/query-tasks/codec-query/fail"
35509            ) {
35510                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
35511                return;
35512            }
35513        }
35514
35515        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
35516            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
35517            let body = format!(
35518                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
35519            );
35520            write_mock_response(stream, "400 Bad Request", &body);
35521            return;
35522        }
35523
35524        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
35525        {
35526            write_mock_response(
35527                stream,
35528                "409 Conflict",
35529                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
35530            );
35531            return;
35532        }
35533
35534        if behavior.workflow_completion_status.is_some()
35535            && path == "/api/worker/workflow-tasks/poll"
35536            && request_number == 1
35537        {
35538            write_mock_response(
35539                stream,
35540                "200 OK",
35541                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"}}"#,
35542            );
35543            return;
35544        }
35545
35546        if matches!(
35547            path,
35548            "/api/worker/workflow-tasks/workflow-timeout-task/complete"
35549                | "/api/worker/workflow-tasks/workflow-timeout-task/fail"
35550        ) {
35551            if let (Some(status), Some(body)) = (
35552                behavior.workflow_completion_status,
35553                behavior.workflow_completion_body,
35554            ) {
35555                write_mock_response(stream, status, body);
35556                return;
35557            }
35558        }
35559
35560        if behavior.waiting_query_worker {
35561            if behavior.complete_named_signal
35562                && path == "/api/worker/workflow-tasks/poll"
35563                && request_number == 1
35564            {
35565                let body = json!({
35566                    "task": {
35567                        "task_id": "snapshot-open",
35568                        "workflow_id": "snapshot-1",
35569                        "run_id": "snapshot-run-1",
35570                        "workflow_type": "snapshot",
35571                        "payload_codec": DEFAULT_CODEC,
35572                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
35573                            .expect("Avro workflow arguments"),
35574                        "history_events": [],
35575                        "workflow_task_attempt": 1,
35576                        "lease_owner": "rust-snapshot-worker"
35577                    }
35578                })
35579                .to_string();
35580                write_mock_response(stream, "200 OK", &body);
35581                return;
35582            }
35583
35584            let signal_request = request_number - usize::from(behavior.complete_named_signal);
35585            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
35586            if path == "/api/worker/workflow-tasks/poll"
35587                && signal_request >= 1
35588                && signal_request <= signal_request_limit
35589            {
35590                let finish = behavior.complete_named_signal && signal_request == 3;
35591                let amounts = if signal_request == 1 {
35592                    vec![3]
35593                } else {
35594                    vec![3, 5]
35595                };
35596                let task_id = if signal_request == 1 {
35597                    "snapshot-wait-3"
35598                } else if finish {
35599                    "snapshot-finish"
35600                } else {
35601                    "snapshot-wait-5"
35602                };
35603                let mut history_events = std::iter::once(json!({
35604                    "event_type": "SignalWaitOpened",
35605                    "payload": {"sequence": 1, "signal_name": "finish"}
35606                }))
35607                .chain(amounts.iter().enumerate().map(|(index, amount)| {
35608                    json!({
35609                        "event_type": "SignalReceived",
35610                        "payload": {
35611                            "signal_id": format!("increment-{amount}"),
35612                            "signal_name": "increment",
35613                            "workflow_sequence": index + 2,
35614                            "payload_codec": DEFAULT_CODEC,
35615                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
35616                                .expect("Avro signal envelope")
35617                        }
35618                    })
35619                }))
35620                .collect::<Vec<_>>();
35621                let (resume_id, resume_name, resume_arguments) = if finish {
35622                    history_events.push(json!({
35623                        "event_type": "SignalReceived",
35624                        "payload": {
35625                            "signal_id": "finish",
35626                            "signal_name": "finish",
35627                            "workflow_sequence": 4,
35628                            "payload_codec": DEFAULT_CODEC,
35629                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
35630                                .expect("Avro finish signal envelope")
35631                        }
35632                    }));
35633                    (
35634                        "finish".to_string(),
35635                        "finish".to_string(),
35636                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
35637                            .expect("Avro finish resume signal"),
35638                    )
35639                } else {
35640                    let amount = amounts.last().expect("amount");
35641                    (
35642                        format!("increment-{amount}"),
35643                        "increment".to_string(),
35644                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
35645                            .expect("Avro increment resume signal"),
35646                    )
35647                };
35648                let body = json!({
35649                    "task": {
35650                        "task_id": task_id,
35651                        "workflow_id": "snapshot-1",
35652                        "run_id": "snapshot-run-1",
35653                        "workflow_type": "snapshot",
35654                        "payload_codec": DEFAULT_CODEC,
35655                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
35656                            .expect("Avro workflow arguments"),
35657                        "history_events": history_events,
35658                        "workflow_task_attempt": 1,
35659                        "workflow_signal_id": resume_id,
35660                        "signal_name": resume_name,
35661                        "signal_arguments": resume_arguments,
35662                        "lease_owner": "rust-snapshot-worker"
35663                    }
35664                })
35665                .to_string();
35666                write_mock_response(stream, "200 OK", &body);
35667                return;
35668            }
35669
35670            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
35671                let history_events = [3, 5]
35672                    .into_iter()
35673                    .enumerate()
35674                    .map(|(index, amount)| {
35675                        json!({
35676                            "event_type": "SignalReceived",
35677                            "payload": {
35678                                "signal_id": format!("increment-{amount}"),
35679                                "signal_name": "increment",
35680                                "workflow_sequence": index + 2,
35681                                "payload_codec": DEFAULT_CODEC,
35682                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
35683                                    .expect("Avro query signal envelope")
35684                            }
35685                        })
35686                    })
35687                    .collect::<Vec<_>>();
35688                let body = json!({
35689                    "task": {
35690                        "query_task_id": "snapshot-current",
35691                        "query_task_attempt": 1,
35692                        "lease_owner": "rust-snapshot-worker",
35693                        "workflow_id": "snapshot-1",
35694                        "run_id": "snapshot-run-1",
35695                        "workflow_type": "snapshot",
35696                        "query_name": "current",
35697                        "payload_codec": DEFAULT_CODEC,
35698                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
35699                            .expect("Avro workflow arguments"),
35700                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
35701                            .expect("Avro query arguments"),
35702                        "history_events": history_events,
35703                        "run_status": "waiting"
35704                    }
35705                })
35706                .to_string();
35707                write_mock_response(stream, "200 OK", &body);
35708                return;
35709            }
35710
35711            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
35712                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
35713            {
35714                write_mock_response(
35715                    stream,
35716                    "200 OK",
35717                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
35718                );
35719                return;
35720            }
35721
35722            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
35723                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
35724                return;
35725            }
35726
35727            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
35728                write_mock_response(
35729                    stream,
35730                    "200 OK",
35731                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
35732                );
35733                return;
35734            }
35735
35736            if path == "/api/worker/query-tasks/snapshot-current/complete" {
35737                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
35738                return;
35739            }
35740        }
35741
35742        if matches!(
35743            path,
35744            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
35745        ) {
35746            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
35747                .expect("typed mock result");
35748            let body = json!({
35749                "result": typed_fidelity_probe().into_json().expect("result projection"),
35750                "result_envelope": result,
35751            })
35752            .to_string();
35753            write_mock_response(stream, "200 OK", &body);
35754            return;
35755        }
35756
35757        if path == "/api/workflows/typed-1" {
35758            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
35759                .expect("typed mock result");
35760            let body = json!({
35761                "workflow_id": "typed-1",
35762                "run_id": "run-typed-1",
35763                "workflow_type": "typed.echo",
35764                "status": "completed",
35765                "output": typed_fidelity_probe().into_json().expect("output projection"),
35766                "output_envelope": result,
35767            })
35768            .to_string();
35769            write_mock_response(stream, "200 OK", &body);
35770            return;
35771        }
35772
35773        let (status, body) = match path {
35774            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
35775            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
35776            "/api/workflows" => (
35777                "201 Created",
35778                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
35779            ),
35780            "/api/worker/register" if behavior.decline_registration => (
35781                "200 OK",
35782                r#"{"worker_id":"declined-worker","registered":false}"#,
35783            ),
35784            "/api/worker/register" if behavior.waiting_query_worker => (
35785                "200 OK",
35786                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
35787            ),
35788            "/api/worker/register" => (
35789                "200 OK",
35790                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
35791            ),
35792            "/api/worker/heartbeat" => ("200 OK", "{}"),
35793            "/api/worker/activity-tasks/poll"
35794                if behavior.cancelled_activity && request_number == 1 =>
35795            {
35796                (
35797                    "200 OK",
35798                    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"}}"#,
35799                )
35800            }
35801            "/api/worker/activity-tasks/poll"
35802                if behavior.long_poll_capacity_responses_per_path > 0
35803                    && request_number
35804                        == behavior
35805                            .long_poll_capacity_responses_per_path
35806                            .saturating_add(1) =>
35807            {
35808                (
35809                    "200 OK",
35810                    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"}}"#,
35811                )
35812            }
35813            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
35814                ("200 OK", r#"{"task":null}"#)
35815            }
35816            "/api/worker/query-tasks/poll"
35817                if behavior.reject_query_completion && request_number == 1 =>
35818            {
35819                (
35820                    "200 OK",
35821                    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"}}"#,
35822                )
35823            }
35824            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
35825            "/api/worker/query-tasks/query-capture/complete"
35826            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
35827            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
35828                "200 OK",
35829                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
35830            ),
35831            "/api/worker/activity-tasks/activity-cancel/complete" => (
35832                "409 Conflict",
35833                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
35834            ),
35835            "/api/worker/activity-tasks/activity-typed/complete"
35836            | "/api/worker/activity-tasks/activity-typed/fail"
35837            | "/api/worker/activity-tasks/capacity-activity/complete"
35838            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
35839            "/api/workflows/counter-1/query/current" => (
35840                "200 OK",
35841                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
35842            ),
35843            "/api/workflows/counter-1/query/missing" => (
35844                "404 Not Found",
35845                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
35846            ),
35847            "/api/workflows/wf-lifecycle/cancel" => (
35848                "200 OK",
35849                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
35850            ),
35851            "/api/workflows/wf-lifecycle/terminate" => (
35852                "200 OK",
35853                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
35854            ),
35855            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
35856                "200 OK",
35857                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
35858            ),
35859            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
35860                "200 OK",
35861                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
35862            ),
35863            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
35864                "202 Accepted",
35865                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
35866            ),
35867            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
35868                "200 OK",
35869                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}"#,
35870            ),
35871            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
35872                "409 Conflict",
35873                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
35874            ),
35875            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
35876            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
35877                "409 Conflict",
35878                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
35879            ),
35880            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
35881                "200 OK",
35882                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"}]}}"#,
35883            ),
35884            "/api/workflows/wf-cancelled" => (
35885                "200 OK",
35886                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
35887            ),
35888            "/api/workflows/wf-terminated" => (
35889                "200 OK",
35890                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
35891            ),
35892            "/api/workflows/wf-timed-out" => (
35893                "200 OK",
35894                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
35895            ),
35896            // Native-style terminal descriptions without failure detail (#156).
35897            "/api/workflows/wf-native-failed"
35898            | "/api/workflows/wf-native-failed/runs/run-native-failed" => (
35899                "200 OK",
35900                r#"{"workflow_id":"wf-native-failed","run_id":"run-native-failed","status":"failed","closed_reason":"failed","output":null}"#,
35901            ),
35902            "/api/workflows/wf-native-failed/runs/run-native-failed/history" => (
35903                "200 OK",
35904                r#"{"events":[{"sequence":1,"event_type":"WorkflowStarted","payload":{}},{"sequence":6,"event_type":"WorkflowFailed","payload":{"failure_id":"failure-native","failure_category":"application","non_retryable":true,"exception_type":"ActivityFailed","exception_class":"durable_workflow::ActivityFailure","message":"activity failed (activity): rejected bob","exception":{"type":"ActivityFailed","class":"durable_workflow::ActivityFailure","message":"activity failed (activity): rejected bob"}}}]}"#,
35905            ),
35906            "/api/workflows/wf-native-timed-out" => (
35907                "200 OK",
35908                r#"{"workflow_id":"wf-native-timed-out","run_id":"run-native-timed-out","status":"failed","closed_reason":"timed_out"}"#,
35909            ),
35910            "/api/workflows/wf-native-timed-out/runs/run-native-timed-out/history" => (
35911                "200 OK",
35912                r#"{"events":[{"sequence":5,"event_type":"WorkflowTimedOut","payload":{"failure_id":"failure-deadline","timeout_kind":"execution_timeout","failure_category":"timeout","message":"Workflow execution deadline expired."}}]}"#,
35913            ),
35914            "/api/workflows/wf-native-paged" => (
35915                "200 OK",
35916                r#"{"workflow_id":"wf-native-paged","run_id":"run-native-paged","status":"failed","closed_reason":"failed"}"#,
35917            ),
35918            "/api/workflows/wf-native-paged/runs/run-native-paged/history" => (
35919                "200 OK",
35920                r#"{"events":[{"sequence":1,"event_type":"WorkflowStarted","payload":{}}],"next_page_token":"page-2"}"#,
35921            ),
35922            "/api/workflows/wf-native-paged/runs/run-native-paged/history?next_page_token=page-2" => (
35923                "200 OK",
35924                r#"{"events":[{"sequence":2,"event_type":"WorkflowFailed","payload":{"exception_type":"PagedFailure","message":"found on page two"}}]}"#,
35925            ),
35926            "/api/workflows/wf-native-no-history" => (
35927                "200 OK",
35928                r#"{"workflow_id":"wf-native-no-history","run_id":"run-native-no-history","status":"failed","closed_reason":"failed"}"#,
35929            ),
35930            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
35931                "200 OK",
35932                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
35933            ),
35934            "/api/workflows/wf-selected" => (
35935                "200 OK",
35936                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
35937            ),
35938            "/api/workflows/wf-selected/runs/run-selected" => (
35939                "200 OK",
35940                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
35941            ),
35942            _ => ("404 Not Found", r#"{"message":"not found"}"#),
35943        };
35944        write_mock_response(stream, status, body);
35945    }
35946
35947    fn mock_request_is_complete(request: &[u8]) -> bool {
35948        let Some(header_end) = request
35949            .windows(4)
35950            .position(|window| window == b"\r\n\r\n")
35951            .map(|position| position + 4)
35952        else {
35953            return false;
35954        };
35955        let headers = String::from_utf8_lossy(&request[..header_end]);
35956        let content_length = headers.lines().find_map(|line| {
35957            let (name, value) = line.split_once(':')?;
35958            name.eq_ignore_ascii_case("content-length")
35959                .then(|| value.trim().parse::<usize>().ok())
35960                .flatten()
35961        });
35962
35963        request.len() >= header_end + content_length.unwrap_or(0)
35964    }
35965
35966    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
35967        let response = format!(
35968            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
35969            body.len()
35970        );
35971
35972        let _ = stream.write_all(response.as_bytes());
35973        let _ = stream.flush();
35974    }
35975
35976    fn typed_activity_failure_server(
35977        path: &str,
35978        _body: &str,
35979        request_number: usize,
35980    ) -> Option<(&'static str, String)> {
35981        match path {
35982            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
35983                "200 OK",
35984                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(),
35985            )),
35986            "/api/worker/activity-tasks/typed-failure/fail" => Some(("200 OK", "{}".into())),
35987            _ => None,
35988        }
35989    }
35990
35991    #[tokio::test]
35992    async fn managed_activity_reports_application_type_and_non_retryable_marker() {
35993        for non_retryable in [false, true] {
35994            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
35995                request_override: Some(typed_activity_failure_server),
35996                ..MockWorkerBehavior::default()
35997            });
35998            let client = Client::builder(server.base_url()).build().unwrap();
35999            let mut worker = Worker::new(client, "typed-queue").worker_id("typed-worker");
36000            worker.register_activity("typed.failure", move |_, _| async move {
36001                Err(ActivityError::new("PaymentDeclined", "card declined")
36002                    .non_retryable(non_retryable)
36003                    .into())
36004            });
36005            assert_eq!(worker.run_once().await.unwrap(), 1);
36006            assert_eq!(
36007                server.request_body("/api/worker/activity-tasks/typed-failure/fail"),
36008                json!({
36009                    "activity_attempt_id": "typed-attempt",
36010                    "lease_owner": "typed-worker",
36011                    "failure": {"type": "PaymentDeclined", "message": "card declined",
36012                                "non_retryable": non_retryable}
36013                })
36014            );
36015        }
36016    }
36017
36018    fn activity_completion_backend_recovery(
36019        path: &str,
36020        _body: &str,
36021        request_number: usize,
36022    ) -> Option<(&'static str, String)> {
36023        match path {
36024            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
36025                "200 OK",
36026                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(),
36027            )),
36028            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
36029                "503 Service Unavailable",
36030                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(),
36031            )),
36032            "/api/worker/activity-tasks/recover-activity/complete" => Some((
36033                "200 OK",
36034                r#"{"outcome":"completed","recorded":true}"#.to_string(),
36035            )),
36036            _ => None,
36037        }
36038    }
36039
36040    fn workflow_completion_backend_recovery(
36041        path: &str,
36042        _body: &str,
36043        request_number: usize,
36044    ) -> Option<(&'static str, String)> {
36045        match path {
36046            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
36047                "200 OK",
36048                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
36049            )),
36050            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
36051                "503 Service Unavailable",
36052                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(),
36053            )),
36054            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
36055                "200 OK",
36056                r#"{"outcome":"completed","recorded":true}"#.to_string(),
36057            )),
36058            _ => None,
36059        }
36060    }
36061
36062    fn workflow_completion_lock_pressure(
36063        path: &str,
36064        body: &str,
36065        request_number: usize,
36066    ) -> Option<(&'static str, String)> {
36067        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number == 1 {
36068            return Some((
36069                "503 Service Unavailable",
36070                json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
36071                    "outcome":"deferred", "recorded":false, "retryable":true,
36072                    "retry_after_seconds":1, "task_id":"recover-workflow",
36073                    "lease_owner":"recover-worker", "workflow_task_attempt":3,
36074                    "backend":{"driver":"sqlite", "lock_pressure":true}})
36075                .to_string(),
36076            ));
36077        }
36078        workflow_completion_backend_recovery(path, body, request_number)
36079    }
36080
36081    fn workflow_completion_lock_pressure_forever(
36082        path: &str,
36083        body: &str,
36084        request_number: usize,
36085    ) -> Option<(&'static str, String)> {
36086        if path == "/api/worker/workflow-tasks/recover-workflow/complete" {
36087            return workflow_completion_lock_pressure(path, body, 1);
36088        }
36089        workflow_completion_lock_pressure(path, body, request_number)
36090    }
36091
36092    fn workflow_completion_lock_pressure_then_expired(
36093        path: &str,
36094        body: &str,
36095        request_number: usize,
36096    ) -> Option<(&'static str, String)> {
36097        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
36098            return Some(("409 Conflict", json!({"reason":"lease_expired", "recorded":false,
36099                "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3}).to_string()));
36100        }
36101        workflow_completion_lock_pressure(path, body, request_number)
36102    }
36103
36104    fn workflow_completion_lock_pressure_then_slow(
36105        path: &str,
36106        body: &str,
36107        request_number: usize,
36108    ) -> Option<(&'static str, String)> {
36109        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
36110            thread::sleep(Duration::from_secs(2));
36111        }
36112        workflow_completion_lock_pressure(path, body, request_number)
36113    }
36114
36115    fn workflow_completion_pressure_then_backend_loss(
36116        path: &str,
36117        body: &str,
36118        request_number: usize,
36119    ) -> Option<(&'static str, String)> {
36120        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
36121            return Some((
36122                "503 Service Unavailable",
36123                json!({"reason":"backend_unavailable", "operation":"complete_workflow_task",
36124                    "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
36125                    "retryable":true, "retry_after_seconds":3, "task_id":"recover-workflow",
36126                    "lease_owner":"recover-worker", "workflow_task_attempt":3})
36127                .to_string(),
36128            ));
36129        }
36130        workflow_completion_lock_pressure(path, body, request_number)
36131    }
36132
36133    fn completion_deferral_worker(server: &MockWorkerServer, calls: Arc<AtomicUsize>) -> Worker {
36134        let client = Client::builder(server.base_url())
36135            .timeout(Duration::from_secs(4))
36136            .build()
36137            .unwrap();
36138        let mut worker = Worker::new(client, "recover-queue")
36139            .worker_id("recover-worker")
36140            .poll_timeout(Duration::from_millis(10));
36141        worker.register_workflow("recover.workflow", move |_ctx, _args| {
36142            let calls = Arc::clone(&calls);
36143            async move {
36144                calls.fetch_add(1, Ordering::SeqCst);
36145                Ok(json!("done"))
36146            }
36147        });
36148        worker
36149    }
36150
36151    #[tokio::test]
36152    async fn workflow_completion_deferral_stops_at_original_cleanup_budget() {
36153        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36154            request_override: Some(workflow_completion_lock_pressure_forever),
36155            ..MockWorkerBehavior::default()
36156        });
36157        let calls = Arc::new(AtomicUsize::new(0));
36158        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
36159            .with_storage_admission(Arc::new(AtomicBool::new(false)));
36160        worker
36161            .client
36162            .worker_storage_admission
36163            .as_mut()
36164            .unwrap()
36165            .workflow_completion_retry_deadline =
36166            Some(tokio::time::Instant::now() + Duration::from_millis(250));
36167        let result = tokio::time::timeout(Duration::from_secs(2), worker.poll_workflow_once())
36168            .await
36169            .unwrap();
36170        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
36171        assert_eq!(calls.load(Ordering::SeqCst), 1);
36172        assert_eq!(
36173            server
36174                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
36175                .len(),
36176            1
36177        );
36178    }
36179
36180    #[tokio::test]
36181    async fn workflow_completion_deferral_bounds_the_inflight_retry() {
36182        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36183            request_override: Some(workflow_completion_lock_pressure_then_slow),
36184            ..MockWorkerBehavior::default()
36185        });
36186        let calls = Arc::new(AtomicUsize::new(0));
36187        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
36188            .with_storage_admission(Arc::new(AtomicBool::new(false)));
36189        let start = tokio::time::Instant::now();
36190        worker
36191            .client
36192            .worker_storage_admission
36193            .as_mut()
36194            .unwrap()
36195            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
36196        assert!(matches!(
36197            worker.poll_workflow_once().await,
36198            Err(Error::Timeout)
36199        ));
36200        assert!(start.elapsed() < Duration::from_secs(2));
36201        assert_eq!(calls.load(Ordering::SeqCst), 1);
36202        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
36203        assert_eq!(bodies.len(), 2);
36204        assert_eq!(bodies[0], bodies[1]);
36205    }
36206
36207    #[tokio::test]
36208    async fn workflow_completion_deferral_retains_deadline_when_backend_reason_changes() {
36209        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36210            request_override: Some(workflow_completion_pressure_then_backend_loss),
36211            ..MockWorkerBehavior::default()
36212        });
36213        let calls = Arc::new(AtomicUsize::new(0));
36214        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
36215            .with_storage_admission(Arc::new(AtomicBool::new(false)));
36216        let start = tokio::time::Instant::now();
36217        worker
36218            .client
36219            .worker_storage_admission
36220            .as_mut()
36221            .unwrap()
36222            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
36223        let result = worker.poll_workflow_once().await;
36224        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
36225        assert!(start.elapsed() < Duration::from_secs(2));
36226        assert_eq!(calls.load(Ordering::SeqCst), 1);
36227        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
36228        assert_eq!(bodies.len(), 2);
36229        assert_eq!(bodies[0], bodies[1]);
36230    }
36231
36232    #[tokio::test]
36233    async fn workflow_completion_deferral_shutdown_interrupts_prolonged_pressure() {
36234        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36235            request_override: Some(workflow_completion_lock_pressure_forever),
36236            ..MockWorkerBehavior::default()
36237        });
36238        let calls = Arc::new(AtomicUsize::new(0));
36239        let stop = Arc::new(AtomicBool::new(false));
36240        let worker = completion_deferral_worker(&server, Arc::clone(&calls))
36241            .with_storage_admission(Arc::clone(&stop));
36242        let shutdown = async {
36243            while server
36244                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
36245                .is_empty()
36246            {
36247                tokio::time::sleep(Duration::from_millis(10)).await;
36248            }
36249            stop.store(true, Ordering::SeqCst);
36250        };
36251        let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
36252            tokio::join!(worker.poll_workflow_once(), shutdown)
36253        })
36254        .await
36255        .unwrap();
36256        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
36257        assert_eq!(calls.load(Ordering::SeqCst), 1);
36258        assert_eq!(
36259            server
36260                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
36261                .len(),
36262            1
36263        );
36264    }
36265
36266    #[tokio::test]
36267    async fn workflow_completion_deferral_preserves_later_expiry_refusal() {
36268        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36269            request_override: Some(workflow_completion_lock_pressure_then_expired),
36270            ..MockWorkerBehavior::default()
36271        });
36272        let calls = Arc::new(AtomicUsize::new(0));
36273        let worker = completion_deferral_worker(&server, Arc::clone(&calls));
36274        let result = worker.run_once().await;
36275        assert!(
36276            matches!(result, Err(Error::Http { status, ref body }) if status.as_u16() == 409 && body.contains("lease_expired"))
36277        );
36278        assert_eq!(calls.load(Ordering::SeqCst), 1);
36279        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
36280        assert_eq!(bodies.len(), 2);
36281        assert_eq!(bodies[0], bodies[1]);
36282        assert!(server
36283            .request_bodies("/api/worker/workflow-tasks/recover-workflow/fail")
36284            .is_empty());
36285    }
36286
36287    #[tokio::test]
36288    async fn managed_workflow_completion_deferral_preserves_bytes_and_server_delay() {
36289        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36290            request_override: Some(workflow_completion_lock_pressure),
36291            ..MockWorkerBehavior::default()
36292        });
36293        let client = Client::builder(server.base_url())
36294            .timeout(Duration::from_secs(2))
36295            .build()
36296            .unwrap();
36297        let calls = Arc::new(AtomicUsize::new(0));
36298        let mut worker = Worker::new(client, "recover-queue")
36299            .worker_id("recover-worker")
36300            .recover_transient_outages(true)
36301            .poll_timeout(Duration::from_millis(10))
36302            .retry_policy(WorkerRetryPolicy {
36303                max_retries: 1,
36304                initial_backoff: Duration::from_millis(10),
36305                max_backoff: Duration::from_millis(10),
36306            });
36307        worker.register_workflow("recover.workflow", {
36308            let calls = Arc::clone(&calls);
36309            move |_ctx, _args| {
36310                let calls = Arc::clone(&calls);
36311                async move {
36312                    calls.fetch_add(1, Ordering::SeqCst);
36313                    Ok(json!("done"))
36314                }
36315            }
36316        });
36317        let start = tokio::time::Instant::now();
36318        assert_eq!(worker.run_once().await.unwrap(), 1);
36319        assert!(start.elapsed() >= Duration::from_secs(1));
36320        assert_eq!(calls.load(Ordering::SeqCst), 1);
36321        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
36322        assert_eq!(bodies.len(), 2);
36323        assert_eq!(bodies[0], bodies[1]);
36324    }
36325
36326    #[test]
36327    fn workflow_completion_deferral_requires_an_exact_unrecorded_fence() {
36328        let path = "/worker/workflow-tasks/recover-workflow/complete";
36329        let request = json!({"lease_owner":"recover-worker", "workflow_task_attempt":3});
36330        let response = json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
36331            "outcome":"deferred", "recorded":false, "retryable":true, "retry_after_seconds":1,
36332            "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3,
36333            "backend":{"driver":"sqlite", "lock_pressure":true}});
36334        let error = |body: Value| Error::Http {
36335            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
36336            body: body.to_string(),
36337        };
36338        assert_eq!(
36339            worker_deferred_workflow_completion_retry_after(
36340                &error(response.clone()),
36341                path,
36342                Some(&request)
36343            ),
36344            Some(Duration::from_secs(1))
36345        );
36346        for (field, value) in [
36347            ("reason", json!("backend_unavailable")),
36348            ("operation", json!("complete_activity_task")),
36349            ("task_id", json!("other-task")),
36350            ("lease_owner", json!("other-owner")),
36351            ("workflow_task_attempt", json!(4)),
36352            ("recorded", json!(true)),
36353            ("recorded", Value::Null),
36354            ("recorded", json!("false")),
36355            ("retryable", json!(false)),
36356            ("retry_after_seconds", json!(0)),
36357            ("retry_after_seconds", json!(-1)),
36358            ("retry_after_seconds", json!(1.0)),
36359            ("retry_after_seconds", json!("1")),
36360            ("retry_after_seconds", json!(6)),
36361            ("backend", json!({"lock_pressure":false})),
36362        ] {
36363            let mut invalid = response.clone();
36364            invalid[field] = value;
36365            assert_eq!(
36366                worker_deferred_workflow_completion_retry_after(
36367                    &error(invalid),
36368                    path,
36369                    Some(&request)
36370                ),
36371                None,
36372                "invalid {field}"
36373            );
36374        }
36375        for field in [
36376            "reason",
36377            "operation",
36378            "task_id",
36379            "lease_owner",
36380            "workflow_task_attempt",
36381            "recorded",
36382            "retryable",
36383            "retry_after_seconds",
36384            "backend",
36385        ] {
36386            let mut missing = response.clone();
36387            missing.as_object_mut().unwrap().remove(field);
36388            assert_eq!(
36389                worker_deferred_workflow_completion_retry_after(
36390                    &error(missing),
36391                    path,
36392                    Some(&request)
36393                ),
36394                None,
36395                "missing {field}"
36396            );
36397        }
36398        assert_eq!(
36399            worker_deferred_workflow_completion_retry_after(
36400                &error(response.clone()),
36401                "/worker/activity-tasks/recover-workflow/complete",
36402                Some(&request)
36403            ),
36404            None
36405        );
36406        assert_eq!(
36407            worker_deferred_workflow_completion_retry_after(&error(response.clone()), path, None),
36408            None
36409        );
36410        let wrong_status = Error::Http {
36411            status: reqwest::StatusCode::CONFLICT,
36412            body: response.to_string(),
36413        };
36414        assert_eq!(
36415            worker_deferred_workflow_completion_retry_after(&wrong_status, path, Some(&request)),
36416            None
36417        );
36418    }
36419
36420    fn activity_completion_stale_after_backend_recovery(
36421        path: &str,
36422        body: &str,
36423        request_number: usize,
36424    ) -> Option<(&'static str, String)> {
36425        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
36426            return Some((
36427                "409 Conflict",
36428                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(),
36429            ));
36430        }
36431        activity_completion_backend_recovery(path, body, request_number)
36432    }
36433
36434    fn activity_completion_remains_unavailable(
36435        path: &str,
36436        body: &str,
36437        request_number: usize,
36438    ) -> Option<(&'static str, String)> {
36439        if path == "/api/worker/activity-tasks/recover-activity/complete" {
36440            return activity_completion_backend_recovery(path, body, 1);
36441        }
36442        activity_completion_backend_recovery(path, body, request_number)
36443    }
36444
36445    #[tokio::test]
36446    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
36447        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36448            request_override: Some(activity_completion_backend_recovery),
36449            ..MockWorkerBehavior::default()
36450        });
36451        let client = Client::builder(server.base_url())
36452            .timeout(Duration::from_secs(2))
36453            .build()
36454            .expect("client");
36455        let handler_calls = Arc::new(AtomicUsize::new(0));
36456        let mut worker = Worker::new(client, "recover-queue")
36457            .worker_id("recover-worker")
36458            .poll_timeout(Duration::from_millis(10));
36459        worker.register_activity("recover.activity", {
36460            let handler_calls = Arc::clone(&handler_calls);
36461            move |_ctx, _args| {
36462                let handler_calls = Arc::clone(&handler_calls);
36463                async move {
36464                    handler_calls.fetch_add(1, Ordering::SeqCst);
36465                    Ok(json!("done"))
36466                }
36467            }
36468        });
36469
36470        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
36471        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
36472        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
36473        assert_eq!(bodies.len(), 2);
36474        assert_eq!(bodies[0], bodies[1]);
36475    }
36476
36477    #[tokio::test]
36478    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
36479        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36480            request_override: Some(workflow_completion_backend_recovery),
36481            ..MockWorkerBehavior::default()
36482        });
36483        let client = Client::builder(server.base_url())
36484            .timeout(Duration::from_secs(2))
36485            .build()
36486            .expect("client");
36487        let handler_calls = Arc::new(AtomicUsize::new(0));
36488        let mut worker = Worker::new(client, "recover-queue")
36489            .worker_id("recover-worker")
36490            .poll_timeout(Duration::from_millis(10));
36491        worker.register_workflow("recover.workflow", {
36492            let handler_calls = Arc::clone(&handler_calls);
36493            move |_ctx, _args| {
36494                let handler_calls = Arc::clone(&handler_calls);
36495                async move {
36496                    handler_calls.fetch_add(1, Ordering::SeqCst);
36497                    Ok(json!("done"))
36498                }
36499            }
36500        });
36501
36502        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
36503        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
36504        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
36505        assert_eq!(bodies.len(), 2);
36506        assert_eq!(bodies[0], bodies[1]);
36507    }
36508
36509    #[tokio::test]
36510    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
36511        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36512            request_override: Some(activity_completion_stale_after_backend_recovery),
36513            ..MockWorkerBehavior::default()
36514        });
36515        let client = Client::builder(server.base_url())
36516            .timeout(Duration::from_secs(2))
36517            .build()
36518            .expect("client");
36519        let handler_calls = Arc::new(AtomicUsize::new(0));
36520        let mut worker = Worker::new(client, "recover-queue")
36521            .worker_id("recover-worker")
36522            .poll_timeout(Duration::from_millis(10));
36523        worker.register_activity("recover.activity", {
36524            let handler_calls = Arc::clone(&handler_calls);
36525            move |_ctx, _args| {
36526                let handler_calls = Arc::clone(&handler_calls);
36527                async move {
36528                    handler_calls.fetch_add(1, Ordering::SeqCst);
36529                    Ok(json!("done"))
36530                }
36531            }
36532        });
36533
36534        assert_eq!(
36535            worker
36536                .run_once()
36537                .await
36538                .expect("authoritative stale outcome"),
36539            1
36540        );
36541        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
36542        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
36543        assert_eq!(bodies.len(), 2);
36544        assert_eq!(bodies[0], bodies[1]);
36545    }
36546
36547    #[test]
36548    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
36549        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
36550        let response = json!({
36551            "reason":"backend_unavailable", "operation":"complete_activity_task",
36552            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
36553            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
36554            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
36555        });
36556        let path = "/worker/activity-tasks/recover-activity/complete";
36557        let error = |body: Value| Error::Http {
36558            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
36559            body: body.to_string(),
36560        };
36561        assert_eq!(
36562            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
36563            Some(Duration::from_secs(1))
36564        );
36565
36566        for (field, invalid) in [
36567            ("operation", json!("poll_activity_task")),
36568            ("outcome", json!("rejected")),
36569            ("worker_id", json!("another-worker")),
36570            ("task_queue", json!("recover-queue")),
36571            ("retryable", json!(false)),
36572            ("retry_after_seconds", json!(0)),
36573            ("task_id", json!("another-task")),
36574            ("lease_owner", json!("another-worker")),
36575            ("activity_attempt_id", json!("another-attempt")),
36576        ] {
36577            let mut invalid_response = response.clone();
36578            invalid_response[field] = invalid;
36579            assert_eq!(
36580                worker_fenced_completion_retry_after(
36581                    &error(invalid_response),
36582                    path,
36583                    Some(&request)
36584                ),
36585                None,
36586                "must not retry mismatched {field}"
36587            );
36588        }
36589        assert_eq!(
36590            worker_fenced_completion_retry_after(&error(response), path, None),
36591            None
36592        );
36593    }
36594
36595    #[tokio::test]
36596    async fn shutdown_interrupts_fenced_completion_backend_wait() {
36597        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36598            request_override: Some(activity_completion_remains_unavailable),
36599            ..MockWorkerBehavior::default()
36600        });
36601        let client = Client::builder(server.base_url())
36602            .timeout(Duration::from_secs(2))
36603            .build()
36604            .expect("client");
36605        let stop = Arc::new(AtomicBool::new(false));
36606        let worker = Worker::new(client, "recover-queue")
36607            .worker_id("recover-worker")
36608            .with_storage_admission(Arc::clone(&stop));
36609        let completion = tokio::spawn(async move {
36610            worker
36611                .client
36612                .complete_activity_task(
36613                    "recover-activity",
36614                    "recover-attempt",
36615                    "recover-worker",
36616                    json!("done"),
36617                    DEFAULT_CODEC,
36618                )
36619                .await
36620        });
36621        let path = "/api/worker/activity-tasks/recover-activity/complete";
36622        tokio::time::timeout(Duration::from_secs(2), async {
36623            while server.request_count(path) == 0 {
36624                tokio::time::sleep(Duration::from_millis(10)).await;
36625            }
36626        })
36627        .await
36628        .expect("first completion request");
36629        stop.store(true, Ordering::SeqCst);
36630        let error = tokio::time::timeout(Duration::from_secs(1), completion)
36631            .await
36632            .expect("shutdown must interrupt retry wait")
36633            .expect("completion task")
36634            .expect_err("backend is still unavailable");
36635        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
36636        assert_eq!(server.request_count(path), 1);
36637    }
36638}