Skip to content
Durable Workflowrust

durable_workflow/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod activity_checkpoint;
4mod activity_error;
5mod activity_hydration;
6mod activity_lease;
7mod activity_retry;
8mod cancellation_context;
9mod cancellation_replay_clock;
10mod cancellation_scope;
11mod cancellation_scope_history;
12mod cancellation_scope_replay;
13mod cooperative_cancellation;
14mod external_signal;
15mod failure_reporting;
16mod local_activity;
17pub mod metrics;
18mod nexus;
19pub mod pagination;
20mod query_authority;
21mod raw_request;
22mod replay_clock;
23mod run_activities;
24mod runtime_payloads;
25mod runtime_uploads;
26mod server_capabilities_digest;
27mod signal_with_start;
28mod sticky_worker;
29mod sticky_workflow_cache;
30#[cfg(feature = "telemetry")]
31pub mod telemetry;
32pub mod testing;
33pub use pagination::{
34    PaginationError, WorkflowHistoryIterator, WorkflowHistoryOptions, WorkflowHistoryPage,
35    WorkflowIterator, WorkflowListOptions, WorkflowListPage, WorkflowSummary,
36};
37mod terminal_failure_detail;
38mod tls;
39mod update_outcome;
40mod worker_capacity;
41mod worker_session;
42mod workflow_hydration;
43mod workflow_logging;
44pub use workflow_logging::{WorkflowLogger, WorkflowReplayState};
45
46pub use activity_checkpoint::{ActivityHeartbeatCheckpoint, ActivityHeartbeatResumeUnavailable};
47pub use activity_error::ActivityError;
48pub use activity_retry::{ActivityAttemptLimit, ActivityRetryInfo};
49pub use cancellation_context::{
50    CancellationCause, CancellationContext, CancellationLineage, ScopedCancellationContext,
51    ScopedCancellationLineage,
52};
53pub use cancellation_scope::CancellationScopeOpenReceipt;
54#[doc(hidden)]
55pub use cancellation_scope_history::{
56    CancellationScopeDeliveryBudget, CancellationScopeDeliveryReceipt,
57};
58#[doc(hidden)]
59pub use cancellation_scope_replay::CancellationScopeRequested;
60pub use external_signal::{ExternalSignalCall, ExternalSignalOutcome, ExternalSignalResult};
61pub use failure_reporting::FailureReportError;
62pub use run_activities::{
63    WorkflowActivity, WorkflowActivityAttempt, WorkflowActivityList, WorkflowActivityMetadataError,
64};
65
66pub use cooperative_cancellation::{
67    CancellationCallKind, CancellationDelivery, CancellationDeliveryReceipt,
68    CancellationDeliveryReply, CancellationHistory, CancellationRequest, CancellationShield,
69    CooperativeCancellationOptions, CooperativeCancellationRequested, CooperativeWorkflowTask,
70    CooperativeWorkflowTaskPoll, WorkflowCancellationRequest, WorkflowTaskHeartbeat,
71};
72
73use std::{
74    any::{type_name, Any, TypeId},
75    collections::{BTreeMap, BTreeSet, HashMap},
76    future::Future,
77    io::{self, Read},
78    panic::Location,
79    pin::Pin,
80    sync::{
81        atomic::{AtomicBool, AtomicUsize, Ordering},
82        Arc, Mutex, OnceLock,
83    },
84    task::{Context as TaskContext, Poll},
85    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
86};
87
88use apache_avro::{from_avro_datum, to_avro_datum, types::Value as AvroDatum, Schema};
89use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
90use chrono::DateTime;
91use futures_util::{future::OptionFuture, task::noop_waker_ref};
92pub use local_activity::LocalActivityOptions;
93pub use raw_request::{
94    worker_protocol_compatible, HttpRefusal, RawMethod, RawRequest, RawResponse,
95};
96use serde::{
97    de::DeserializeOwned,
98    ser::{SerializeMap, SerializeSeq},
99    Deserialize, Deserializer, Serialize, Serializer,
100};
101pub use serde_json::{json, Value};
102use sha2::{Digest, Sha256};
103pub use signal_with_start::{ClosedRunPolicy, OpenRunPolicy, SignalWithStartOptions};
104pub use sticky_workflow_cache::{StickyCacheMetrics, StickyCacheOptions};
105use thiserror::Error;
106pub use update_outcome::{UpdatePending, UpdateWaitStage};
107pub use uuid::Uuid;
108pub use worker_session::{WorkerSession, WorkerSessionOptions};
109
110pub const WORKER_PROTOCOL_VERSION: &str = "1.20";
111pub const MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
112
113/// Select the worker request protocol without enabling optional capabilities.
114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
115#[non_exhaustive]
116pub enum WorkerProtocolVersion {
117    /// Compatibility with Servers that implement only worker protocol 1.19.
118    V119,
119    /// The default worker protocol.
120    #[default]
121    V120,
122}
123
124impl WorkerProtocolVersion {
125    fn as_str(self) -> &'static str {
126        match self {
127            Self::V119 => MINIMUM_WORKER_PROTOCOL_VERSION,
128            Self::V120 => WORKER_PROTOCOL_VERSION,
129        }
130    }
131}
132const WORKFLOW_HISTORY_PAGE_SIZE: usize = 500;
133/// First additive worker protocol that defines portable worker-affinity features.
134pub const PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION: &str = "1.18";
135pub const CONTROL_PLANE_VERSION: &str = "2";
136pub const DEFAULT_CODEC: &str = "avro";
137pub const SDK_VERSION: &str = concat!("durable-workflow-rust/", env!("CARGO_PKG_VERSION"));
138/// Worker-registration capability for authored condition-wait occurrence identity.
139pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY: &str =
140    "condition_wait_occurrence_identity";
141/// Worker-registration capability for portable memo upserts.
142pub const MEMO_UPSERTS_CAPABILITY: &str = "memo_upserts";
143/// Worker-registration capability for server-routed read-only queries.
144pub const QUERY_TASKS_CAPABILITY: &str = "query_tasks";
145/// Worker-registration capability for canonical typed search attributes.
146pub const TYPED_SEARCH_ATTRIBUTES_CAPABILITY: &str = "typed_search_attributes";
147/// Worker-registration capability for synchronous workflow updates.
148pub const WORKFLOW_UPDATES_CAPABILITY: &str = "workflow_updates";
149/// Worker-registration capability for durable named input streams.
150pub const MESSAGE_STREAMS_CAPABILITY: &str = "message_streams";
151/// Worker-registration capability for persisted first-completion selection.
152pub const DURABLE_SELECTION_CAPABILITY: &str = "durable_selection";
153pub const MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.15";
154pub const MESSAGE_STREAM_SIGNAL: &str = "__durable_workflow_message_stream";
155pub const MESSAGE_STREAM_SCHEMA: &str = "durable-workflow.v2.message-stream.message";
156pub const MESSAGE_STREAM_CURSOR_SCHEMA: &str = "durable-workflow.v2.message-stream.cursor";
157pub const MESSAGE_STREAM_MAX_BATCH: usize = 100;
158/// First additive worker protocol that defines query-task transport.
159pub const QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
160/// First additive worker protocol that defines typed search-attribute upserts.
161pub const SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.8";
162/// First additive worker protocol that defines portable memo upserts.
163pub const MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.14";
164/// First additive worker protocol that preserves declared search-attribute types.
165pub const TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.16";
166/// First additive worker protocol that defines external durable condition waits.
167pub const CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.9";
168/// First additive worker protocol that preserves authored condition-wait occurrences.
169pub const CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.17";
170/// First additive worker protocol that defines durable selection groups.
171pub const DURABLE_SELECTION_MINIMUM_WORKER_PROTOCOL_VERSION: &str = "1.19";
172
173pub fn worker_protocol_supports_message_streams(version: &str) -> bool {
174    let Some((major, minor)) = version.split_once('.') else {
175        return false;
176    };
177    major == "1" && minor.parse::<u64>().is_ok_and(|minor| minor >= 15)
178}
179
180fn validate_user_signal_name(signal_name: &str) -> Result<()> {
181    if signal_name == MESSAGE_STREAM_SIGNAL {
182        return Err(Error::Codec(format!(
183            "signal name {MESSAGE_STREAM_SIGNAL:?} is reserved by the workflow runtime"
184        )));
185    }
186    Ok(())
187}
188
189const REQUEST_ID_CONFLICT_REASON: &str = "request_id_conflict";
190const REQUEST_ID_AMBIGUOUS_REASON: &str = "request_id_ambiguous";
191const MAX_REQUEST_ID_CHARACTERS: usize = 255;
192
193/// The caller command key is a case-sensitive body field of 1 to 255 Unicode characters.
194fn validate_request_id(request_id: &str) -> Result<()> {
195    if request_id.is_empty() || request_id.chars().count() > MAX_REQUEST_ID_CHARACTERS {
196        return Err(Error::Codec(format!(
197            "request_id must be 1 to {MAX_REQUEST_ID_CHARACTERS} Unicode characters"
198        )));
199    }
200    Ok(())
201}
202
203/// Encode one identifier as exactly one control-plane path segment.
204///
205/// The value is percent-encoded like [`RawRequest`] segments, so `/`, `?` or
206/// `#` in an id stays inside its segment. An empty, `.` or `..` value is
207/// refused before any request: it would address another route, such as
208/// `/workflows` instead of one workflow.
209fn path_segment(field: &'static str, value: &str) -> Result<String> {
210    if value.is_empty() || value == "." || value == ".." {
211        return Err(Error::InvalidPathSegment { field });
212    }
213    Ok(percent_encode_path_segment(value))
214}
215
216fn generated_request_id(command: &str) -> String {
217    format!("sdk-rust-{command}-{}", Uuid::new_v4().simple())
218}
219
220/// Guarantee the sent caller command key on a receipt from a Server that does not echo it.
221fn with_request_id(mut receipt: Value, request_id: &str) -> Value {
222    if receipt.is_null() {
223        return json!({ "request_id": request_id });
224    }
225    if let Some(receipt) = receipt.as_object_mut() {
226        receipt
227            .entry("request_id")
228            .or_insert_with(|| Value::String(request_id.to_string()));
229    }
230    receipt
231}
232
233const MAX_LONG_POLL_TIMEOUT_SECONDS: u64 = 60;
234const WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE: &str =
235    "Workflow task waiting for scheduled history.";
236const WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE: &str = "WorkflowTaskWaitingForHistory";
237const MISSING_TASK_PAYLOAD_CODEC: &str = "\0missing-task-payload-codec";
238const NULL_TASK_PAYLOAD_CODEC: &str = "\0null-task-payload-codec";
239const NON_STRING_TASK_PAYLOAD_CODEC: &str = "\0non-string-task-payload-codec";
240const MAX_MEMO_ENTRIES: usize = 100;
241const MAX_MEMO_VALUE_SIZE_BYTES: usize = 10_240;
242const MAX_MEMO_TOTAL_SIZE_BYTES: usize = 65_536;
243
244const QUERY_TASK_FINAL_REJECTION_REASONS: &[&str] = &[
245    "lease_expired",
246    "query_task_not_found",
247    "query_task_not_leased",
248    "query_task_timed_out",
249    "query_deadline_unavailable",
250    "lease_owner_mismatch",
251    "query_task_attempt_mismatch",
252];
253
254/// Manifest for the default service-worker profile.
255///
256/// Inline local execution is enabled separately by [`Worker::local_activities`].
257/// Local execution, sessions and caching require explicit Worker configuration.
258pub fn portable_worker_affinity_capability_manifest() -> Value {
259    json!({
260        "local_activities": {
261            "supported": false,
262            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
263            "reason": "rust_worker_does_not_execute_record_local_activity",
264        },
265        "worker_sessions": {
266            "supported": false,
267            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
268            "reason": "rust_worker_has_no_typed_session_lifecycle",
269        },
270        "sticky_execution": {
271            "supported": false,
272            "minimum_protocol_version": PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
273            "reason": "rust_worker_uses_complete_durable_history_replay",
274        },
275    })
276}
277
278/// Canonical Avro Value schema packaged with the crate and parsed by the runtime.
279pub const AVRO_VALUE_SCHEMA_JSON: &str =
280    include_str!("../schema/durable_workflow.protocol.Value.v1.avsc");
281pub const AVRO_VALUE_SCHEMA_FINGERPRINT_HEX: &str = "e2a33dff55802237";
282pub const AVRO_VALUE_SCHEMA_FINGERPRINT: [u8; 8] = [0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
283const AVRO_SINGLE_OBJECT_MAGIC: [u8; 2] = [0xc3, 0x01];
284
285static AVRO_VALUE_SCHEMA: OnceLock<std::result::Result<Schema, String>> = OnceLock::new();
286static AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA: OnceLock<std::result::Result<Schema, String>> =
287    OnceLock::new();
288
289#[derive(Clone, Copy)]
290enum RequestProtocol {
291    ControlPlane,
292    DefaultWorker,
293    Worker(&'static str),
294}
295
296pub type Result<T> = std::result::Result<T, Error>;
297
298pub use nexus::{
299    NexusOperationFailure, NexusOperationMode, NexusOperationResult, NexusServiceCall,
300    NexusServiceOptions, NexusWaitFor,
301};
302
303#[derive(Debug, Error)]
304#[non_exhaustive]
305pub enum Error {
306    #[error("replay time is unavailable without a supported authoritative consumed boundary")]
307    ReplayClockUnavailable,
308    #[error("transport error: {0}")]
309    Transport(#[from] reqwest::Error),
310    #[error(
311        "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"
312    )]
313    InvalidBaseUrl,
314    /// A supplied static credential failed validation before client construction.
315    #[error(
316        "invalid static credential option {option}: leading or trailing Unicode whitespace or control character"
317    )]
318    InvalidStaticCredential { option: &'static str },
319    #[error("invalid additional root certificates: {0}")]
320    InvalidRootCertificates(String),
321    #[error("invalid raw request: {0}")]
322    InvalidRawRequest(String),
323    /// An identifier placed in a request path was empty, `.` or `..`, so it
324    /// cannot stay one path segment. Nothing was sent.
325    #[error("invalid path segment for {field}: must not be empty, \".\" or \"..\"")]
326    InvalidPathSegment { field: &'static str },
327    #[error(transparent)]
328    FailureReporting(#[from] FailureReportError),
329    #[error(transparent)]
330    Testing(#[from] testing::TestingError),
331    #[error(transparent)]
332    Pagination(#[from] pagination::PaginationError),
333    #[error(transparent)]
334    WorkflowActivityMetadata(#[from] WorkflowActivityMetadataError),
335    #[error("json error: {0}")]
336    Json(#[from] serde_json::Error),
337    #[error("http {status}: {body}")]
338    Http {
339        status: reqwest::StatusCode,
340        body: String,
341    },
342    #[error("codec error: {0}")]
343    Codec(String),
344    #[error(transparent)]
345    QueryFailed(QueryFailure),
346    #[error(transparent)]
347    Protocol(ProtocolFailure),
348    /// The Server refused a workflow-task completion as larger than its
349    /// aggregate completion limit. Never retried; see
350    /// [`WorkflowTaskCompletionTooLarge`].
351    #[error(transparent)]
352    WorkflowTaskCompletionTooLarge(WorkflowTaskCompletionTooLarge),
353    /// The Server refused a workflow-task completion because recording it
354    /// would exceed its history-transaction budget. Never retried; see
355    /// [`WorkflowTaskHistoryLimitExceeded`].
356    #[error(transparent)]
357    WorkflowTaskHistoryLimitExceeded(WorkflowTaskHistoryLimitExceeded),
358    #[error(transparent)]
359    NonDeterministicReplay(ReplayFailure),
360    #[error(transparent)]
361    ChildWorkflowFailed(ChildWorkflowFailure),
362    #[error(transparent)]
363    ActivityFailed(ActivityFailure),
364    #[error(transparent)]
365    ActivityError(#[from] ActivityError),
366    #[error(transparent)]
367    NexusOperationFailed(Box<NexusOperationFailure>),
368    #[error(transparent)]
369    ParallelFailed(ParallelFailure),
370    #[error(transparent)]
371    SagaCompensationFailed(SagaCompensationFailure),
372    #[error(transparent)]
373    InvalidParallelGroup(ParallelGroupError),
374    #[error(transparent)]
375    DurableOperationCancelled(DurableOperationCancelled),
376    #[error(transparent)]
377    WorkflowCancellationRequested(WorkflowCancellationRequested),
378    #[error(transparent)]
379    CooperativeCancellationRequested(CooperativeCancellationRequested),
380    #[error(transparent)]
381    CancellationScopeRequested(CancellationScopeRequested),
382    #[error(transparent)]
383    WorkflowCommandRejected(WorkflowCommandRejection),
384    #[error(transparent)]
385    WorkflowFailed(WorkflowTerminalOutcome),
386    #[error(transparent)]
387    WorkflowCancelled(WorkflowTerminalOutcome),
388    #[error(transparent)]
389    WorkflowTerminated(WorkflowTerminalOutcome),
390    #[error(transparent)]
391    WorkflowTimedOut(WorkflowTerminalOutcome),
392    #[error(transparent)]
393    ActivityTaskRejected(ActivityTaskRejection),
394    #[error("activity lease renewal unavailable: {0}")]
395    ActivityLeaseRenewalUnavailable(String),
396    #[error("workflow handler {0:?} is not registered")]
397    WorkflowNotRegistered(String),
398    #[error("activity handler {0:?} is not registered")]
399    ActivityNotRegistered(String),
400    #[error(
401        "{handler_kind} handler {handler_name:?} {value_kind} type {rust_type} is incompatible with the fixed Avro Value codec: {message}"
402    )]
403    HandlerType {
404        handler_kind: HandlerKind,
405        handler_name: String,
406        value_kind: HandlerValueKind,
407        rust_type: &'static str,
408        message: String,
409    },
410    #[error("workflow future yielded without emitting a durable command")]
411    WorkflowYieldedWithoutCommand,
412    #[error(
413        "workflow_stream_command_identity_missing: workflow stream authoring requires a non-empty server-provided workflow_command_id or task_id"
414    )]
415    MissingWorkflowCommandIdentity,
416    #[error("workflow state lock is poisoned")]
417    WorkflowStatePoisoned,
418    #[error("timer duration is too large for the worker protocol")]
419    TimerDurationOverflow,
420    #[error(transparent)]
421    InvalidConditionWaitOptions(#[from] ConditionWaitOptionsError),
422    #[error(transparent)]
423    InvalidSearchAttributeUpdate(#[from] SearchAttributeUpdateError),
424    #[error("operation timed out")]
425    Timeout,
426    /// A response body, after decoding (for example gzip), exceeded
427    /// [`ClientBuilder::max_response_bytes`]. The rest was not read.
428    #[error("response body exceeded {limit_bytes} bytes after decoding")]
429    ResponseBodyTooLarge { limit_bytes: usize },
430    #[error(
431        "missing {role}-plane credentials: configure ClientBuilder::{role}_token or ClientBuilder::token; a {opposite_role}-plane token cannot authorize this request"
432    )]
433    MissingRoleCredentials {
434        role: &'static str,
435        opposite_role: &'static str,
436    },
437    #[error("worker loop error: {0}")]
438    WorkerLoop(String),
439    #[error(
440        "workflow command contract for {workflow_type:?} declares update validators, but this Rust SDK cannot execute synchronous pre-accept update validation"
441    )]
442    UnsupportedUpdateValidators { workflow_type: String },
443    #[error("{primary}; worker deregistration also failed: {deregistration}")]
444    WorkerShutdown {
445        primary: Box<Error>,
446        deregistration: Box<Error>,
447    },
448    #[error("invalid child workflow options: {0}")]
449    InvalidChildWorkflowOptions(String),
450    #[error("invalid workflow memo update: {0}")]
451    InvalidMemoUpdate(String),
452    #[error(
453        "workflow_memo_updates_unavailable: the connected runtime did not advertise workflow memo update support"
454    )]
455    WorkflowMemoUpdatesUnavailable,
456    /// The connected Server does not advertise the `signal_external_workflow`
457    /// workflow-task command. Nothing was submitted. Returned to workflow code
458    /// from [`WorkflowContext::signal_external_workflow`]; if the workflow
459    /// returns it, the worker fails the workflow task (not the run).
460    #[error(
461        "signal_external_workflow_unavailable: the connected Server does not advertise the signal_external_workflow workflow command; nothing was submitted"
462    )]
463    SignalExternalWorkflowUnavailable,
464    /// [`WorkflowContext::signal_external_workflow`] was given an invalid
465    /// target or signal name. Nothing was submitted.
466    #[error("invalid external signal: {0}")]
467    InvalidExternalSignal(String),
468    /// An accepted update had not completed when the wait ended; it has no
469    /// result yet. See [`UpdatePending`].
470    #[error(transparent)]
471    UpdateStillPending(UpdatePending),
472    /// The connected Server does not advertise `update_outcome_reads`, so an
473    /// update outcome cannot be read by update id. Nothing was read or sent.
474    #[error(
475        "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"
476    )]
477    UpdateOutcomeReadsUnavailable,
478    /// The connected Server does not advertise `signal_with_start`, so the
479    /// atomic intake is unavailable. Nothing was sent.
480    #[error(
481        "signal_with_start_unavailable: the connected Server does not advertise signal_with_start; separate start_workflow() and signal_workflow() calls are not atomic, because the run can close between them"
482    )]
483    SignalWithStartUnavailable,
484    /// A successful update outcome read did not answer with a receipt for the
485    /// requested update: it lacked a matching `update_id` and `update_status`,
486    /// or claimed a finished outcome without being completed. No outcome is
487    /// returned for it.
488    #[error(
489        "update_outcome_unrecognized: the Server's answer is not an outcome receipt for update {update_id:?} on workflow {workflow_id:?}; no outcome was read"
490    )]
491    UnrecognizedUpdateOutcome {
492        workflow_id: String,
493        update_id: String,
494        receipt: Value,
495    },
496    #[error("cooperative cancellation is unavailable: {0}")]
497    CooperativeCancellationUnavailable(String),
498    #[error("cancellation_scope_execution_not_supported: Rust worker cannot replay scoped cancellation history")]
499    CancellationScopeExecutionUnavailable,
500    #[error("invalid cooperative cancellation: {0}")]
501    InvalidCooperativeCancellation(String),
502    #[error("activity execution no longer owns its claim: {0}")]
503    ActivityExecutionAbandoned(String),
504    #[error(transparent)]
505    InvalidActivityOptions(ActivityOptionsError),
506    #[error(transparent)]
507    InvalidContinueAsNewOptions(#[from] ContinueAsNewOptionsError),
508    #[doc(hidden)]
509    #[error("workflow requested continue as new")]
510    ContinueAsNew(ContinueAsNewRequest),
511}
512
513impl Error {
514    /// The caller command key echoed by the Server in a refusal body.
515    ///
516    /// Signals and updates send their key as the `request_id` body field, and a
517    /// Server refusal can echo it. A `request_id_conflict` refusal always
518    /// carries it: when the Server does not echo it (native Server 3.9.0 does
519    /// not), the SDK adds the key it sent. Transport failures and other
520    /// refusals without an echoed key return `None`: keep the key you passed
521    /// to a `*_with_request_id` method, or obtained from
522    /// [`Client::generate_signal_request_id`] or
523    /// [`Client::generate_update_request_id`], to retry the same logical command
524    /// after an uncertain outcome.
525    pub fn request_id(&self) -> Option<String> {
526        self.refusal_body()?
527            .get("request_id")
528            .and_then(Value::as_str)
529            .filter(|request_id| !request_id.is_empty())
530            .map(str::to_string)
531    }
532
533    /// Whether the Server refused a signal or update because its caller command
534    /// key is retained for a command with a different intent
535    /// (HTTP 409, `reason: "request_id_conflict"`).
536    ///
537    /// The SDK never resends this refusal, and the caller should not retry it
538    /// unchanged: send the original input to recover the retained receipt, or
539    /// use a new key for new input.
540    pub fn is_request_id_conflict(&self) -> bool {
541        self.request_id_conflict().is_some()
542    }
543
544    /// The retained-command details of a `request_id_conflict` refusal.
545    pub fn request_id_conflict(&self) -> Option<RequestIdConflict> {
546        let status = match self {
547            Self::Http { status, .. } => status.as_u16(),
548            Self::WorkflowCommandRejected(rejection) => rejection.status,
549            _ => return None,
550        };
551        request_id_conflict(status, self.refusal_body()?)
552    }
553
554    /// Whether the Server refused a signal or update because its caller command
555    /// key matches more than one retained command, so it cannot select one
556    /// receipt (HTTP 409, `reason: "request_id_ambiguous"`).
557    ///
558    /// This happens only for keys retained before the Server compared command
559    /// intent, for example after an upgrade from a Server that stored keys
560    /// without making them unique. Nothing was admitted or recorded and no
561    /// receipt was selected. The SDK never resends this refusal, and resending
562    /// it unchanged gets the same answer: inspect the workflow's recorded
563    /// signals and updates to find out what was applied, and use a new key
564    /// for any new command.
565    pub fn is_request_id_ambiguous(&self) -> bool {
566        self.request_id_ambiguous().is_some()
567    }
568
569    /// The details of a `request_id_ambiguous` refusal.
570    pub fn request_id_ambiguous(&self) -> Option<RequestIdAmbiguous> {
571        let status = match self {
572            Self::Http { status, .. } => status.as_u16(),
573            Self::WorkflowCommandRejected(rejection) => rejection.status,
574            _ => return None,
575        };
576        request_id_ambiguous(status, self.refusal_body()?)
577    }
578
579    /// Record the sent caller command key on a `request_id_conflict` or
580    /// `request_id_ambiguous` refusal whose body does not echo it, so
581    /// [`Error::request_id`], [`RequestIdConflict::request_id`] and
582    /// [`RequestIdAmbiguous::request_id`] name the key. Every other error, and
583    /// a body that already echoes a key, is returned unchanged.
584    fn with_sent_request_id(self, request_id: &str) -> Self {
585        let Self::Http { status, body } = self else {
586            return self;
587        };
588        let echoed = |map: &serde_json::Map<String, Value>| {
589            map.get("request_id")
590                .and_then(Value::as_str)
591                .is_some_and(|echoed| !echoed.is_empty())
592        };
593        match serde_json::from_str::<Value>(&body) {
594            Ok(Value::Object(mut map))
595                if matches!(
596                    map.get("reason").and_then(Value::as_str),
597                    Some(REQUEST_ID_CONFLICT_REASON | REQUEST_ID_AMBIGUOUS_REASON)
598                ) && !echoed(&map) =>
599            {
600                map.insert(
601                    "request_id".to_string(),
602                    Value::String(request_id.to_string()),
603                );
604                Self::Http {
605                    status,
606                    body: Value::Object(map).to_string(),
607                }
608            }
609            _ => Self::Http { status, body },
610        }
611    }
612
613    /// Whether an update outcome read found no retained update with that id
614    /// for the workflow (HTTP 404, `reason: "update_not_found"`).
615    ///
616    /// That includes an update pruned with its run, so it does not prove the
617    /// update was never admitted.
618    pub fn is_update_not_found(&self) -> bool {
619        matches!(self, Self::Http { status, .. } if status.as_u16() == 404)
620            && self
621                .refusal_body()
622                .and_then(|body| {
623                    body.get("reason")
624                        .and_then(Value::as_str)
625                        .map(str::to_string)
626                })
627                .as_deref()
628                == Some("update_not_found")
629    }
630
631    fn refusal_body(&self) -> Option<Value> {
632        match self {
633            Self::Http { body, .. } => serde_json::from_str(body).ok(),
634            Self::WorkflowCommandRejected(rejection) => Some(rejection.body.clone()),
635            _ => None,
636        }
637    }
638}
639
640/// A refused signal or update whose caller command key is already retained for
641/// a command with a different intent.
642///
643/// Nothing was admitted or recorded, and the key stays bound to the retained
644/// command. Send a new key for a different command, or repeat the retained
645/// command's exact intent to receive its receipt. `conflict` lists the
646/// mismatched intent parts: `name`, `arguments` or `target_or_arguments`
647/// (native Server 3.9.0). `retained_command_id` names the retained command.
648/// `request_id` is the key that was sent. `retained_command_type` is `None`
649/// when the Server does not report it, as native Server 3.9.0 does not; the
650/// full answer, including `outcome: "rejected_request_id_conflict"`, is in
651/// `body`.
652///
653/// A Server that advertises `capabilities.command_request_keys` in
654/// [`Client::cluster_info`] compares every keyed signal and update this way.
655/// Older Servers (PHP Server 2.x and native up to 3.8) do not: a repeated
656/// signal key can record a second signal there, and an update retried with
657/// changed arguments returns the original receipt.
658#[derive(Clone, Debug, PartialEq)]
659#[non_exhaustive]
660pub struct RequestIdConflict {
661    pub status: u16,
662    pub request_id: String,
663    pub message: String,
664    pub retained_command_id: Option<String>,
665    pub retained_command_type: Option<String>,
666    pub retained_outcome: Option<String>,
667    pub conflict: Vec<String>,
668    pub body: Value,
669}
670
671fn request_id_conflict(status: u16, body: Value) -> Option<RequestIdConflict> {
672    if body.get("reason").and_then(Value::as_str) != Some(REQUEST_ID_CONFLICT_REASON) {
673        return None;
674    }
675    let string = |name: &str| body.get(name).and_then(Value::as_str).map(str::to_string);
676    Some(RequestIdConflict {
677        status,
678        request_id: string("request_id").unwrap_or_default(),
679        message: string("message")
680            .or_else(|| string("error"))
681            .unwrap_or_else(|| "request id is retained for a different command intent".to_string()),
682        retained_command_id: string("retained_command_id"),
683        retained_command_type: string("retained_command_type"),
684        retained_outcome: string("retained_outcome"),
685        conflict: body
686            .get("conflict")
687            .and_then(Value::as_array)
688            .map(|parts| {
689                parts
690                    .iter()
691                    .filter_map(Value::as_str)
692                    .map(str::to_string)
693                    .collect()
694            })
695            .unwrap_or_default(),
696        body,
697    })
698}
699
700/// A refused signal or update whose caller command key matches more than one
701/// retained command, so the Server could not select a receipt.
702///
703/// Only keys retained before the Server compared command intent can be
704/// ambiguous, for example rows written by an older Server that stored keys
705/// without making them unique. Nothing was admitted or recorded, and no
706/// receipt was selected: never treat this as the original command's receipt.
707/// Inspect the workflow's recorded signals and updates to see what was
708/// applied, and use a new key for any new command. `request_id` is the key that was sent. The full answer,
709/// including `retained: true` and `intent_verified: false`, is in `body`.
710#[derive(Clone, Debug, PartialEq)]
711#[non_exhaustive]
712pub struct RequestIdAmbiguous {
713    pub status: u16,
714    pub request_id: String,
715    pub message: String,
716    pub body: Value,
717}
718
719fn request_id_ambiguous(status: u16, body: Value) -> Option<RequestIdAmbiguous> {
720    if body.get("reason").and_then(Value::as_str) != Some(REQUEST_ID_AMBIGUOUS_REASON) {
721        return None;
722    }
723    let string = |name: &str| body.get(name).and_then(Value::as_str).map(str::to_string);
724    Some(RequestIdAmbiguous {
725        status,
726        request_id: string("request_id").unwrap_or_default(),
727        message: string("message")
728            .or_else(|| string("error"))
729            .unwrap_or_else(|| "request id matches more than one retained command".to_string()),
730        body,
731    })
732}
733
734/// Handler namespaces checked independently within a Worker.
735#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
736pub enum RegistrationKind {
737    Workflow,
738    Activity,
739    Query,
740    Update,
741}
742
743impl std::fmt::Display for RegistrationKind {
744    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
745        formatter.write_str(match self {
746            Self::Workflow => "workflow",
747            Self::Activity => "activity",
748            Self::Query => "query",
749            Self::Update => "update",
750        })
751    }
752}
753
754/// The authoring adapter and source location of a handler registration.
755#[derive(Clone, Debug, PartialEq, Eq)]
756pub struct HandlerRegistration {
757    pub method: &'static str,
758    pub handler_type: &'static str,
759    pub file: &'static str,
760    pub line: u32,
761    pub column: u32,
762}
763
764impl std::fmt::Display for HandlerRegistration {
765    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
766        write!(
767            formatter,
768            "{} at {}:{}:{} ({})",
769            self.method, self.file, self.line, self.column, self.handler_type
770        )
771    }
772}
773
774/// Ambiguous local configuration, rejected before contacting Server.
775#[derive(Clone, Debug, Error, PartialEq, Eq)]
776#[error("duplicate_registration: {handler_kind} name {handler_name:?} in workflow scope {workflow_type:?}; first {first_definition}; conflicting {second_definition}")]
777pub struct DuplicateRegistrationError {
778    pub handler_kind: RegistrationKind,
779    pub handler_name: String,
780    /// Query/update registrations are scoped to their owning workflow type.
781    pub workflow_type: Option<String>,
782    pub first_definition: HandlerRegistration,
783    pub second_definition: HandlerRegistration,
784}
785
786impl From<DuplicateRegistrationError> for Error {
787    fn from(error: DuplicateRegistrationError) -> Self {
788        Self::WorkerLoop(error.to_string())
789    }
790}
791
792/// Validation failure for a durable condition-wait definition.
793#[derive(Clone, Debug, Error, PartialEq, Eq)]
794pub enum ConditionWaitOptionsError {
795    #[error("condition_key must be non-empty")]
796    EmptyKey,
797    #[error("condition_definition_fingerprint must be non-empty")]
798    EmptyPredicateIdentity,
799    #[error("condition timeout is too large for the worker protocol")]
800    TimeoutOverflow,
801}
802
803/// Stable identity and optional durable timeout for a condition wait.
804///
805/// `predicate_identity` is recorded as the worker protocol's
806/// `condition_definition_fingerprint` and must change whenever predicate
807/// behavior changes. Prefer the [`wait_condition!`] macro when the predicate
808/// is written inline; it derives this identity from the predicate tokens.
809#[derive(Clone, Debug, PartialEq, Eq)]
810pub struct ConditionWaitOptions {
811    condition_key: String,
812    predicate_identity: String,
813    timeout: Option<Duration>,
814}
815
816impl ConditionWaitOptions {
817    pub fn new(condition_key: impl Into<String>, predicate_identity: impl Into<String>) -> Self {
818        Self {
819            condition_key: condition_key.into(),
820            predicate_identity: predicate_identity.into(),
821            timeout: None,
822        }
823    }
824
825    pub fn timeout(mut self, timeout: Duration) -> Self {
826        self.timeout = Some(timeout);
827        self
828    }
829
830    fn validate(
831        &self,
832    ) -> std::result::Result<ValidatedConditionWaitOptions, ConditionWaitOptionsError> {
833        let condition_key = self.condition_key.trim();
834        if condition_key.is_empty() {
835            return Err(ConditionWaitOptionsError::EmptyKey);
836        }
837        let predicate_identity = self.predicate_identity.trim();
838        if predicate_identity.is_empty() {
839            return Err(ConditionWaitOptionsError::EmptyPredicateIdentity);
840        }
841        let timeout_seconds = self
842            .timeout
843            .map(|timeout| {
844                timeout
845                    .as_secs()
846                    .checked_add(u64::from(timeout.subsec_nanos() > 0))
847                    .ok_or(ConditionWaitOptionsError::TimeoutOverflow)
848            })
849            .transpose()?;
850
851        Ok(ValidatedConditionWaitOptions {
852            condition_key: condition_key.to_string(),
853            predicate_identity: predicate_identity.to_string(),
854            timeout_seconds,
855        })
856    }
857}
858
859#[derive(Clone, Debug, PartialEq, Eq)]
860struct ValidatedConditionWaitOptions {
861    condition_key: String,
862    predicate_identity: String,
863    timeout_seconds: Option<u64>,
864}
865
866const CONDITION_WAIT_OCCURRENCE_PREFIX: &str = "rust:condition-wait:";
867
868/// Unambiguous terminal result of a durable condition wait.
869#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
870#[serde(rename_all = "snake_case")]
871pub enum ConditionWaitResult {
872    Satisfied,
873    TimedOut,
874}
875
876impl ConditionWaitResult {
877    pub fn is_satisfied(self) -> bool {
878        self == Self::Satisfied
879    }
880
881    pub fn is_timed_out(self) -> bool {
882        self == Self::TimedOut
883    }
884}
885
886/// Build the stable condition definition identity used by [`wait_condition!`].
887#[doc(hidden)]
888pub fn __condition_definition_fingerprint(source: &str) -> String {
889    let mut digest = Sha256::new();
890    digest.update(b"durable-workflow-rust.wait-condition.v1\0");
891    digest.update(source.as_bytes());
892    format!("sha256:{:x}", digest.finalize())
893}
894
895/// Create a durable condition wait whose predicate definition is fingerprinted
896/// from its inline Rust tokens.
897///
898/// The returned [`ConditionWaitCall`] must be awaited. The timeout form is
899/// `wait_condition!(ctx, "approval", timeout: duration, || predicate)`.
900///
901/// The identity includes the call site's [`module_path!`] and the predicate's
902/// [`stringify!`] output. Moving or renaming the workflow module changes it,
903/// even when the predicate behaves the same. Compiler upgrades can also change
904/// token stringification. Keep those identities stable while waits are open,
905/// or drain the affected runs before changing them.
906///
907/// Use [`ConditionWaitOptions::new`] with an explicit stable predicate identity
908/// when module moves or compiler changes must not affect it. Choose that
909/// identity before starting runs; replacing an existing macro fingerprint with
910/// a new label does not migrate histories. Change an explicit identity whenever
911/// the predicate's behavior changes.
912#[macro_export]
913macro_rules! wait_condition {
914    ($ctx:expr, $key:expr, timeout: $timeout:expr, $predicate:expr $(,)?) => {{
915        $ctx.wait_condition(
916            $crate::ConditionWaitOptions::new(
917                $key,
918                $crate::__condition_definition_fingerprint(concat!(
919                    module_path!(),
920                    "\0",
921                    stringify!($predicate)
922                )),
923            )
924            .timeout($timeout),
925            $predicate,
926        )
927    }};
928    ($ctx:expr, $key:expr, $predicate:expr $(,)?) => {{
929        $ctx.wait_condition(
930            $crate::ConditionWaitOptions::new(
931                $key,
932                $crate::__condition_definition_fingerprint(concat!(
933                    module_path!(),
934                    "\0",
935                    stringify!($predicate)
936                )),
937            ),
938            $predicate,
939        )
940    }};
941}
942
943const MAX_SEARCH_ATTRIBUTES_PER_UPDATE: usize = 100;
944const MAX_SEARCH_ATTRIBUTE_KEY_LENGTH: usize = 64;
945const MAX_SEARCH_ATTRIBUTE_STRING_LENGTH: usize = 2_048;
946const MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH: usize = 255;
947const MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES: usize = 65_536;
948
949/// Validation failure for a typed workflow search-attribute update.
950#[derive(Clone, Debug, Error, PartialEq, Eq)]
951pub enum SearchAttributeUpdateError {
952    #[error("search-attribute update requires at least one attribute")]
953    Empty,
954    #[error("search attribute key {0:?} must be 1-64 URL-safe ASCII characters")]
955    InvalidKey(String),
956    #[error("search-attribute update exceeds the limit of 100 attributes")]
957    TooManyAttributes,
958    #[error("search attribute {key:?} {kind} value exceeds {limit} bytes")]
959    ValueTooLong {
960        key: String,
961        kind: &'static str,
962        limit: usize,
963    },
964    #[error(
965        "search attribute {0:?} must not contain an empty string value; use delete() to remove it"
966    )]
967    EmptyString(String),
968    #[error("search attribute {0:?} has a non-finite float value")]
969    NonFiniteFloat(String),
970    #[error("search attribute {0:?} must use an RFC 3339 datetime with an explicit timezone")]
971    InvalidDateTime(String),
972    #[error("search-attribute update exceeds the 65536-byte protocol limit")]
973    PayloadTooLarge,
974}
975
976/// One public typed search-attribute value.
977#[derive(Clone, Debug, PartialEq)]
978pub enum SearchAttributeValue {
979    String(String),
980    Keyword(String),
981    KeywordList(Vec<String>),
982    Int(i64),
983    Float(f64),
984    Bool(bool),
985    DateTime(String),
986    Delete,
987}
988
989impl SearchAttributeValue {
990    fn type_name(&self) -> Option<&'static str> {
991        match self {
992            Self::String(_) => Some("string"),
993            Self::Keyword(_) => Some("keyword"),
994            Self::KeywordList(_) => Some("keyword_list"),
995            Self::Int(_) => Some("int"),
996            Self::Float(_) => Some("float"),
997            Self::Bool(_) => Some("bool"),
998            Self::DateTime(_) => Some("datetime"),
999            Self::Delete => None,
1000        }
1001    }
1002
1003    fn normalized(self, key: &str) -> std::result::Result<Self, SearchAttributeUpdateError> {
1004        let normalize_string = |value: String, kind: &'static str, limit: usize| {
1005            let value = value.trim().to_string();
1006            if value.is_empty() {
1007                return Err(SearchAttributeUpdateError::EmptyString(key.to_string()));
1008            }
1009            if value.len() > limit {
1010                return Err(SearchAttributeUpdateError::ValueTooLong {
1011                    key: key.to_string(),
1012                    kind,
1013                    limit,
1014                });
1015            }
1016            Ok(value)
1017        };
1018
1019        match self {
1020            Self::String(value) => Ok(Self::String(normalize_string(
1021                value,
1022                "string",
1023                MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
1024            )?)),
1025            Self::Keyword(value) => Ok(Self::Keyword(normalize_string(
1026                value,
1027                "keyword",
1028                MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
1029            )?)),
1030            Self::KeywordList(values) => {
1031                let values = values
1032                    .into_iter()
1033                    .map(|value| {
1034                        let value = value.trim().to_string();
1035                        if value.len() > MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH {
1036                            return Err(SearchAttributeUpdateError::ValueTooLong {
1037                                key: key.to_string(),
1038                                kind: "keyword-list entry",
1039                                limit: MAX_SEARCH_ATTRIBUTE_KEYWORD_LENGTH,
1040                            });
1041                        }
1042                        Ok(value)
1043                    })
1044                    .collect::<std::result::Result<Vec<_>, _>>()?;
1045                Ok(Self::KeywordList(values))
1046            }
1047            Self::Float(value) if !value.is_finite() => {
1048                Err(SearchAttributeUpdateError::NonFiniteFloat(key.to_string()))
1049            }
1050            Self::DateTime(value) => {
1051                let value =
1052                    normalize_string(value, "datetime", MAX_SEARCH_ATTRIBUTE_STRING_LENGTH)?;
1053                if DateTime::parse_from_rfc3339(&value).is_err() {
1054                    return Err(SearchAttributeUpdateError::InvalidDateTime(key.to_string()));
1055                }
1056                Ok(Self::DateTime(value))
1057            }
1058            value => Ok(value),
1059        }
1060    }
1061
1062    fn into_json(self) -> Value {
1063        match self {
1064            Self::String(value) | Self::Keyword(value) | Self::DateTime(value) => {
1065                Value::String(value)
1066            }
1067            Self::KeywordList(values) => {
1068                Value::Array(values.into_iter().map(Value::String).collect())
1069            }
1070            Self::Int(value) => json!(value),
1071            Self::Float(value) => json!(value),
1072            Self::Bool(value) => json!(value),
1073            Self::Delete => Value::Null,
1074        }
1075    }
1076}
1077
1078/// Validated typed workflow-side search-attribute mutation.
1079#[derive(Clone, Debug, Default, PartialEq)]
1080pub struct SearchAttributeUpdate {
1081    attributes: BTreeMap<String, SearchAttributeValue>,
1082}
1083
1084impl SearchAttributeUpdate {
1085    pub fn new() -> Self {
1086        Self::default()
1087    }
1088
1089    pub fn set(
1090        mut self,
1091        key: impl Into<String>,
1092        value: SearchAttributeValue,
1093    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1094        let key = key.into();
1095        validate_search_attribute_key(&key)?;
1096        if !self.attributes.contains_key(&key)
1097            && self.attributes.len() >= MAX_SEARCH_ATTRIBUTES_PER_UPDATE
1098        {
1099            return Err(SearchAttributeUpdateError::TooManyAttributes);
1100        }
1101        self.attributes.insert(key.clone(), value.normalized(&key)?);
1102        self.validate_size()?;
1103        Ok(self)
1104    }
1105
1106    pub fn string(
1107        self,
1108        key: impl Into<String>,
1109        value: impl Into<String>,
1110    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1111        self.set(key, SearchAttributeValue::String(value.into()))
1112    }
1113
1114    pub fn keyword(
1115        self,
1116        key: impl Into<String>,
1117        value: impl Into<String>,
1118    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1119        self.set(key, SearchAttributeValue::Keyword(value.into()))
1120    }
1121
1122    pub fn keyword_list<I, V>(
1123        self,
1124        key: impl Into<String>,
1125        values: I,
1126    ) -> std::result::Result<Self, SearchAttributeUpdateError>
1127    where
1128        I: IntoIterator<Item = V>,
1129        V: Into<String>,
1130    {
1131        self.set(
1132            key,
1133            SearchAttributeValue::KeywordList(values.into_iter().map(Into::into).collect()),
1134        )
1135    }
1136
1137    pub fn int(
1138        self,
1139        key: impl Into<String>,
1140        value: i64,
1141    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1142        self.set(key, SearchAttributeValue::Int(value))
1143    }
1144
1145    pub fn float(
1146        self,
1147        key: impl Into<String>,
1148        value: f64,
1149    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1150        self.set(key, SearchAttributeValue::Float(value))
1151    }
1152
1153    pub fn bool(
1154        self,
1155        key: impl Into<String>,
1156        value: bool,
1157    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1158        self.set(key, SearchAttributeValue::Bool(value))
1159    }
1160
1161    pub fn datetime(
1162        self,
1163        key: impl Into<String>,
1164        value: impl Into<String>,
1165    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1166        self.set(key, SearchAttributeValue::DateTime(value.into()))
1167    }
1168
1169    pub fn delete(
1170        self,
1171        key: impl Into<String>,
1172    ) -> std::result::Result<Self, SearchAttributeUpdateError> {
1173        self.set(key, SearchAttributeValue::Delete)
1174    }
1175
1176    fn validate_size(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
1177        let (attributes, _) = self.clone().into_wire_parts();
1178        if serde_json::to_vec(&attributes)
1179            .map(|payload| payload.len() > MAX_SEARCH_ATTRIBUTE_UPDATE_BYTES)
1180            .unwrap_or(true)
1181        {
1182            return Err(SearchAttributeUpdateError::PayloadTooLarge);
1183        }
1184        Ok(())
1185    }
1186
1187    fn into_wire_parts(self) -> (Value, BTreeMap<String, String>) {
1188        let mut attributes = serde_json::Map::new();
1189        let mut attribute_types = BTreeMap::new();
1190        for (key, value) in self.attributes {
1191            if let Some(type_name) = value.type_name() {
1192                attribute_types.insert(key.clone(), type_name.to_string());
1193            }
1194            attributes.insert(key, value.into_json());
1195        }
1196        (Value::Object(attributes), attribute_types)
1197    }
1198
1199    fn validate(&self) -> std::result::Result<(), SearchAttributeUpdateError> {
1200        if self.attributes.is_empty() {
1201            return Err(SearchAttributeUpdateError::Empty);
1202        }
1203        self.validate_size()
1204    }
1205}
1206
1207fn validate_search_attribute_key(key: &str) -> std::result::Result<(), SearchAttributeUpdateError> {
1208    let valid = !key.is_empty()
1209        && key.len() <= MAX_SEARCH_ATTRIBUTE_KEY_LENGTH
1210        && key
1211            .bytes()
1212            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
1213    if valid {
1214        Ok(())
1215    } else {
1216        Err(SearchAttributeUpdateError::InvalidKey(key.to_string()))
1217    }
1218}
1219
1220/// The registered handler family reported by [`Error::HandlerType`].
1221#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1222pub enum HandlerKind {
1223    Workflow,
1224    Activity,
1225}
1226
1227impl std::fmt::Display for HandlerKind {
1228    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1229        formatter.write_str(match self {
1230            Self::Workflow => "workflow",
1231            Self::Activity => "activity",
1232        })
1233    }
1234}
1235
1236/// Whether a typed handler failed to adapt its input or result.
1237#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1238pub enum HandlerValueKind {
1239    Input,
1240    Result,
1241}
1242
1243impl std::fmt::Display for HandlerValueKind {
1244    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1245        formatter.write_str(match self {
1246            Self::Input => "input",
1247            Self::Result => "result",
1248        })
1249    }
1250}
1251
1252/// The lifecycle command sent to a workflow execution.
1253#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1254pub enum WorkflowCommandKind {
1255    Cancel,
1256    Terminate,
1257}
1258
1259impl WorkflowCommandKind {
1260    fn as_str(self) -> &'static str {
1261        match self {
1262            Self::Cancel => "cancel",
1263            Self::Terminate => "terminate",
1264        }
1265    }
1266}
1267
1268/// Optional structured fields for a cancellation or termination request.
1269#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
1270pub struct WorkflowCommandOptions {
1271    #[serde(skip_serializing_if = "Option::is_none")]
1272    pub reason: Option<String>,
1273    #[serde(skip_serializing_if = "Option::is_none")]
1274    pub request_id: Option<String>,
1275}
1276
1277/// Server-enforced timeout policy for a workflow start.
1278///
1279/// These deadlines are distinct from [`WorkflowResultOptions::timeout`], which
1280/// only bounds how long the caller waits. A server deadline produces a terminal
1281/// [`Error::WorkflowTimedOut`] outcome whose reason is `execution_timeout` or
1282/// `run_timeout`.
1283#[derive(Clone, Debug, PartialEq, Eq)]
1284pub struct WorkflowStartOptions {
1285    pub execution_timeout_seconds: u64,
1286    pub run_timeout_seconds: u64,
1287}
1288
1289impl Default for WorkflowStartOptions {
1290    fn default() -> Self {
1291        Self {
1292            execution_timeout_seconds: 3600,
1293            run_timeout_seconds: 600,
1294        }
1295    }
1296}
1297
1298impl WorkflowStartOptions {
1299    pub fn new() -> Self {
1300        Self::default()
1301    }
1302
1303    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
1304        self.execution_timeout_seconds = seconds;
1305        self
1306    }
1307
1308    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
1309        self.run_timeout_seconds = seconds;
1310        self
1311    }
1312
1313    fn validate(&self) -> Result<()> {
1314        if self.execution_timeout_seconds == 0 {
1315            return Err(Error::Codec(
1316                "execution_timeout_seconds must be at least 1".to_string(),
1317            ));
1318        }
1319        if self.run_timeout_seconds == 0 {
1320            return Err(Error::Codec(
1321                "run_timeout_seconds must be at least 1".to_string(),
1322            ));
1323        }
1324        if self.run_timeout_seconds > self.execution_timeout_seconds {
1325            return Err(Error::Codec(
1326                "run_timeout_seconds cannot exceed execution_timeout_seconds".to_string(),
1327            ));
1328        }
1329
1330        Ok(())
1331    }
1332}
1333
1334/// Optional routing overrides for a continue-as-new transition.
1335///
1336/// Omitted values retain the current workflow type and task queue. Server-owned
1337/// instance metadata is not accepted here and is carried by the server.
1338#[derive(Clone, Debug, Default, PartialEq, Eq)]
1339pub struct ContinueAsNewOptions {
1340    pub workflow_type: Option<String>,
1341    pub task_queue: Option<String>,
1342}
1343
1344impl ContinueAsNewOptions {
1345    pub fn new() -> Self {
1346        Self::default()
1347    }
1348
1349    pub fn workflow_type(mut self, workflow_type: impl Into<String>) -> Self {
1350        self.workflow_type = Some(workflow_type.into());
1351        self
1352    }
1353
1354    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
1355        self.task_queue = Some(task_queue.into());
1356        self
1357    }
1358
1359    fn validate(&self) -> std::result::Result<(), ContinueAsNewOptionsError> {
1360        for (field, value) in [
1361            ("workflow_type", self.workflow_type.as_deref()),
1362            ("task_queue", self.task_queue.as_deref()),
1363        ] {
1364            if value.is_some_and(|value| value.trim().is_empty()) {
1365                return Err(ContinueAsNewOptionsError {
1366                    field,
1367                    message: format!("{field} must not be empty"),
1368                });
1369            }
1370        }
1371        Ok(())
1372    }
1373}
1374
1375/// A stable validation error raised before a continue-as-new command is emitted.
1376#[derive(Clone, Debug, Error, PartialEq, Eq)]
1377#[error("invalid continue-as-new option {field}: {message}")]
1378pub struct ContinueAsNewOptionsError {
1379    pub field: &'static str,
1380    pub message: String,
1381}
1382
1383/// Public history-budget information attached to the current workflow task.
1384#[derive(Clone, Debug, Default, PartialEq, Eq)]
1385pub struct WorkflowHistoryBudget {
1386    pub event_count: u64,
1387    pub size_bytes: Option<u64>,
1388    pub continue_as_new_recommended: bool,
1389    pub pressure: Option<String>,
1390}
1391
1392#[doc(hidden)]
1393#[derive(Clone, Debug)]
1394pub struct ContinueAsNewRequest {
1395    arguments: AvroValue,
1396    options: ContinueAsNewOptions,
1397}
1398
1399impl WorkflowCommandOptions {
1400    pub fn new() -> Self {
1401        Self::default()
1402    }
1403
1404    pub fn reason(mut self, reason: impl Into<String>) -> Self {
1405        self.reason = Some(reason.into());
1406        self
1407    }
1408
1409    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
1410        self.request_id = Some(request_id.into());
1411        self
1412    }
1413}
1414
1415/// The accepted, machine-readable result of a lifecycle command.
1416#[derive(Clone, Debug, PartialEq)]
1417pub struct WorkflowCommandResult {
1418    pub command: WorkflowCommandKind,
1419    pub workflow_id: String,
1420    pub run_id: Option<String>,
1421    pub outcome: Option<String>,
1422    pub reason: Option<String>,
1423    pub command_status: Option<String>,
1424    pub raw: Value,
1425}
1426
1427/// A new run continuing a failed run from its recorded activity boundary.
1428#[derive(Clone, Debug, PartialEq)]
1429pub struct WorkflowRedriveResult {
1430    pub workflow_id: String,
1431    pub source_run_id: String,
1432    pub run_id: String,
1433    pub resume_step_sequence: u64,
1434    pub raw: Value,
1435}
1436
1437/// A stable rejection returned by instance- or selected-run lifecycle commands.
1438#[derive(Clone, Debug, Error)]
1439#[error("workflow {command:?} rejected ({reason}, HTTP {status}): {message}")]
1440pub struct WorkflowCommandRejection {
1441    pub command: WorkflowCommandKind,
1442    pub status: u16,
1443    pub reason: String,
1444    pub message: String,
1445    pub workflow_id: String,
1446    pub run_id: Option<String>,
1447    pub target_scope: Option<String>,
1448    pub body: Value,
1449}
1450
1451/// Stable terminal categories returned by [`WorkflowHandle::result`].
1452#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1453pub enum WorkflowTerminalKind {
1454    Failed,
1455    Cancelled,
1456    Terminated,
1457    TimedOut,
1458}
1459
1460/// A typed terminal workflow outcome with durable identity and failure metadata.
1461///
1462/// Match the corresponding [`enum@Error`] variant and inspect these fields instead
1463/// of parsing its display representation. Fields remain `None` when an older
1464/// server did not publish that metadata.
1465#[derive(Clone, Debug, Error)]
1466#[error("workflow {workflow_id} run {run_id:?} ended as {kind:?} ({reason})")]
1467pub struct WorkflowTerminalOutcome {
1468    pub kind: WorkflowTerminalKind,
1469    pub workflow_id: String,
1470    pub run_id: Option<String>,
1471    pub reason: String,
1472    pub failure_category: Option<String>,
1473    pub failure_id: Option<String>,
1474    pub exception_type: Option<String>,
1475    pub exception_class: Option<String>,
1476    pub non_retryable: Option<bool>,
1477    pub message: Option<String>,
1478    pub exception: Option<Value>,
1479    pub raw: Value,
1480}
1481
1482/// A worker-side activity settlement or heartbeat rejected by durable state.
1483#[derive(Clone, Debug, Error)]
1484#[error("activity task {operation} rejected ({reason}, HTTP {status})")]
1485pub struct ActivityTaskRejection {
1486    pub operation: String,
1487    pub status: u16,
1488    pub reason: String,
1489    pub task_id: String,
1490    pub activity_attempt_id: String,
1491    pub cancel_requested: bool,
1492    pub can_continue: Option<bool>,
1493    pub run_closed_reason: Option<String>,
1494    pub body: Value,
1495}
1496
1497/// Stable validation categories for [`ActivityOptions`].
1498#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1499pub enum ActivityOptionsErrorKind {
1500    EmptyTaskQueue,
1501    EmptyRetryPolicy,
1502    InvalidMaxAttempts,
1503    BackoffWithoutRetryBudget,
1504    TooManyBackoffIntervals,
1505    InvalidBackoffCoefficient,
1506    BackoffGenerationTooLarge,
1507    BackoffOverflow,
1508    EmptyNonRetryableErrorType,
1509    TimeoutNotPositive,
1510    MissingTotalTimeout,
1511    TimeoutOverflow,
1512    TimeoutOrder,
1513}
1514
1515/// A machine-readable activity-options validation failure.
1516#[derive(Clone, Debug, Error, PartialEq, Eq)]
1517#[error("invalid activity options ({kind:?}, {field:?}): {message}")]
1518pub struct ActivityOptionsError {
1519    pub kind: ActivityOptionsErrorKind,
1520    pub field: Option<&'static str>,
1521    pub message: String,
1522}
1523
1524impl ActivityOptionsError {
1525    fn new(
1526        kind: ActivityOptionsErrorKind,
1527        field: Option<&'static str>,
1528        message: impl Into<String>,
1529    ) -> Self {
1530        Self {
1531            kind,
1532            field,
1533            message: message.into(),
1534        }
1535    }
1536}
1537
1538/// Stable terminal categories returned when an awaited activity does not succeed.
1539#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1540pub enum ActivityFailureKind {
1541    Failed,
1542    Cancelled,
1543    TimedOut,
1544}
1545
1546/// A stable, machine-readable terminal activity failure.
1547///
1548/// Match [`Error::ActivityFailed`] and inspect `kind`, `reason`,
1549/// `failure_category`, or `timeout_kind`; display text is only diagnostic.
1550#[derive(Clone, Debug, Error, PartialEq)]
1551#[error("activity failed ({reason}): {message}")]
1552pub struct ActivityFailure {
1553    pub kind: ActivityFailureKind,
1554    pub reason: String,
1555    pub message: String,
1556    pub activity_execution_id: Option<String>,
1557    pub activity_attempt_id: Option<String>,
1558    pub activity_type: Option<String>,
1559    pub activity_class: Option<String>,
1560    pub attempt_number: Option<u64>,
1561    pub failure_id: Option<String>,
1562    pub failure_category: Option<String>,
1563    pub timeout_kind: Option<String>,
1564    pub non_retryable: bool,
1565    pub exception_type: Option<String>,
1566    pub exception_class: Option<String>,
1567    pub code: Option<Value>,
1568    pub exception: Option<Value>,
1569}
1570
1571/// Why an activity attempt lost its worker. See [`ActivityFailure::lease_loss_reason`].
1572#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1573#[non_exhaustive]
1574pub enum LeaseLossReason {
1575    /// The Server settled the attempt because its lease expired.
1576    LeaseExpired,
1577    /// The Server settled the attempt because its worker deregistered. Only
1578    /// reported when the recorded exception carries that `failure_reason`.
1579    WorkerDeregistered,
1580    /// The worker released the attempt because it could not renew the lease.
1581    WorkerLost,
1582}
1583
1584impl LeaseLossReason {
1585    /// The stable wire name: `lease_expired`, `worker_deregistered` or `worker_lost`.
1586    pub fn as_str(self) -> &'static str {
1587        match self {
1588            Self::LeaseExpired => "lease_expired",
1589            Self::WorkerDeregistered => "worker_deregistered",
1590            Self::WorkerLost => "worker_lost",
1591        }
1592    }
1593}
1594
1595impl std::fmt::Display for LeaseLossReason {
1596    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1597        f.write_str(self.as_str())
1598    }
1599}
1600
1601/// `exception_class` the Server records when it settles a lost activity lease.
1602const ACTIVITY_LEASE_EXPIRED_CLASS: &str =
1603    "Workflow\\V2\\Exceptions\\ActivityLeaseExpiredException";
1604
1605impl ActivityFailure {
1606    /// Why the attempt lost its worker, or `None` when it failed for another
1607    /// reason.
1608    ///
1609    /// `WorkerLost` means a worker released the attempt (`exception_type`
1610    /// `worker_lost`) because it could not keep the lease. A lease the Server
1611    /// settled (`ActivityLeaseExpiredException`) reports the Server's recorded
1612    /// `failure_reason`: `WorkerDeregistered`, or `LeaseExpired` by default.
1613    /// The Server records that reason beside the exception in the history
1614    /// payload; replay copies it into `exception.failure_reason`, so this
1615    /// works without a new field. Whether to retry is the retry policy's
1616    /// choice; the default policy is unchanged.
1617    pub fn lease_loss_reason(&self) -> Option<LeaseLossReason> {
1618        if self.exception_type.as_deref() == Some(activity_lease::authority::WORKER_LOST_TYPE) {
1619            return Some(LeaseLossReason::WorkerLost);
1620        }
1621        if self.exception_class.as_deref() != Some(ACTIVITY_LEASE_EXPIRED_CLASS) {
1622            return None;
1623        }
1624        let recorded = self.exception.as_ref().and_then(|exception| {
1625            exception
1626                .get("failure_reason")
1627                .or_else(|| exception.get("properties")?.get("failure_reason"))
1628                .and_then(Value::as_str)
1629        });
1630        Some(match recorded {
1631            Some("worker_deregistered") => LeaseLossReason::WorkerDeregistered,
1632            _ => LeaseLossReason::LeaseExpired,
1633        })
1634    }
1635}
1636
1637/// Stable terminal categories returned when an awaited child does not succeed.
1638#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1639pub enum ChildWorkflowFailureKind {
1640    Failed,
1641    Cancelled,
1642    Terminated,
1643}
1644
1645/// A stable, machine-readable child workflow failure delivered to its parent.
1646///
1647/// Match [`Error::ChildWorkflowFailed`] and inspect `reason` or `kind` instead
1648/// of parsing the display message. Child and parent identifiers retain the
1649/// relationship recorded in durable history across worker restarts.
1650#[derive(Clone, Debug, Error)]
1651#[error("child workflow failed ({reason}): {message}")]
1652pub struct ChildWorkflowFailure {
1653    pub kind: ChildWorkflowFailureKind,
1654    pub reason: String,
1655    pub message: String,
1656    pub parent_workflow_id: Option<String>,
1657    pub parent_workflow_run_id: Option<String>,
1658    pub child_workflow_id: Option<String>,
1659    pub child_workflow_run_id: Option<String>,
1660    pub child_workflow_type: Option<String>,
1661    pub failure_id: Option<String>,
1662    pub failure_category: Option<String>,
1663    pub exception_type: Option<String>,
1664    pub exception_class: Option<String>,
1665    pub non_retryable: bool,
1666    pub code: Option<Value>,
1667    pub exception: Option<Value>,
1668}
1669
1670/// The identity of one durable workflow execution.
1671#[derive(Clone, Debug, PartialEq, Eq)]
1672pub struct WorkflowIdentity {
1673    pub workflow_id: Option<String>,
1674    pub run_id: Option<String>,
1675}
1676
1677/// The schedule fire that started a run, read from the run's own
1678/// `ScheduleTriggered` history event.
1679///
1680/// `occurrence_time` is the time the scheduler evaluated, as recorded (RFC
1681/// 3339): the jittered fire time for a tick, or the enumerated time for a
1682/// backfill. It is not the run's actual start time. It is `None` for a fire
1683/// recorded without an occurrence, such as a manual trigger.
1684#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1685#[non_exhaustive]
1686pub struct ScheduleOrigin {
1687    pub schedule_id: String,
1688    pub occurrence_time: Option<String>,
1689    pub trigger_number: Option<u64>,
1690}
1691
1692impl ScheduleOrigin {
1693    /// The run's schedule origin from recorded history, or `None` when no
1694    /// schedule started it.
1695    fn from_history(history: &[HistoryEvent]) -> Option<Self> {
1696        let event = history
1697            .iter()
1698            .find(|event| event.event_type == "ScheduleTriggered")?;
1699        let schedule_id = event
1700            .payload
1701            .get("schedule_id")
1702            .and_then(Value::as_str)
1703            .filter(|id| !id.is_empty())?
1704            .to_string();
1705        let occurrence_time = event
1706            .payload
1707            .get("occurrence_time")
1708            .and_then(Value::as_str)
1709            .filter(|time| DateTime::parse_from_rfc3339(time).is_ok())
1710            .map(str::to_string);
1711        let trigger_number = event
1712            .payload
1713            .get("trigger_number")
1714            .and_then(Value::as_u64)
1715            .filter(|number| *number > 0);
1716        Some(Self {
1717            schedule_id,
1718            occurrence_time,
1719            trigger_number,
1720        })
1721    }
1722}
1723
1724/// A successful child result together with its durable parent-child identity.
1725#[derive(Clone, Debug, PartialEq)]
1726pub struct ChildWorkflowResult {
1727    pub parent: WorkflowIdentity,
1728    pub child: WorkflowIdentity,
1729    pub child_workflow_type: Option<String>,
1730    pub result: Value,
1731}
1732
1733/// Lossless successful child result for fixed Avro Value workflows.
1734#[derive(Clone, Debug, PartialEq)]
1735pub struct ChildWorkflowAvroResult {
1736    pub parent: WorkflowIdentity,
1737    pub child: WorkflowIdentity,
1738    pub child_workflow_type: Option<String>,
1739    pub result: AvroValue,
1740}
1741
1742/// Stable user-facing identity for one member of a durable selection group.
1743#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
1744#[serde(untagged)]
1745pub enum SelectionKey {
1746    Index(usize),
1747    Name(String),
1748}
1749
1750impl From<usize> for SelectionKey {
1751    fn from(value: usize) -> Self {
1752        Self::Index(value)
1753    }
1754}
1755
1756impl From<String> for SelectionKey {
1757    fn from(value: String) -> Self {
1758        Self::Name(value)
1759    }
1760}
1761
1762impl From<&str> for SelectionKey {
1763    fn from(value: &str) -> Self {
1764        Self::Name(value.to_string())
1765    }
1766}
1767
1768/// Typed result of explicitly awaiting a cancelled non-winning operation.
1769#[derive(Clone, Debug, Error, PartialEq, Eq)]
1770#[error("selected {operation_kind} operation {operation_identity} was explicitly cancelled")]
1771pub struct DurableOperationCancelled {
1772    pub selection_group_id: String,
1773    pub member_key: SelectionKey,
1774    pub member_index: usize,
1775    pub operation_kind: String,
1776    pub operation_identity: String,
1777}
1778
1779/// Stable identity for one enclosing deterministic parallel group.
1780///
1781/// The same fields are attached to every ordinary activity, timer, or child
1782/// workflow command in the group. Nested leaves carry an outer-to-inner path;
1783/// no Rust-specific wire command is introduced.
1784#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
1785pub struct ParallelGroupMetadata {
1786    pub parallel_group_id: String,
1787    pub parallel_group_kind: String,
1788    pub parallel_group_base_sequence: u64,
1789    pub parallel_group_size: usize,
1790    pub parallel_group_index: usize,
1791    #[serde(default, skip_serializing_if = "Option::is_none")]
1792    pub parallel_group_mode: Option<String>,
1793    #[serde(default, skip_serializing_if = "Option::is_none")]
1794    pub selection_member_key: Option<SelectionKey>,
1795    #[serde(default, skip_serializing_if = "Option::is_none")]
1796    pub selection_member_index: Option<usize>,
1797    #[serde(default, skip_serializing_if = "Option::is_none")]
1798    pub selection_member_base_sequence: Option<u64>,
1799    #[serde(default, skip_serializing_if = "Option::is_none")]
1800    pub selection_member_size: Option<usize>,
1801    #[serde(default, skip_serializing_if = "Option::is_none")]
1802    pub selection_member_kind: Option<String>,
1803}
1804
1805/// One input-ordered result returned by [`WorkflowContext::parallel`].
1806#[derive(Clone, Debug, PartialEq)]
1807pub enum ParallelResult {
1808    Activity(Value),
1809    ChildWorkflow(ChildWorkflowResult),
1810    Timer,
1811    Signal(Vec<Value>),
1812    Condition(ConditionWaitResult),
1813    Group(Vec<ParallelResult>),
1814}
1815
1816/// Lossless fixed-Avro counterpart to [`ParallelResult`].
1817#[derive(Clone, Debug, PartialEq)]
1818pub enum ParallelAvroResult {
1819    Activity(AvroValue),
1820    ChildWorkflow(ChildWorkflowAvroResult),
1821    Timer,
1822    Signal(Vec<AvroValue>),
1823    Condition(ConditionWaitResult),
1824    Group(Vec<ParallelAvroResult>),
1825}
1826
1827impl ParallelAvroResult {
1828    fn into_json_result(self) -> Result<ParallelResult> {
1829        match self {
1830            Self::Activity(value) => Ok(ParallelResult::Activity(value.into_json()?)),
1831            Self::ChildWorkflow(result) => Ok(ParallelResult::ChildWorkflow(ChildWorkflowResult {
1832                parent: result.parent,
1833                child: result.child,
1834                child_workflow_type: result.child_workflow_type,
1835                result: result.result.into_json()?,
1836            })),
1837            Self::Timer => Ok(ParallelResult::Timer),
1838            Self::Signal(values) => Ok(ParallelResult::Signal(
1839                values
1840                    .into_iter()
1841                    .map(AvroValue::into_json)
1842                    .collect::<Result<Vec<_>>>()?,
1843            )),
1844            Self::Condition(result) => Ok(ParallelResult::Condition(result)),
1845            Self::Group(results) => Ok(ParallelResult::Group(
1846                results
1847                    .into_iter()
1848                    .map(Self::into_json_result)
1849                    .collect::<Result<Vec<_>>>()?,
1850            )),
1851        }
1852    }
1853}
1854
1855/// One successful leaf retained when another parallel member failed.
1856#[derive(Clone, Debug, PartialEq)]
1857pub struct ParallelCompletion {
1858    pub member_path: Vec<usize>,
1859    pub result: ParallelResult,
1860}
1861
1862/// A deterministic join failed after some siblings had already completed.
1863///
1864/// `cause` retains the typed activity, child-workflow, cancellation, or codec
1865/// error. `completed` is declaration ordered and contains only durable
1866/// successes observed in the same replay. Late sibling completions can add
1867/// entries on a later replay without changing `member_path` or the selected
1868/// positional failure.
1869#[derive(Debug, Error)]
1870#[error("parallel group {group_id} member {member_path:?} failed: {cause}")]
1871pub struct ParallelFailure {
1872    pub group_id: String,
1873    pub member_path: Vec<usize>,
1874    pub group_path: Vec<ParallelGroupMetadata>,
1875    pub completed: Vec<ParallelCompletion>,
1876    #[source]
1877    pub cause: Box<Error>,
1878}
1879
1880/// Stable validation error returned before an invalid group emits commands.
1881#[derive(Clone, Debug, Error, PartialEq, Eq)]
1882#[error("invalid deterministic parallel group ({reason}): {message}")]
1883pub struct ParallelGroupError {
1884    pub reason: &'static str,
1885    pub member_path: Vec<usize>,
1886    pub message: String,
1887}
1888
1889/// Cooperative workflow cancellation observed at an author-controlled point.
1890#[derive(Clone, Debug, Error, PartialEq, Eq)]
1891#[error("workflow cancellation was requested")]
1892pub struct WorkflowCancellationRequested;
1893
1894/// A forward saga failure followed by a terminal compensation failure.
1895#[derive(Debug, Error)]
1896#[error(
1897    "saga forward execution failed; compensation activity {compensation_activity_type} (registration {compensation_registration_order}) also failed: {compensation_failure}"
1898)]
1899pub struct SagaCompensationFailure {
1900    pub initiating_failure: Box<Error>,
1901    pub compensation_failure: Box<Error>,
1902    pub compensation_activity_type: String,
1903    pub compensation_registration_order: usize,
1904}
1905
1906/// Server behavior when a parent closes while its child is still open.
1907#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1908pub enum ParentClosePolicy {
1909    #[default]
1910    Abandon,
1911    /// Legacy terminal cancellation without cooperative cleanup.
1912    RequestCancel,
1913    /// Request cooperative cleanup with the original lineage and deadline.
1914    RequestCancellation,
1915    Terminate,
1916}
1917
1918impl ParentClosePolicy {
1919    fn as_str(self) -> &'static str {
1920        match self {
1921            Self::Abandon => "abandon",
1922            Self::RequestCancel => "request_cancel",
1923            Self::RequestCancellation => "request_cancellation",
1924            Self::Terminate => "terminate",
1925        }
1926    }
1927}
1928
1929/// Cancellation at an awaiting operation. Activities default to Try, children to Abandon.
1930#[non_exhaustive]
1931#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1932pub enum CancellationPolicy {
1933    /// Request cancellation and continue without waiting. Historical Activity default.
1934    TryCancel,
1935    /// Wait for recorded child termination or the original Activity attempt's stop receipt.
1936    WaitCancellationCompleted,
1937    /// Leave work independent. Historical child default. Remote Activities require a total timeout.
1938    #[default]
1939    Abandon,
1940}
1941
1942impl CancellationPolicy {
1943    fn as_str(self) -> &'static str {
1944        match self {
1945            Self::TryCancel => "try_cancel",
1946            Self::WaitCancellationCompleted => "wait_cancellation_completed",
1947            Self::Abandon => "abandon",
1948        }
1949    }
1950}
1951
1952/// Durable retry policy for one child workflow invocation.
1953#[derive(Clone, Debug, Default, PartialEq, Eq)]
1954pub struct ChildWorkflowRetryPolicy {
1955    pub max_attempts: Option<u32>,
1956    pub backoff_seconds: Vec<u64>,
1957    pub non_retryable_error_types: Vec<String>,
1958}
1959
1960/// Options recorded with a child-workflow command.
1961///
1962/// The task queue is mandatory so routing is explicit and replay-stable.
1963#[derive(Clone, Debug, PartialEq, Eq)]
1964pub struct ChildWorkflowOptions {
1965    pub task_queue: String,
1966    pub parent_close_policy: ParentClosePolicy,
1967    pub cancellation_policy: CancellationPolicy,
1968    pub retry_policy: Option<ChildWorkflowRetryPolicy>,
1969    pub execution_timeout_seconds: Option<u64>,
1970    pub run_timeout_seconds: Option<u64>,
1971}
1972
1973impl ChildWorkflowOptions {
1974    pub fn new(task_queue: impl Into<String>) -> Self {
1975        Self {
1976            task_queue: task_queue.into(),
1977            parent_close_policy: ParentClosePolicy::Abandon,
1978            cancellation_policy: CancellationPolicy::Abandon,
1979            retry_policy: None,
1980            execution_timeout_seconds: None,
1981            run_timeout_seconds: None,
1982        }
1983    }
1984
1985    pub fn parent_close_policy(mut self, policy: ParentClosePolicy) -> Self {
1986        self.parent_close_policy = policy;
1987        self
1988    }
1989
1990    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
1991        self.cancellation_policy = policy;
1992        self
1993    }
1994
1995    pub fn retry_policy(mut self, policy: ChildWorkflowRetryPolicy) -> Self {
1996        self.retry_policy = Some(policy);
1997        self
1998    }
1999
2000    pub fn execution_timeout_seconds(mut self, seconds: u64) -> Self {
2001        self.execution_timeout_seconds = Some(seconds);
2002        self
2003    }
2004
2005    pub fn run_timeout_seconds(mut self, seconds: u64) -> Self {
2006        self.run_timeout_seconds = Some(seconds);
2007        self
2008    }
2009}
2010
2011/// Backoff intervals for one durable activity retry policy.
2012#[derive(Clone, Debug, PartialEq, Eq)]
2013pub enum ActivityBackoff {
2014    /// Use these intervals between attempts. The server repeats the final
2015    /// interval if the retry budget contains more attempts than entries.
2016    /// All entries are retained, including those beyond the retry budget.
2017    Explicit(Vec<Duration>),
2018    /// Generate one interval for every retry using integer exponential growth.
2019    Exponential {
2020        initial_interval: Duration,
2021        coefficient: u32,
2022        maximum_interval: Option<Duration>,
2023    },
2024}
2025
2026/// Durable server-side retry policy for one activity execution.
2027#[derive(Clone, Debug, Default, PartialEq, Eq)]
2028pub struct ActivityRetryPolicy {
2029    pub max_attempts: Option<u32>,
2030    pub backoff: Option<ActivityBackoff>,
2031    pub non_retryable_error_types: Vec<String>,
2032}
2033
2034impl ActivityRetryPolicy {
2035    /// Start a policy with a finite attempt budget, including the first attempt.
2036    pub fn new(max_attempts: u32) -> Self {
2037        Self {
2038            max_attempts: Some(max_attempts),
2039            ..Self::default()
2040        }
2041    }
2042
2043    /// Preserve the complete explicit list independently of the attempt budget.
2044    /// Unused entries remain part of the policy compared during replay.
2045    /// Set explicit durable retry intervals. Each positive fractional second
2046    /// is rounded up when encoded: `Duration::from_millis(100)` becomes one
2047    /// second. Zero stays zero. Queue latency can delay the next attempt further.
2048    pub fn backoff_intervals(mut self, intervals: impl IntoIterator<Item = Duration>) -> Self {
2049        self.backoff = Some(ActivityBackoff::Explicit(intervals.into_iter().collect()));
2050        self
2051    }
2052
2053    /// Generate durable retry intervals from `initial_interval` and `coefficient`.
2054    /// Each interval is capped by `maximum_interval`, when present, then rounded
2055    /// up to whole seconds. A 100 ms interval or cap therefore encodes one second.
2056    /// Passing `None` selects no interval cap. The generated list still has a
2057    /// finite attempt budget. Arithmetic or protocol overflow returns
2058    /// [`ActivityOptionsErrorKind::BackoffOverflow`] during validation.
2059    /// Zero stays zero. This policy is separate from HTTP transport retries.
2060    pub fn exponential_backoff(
2061        mut self,
2062        initial_interval: Duration,
2063        coefficient: u32,
2064        maximum_interval: Option<Duration>,
2065    ) -> Self {
2066        self.backoff = Some(ActivityBackoff::Exponential {
2067            initial_interval,
2068            coefficient,
2069            maximum_interval,
2070        });
2071        self
2072    }
2073
2074    pub fn non_retryable_error_type(mut self, error_type: impl Into<String>) -> Self {
2075        self.non_retryable_error_types.push(error_type.into());
2076        self
2077    }
2078
2079    pub fn non_retryable_error_types(
2080        mut self,
2081        error_types: impl IntoIterator<Item = impl Into<String>>,
2082    ) -> Self {
2083        self.non_retryable_error_types
2084            .extend(error_types.into_iter().map(Into::into));
2085        self
2086    }
2087}
2088
2089/// Options recorded atomically on one deterministic `schedule_activity` command.
2090///
2091/// Durations are rounded up to whole seconds when encoded, so the server never
2092/// receives a shorter timeout or backoff than the caller requested.
2093#[derive(Clone, Debug, Default, PartialEq, Eq)]
2094pub struct ActivityOptions {
2095    pub task_queue: Option<String>,
2096    pub retry_policy: Option<ActivityRetryPolicy>,
2097    pub start_to_close_timeout: Option<Duration>,
2098    pub schedule_to_start_timeout: Option<Duration>,
2099    pub schedule_to_close_timeout: Option<Duration>,
2100    pub heartbeat_timeout: Option<Duration>,
2101    pub cancellation_policy: Option<CancellationPolicy>,
2102}
2103
2104impl ActivityOptions {
2105    pub fn new() -> Self {
2106        Self::default()
2107    }
2108
2109    pub fn task_queue(mut self, task_queue: impl Into<String>) -> Self {
2110        self.task_queue = Some(task_queue.into());
2111        self
2112    }
2113
2114    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
2115        self.retry_policy = Some(policy);
2116        self
2117    }
2118
2119    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
2120        self.start_to_close_timeout = Some(timeout);
2121        self
2122    }
2123
2124    pub fn schedule_to_start_timeout(mut self, timeout: Duration) -> Self {
2125        self.schedule_to_start_timeout = Some(timeout);
2126        self
2127    }
2128
2129    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
2130        self.schedule_to_close_timeout = Some(timeout);
2131        self
2132    }
2133
2134    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
2135        self.heartbeat_timeout = Some(timeout);
2136        self
2137    }
2138
2139    pub fn cancellation_policy(mut self, policy: CancellationPolicy) -> Self {
2140        self.cancellation_policy = Some(policy);
2141        self
2142    }
2143
2144    fn validate(&self) -> std::result::Result<ValidatedActivityOptions, ActivityOptionsError> {
2145        if self.cancellation_policy == Some(CancellationPolicy::Abandon)
2146            && self.schedule_to_close_timeout.is_none()
2147        {
2148            return Err(ActivityOptionsError::new(
2149                ActivityOptionsErrorKind::MissingTotalTimeout,
2150                Some("schedule_to_close_timeout"),
2151                "remote Activity Abandon requires a finite positive total timeout",
2152            ));
2153        }
2154        if self
2155            .task_queue
2156            .as_deref()
2157            .is_some_and(|queue| queue.trim().is_empty())
2158        {
2159            return Err(ActivityOptionsError::new(
2160                ActivityOptionsErrorKind::EmptyTaskQueue,
2161                Some("task_queue"),
2162                "task_queue must not be empty",
2163            ));
2164        }
2165
2166        for (field, value) in [
2167            ("start_to_close_timeout", self.start_to_close_timeout),
2168            ("schedule_to_start_timeout", self.schedule_to_start_timeout),
2169            ("schedule_to_close_timeout", self.schedule_to_close_timeout),
2170            ("heartbeat_timeout", self.heartbeat_timeout),
2171        ] {
2172            if value.is_some_and(|value| value.is_zero()) {
2173                return Err(ActivityOptionsError::new(
2174                    ActivityOptionsErrorKind::TimeoutNotPositive,
2175                    Some(field),
2176                    format!("{field} must be positive"),
2177                ));
2178            }
2179        }
2180
2181        validate_timeout_order(
2182            "heartbeat_timeout",
2183            self.heartbeat_timeout,
2184            "start_to_close_timeout",
2185            self.start_to_close_timeout,
2186        )?;
2187        validate_timeout_order(
2188            "start_to_close_timeout",
2189            self.start_to_close_timeout,
2190            "schedule_to_close_timeout",
2191            self.schedule_to_close_timeout,
2192        )?;
2193        validate_timeout_order(
2194            "schedule_to_start_timeout",
2195            self.schedule_to_start_timeout,
2196            "schedule_to_close_timeout",
2197            self.schedule_to_close_timeout,
2198        )?;
2199
2200        Ok(ValidatedActivityOptions {
2201            task_queue: self.task_queue.clone(),
2202            retry_policy: self
2203                .retry_policy
2204                .as_ref()
2205                .map(validate_activity_retry_policy)
2206                .transpose()?,
2207            start_to_close_timeout: timeout_seconds(
2208                "start_to_close_timeout",
2209                self.start_to_close_timeout,
2210            )?,
2211            schedule_to_start_timeout: timeout_seconds(
2212                "schedule_to_start_timeout",
2213                self.schedule_to_start_timeout,
2214            )?,
2215            schedule_to_close_timeout: timeout_seconds(
2216                "schedule_to_close_timeout",
2217                self.schedule_to_close_timeout,
2218            )?,
2219            heartbeat_timeout: timeout_seconds("heartbeat_timeout", self.heartbeat_timeout)?,
2220            cancellation_policy: self.cancellation_policy,
2221        })
2222    }
2223}
2224
2225/// A deferred durable leaf or nested group for [`WorkflowContext::parallel`].
2226///
2227/// Constructors capture arguments but perform no I/O. The join validates the
2228/// complete tree, attaches the existing parallel-group metadata to every
2229/// ordinary command, schedules all leaves, and then suspends.
2230pub enum ParallelOperation {
2231    Activity {
2232        activity_type: String,
2233        options: ActivityOptions,
2234        arguments: Result<AvroValue>,
2235    },
2236    ChildWorkflow {
2237        workflow_type: String,
2238        options: ChildWorkflowOptions,
2239        arguments: Result<AvroValue>,
2240    },
2241    Timer(Duration),
2242    Signal(String),
2243    Condition {
2244        options: ConditionWaitOptions,
2245        predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
2246    },
2247    Group(Vec<ParallelOperation>),
2248}
2249
2250impl ParallelOperation {
2251    pub fn activity<T: Serialize>(activity_type: impl Into<String>, args: T) -> Self {
2252        Self::activity_with_options(activity_type, ActivityOptions::new(), args)
2253    }
2254
2255    pub fn activity_with_options<T: Serialize>(
2256        activity_type: impl Into<String>,
2257        options: ActivityOptions,
2258        args: T,
2259    ) -> Self {
2260        Self::Activity {
2261            activity_type: activity_type.into(),
2262            options,
2263            arguments: AvroValue::from_serialize(&args),
2264        }
2265    }
2266
2267    pub fn child_workflow<T: Serialize>(
2268        workflow_type: impl Into<String>,
2269        options: ChildWorkflowOptions,
2270        args: T,
2271    ) -> Self {
2272        Self::ChildWorkflow {
2273            workflow_type: workflow_type.into(),
2274            options,
2275            arguments: AvroValue::from_serialize(&args),
2276        }
2277    }
2278
2279    pub fn timer(duration: Duration) -> Self {
2280        Self::Timer(duration)
2281    }
2282
2283    pub fn signal(signal_name: impl Into<String>) -> Self {
2284        Self::Signal(signal_name.into())
2285    }
2286
2287    pub fn condition<F>(options: ConditionWaitOptions, predicate: F) -> Self
2288    where
2289        F: Fn() -> Result<bool> + Send + 'static,
2290    {
2291        Self::Condition {
2292            options,
2293            predicate: Box::new(predicate),
2294        }
2295    }
2296
2297    pub fn group(operations: Vec<ParallelOperation>) -> Self {
2298        Self::Group(operations)
2299    }
2300}
2301
2302#[derive(Clone, Debug)]
2303struct ValidatedActivityOptions {
2304    task_queue: Option<String>,
2305    retry_policy: Option<Value>,
2306    start_to_close_timeout: Option<u64>,
2307    schedule_to_start_timeout: Option<u64>,
2308    schedule_to_close_timeout: Option<u64>,
2309    heartbeat_timeout: Option<u64>,
2310    cancellation_policy: Option<CancellationPolicy>,
2311}
2312
2313fn validate_timeout_order(
2314    smaller_name: &'static str,
2315    smaller: Option<Duration>,
2316    larger_name: &'static str,
2317    larger: Option<Duration>,
2318) -> std::result::Result<(), ActivityOptionsError> {
2319    if matches!((smaller, larger), (Some(smaller), Some(larger)) if smaller > larger) {
2320        return Err(ActivityOptionsError::new(
2321            ActivityOptionsErrorKind::TimeoutOrder,
2322            Some(smaller_name),
2323            format!("{smaller_name} must be <= {larger_name}"),
2324        ));
2325    }
2326    Ok(())
2327}
2328
2329fn timeout_seconds(
2330    field: &'static str,
2331    value: Option<Duration>,
2332) -> std::result::Result<Option<u64>, ActivityOptionsError> {
2333    value
2334        .map(|value| {
2335            activity_protocol_seconds(value).ok_or_else(|| {
2336                ActivityOptionsError::new(
2337                    ActivityOptionsErrorKind::TimeoutOverflow,
2338                    Some(field),
2339                    format!("{field} is too large for the worker protocol"),
2340                )
2341            })
2342        })
2343        .transpose()
2344}
2345
2346fn duration_seconds_ceil(value: Duration) -> Option<u64> {
2347    value
2348        .as_secs()
2349        .checked_add(u64::from(value.subsec_nanos() > 0))
2350}
2351
2352fn activity_protocol_seconds(value: Duration) -> Option<u64> {
2353    duration_seconds_ceil(value).filter(|seconds| *seconds <= i64::MAX as u64)
2354}
2355
2356fn validate_activity_retry_policy(
2357    policy: &ActivityRetryPolicy,
2358) -> std::result::Result<Value, ActivityOptionsError> {
2359    if policy.max_attempts.is_none()
2360        && policy.backoff.is_none()
2361        && policy.non_retryable_error_types.is_empty()
2362    {
2363        return Err(ActivityOptionsError::new(
2364            ActivityOptionsErrorKind::EmptyRetryPolicy,
2365            Some("retry_policy"),
2366            "retry_policy must configure at least one field",
2367        ));
2368    }
2369    if policy.max_attempts == Some(0) {
2370        return Err(ActivityOptionsError::new(
2371            ActivityOptionsErrorKind::InvalidMaxAttempts,
2372            Some("retry_policy.max_attempts"),
2373            "max_attempts must be >= 1",
2374        ));
2375    }
2376    if policy
2377        .non_retryable_error_types
2378        .iter()
2379        .any(|error_type| error_type.trim().is_empty())
2380    {
2381        return Err(ActivityOptionsError::new(
2382            ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
2383            Some("retry_policy.non_retryable_error_types"),
2384            "non_retryable_error_types must not contain empty values",
2385        ));
2386    }
2387
2388    let backoff_seconds = match &policy.backoff {
2389        None => None,
2390        Some(backoff) => {
2391            let max_attempts = policy.max_attempts.ok_or_else(|| {
2392                ActivityOptionsError::new(
2393                    ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
2394                    Some("retry_policy.backoff"),
2395                    "backoff requires max_attempts",
2396                )
2397            })?;
2398            let retry_count = max_attempts.saturating_sub(1) as usize;
2399            let intervals = match backoff {
2400                ActivityBackoff::Explicit(intervals) => intervals.clone(),
2401                ActivityBackoff::Exponential {
2402                    initial_interval,
2403                    coefficient,
2404                    maximum_interval,
2405                } => {
2406                    if *coefficient < 1 {
2407                        return Err(ActivityOptionsError::new(
2408                            ActivityOptionsErrorKind::InvalidBackoffCoefficient,
2409                            Some("retry_policy.backoff.coefficient"),
2410                            "backoff coefficient must be >= 1",
2411                        ));
2412                    }
2413                    if retry_count > 10_000 {
2414                        return Err(ActivityOptionsError::new(
2415                            ActivityOptionsErrorKind::BackoffGenerationTooLarge,
2416                            Some("retry_policy.max_attempts"),
2417                            "generated backoff supports at most 10000 retry intervals",
2418                        ));
2419                    }
2420                    let mut current = *initial_interval;
2421                    let mut intervals = Vec::with_capacity(retry_count);
2422                    for _ in 0..retry_count {
2423                        let interval = maximum_interval
2424                            .map(|maximum| current.min(maximum))
2425                            .unwrap_or(current);
2426                        intervals.push(interval);
2427                        if maximum_interval.is_some_and(|maximum| interval == maximum) {
2428                            break;
2429                        }
2430                        current = current.checked_mul(*coefficient).ok_or_else(|| {
2431                            ActivityOptionsError::new(
2432                                ActivityOptionsErrorKind::BackoffOverflow,
2433                                Some("retry_policy.backoff"),
2434                                "generated backoff interval overflowed",
2435                            )
2436                        })?;
2437                    }
2438                    intervals
2439                }
2440            };
2441            Some(
2442                intervals
2443                    .into_iter()
2444                    .map(|interval| {
2445                        activity_protocol_seconds(interval).ok_or_else(|| {
2446                            ActivityOptionsError::new(
2447                                ActivityOptionsErrorKind::BackoffOverflow,
2448                                Some("retry_policy.backoff"),
2449                                "backoff interval is too large for the worker protocol",
2450                            )
2451                        })
2452                    })
2453                    .collect::<std::result::Result<Vec<_>, _>>()?,
2454            )
2455        }
2456    };
2457
2458    let mut encoded = serde_json::Map::new();
2459    if let Some(max_attempts) = policy.max_attempts {
2460        encoded.insert("max_attempts".to_string(), json!(max_attempts));
2461    }
2462    if let Some(backoff_seconds) = backoff_seconds {
2463        encoded.insert("backoff_seconds".to_string(), json!(backoff_seconds));
2464    }
2465    if !policy.non_retryable_error_types.is_empty() {
2466        let mut canonical_error_types = Vec::new();
2467        for error_type in policy
2468            .non_retryable_error_types
2469            .iter()
2470            .map(|error_type| error_type.trim())
2471        {
2472            if !canonical_error_types.contains(&error_type) {
2473                canonical_error_types.push(error_type);
2474            }
2475        }
2476        encoded.insert(
2477            "non_retryable_error_types".to_string(),
2478            json!(canonical_error_types),
2479        );
2480    }
2481    Ok(Value::Object(encoded))
2482}
2483
2484/// A stable, machine-readable failure raised when workflow code no longer
2485/// reconstructs the durable command stream recorded in history.
2486#[derive(Clone, Debug, Error)]
2487#[error("non-deterministic workflow replay ({reason}) at sequence {sequence:?}: {message}")]
2488pub struct ReplayFailure {
2489    pub reason: String,
2490    pub sequence: Option<u64>,
2491    pub expected: Option<String>,
2492    pub actual: Option<String>,
2493    pub message: String,
2494}
2495
2496impl ReplayFailure {
2497    fn new(
2498        reason: impl Into<String>,
2499        sequence: Option<u64>,
2500        expected: Option<String>,
2501        actual: Option<String>,
2502        message: impl Into<String>,
2503    ) -> Self {
2504        Self {
2505            reason: reason.into(),
2506            sequence,
2507            expected,
2508            actual,
2509            message: message.into(),
2510        }
2511    }
2512}
2513
2514/// A stable, machine-readable workflow query or query-task settlement failure.
2515#[derive(Clone, Debug, Error)]
2516#[error("query failed ({reason}, HTTP {status}): {message}")]
2517pub struct QueryFailure {
2518    pub status: u16,
2519    pub reason: String,
2520    pub message: String,
2521    pub body: Value,
2522}
2523
2524/// A stable failure returned when a server rejects an SDK protocol version.
2525#[derive(Clone, Debug, Error)]
2526#[error("protocol rejected ({reason}, HTTP {status}): {message}")]
2527pub struct ProtocolFailure {
2528    pub status: u16,
2529    pub reason: String,
2530    pub message: String,
2531    pub supported_version: Option<String>,
2532    pub requested_version: Option<String>,
2533    pub body: Value,
2534}
2535
2536/// The `limit_kind` a native Server (3.6.0 or later) reports when it refuses a
2537/// workflow-task completion body as too large.
2538pub const WORKFLOW_TASK_COMPLETION_BYTES_LIMIT_KIND: &str = "workflow_task_completion_bytes";
2539
2540/// A workflow-task completion the Server refused as larger than its aggregate
2541/// completion limit (HTTP 413, `reason: "payload_too_large"`,
2542/// `limit_kind: "workflow_task_completion_bytes"`).
2543///
2544/// Native Server 3.6.0 accepts a completion with commands up to 16 times the
2545/// per-payload limit (32 MiB by default); each command's arguments must still
2546/// meet the per-payload limit. The refusal is deterministic: running the same
2547/// workflow task again produces the same completion, so the SDK never resends it. `limit`
2548/// is the Server's limit in bytes when it reports one, and `size` is the
2549/// encoded request body the SDK sent. A [`Worker`] answers the refusal by
2550/// completing the same task once with a non-retryable `fail_workflow` command
2551/// whose message starts with `Structural limit exceeded:`, so the run fails
2552/// with failure category `structural_limit` instead of retrying the task or
2553/// parking the run. Split the fan-out into smaller batches, move work into child
2554/// workflows, or continue as new; offload large payloads with external payload
2555/// storage.
2556#[derive(Clone, Debug, Error)]
2557pub struct WorkflowTaskCompletionTooLarge {
2558    pub status: u16,
2559    pub limit_kind: String,
2560    pub limit: Option<u64>,
2561    pub size: u64,
2562    pub message: String,
2563    pub body: Value,
2564}
2565
2566impl std::fmt::Display for WorkflowTaskCompletionTooLarge {
2567    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2568        write!(
2569            formatter,
2570            "Structural limit exceeded: {}: the workflow task completion is {} bytes, over the server limit",
2571            self.limit_kind, self.size
2572        )?;
2573        if let Some(limit) = self.limit {
2574            write!(formatter, " of {limit} bytes")?;
2575        }
2576        formatter.write_str(
2577            ". Split the fan-out into smaller batches, move work into child workflows, or continue-as-new; offload large payloads with external payload storage.",
2578        )
2579    }
2580}
2581
2582/// The refusal reasons a Server returns (HTTP 409) when recording a
2583/// workflow-task completion would exceed its history-transaction budget:
2584/// `history_transaction_limit_exceeded` from the transaction meter, and
2585/// `completion_budget_exceeded` from the early whole-completion count.
2586pub const WORKFLOW_TASK_HISTORY_LIMIT_REASONS: [&str; 2] = [
2587    "history_transaction_limit_exceeded",
2588    "completion_budget_exceeded",
2589];
2590
2591/// A workflow-task completion the Server refused because recording it would
2592/// exceed its history-transaction budget (HTTP 409, `reason:
2593/// "history_transaction_limit_exceeded"` or `"completion_budget_exceeded"`).
2594///
2595/// A completion is recorded in one history transaction, bounded by the
2596/// Server's `history_transaction_size` (events), `history_transaction_bytes`
2597/// and `history_transaction_rows` structural limits. `ActivityScheduled`
2598/// events repeat their arguments, so a fan-out within the completion size limit
2599/// can still exceed a lowered `DW_V2_LIMIT_HISTORY_TRANSACTION_BYTES`. The
2600/// refusal rolls the transaction back, so nothing was recorded. Native Server
2601/// 3.13.0 names `limit_kind`, the measured `current_value` and the
2602/// `configured_limit`; each field is `None` here when the Server did not report
2603/// it, and `limit_kind` is then the refusal reason.
2604///
2605/// Like [`WorkflowTaskCompletionTooLarge`], the refusal is deterministic: the
2606/// same task produces the same completion, so the SDK never resends it. A
2607/// [`Worker`] completes the same task once with a non-retryable
2608/// `fail_workflow` command whose message starts with `Structural limit
2609/// exceeded:`, so the run fails with failure category `structural_limit`
2610/// instead of retrying the task forever.
2611#[derive(Clone, Debug, Error)]
2612pub struct WorkflowTaskHistoryLimitExceeded {
2613    pub status: u16,
2614    pub reason: String,
2615    pub limit_kind: String,
2616    pub current_value: Option<u64>,
2617    pub configured_limit: Option<u64>,
2618    pub message: String,
2619    pub body: Value,
2620}
2621
2622impl std::fmt::Display for WorkflowTaskHistoryLimitExceeded {
2623    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2624        let unit = match self.limit_kind.as_str() {
2625            "history_transaction_size" => "history events",
2626            "history_transaction_bytes" => "history bytes",
2627            "history_transaction_rows" => "rows",
2628            _ => "units",
2629        };
2630        write!(
2631            formatter,
2632            "Structural limit exceeded: {}: the workflow task completion would write ",
2633            self.limit_kind
2634        )?;
2635        match self.current_value {
2636            Some(value) => write!(formatter, "{value} {unit}")?,
2637            None => formatter.write_str("more than the limit allows")?,
2638        }
2639        formatter.write_str(" in one history transaction, over the server limit")?;
2640        if let Some(limit) = self.configured_limit {
2641            write!(formatter, " of {limit} {unit}")?;
2642        }
2643        formatter.write_str(
2644            ". Split the fan-out into smaller batches, move work into child workflows, or continue-as-new; offload large payloads with external payload storage.",
2645        )
2646    }
2647}
2648
2649#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
2650pub struct PayloadEnvelope {
2651    pub codec: String,
2652    pub blob: String,
2653}
2654
2655impl PayloadEnvelope {
2656    pub fn avro<T: Serialize>(value: &T) -> Result<Self> {
2657        encode_payload(value, DEFAULT_CODEC)
2658    }
2659
2660    /// Encode an explicit typed value, including the bytes branch that JSON
2661    /// serialization cannot represent.
2662    pub fn avro_value(value: &AvroValue) -> Result<Self> {
2663        encode_avro_value(value)
2664    }
2665}
2666
2667/// Native adapter for the fixed language-neutral Avro Value schema.
2668#[derive(Clone, Debug)]
2669pub enum AvroValue {
2670    Null,
2671    Boolean(bool),
2672    Long(i64),
2673    Double(f64),
2674    Bytes(Vec<u8>),
2675    String(String),
2676    Array(Vec<AvroValue>),
2677    Map(BTreeMap<String, AvroValue>),
2678}
2679
2680impl PartialEq for AvroValue {
2681    fn eq(&self, other: &Self) -> bool {
2682        match (self, other) {
2683            (Self::Null, Self::Null) => true,
2684            (Self::Boolean(left), Self::Boolean(right)) => left == right,
2685            (Self::Long(left), Self::Long(right)) => left == right,
2686            (Self::Double(left), Self::Double(right)) => left.to_bits() == right.to_bits(),
2687            (Self::Bytes(left), Self::Bytes(right)) => left == right,
2688            (Self::String(left), Self::String(right)) => left == right,
2689            (Self::Array(left), Self::Array(right)) => left == right,
2690            (Self::Map(left), Self::Map(right)) => left == right,
2691            _ => false,
2692        }
2693    }
2694}
2695
2696impl AvroValue {
2697    fn from_serialize<T: Serialize>(value: &T) -> Result<Self> {
2698        Self::from_serde_value(
2699            serde_value::to_value(value).map_err(|error| {
2700                Error::Codec(format!("could not adapt value for Avro: {error}"))
2701            })?,
2702        )
2703    }
2704
2705    fn from_serde_value(value: serde_value::Value) -> Result<Self> {
2706        use serde_value::Value as SerdeValue;
2707
2708        match value {
2709            SerdeValue::Unit => Ok(Self::Null),
2710            SerdeValue::Bool(value) => Ok(Self::Boolean(value)),
2711            SerdeValue::I8(value) => Ok(Self::Long(i64::from(value))),
2712            SerdeValue::I16(value) => Ok(Self::Long(i64::from(value))),
2713            SerdeValue::I32(value) => Ok(Self::Long(i64::from(value))),
2714            SerdeValue::I64(value) => Ok(Self::Long(value)),
2715            SerdeValue::U8(value) => Ok(Self::Long(i64::from(value))),
2716            SerdeValue::U16(value) => Ok(Self::Long(i64::from(value))),
2717            SerdeValue::U32(value) => Ok(Self::Long(i64::from(value))),
2718            SerdeValue::U64(value) => i64::try_from(value).map(Self::Long).map_err(|_| {
2719                Error::Codec(
2720                    "integer_overflow: Avro Value long must be within signed 64-bit range"
2721                        .to_string(),
2722                )
2723            }),
2724            SerdeValue::F32(value) => Self::finite_double(f64::from(value)),
2725            SerdeValue::F64(value) => Self::finite_double(value),
2726            SerdeValue::Char(value) => Ok(Self::String(value.to_string())),
2727            SerdeValue::String(value) => Ok(Self::String(value)),
2728            SerdeValue::Bytes(value) => Ok(Self::Bytes(value)),
2729            SerdeValue::Option(None) => Ok(Self::Null),
2730            SerdeValue::Option(Some(value)) | SerdeValue::Newtype(value) => {
2731                Self::from_serde_value(*value)
2732            }
2733            SerdeValue::Seq(values) => values
2734                .into_iter()
2735                .map(Self::from_serde_value)
2736                .collect::<Result<Vec<_>>>()
2737                .map(Self::Array),
2738            SerdeValue::Map(values) => values
2739                .into_iter()
2740                .map(|(key, value)| {
2741                    let SerdeValue::String(key) = key else {
2742                        return Err(Error::Codec(
2743                            "invalid_map_key: Avro Value map keys must be strings".to_string(),
2744                        ));
2745                    };
2746
2747                    Ok((key, Self::from_serde_value(value)?))
2748                })
2749                .collect::<Result<BTreeMap<_, _>>>()
2750                .map(Self::Map),
2751        }
2752    }
2753
2754    fn finite_double(value: f64) -> Result<Self> {
2755        if !value.is_finite() {
2756            return Err(Error::Codec(
2757                "non_finite_float: Avro Value doubles must be finite".to_string(),
2758            ));
2759        }
2760
2761        Ok(Self::Double(value))
2762    }
2763
2764    fn into_json(self) -> Result<Value> {
2765        match self {
2766            Self::Null => Ok(Value::Null),
2767            Self::Boolean(value) => Ok(Value::Bool(value)),
2768            Self::Long(value) => Ok(Value::Number(value.into())),
2769            Self::Double(value) => serde_json::Number::from_f64(value)
2770                .map(Value::Number)
2771                .ok_or_else(|| {
2772                    Error::Codec(
2773                        "non_finite_float: decoded Avro Value double is not finite".to_string(),
2774                    )
2775                }),
2776            Self::Bytes(value) => Ok(json!({
2777                "$type": "bytes",
2778                "base64": BASE64.encode(value),
2779            })),
2780            Self::String(value) => Ok(Value::String(value)),
2781            Self::Array(values) => values
2782                .into_iter()
2783                .map(Self::into_json)
2784                .collect::<Result<Vec<_>>>()
2785                .map(Value::Array),
2786            Self::Map(values) => values
2787                .into_iter()
2788                .map(|(key, value)| Ok((key, value.into_json()?)))
2789                .collect::<Result<serde_json::Map<_, _>>>()
2790                .map(Value::Object),
2791        }
2792    }
2793
2794    fn into_serde_value(self) -> serde_value::Value {
2795        use serde_value::Value as SerdeValue;
2796
2797        match self {
2798            Self::Null => SerdeValue::Unit,
2799            Self::Boolean(value) => SerdeValue::Bool(value),
2800            Self::Long(value) => SerdeValue::I64(value),
2801            Self::Double(value) => SerdeValue::F64(value),
2802            Self::Bytes(value) => SerdeValue::Bytes(value),
2803            Self::String(value) => SerdeValue::String(value),
2804            Self::Array(values) => {
2805                SerdeValue::Seq(values.into_iter().map(Self::into_serde_value).collect())
2806            }
2807            Self::Map(values) => SerdeValue::Map(
2808                values
2809                    .into_iter()
2810                    .map(|(key, value)| (SerdeValue::String(key), value.into_serde_value()))
2811                    .collect(),
2812            ),
2813        }
2814    }
2815
2816    pub fn deserialize<T: DeserializeOwned>(self) -> Result<T> {
2817        self.into_serde_value().deserialize_into().map_err(|error| {
2818            Error::Codec(format!(
2819                "avro_value_type_mismatch: could not adapt decoded value: {error}"
2820            ))
2821        })
2822    }
2823}
2824
2825impl Serialize for AvroValue {
2826    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2827    where
2828        S: Serializer,
2829    {
2830        match self {
2831            Self::Null => serializer.serialize_unit(),
2832            Self::Boolean(value) => serializer.serialize_bool(*value),
2833            Self::Long(value) => serializer.serialize_i64(*value),
2834            Self::Double(value) => serializer.serialize_f64(*value),
2835            Self::Bytes(value) => serializer.serialize_bytes(value),
2836            Self::String(value) => serializer.serialize_str(value),
2837            Self::Array(values) => {
2838                let mut sequence = serializer.serialize_seq(Some(values.len()))?;
2839                for value in values {
2840                    sequence.serialize_element(value)?;
2841                }
2842                sequence.end()
2843            }
2844            Self::Map(values) => {
2845                let mut map = serializer.serialize_map(Some(values.len()))?;
2846                for (key, value) in values {
2847                    map.serialize_entry(key, value)?;
2848                }
2849                map.end()
2850            }
2851        }
2852    }
2853}
2854
2855pub fn encode_avro_value(value: &AvroValue) -> Result<PayloadEnvelope> {
2856    let datum = avro_value_to_datum(value)?;
2857    let datum = to_avro_datum(avro_value_ordered_map_encoding_schema()?, datum)
2858        .map_err(|err| Error::Codec(format!("avro_value_encode_failed: {err}")))?;
2859    let mut bytes = Vec::with_capacity(datum.len() + 10);
2860    bytes.extend_from_slice(&AVRO_SINGLE_OBJECT_MAGIC);
2861    bytes.extend_from_slice(&AVRO_VALUE_SCHEMA_FINGERPRINT);
2862    bytes.extend_from_slice(&datum);
2863    Ok(PayloadEnvelope {
2864        codec: DEFAULT_CODEC.to_string(),
2865        blob: BASE64.encode(bytes),
2866    })
2867}
2868
2869pub fn decode_avro_value(envelope: &PayloadEnvelope) -> Result<AvroValue> {
2870    if envelope.codec != DEFAULT_CODEC {
2871        return Err(unsupported_payload_codec(&envelope.codec));
2872    }
2873    decode_avro_value_blob(&envelope.blob)
2874}
2875
2876pub fn encode_payload<T: Serialize>(value: &T, codec: &str) -> Result<PayloadEnvelope> {
2877    let blob = match codec {
2878        DEFAULT_CODEC => encode_avro_value(&AvroValue::from_serialize(value)?)?.blob,
2879        other => return Err(unsupported_payload_codec(other)),
2880    };
2881
2882    Ok(PayloadEnvelope {
2883        codec: codec.to_string(),
2884        blob,
2885    })
2886}
2887
2888pub fn decode_payload<T: DeserializeOwned>(envelope: &PayloadEnvelope) -> Result<T> {
2889    match envelope.codec.as_str() {
2890        DEFAULT_CODEC => decode_avro_value(envelope)?.deserialize(),
2891        other => Err(unsupported_payload_codec(other)),
2892    }
2893}
2894
2895fn handler_type_error<T>(
2896    handler_kind: HandlerKind,
2897    handler_name: &str,
2898    value_kind: HandlerValueKind,
2899    message: impl Into<String>,
2900) -> Error {
2901    Error::HandlerType {
2902        handler_kind,
2903        handler_name: handler_name.to_string(),
2904        value_kind,
2905        rust_type: type_name::<T>(),
2906        message: message.into(),
2907    }
2908}
2909
2910fn decode_handler_input<T: DeserializeOwned>(
2911    arguments: AvroValue,
2912    handler_kind: HandlerKind,
2913    handler_name: &str,
2914) -> Result<T> {
2915    let argument = match arguments {
2916        AvroValue::Array(mut arguments) if arguments.len() == 1 => {
2917            arguments.pop().expect("one typed handler argument")
2918        }
2919        AvroValue::Array(arguments) if arguments.is_empty() => AvroValue::Null,
2920        AvroValue::Array(arguments) => {
2921            return Err(handler_type_error::<T>(
2922                handler_kind,
2923                handler_name,
2924                HandlerValueKind::Input,
2925                format!(
2926                    "typed handlers accept one request value, but the task carried {} arguments",
2927                    arguments.len()
2928                ),
2929            ));
2930        }
2931        argument => argument,
2932    };
2933
2934    argument.deserialize().map_err(|error| {
2935        handler_type_error::<T>(
2936            handler_kind,
2937            handler_name,
2938            HandlerValueKind::Input,
2939            error.to_string(),
2940        )
2941    })
2942}
2943
2944fn decode_workflow_entry<T: DeserializeOwned>(
2945    arguments: AvroValue,
2946    workflow_type: &str,
2947) -> Result<T> {
2948    decode_handler_input(arguments, HandlerKind::Workflow, workflow_type).map_err(|_| {
2949        // Serde errors may contain recorded values. The entry refusal exposes
2950        // only the registered workflow and expected Rust type.
2951        handler_type_error::<T>(
2952            HandlerKind::Workflow,
2953            workflow_type,
2954            HandlerValueKind::Input,
2955            "workflow_entry_arguments_mismatch: restore compatible entry code before retrying the original task",
2956        )
2957    })
2958}
2959
2960fn encode_handler_result<T: Serialize>(
2961    result: &T,
2962    handler_kind: HandlerKind,
2963    handler_name: &str,
2964) -> Result<AvroValue> {
2965    AvroValue::from_serialize(result).map_err(|error| {
2966        handler_type_error::<T>(
2967            handler_kind,
2968            handler_name,
2969            HandlerValueKind::Result,
2970            error.to_string(),
2971        )
2972    })
2973}
2974
2975fn decode_handler_result<T: DeserializeOwned>(
2976    result: AvroValue,
2977    handler_kind: HandlerKind,
2978    handler_name: &str,
2979) -> Result<T> {
2980    result.deserialize().map_err(|error| {
2981        handler_type_error::<T>(
2982            handler_kind,
2983            handler_name,
2984            HandlerValueKind::Result,
2985            error.to_string(),
2986        )
2987    })
2988}
2989
2990#[cfg(test)]
2991fn encode_value_envelope(value: &Value, codec: &str) -> Result<Value> {
2992    Ok(serde_json::to_value(encode_payload(value, codec)?)?)
2993}
2994
2995fn decode_wire_value(value: &Value, fallback_codec: &str) -> Result<Value> {
2996    validate_payload_codec(fallback_codec)?;
2997
2998    if value.is_null() {
2999        return Ok(Value::Null);
3000    }
3001
3002    if let Some((codec, blob)) = payload_envelope_parts(value)? {
3003        return decode_blob(blob, codec);
3004    }
3005
3006    if let Some(blob) = value.as_str() {
3007        return decode_blob(blob, fallback_codec);
3008    }
3009
3010    Err(untagged_payload_value())
3011}
3012
3013fn encode_typed_envelope(value: &AvroValue, codec: &str) -> Result<Value> {
3014    let envelope = match codec {
3015        DEFAULT_CODEC => encode_avro_value(value)?,
3016        other => return Err(unsupported_payload_codec(other)),
3017    };
3018    Ok(serde_json::to_value(envelope)?)
3019}
3020
3021fn decode_wire_avro_value(value: &Value, fallback_codec: &str) -> Result<AvroValue> {
3022    validate_payload_codec(fallback_codec)?;
3023
3024    if value.is_null() {
3025        return Ok(AvroValue::Null);
3026    }
3027
3028    if let Some((codec, blob)) = payload_envelope_parts(value)? {
3029        validate_payload_codec(codec)?;
3030        return decode_avro_value_blob(blob);
3031    }
3032
3033    if let Some(blob) = value.as_str() {
3034        return match fallback_codec {
3035            DEFAULT_CODEC => decode_avro_value_blob(blob),
3036            other => Err(unsupported_payload_codec(other)),
3037        };
3038    }
3039
3040    Err(untagged_payload_value())
3041}
3042
3043fn normalize_avro_arguments(value: AvroValue) -> AvroValue {
3044    match value {
3045        AvroValue::Null => AvroValue::Array(Vec::new()),
3046        AvroValue::Array(_) => value,
3047        other => AvroValue::Array(vec![other]),
3048    }
3049}
3050
3051fn decode_blob(blob: &str, codec: &str) -> Result<Value> {
3052    match codec {
3053        DEFAULT_CODEC => decode_avro_value_blob(blob)?.into_json(),
3054        other => Err(unsupported_payload_codec(other)),
3055    }
3056}
3057
3058fn validate_payload_codec(codec: &str) -> Result<()> {
3059    match codec {
3060        DEFAULT_CODEC => Ok(()),
3061        MISSING_TASK_PAYLOAD_CODEC => {
3062            Err(invalid_task_payload_codec("task payload_codec is missing"))
3063        }
3064        NULL_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec("task payload_codec is null")),
3065        NON_STRING_TASK_PAYLOAD_CODEC => Err(invalid_task_payload_codec(
3066            "task payload_codec must be a string",
3067        )),
3068        other => Err(unsupported_payload_codec(other)),
3069    }
3070}
3071
3072fn invalid_task_payload_codec(reason: &str) -> Error {
3073    Error::Codec(format!(
3074        "unsupported_payload_codec: {reason}; Durable Workflow 2.0 requires an explicit string payload_codec=\"avro\" before worker task execution"
3075    ))
3076}
3077
3078fn payload_envelope_parts(value: &Value) -> Result<Option<(&str, &str)>> {
3079    let Some(object) = value.as_object() else {
3080        return Ok(None);
3081    };
3082    if !object.contains_key("codec") && !object.contains_key("blob") {
3083        return Ok(None);
3084    }
3085
3086    let codec = object
3087        .get("codec")
3088        .and_then(Value::as_str)
3089        .ok_or_else(invalid_payload_envelope)?;
3090    validate_payload_codec(codec)?;
3091    let blob = object
3092        .get("blob")
3093        .and_then(Value::as_str)
3094        .ok_or_else(invalid_payload_envelope)?;
3095    Ok(Some((codec, blob)))
3096}
3097
3098fn invalid_payload_envelope() -> Error {
3099    Error::Codec(
3100        "invalid_payload_envelope: durable payloads must use an object with string codec=\"avro\" and blob fields"
3101            .to_string(),
3102    )
3103}
3104
3105fn validate_workflow_task_commands(commands: &[Value]) -> Result<()> {
3106    for command in commands {
3107        let Some(command) = command.as_object() else {
3108            continue;
3109        };
3110        let Some(command_type) = command.get("type").and_then(Value::as_str) else {
3111            continue;
3112        };
3113        let Some(payload_field) = workflow_command_payload_field(command_type) else {
3114            continue;
3115        };
3116
3117        if let Some(codec) = command.get("payload_codec") {
3118            let codec = codec.as_str().ok_or_else(invalid_payload_envelope)?;
3119            validate_payload_codec(codec)?;
3120        }
3121
3122        let payload = command
3123            .get(payload_field)
3124            .ok_or_else(invalid_payload_envelope)?;
3125        if runtime_payloads::Reference::parse(payload)?.is_none() {
3126            validate_outbound_payload_envelope(payload)?;
3127        }
3128    }
3129    Ok(())
3130}
3131
3132fn workflow_completion_protocol_version(commands: &[Value]) -> &'static str {
3133    if commands.iter().any(|command| {
3134        command.get("type").and_then(Value::as_str) == Some("open_condition_wait")
3135            && command
3136                .get("condition_wait_occurrence_id")
3137                .and_then(Value::as_str)
3138                .is_some_and(|occurrence_id| !occurrence_id.is_empty())
3139    }) {
3140        CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
3141    } else if commands.iter().any(|command| {
3142        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
3143            && command.get("attribute_types").is_some()
3144    }) {
3145        TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
3146    } else if commands
3147        .iter()
3148        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
3149    {
3150        MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
3151    } else if commands
3152        .iter()
3153        .any(|command| command.get("type").and_then(Value::as_str) == Some("open_condition_wait"))
3154    {
3155        CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
3156    } else if commands.iter().any(|command| {
3157        command.get("type").and_then(Value::as_str) == Some("upsert_search_attributes")
3158    }) {
3159        SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
3160    } else {
3161        MINIMUM_WORKER_PROTOCOL_VERSION
3162    }
3163}
3164
3165fn workflow_completion_protocol_version_with_message_streams(
3166    commands: &[Value],
3167    has_message_stream_metadata: bool,
3168) -> &'static str {
3169    let command_protocol = workflow_completion_protocol_version(commands);
3170    if has_message_stream_metadata && !worker_protocol_supports_message_streams(command_protocol) {
3171        MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
3172    } else {
3173        command_protocol
3174    }
3175}
3176
3177fn workflow_command_payload_field(command_type: &str) -> Option<&'static str> {
3178    match command_type {
3179        "complete_workflow" | "complete_update" | "record_side_effect" => Some("result"),
3180        "schedule_activity" | "start_child_workflow" | "continue_as_new" => Some("arguments"),
3181        "start_service_operation" => Some("request_payload"),
3182        "upsert_memo" => Some("entries"),
3183        _ => None,
3184    }
3185}
3186
3187fn validate_outbound_payload_envelope(value: &Value) -> Result<()> {
3188    let Some((codec, blob)) = payload_envelope_parts(value)? else {
3189        return Err(untagged_payload_value());
3190    };
3191    validate_payload_codec(codec)?;
3192    decode_avro_value_blob(blob)?;
3193    Ok(())
3194}
3195
3196fn unsupported_payload_codec(codec: &str) -> Error {
3197    Error::Codec(format!(
3198        "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"
3199    ))
3200}
3201
3202fn untagged_payload_value() -> Error {
3203    Error::Codec(
3204        "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"
3205            .to_string(),
3206    )
3207}
3208
3209fn decode_avro_value_blob(blob: &str) -> Result<AvroValue> {
3210    let bytes = BASE64.decode(blob).map_err(|err| {
3211        Error::Codec(format!(
3212            "invalid_payload_framing: expected strict base64 Avro single-object bytes: {err}"
3213        ))
3214    })?;
3215
3216    if serde_json::from_slice::<Value>(&bytes).is_ok() {
3217        return Err(unsupported_payload_codec("json"));
3218    }
3219
3220    if bytes.len() < 10 || bytes[..2] != AVRO_SINGLE_OBJECT_MAGIC {
3221        return Err(Error::Codec(
3222            "invalid_payload_framing: expected Avro single-object magic c301".to_string(),
3223        ));
3224    }
3225
3226    let fingerprint: [u8; 8] = bytes[2..10]
3227        .try_into()
3228        .map_err(|_| Error::Codec("invalid Avro fingerprint length".to_string()))?;
3229    if fingerprint != AVRO_VALUE_SCHEMA_FINGERPRINT {
3230        return Err(Error::Codec(format!(
3231            "unsupported_payload_schema: unknown CRC-64-AVRO fingerprint {}",
3232            fingerprint
3233                .iter()
3234                .map(|byte| format!("{byte:02x}"))
3235                .collect::<String>()
3236        )));
3237    }
3238
3239    let mut datum_reader = StrictAvroDatumReader::new(&bytes[10..]);
3240    // The current fingerprint selects the current immutable schema, so reader
3241    // resolution would only re-walk the same recursive union. Future retained
3242    // writer fingerprints supply a distinct reader schema in this branch.
3243    let datum = from_avro_datum(avro_value_schema()?, &mut datum_reader, None);
3244    if datum_reader.truncated {
3245        return Err(Error::Codec(
3246            "invalid_payload_framing: truncated Avro Value datum".to_string(),
3247        ));
3248    }
3249    let datum = datum.map_err(|err| {
3250        Error::Codec(format!(
3251            "invalid_payload_framing: malformed Avro Value datum: {err}"
3252        ))
3253    })?;
3254    if datum_reader.remaining() != 0 {
3255        return Err(Error::Codec(format!(
3256            "invalid_payload_framing: {} trailing bytes after Avro Value datum",
3257            datum_reader.remaining()
3258        )));
3259    }
3260    avro_value_from_datum(datum)
3261}
3262
3263struct StrictAvroDatumReader<'a> {
3264    bytes: &'a [u8],
3265    offset: usize,
3266    truncated: bool,
3267}
3268
3269impl<'a> StrictAvroDatumReader<'a> {
3270    fn new(bytes: &'a [u8]) -> Self {
3271        Self {
3272            bytes,
3273            offset: 0,
3274            truncated: false,
3275        }
3276    }
3277
3278    fn remaining(&self) -> usize {
3279        self.bytes.len() - self.offset
3280    }
3281}
3282
3283impl Read for StrictAvroDatumReader<'_> {
3284    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
3285        let count = buffer.len().min(self.remaining());
3286        buffer[..count].copy_from_slice(&self.bytes[self.offset..self.offset + count]);
3287        self.offset += count;
3288        if count < buffer.len() {
3289            self.truncated = true;
3290        }
3291
3292        Ok(count)
3293    }
3294}
3295
3296fn avro_value_to_datum(value: &AvroValue) -> Result<AvroDatum> {
3297    let branch = match value {
3298        AvroValue::Null => AvroDatum::Union(0, Box::new(AvroDatum::Null)),
3299        AvroValue::Boolean(value) => AvroDatum::Union(
3300            1,
3301            Box::new(AvroDatum::Record(vec![(
3302                "boolean".to_string(),
3303                AvroDatum::Boolean(*value),
3304            )])),
3305        ),
3306        AvroValue::Long(value) => AvroDatum::Union(
3307            2,
3308            Box::new(AvroDatum::Record(vec![(
3309                "long".to_string(),
3310                AvroDatum::Long(*value),
3311            )])),
3312        ),
3313        AvroValue::Double(value) => {
3314            if !value.is_finite() {
3315                return Err(Error::Codec(
3316                    "non_finite_float: Avro Value doubles must be finite".to_string(),
3317                ));
3318            }
3319            AvroDatum::Union(
3320                3,
3321                Box::new(AvroDatum::Record(vec![(
3322                    "double".to_string(),
3323                    AvroDatum::Double(*value),
3324                )])),
3325            )
3326        }
3327        AvroValue::Bytes(value) => AvroDatum::Union(
3328            4,
3329            Box::new(AvroDatum::Record(vec![(
3330                "bytes".to_string(),
3331                AvroDatum::Bytes(value.clone()),
3332            )])),
3333        ),
3334        AvroValue::String(value) => AvroDatum::Union(
3335            5,
3336            Box::new(AvroDatum::Record(vec![(
3337                "string".to_string(),
3338                AvroDatum::String(value.clone()),
3339            )])),
3340        ),
3341        AvroValue::Array(values) => AvroDatum::Union(
3342            6,
3343            Box::new(AvroDatum::Record(vec![(
3344                "items".to_string(),
3345                AvroDatum::Array(
3346                    values
3347                        .iter()
3348                        .map(avro_value_to_datum)
3349                        .collect::<Result<Vec<_>>>()?,
3350                ),
3351            )])),
3352        ),
3353        AvroValue::Map(values) => AvroDatum::Union(
3354            7,
3355            Box::new(AvroDatum::Record(vec![(
3356                "entries".to_string(),
3357                AvroDatum::Array(
3358                    values
3359                        .iter()
3360                        .map(|(key, value)| {
3361                            Ok(AvroDatum::Record(vec![
3362                                ("key".to_string(), AvroDatum::String(key.clone())),
3363                                ("value".to_string(), avro_value_to_datum(value)?),
3364                            ]))
3365                        })
3366                        .collect::<Result<Vec<_>>>()?,
3367                ),
3368            )])),
3369        ),
3370    };
3371    Ok(AvroDatum::Record(vec![("value".to_string(), branch)]))
3372}
3373
3374fn avro_value_from_datum(datum: AvroDatum) -> Result<AvroValue> {
3375    let AvroDatum::Record(mut outer) = datum else {
3376        return Err(Error::Codec(
3377            "invalid_payload_framing: datum is not a Value record".to_string(),
3378        ));
3379    };
3380    let (_, branch) = outer
3381        .pop()
3382        .filter(|(name, _)| name == "value")
3383        .ok_or_else(|| Error::Codec("invalid_payload_framing: Value field missing".to_string()))?;
3384    let AvroDatum::Union(_, branch) = branch else {
3385        return Err(Error::Codec(
3386            "invalid_payload_framing: invalid Value union".to_string(),
3387        ));
3388    };
3389    match *branch {
3390        AvroDatum::Null => Ok(AvroValue::Null),
3391        AvroDatum::Record(mut fields) => {
3392            let (name, value) = fields.pop().ok_or_else(|| {
3393                Error::Codec("invalid_payload_framing: empty Value branch".to_string())
3394            })?;
3395            match (name.as_str(), value) {
3396                ("boolean", AvroDatum::Boolean(value)) => Ok(AvroValue::Boolean(value)),
3397                ("long", AvroDatum::Long(value)) => Ok(AvroValue::Long(value)),
3398                ("double", AvroDatum::Double(value)) if value.is_finite() => {
3399                    Ok(AvroValue::Double(value))
3400                }
3401                ("bytes", AvroDatum::Bytes(value)) => Ok(AvroValue::Bytes(value)),
3402                ("string", AvroDatum::String(value)) => Ok(AvroValue::String(value)),
3403                ("items", AvroDatum::Array(values)) => values
3404                    .into_iter()
3405                    .map(avro_value_from_datum)
3406                    .collect::<Result<Vec<_>>>()
3407                    .map(AvroValue::Array),
3408                ("entries", AvroDatum::Map(values)) => values
3409                    .into_iter()
3410                    .map(|(key, value)| Ok((key, avro_value_from_datum(value)?)))
3411                    .collect::<Result<BTreeMap<_, _>>>()
3412                    .map(AvroValue::Map),
3413                _ => Err(Error::Codec(
3414                    "invalid_payload_framing: unknown Value branch".to_string(),
3415                )),
3416            }
3417        }
3418        _ => Err(Error::Codec(
3419            "invalid_payload_framing: invalid Value branch".to_string(),
3420        )),
3421    }
3422}
3423
3424fn avro_value_schema() -> Result<&'static Schema> {
3425    match AVRO_VALUE_SCHEMA.get_or_init(|| {
3426        Schema::parse_str(AVRO_VALUE_SCHEMA_JSON)
3427            .map_err(|err| format!("could not parse Avro Value schema: {err}"))
3428    }) {
3429        Ok(schema) => Ok(schema),
3430        Err(message) => Err(Error::Codec(message.clone())),
3431    }
3432}
3433
3434fn avro_value_ordered_map_encoding_schema() -> Result<&'static Schema> {
3435    match AVRO_VALUE_ORDERED_MAP_ENCODING_SCHEMA.get_or_init(|| {
3436        // Apache Avro's Value::Map uses a randomized HashMap. Arrays and maps
3437        // have the same block representation when each ordered array record
3438        // contains the map key followed by its value, so this encoding-only
3439        // adaptation lets the official encoder retain BTreeMap wire order.
3440        let mut schema: Value = serde_json::from_str(AVRO_VALUE_SCHEMA_JSON)
3441            .map_err(|err| format!("could not read packaged Avro Value schema: {err}"))?;
3442        let entries_schema = schema
3443            .pointer_mut("/fields/0/type/7/fields/0/type")
3444            .ok_or_else(|| "packaged Avro Value map schema is missing".to_string())?;
3445        if *entries_schema != json!({"type": "map", "values": "Value"}) {
3446            return Err("packaged Avro Value map schema changed unexpectedly".to_string());
3447        }
3448        *entries_schema = json!({
3449            "type": "array",
3450            "items": {
3451                "type": "record",
3452                "name": "MapEntry",
3453                "fields": [
3454                    {"name": "key", "type": "string"},
3455                    {"name": "value", "type": "Value"}
3456                ]
3457            }
3458        });
3459        Schema::parse_str(&schema.to_string())
3460            .map_err(|err| format!("could not parse ordered-map Avro Value schema: {err}"))
3461    }) {
3462        Ok(schema) => Ok(schema),
3463        Err(message) => Err(Error::Codec(message.clone())),
3464    }
3465}
3466
3467#[derive(Clone, Debug)]
3468pub struct Client {
3469    metrics: metrics::Metrics,
3470    // Managed-worker dispatch recording is separate from client HTTP recording.
3471    worker_dispatch_metrics: metrics::Metrics,
3472    http: reqwest::Client,
3473    hydration_timeout: Duration,
3474    base_url: String,
3475    token: Option<String>,
3476    control_token: Option<String>,
3477    worker_token: Option<String>,
3478    namespace: String,
3479    max_external_payload_bytes: usize,
3480    /// Cap on one decoded response body (`ClientBuilder::max_response_bytes`).
3481    max_response_bytes: usize,
3482    worker_storage_admission: Option<WorkerStorageAdmission>,
3483    worker_task_slot: Option<Arc<worker_capacity::TaskSlotMarker>>,
3484    cooperative_worker_protocol: bool,
3485    worker_protocol_version: WorkerProtocolVersion,
3486    local_activities_enabled: bool,
3487    worker_sessions_enabled: bool,
3488    max_concurrent_worker_sessions: usize,
3489    worker_build_id: Option<String>,
3490    sticky_cache: Option<Arc<Mutex<sticky_workflow_cache::StickyWorkflowCache>>>,
3491    runtime_upload_policy: Arc<Mutex<runtime_uploads::PolicyCache>>,
3492    failure_request_limit: Arc<AtomicUsize>,
3493    activity_lease_renewal_supported: Arc<AtomicBool>,
3494    /// Server #1017: the Server sends sticky hits only the history after the cached sequence.
3495    sticky_history_suffix_supported: Arc<AtomicBool>,
3496    /// Server #1131: the Server advertised `update_outcome_reads`.
3497    update_outcome_reads_supported: Arc<AtomicBool>,
3498    /// Server #1133: the Server advertised `signal_with_start`.
3499    signal_with_start_supported: Arc<AtomicBool>,
3500    activity_lease_discovery: Arc<activity_lease::Discovery>,
3501    activity_lease_authority: Option<Arc<activity_lease::authority::Authority>>,
3502    /// server#1262: the newest capabilities digest learned from a tagged copy,
3503    /// shared by this Client's clones.
3504    capabilities_digest: server_capabilities_digest::Digest,
3505    #[cfg(feature = "telemetry")]
3506    execution_telemetry: Option<telemetry::ExecutionTelemetry>,
3507    #[cfg(feature = "telemetry")]
3508    observability_context_supported: Arc<AtomicBool>,
3509}
3510
3511impl Client {
3512    /// Configure optional propagation. Actual cluster discovery must advertise
3513    /// the exact supported capability before any command carries context.
3514    #[cfg(feature = "telemetry")]
3515    pub fn with_telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
3516        self.execution_telemetry = Some(telemetry);
3517        self
3518    }
3519
3520    #[cfg(feature = "telemetry")]
3521    fn with_observability_context(&self, mut body: Value) -> Value {
3522        if self.observability_context_supported.load(Ordering::SeqCst) {
3523            if let Some(context) = self
3524                .execution_telemetry
3525                .as_ref()
3526                .and_then(|telemetry| telemetry.capture())
3527            {
3528                body["observability_context"] = context;
3529            }
3530        }
3531        body
3532    }
3533
3534    #[cfg(not(feature = "telemetry"))]
3535    fn with_observability_context(&self, body: Value) -> Value {
3536        body
3537    }
3538
3539    pub fn new(base_url: impl Into<String>) -> Result<Self> {
3540        Self::builder(base_url).build()
3541    }
3542
3543    pub fn builder(base_url: impl Into<String>) -> ClientBuilder {
3544        ClientBuilder {
3545            base_url: base_url.into(),
3546            token: None,
3547            control_token: None,
3548            worker_token: None,
3549            namespace: "default".to_string(),
3550            timeout: Duration::from_secs(60),
3551            max_external_payload_bytes: 64 * 1024 * 1024,
3552            max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES,
3553            worker_protocol_version: WorkerProtocolVersion::default(),
3554            additional_root_certificates: Vec::new(),
3555            danger_accept_invalid_certs: false,
3556            metrics: metrics::Metrics::default(),
3557        }
3558    }
3559
3560    pub async fn health(&self) -> Result<Value> {
3561        self.request_json(
3562            reqwest::Method::GET,
3563            "/health",
3564            RequestProtocol::ControlPlane,
3565            Option::<&Value>::None,
3566        )
3567        .await
3568    }
3569
3570    /// Run a read-only cluster-info discovery. For a running worker, a
3571    /// transient failure is retried with the shared jittered backoff (an
3572    /// outage logged as ERROR after 60 s, then every 5 minutes) until it
3573    /// succeeds or the worker stops; elsewhere it is one attempt.
3574    pub(crate) async fn retry_cluster_info<T, F, Fut>(&self, mut read: F) -> Result<T>
3575    where
3576        F: FnMut() -> Fut,
3577        Fut: Future<Output = Result<T>>,
3578    {
3579        let Some(admission) = self.worker_storage_admission.as_ref() else {
3580            return read().await;
3581        };
3582        let mut failures = 0_u32;
3583        let mut outage = OutageLog::default();
3584        loop {
3585            let error = match read().await {
3586                Ok(value) => return Ok(value),
3587                Err(error) => error,
3588            };
3589            if !cluster_info_failure_is_transient(&error) || admission.stop.load(Ordering::SeqCst) {
3590                return Err(error);
3591            }
3592            failures = failures.saturating_add(1);
3593            outage.report("", "", &error);
3594            let delay = worker_outage_delay(failures);
3595            tracing::warn!(
3596                target: "durable_workflow::worker",
3597                error = %error,
3598                retry_in_ms = delay.as_millis() as u64,
3599                "cluster info unavailable; retrying"
3600            );
3601            tokio::select! {
3602                _ = tokio::time::sleep(delay) => {}
3603                _ = wait_for_worker_stop(&admission.stop) => return Err(error),
3604            }
3605        }
3606    }
3607
3608    pub async fn cluster_info(&self) -> Result<Value> {
3609        let discovery: Value = self
3610            .request_json(
3611                reqwest::Method::GET,
3612                "/cluster/info",
3613                RequestProtocol::ControlPlane,
3614                Option::<&Value>::None,
3615            )
3616            .await?;
3617        self.observe_activity_lease_capabilities(
3618            &discovery["worker_protocol"]["server_capabilities"],
3619        );
3620        self.observe_failure_request_limit(&discovery);
3621        Ok(discovery)
3622    }
3623
3624    pub async fn start_workflow<T: Serialize>(
3625        &self,
3626        workflow_type: &str,
3627        task_queue: &str,
3628        workflow_id: &str,
3629        input: T,
3630    ) -> Result<WorkflowHandle> {
3631        self.start_workflow_with_options(
3632            workflow_type,
3633            task_queue,
3634            workflow_id,
3635            WorkflowStartOptions::default(),
3636            input,
3637        )
3638        .await
3639    }
3640
3641    /// Start a workflow with explicit server-enforced execution and run
3642    /// deadlines.
3643    pub async fn start_workflow_with_options<T: Serialize>(
3644        &self,
3645        workflow_type: &str,
3646        task_queue: &str,
3647        workflow_id: &str,
3648        options: WorkflowStartOptions,
3649        input: T,
3650    ) -> Result<WorkflowHandle> {
3651        options.validate()?;
3652        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3653        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3654        let body = self.with_observability_context(json!({
3655            "workflow_id": workflow_id,
3656            "workflow_type": workflow_type,
3657            "task_queue": task_queue,
3658            "input": input_envelope,
3659            "execution_timeout_seconds": options.execution_timeout_seconds,
3660            "run_timeout_seconds": options.run_timeout_seconds
3661        }));
3662
3663        let data: Value = self
3664            .request_json(
3665                reqwest::Method::POST,
3666                "/workflows",
3667                RequestProtocol::ControlPlane,
3668                Some(&body),
3669            )
3670            .await?;
3671
3672        Ok(WorkflowHandle {
3673            client: self.clone(),
3674            workflow_id: data
3675                .get("workflow_id")
3676                .and_then(Value::as_str)
3677                .unwrap_or(workflow_id)
3678                .to_string(),
3679            run_id: data
3680                .get("run_id")
3681                .and_then(Value::as_str)
3682                .map(str::to_string),
3683            workflow_type: data
3684                .get("workflow_type")
3685                .and_then(Value::as_str)
3686                .unwrap_or(workflow_type)
3687                .to_string(),
3688        })
3689    }
3690
3691    /// Send a signal with an SDK-generated caller command key.
3692    ///
3693    /// The key is sent as the `request_id` body field and is present in the
3694    /// returned receipt's `request_id`. A Server that already retains the key
3695    /// for the same signal intent returns the original receipt with
3696    /// `retained: true`; a different intent is refused with
3697    /// [`Error::is_request_id_conflict`]. Choose the key yourself with
3698    /// [`Client::signal_workflow_with_request_id`] when the application must be
3699    /// able to retry the same logical signal after a transport failure.
3700    pub async fn signal_workflow<T: Serialize>(
3701        &self,
3702        workflow_id: &str,
3703        signal_name: &str,
3704        input: T,
3705    ) -> Result<Value> {
3706        let request_id = Self::generate_signal_request_id();
3707        self.signal_workflow_target(workflow_id, None, signal_name, input, &request_id)
3708            .await
3709    }
3710
3711    /// Send a signal with an explicit caller command key (1 to 255 Unicode characters).
3712    ///
3713    /// Resend the identical signal with the same key after an uncertain
3714    /// outcome: the Server returns the retained receipt instead of admitting a
3715    /// second signal, for as long as the retained run's details are kept.
3716    pub async fn signal_workflow_with_request_id<T: Serialize>(
3717        &self,
3718        workflow_id: &str,
3719        signal_name: &str,
3720        input: T,
3721        request_id: &str,
3722    ) -> Result<Value> {
3723        self.signal_workflow_target(workflow_id, None, signal_name, input, request_id)
3724            .await
3725    }
3726
3727    /// A fresh caller command key for one logical signal (`sdk-rust-signal-<uuid>`).
3728    ///
3729    /// Methods without an explicit key generate one of these per call. Obtain it
3730    /// up front and pass it to [`Client::signal_workflow_with_request_id`] so a
3731    /// transport failure does not lose the key needed for a safe retry.
3732    pub fn generate_signal_request_id() -> String {
3733        generated_request_id("signal")
3734    }
3735
3736    /// A fresh caller command key for one logical update (`sdk-rust-update-<uuid>`).
3737    ///
3738    /// [`Client::update_workflow`] generates one of these when `request_id` is
3739    /// `None`. Obtain it up front and pass it explicitly so a transport failure
3740    /// does not lose the key needed for a safe retry.
3741    pub fn generate_update_request_id() -> String {
3742        generated_request_id("update")
3743    }
3744
3745    /// Append one idempotently identified item to an instance-scoped input stream.
3746    pub async fn append_message_stream<T: Serialize>(
3747        &self,
3748        workflow_id: &str,
3749        stream_name: &str,
3750        message_id: &str,
3751        input: T,
3752    ) -> Result<Value> {
3753        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3754        let body = json!({
3755            "message_id": message_id,
3756            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?
3757        });
3758        self.request_json(
3759            reqwest::Method::POST,
3760            &format!(
3761                "/workflows/{}/message-streams/{}/messages",
3762                path_segment("workflow_id", workflow_id)?,
3763                path_segment("stream_name", stream_name)?,
3764            ),
3765            RequestProtocol::ControlPlane,
3766            Some(&body),
3767        )
3768        .await
3769    }
3770
3771    /// Signal only if `run_id` is still the current run for this instance,
3772    /// with an SDK-generated caller command key.
3773    pub async fn signal_workflow_run<T: Serialize>(
3774        &self,
3775        workflow_id: &str,
3776        run_id: &str,
3777        signal_name: &str,
3778        input: T,
3779    ) -> Result<Value> {
3780        let request_id = Self::generate_signal_request_id();
3781        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, &request_id)
3782            .await
3783    }
3784
3785    /// Signal only if `run_id` is still the current run for this instance,
3786    /// with an explicit caller command key (1 to 255 Unicode characters).
3787    ///
3788    /// The selected run is part of the signal's intent: retrying with the same
3789    /// key and a different run target is a `request_id_conflict` refusal.
3790    pub async fn signal_workflow_run_with_request_id<T: Serialize>(
3791        &self,
3792        workflow_id: &str,
3793        run_id: &str,
3794        signal_name: &str,
3795        input: T,
3796        request_id: &str,
3797    ) -> Result<Value> {
3798        self.signal_workflow_target(workflow_id, Some(run_id), signal_name, input, request_id)
3799            .await
3800    }
3801
3802    async fn signal_workflow_target<T: Serialize>(
3803        &self,
3804        workflow_id: &str,
3805        run_id: Option<&str>,
3806        signal_name: &str,
3807        input: T,
3808        request_id: &str,
3809    ) -> Result<Value> {
3810        validate_user_signal_name(signal_name)?;
3811        validate_request_id(request_id)?;
3812        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
3813        let input_envelope = encode_typed_envelope(&input, DEFAULT_CODEC)?;
3814        let body = self.with_observability_context(json!({
3815            "input": input_envelope,
3816            "request_id": request_id,
3817        }));
3818        let path = match run_id {
3819            Some(run_id) => {
3820                format!(
3821                    "/workflows/{}/runs/{}/signal/{}",
3822                    path_segment("workflow_id", workflow_id)?,
3823                    path_segment("run_id", run_id)?,
3824                    path_segment("signal_name", signal_name)?,
3825                )
3826            }
3827            None => format!(
3828                "/workflows/{}/signal/{}",
3829                path_segment("workflow_id", workflow_id)?,
3830                path_segment("signal_name", signal_name)?,
3831            ),
3832        };
3833        let receipt = self
3834            .request_json(
3835                reqwest::Method::POST,
3836                &path,
3837                RequestProtocol::ControlPlane,
3838                Some(&body),
3839            )
3840            .await
3841            .map_err(|error| error.with_sent_request_id(request_id))?;
3842        Ok(with_request_id(receipt, request_id))
3843    }
3844
3845    /// Close the current run as cancelled immediately.
3846    ///
3847    /// Server revokes open tasks and timers without resuming workflow code for
3848    /// cleanup. Use [`Client::request_workflow_cancellation`] for a separate cooperative
3849    /// request on a supporting runtime and opted-in worker.
3850    pub async fn cancel_workflow(
3851        &self,
3852        workflow_id: &str,
3853        options: WorkflowCommandOptions,
3854    ) -> Result<WorkflowCommandResult> {
3855        self.workflow_command(workflow_id, None, WorkflowCommandKind::Cancel, options)
3856            .await
3857    }
3858
3859    /// Close the selected run as cancelled, only if `run_id` is still current.
3860    pub async fn cancel_workflow_run(
3861        &self,
3862        workflow_id: &str,
3863        run_id: &str,
3864        options: WorkflowCommandOptions,
3865    ) -> Result<WorkflowCommandResult> {
3866        self.workflow_command(
3867            workflow_id,
3868            Some(run_id),
3869            WorkflowCommandKind::Cancel,
3870            options,
3871        )
3872        .await
3873    }
3874
3875    /// Forcefully terminate the current run for an instance.
3876    pub async fn terminate_workflow(
3877        &self,
3878        workflow_id: &str,
3879        options: WorkflowCommandOptions,
3880    ) -> Result<WorkflowCommandResult> {
3881        self.workflow_command(workflow_id, None, WorkflowCommandKind::Terminate, options)
3882            .await
3883    }
3884
3885    /// Forcefully terminate only if `run_id` is still current.
3886    pub async fn terminate_workflow_run(
3887        &self,
3888        workflow_id: &str,
3889        run_id: &str,
3890        options: WorkflowCommandOptions,
3891    ) -> Result<WorkflowCommandResult> {
3892        self.workflow_command(
3893            workflow_id,
3894            Some(run_id),
3895            WorkflowCommandKind::Terminate,
3896            options,
3897        )
3898        .await
3899    }
3900
3901    /// Continue a failed run from its recorded activity failure boundary.
3902    pub async fn redrive_workflow_run(
3903        &self,
3904        workflow_id: &str,
3905        failed_run_id: &str,
3906        request_id: Option<&str>,
3907    ) -> Result<WorkflowRedriveResult> {
3908        let body = request_id
3909            .map(|id| json!({"request_id": id}))
3910            .unwrap_or_else(|| json!({}));
3911        let data: Value = self
3912            .request_json(
3913                reqwest::Method::POST,
3914                &format!(
3915                    "/workflows/{}/runs/{}/redrive",
3916                    path_segment("workflow_id", workflow_id)?,
3917                    path_segment("run_id", failed_run_id)?,
3918                ),
3919                RequestProtocol::ControlPlane,
3920                Some(&body),
3921            )
3922            .await?;
3923        if data.get("command_status").and_then(Value::as_str) != Some("accepted")
3924            || data.get("outcome").and_then(Value::as_str) != Some("redriven")
3925        {
3926            return Err(Error::Codec(
3927                "redrive response was not accepted".to_string(),
3928            ));
3929        }
3930        if data.get("workflow_id").and_then(Value::as_str) != Some(workflow_id)
3931            || data.get("continued_from_run_id").and_then(Value::as_str) != Some(failed_run_id)
3932        {
3933            return Err(Error::Codec(
3934                "redrive response does not match the requested source run".to_string(),
3935            ));
3936        }
3937        let run_id = data
3938            .get("run_id")
3939            .and_then(Value::as_str)
3940            .filter(|id| !id.is_empty() && *id != failed_run_id)
3941            .ok_or_else(|| {
3942                Error::Codec("redrive response is missing a distinct successor run_id".to_string())
3943            })?;
3944        let resume_step_sequence = data
3945            .get("resume_step_sequence")
3946            .and_then(Value::as_u64)
3947            .filter(|sequence| *sequence > 0)
3948            .ok_or_else(|| {
3949                Error::Codec("redrive response is missing resume_step_sequence".to_string())
3950            })?;
3951        Ok(WorkflowRedriveResult {
3952            workflow_id: workflow_id.to_string(),
3953            source_run_id: failed_run_id.to_string(),
3954            run_id: run_id.to_string(),
3955            resume_step_sequence,
3956            raw: data,
3957        })
3958    }
3959
3960    async fn workflow_command(
3961        &self,
3962        workflow_id: &str,
3963        run_id: Option<&str>,
3964        command: WorkflowCommandKind,
3965        options: WorkflowCommandOptions,
3966    ) -> Result<WorkflowCommandResult> {
3967        #[cfg(feature = "telemetry")]
3968        let body = if command == WorkflowCommandKind::Cancel {
3969            self.with_observability_context(serde_json::to_value(&options)?)
3970        } else {
3971            serde_json::to_value(&options)?
3972        };
3973        #[cfg(not(feature = "telemetry"))]
3974        let body = &options;
3975        let path = match run_id {
3976            Some(run_id) => format!(
3977                "/workflows/{}/runs/{}/{}",
3978                path_segment("workflow_id", workflow_id)?,
3979                path_segment("run_id", run_id)?,
3980                command.as_str()
3981            ),
3982            None => format!(
3983                "/workflows/{}/{}",
3984                path_segment("workflow_id", workflow_id)?,
3985                command.as_str(),
3986            ),
3987        };
3988        let data = match self
3989            .request_json(
3990                reqwest::Method::POST,
3991                &path,
3992                RequestProtocol::ControlPlane,
3993                Some(&body),
3994            )
3995            .await
3996        {
3997            Ok(data) => data,
3998            Err(Error::Http { status, body }) => {
3999                return Err(Error::WorkflowCommandRejected(workflow_command_rejection(
4000                    command,
4001                    status,
4002                    body,
4003                    workflow_id,
4004                    run_id,
4005                )));
4006            }
4007            Err(error) => return Err(error),
4008        };
4009
4010        Ok(workflow_command_result(command, data, workflow_id, run_id))
4011    }
4012
4013    /// Execute a named, read-only query against a running or completed workflow.
4014    ///
4015    /// Arguments and results use the platform payload envelope. Server and
4016    /// worker rejections are returned as [`Error::QueryFailed`] with a stable
4017    /// reason, HTTP status, and original response body.
4018    pub async fn query_workflow<T: Serialize>(
4019        &self,
4020        workflow_id: &str,
4021        query_name: &str,
4022        input: T,
4023    ) -> Result<Value> {
4024        self.query_workflow_target(workflow_id, None, query_name, input)
4025            .await
4026    }
4027
4028    /// Query only if `run_id` is still current, preventing accidental retargeting.
4029    pub async fn query_workflow_run<T: Serialize>(
4030        &self,
4031        workflow_id: &str,
4032        run_id: &str,
4033        query_name: &str,
4034        input: T,
4035    ) -> Result<Value> {
4036        self.query_workflow_target(workflow_id, Some(run_id), query_name, input)
4037            .await
4038    }
4039
4040    /// Query a workflow and return the lossless fixed Avro Value result.
4041    pub async fn query_workflow_avro_value<T: Serialize>(
4042        &self,
4043        workflow_id: &str,
4044        query_name: &str,
4045        input: T,
4046    ) -> Result<AvroValue> {
4047        self.query_workflow_avro_value_target(workflow_id, None, query_name, input)
4048            .await
4049    }
4050
4051    /// Query a selected run and return the lossless fixed Avro Value result.
4052    pub async fn query_workflow_run_avro_value<T: Serialize>(
4053        &self,
4054        workflow_id: &str,
4055        run_id: &str,
4056        query_name: &str,
4057        input: T,
4058    ) -> Result<AvroValue> {
4059        self.query_workflow_avro_value_target(workflow_id, Some(run_id), query_name, input)
4060            .await
4061    }
4062
4063    async fn query_workflow_avro_value_target<T: Serialize>(
4064        &self,
4065        workflow_id: &str,
4066        run_id: Option<&str>,
4067        query_name: &str,
4068        input: T,
4069    ) -> Result<AvroValue> {
4070        let response = self
4071            .query_workflow_response(workflow_id, run_id, query_name, input)
4072            .await?;
4073        let envelope = response
4074            .get("result_envelope")
4075            .filter(|envelope| !envelope.is_null())
4076            .ok_or_else(|| {
4077                Error::Codec(
4078                    "missing_payload_envelope: typed query result requires result_envelope"
4079                        .to_string(),
4080                )
4081            })?;
4082        decode_wire_avro_value(envelope, DEFAULT_CODEC)
4083    }
4084
4085    async fn query_workflow_target<T: Serialize>(
4086        &self,
4087        workflow_id: &str,
4088        run_id: Option<&str>,
4089        query_name: &str,
4090        input: T,
4091    ) -> Result<Value> {
4092        let response = self
4093            .query_workflow_response(workflow_id, run_id, query_name, input)
4094            .await?;
4095        if let Some(envelope) = response
4096            .get("result_envelope")
4097            .filter(|envelope| !envelope.is_null())
4098        {
4099            return decode_wire_value(envelope, DEFAULT_CODEC);
4100        }
4101
4102        Ok(response.get("result").cloned().unwrap_or(Value::Null))
4103    }
4104
4105    // Typed and JSON readers share route validation and HTTP refusal handling.
4106    async fn query_workflow_response<T: Serialize>(
4107        &self,
4108        workflow_id: &str,
4109        run_id: Option<&str>,
4110        query_name: &str,
4111        input: T,
4112    ) -> Result<Value> {
4113        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
4114        let body = json!({"input": encode_typed_envelope(&input, DEFAULT_CODEC)?});
4115        let path = match run_id {
4116            Some(run_id) => {
4117                format!(
4118                    "/workflows/{}/runs/{}/query/{}",
4119                    path_segment("workflow_id", workflow_id)?,
4120                    path_segment("run_id", run_id)?,
4121                    path_segment("query_name", query_name)?,
4122                )
4123            }
4124            None => format!(
4125                "/workflows/{}/query/{}",
4126                path_segment("workflow_id", workflow_id)?,
4127                path_segment("query_name", query_name)?,
4128            ),
4129        };
4130        let response: Value = match self
4131            .request_json(
4132                reqwest::Method::POST,
4133                &path,
4134                RequestProtocol::ControlPlane,
4135                Some(&body),
4136            )
4137            .await
4138        {
4139            Ok(response) => response,
4140            Err(Error::Http { status, body }) => {
4141                return Err(Error::QueryFailed(query_failure(status, body)));
4142            }
4143            Err(error) => return Err(error),
4144        };
4145        Ok(response)
4146    }
4147
4148    /// Send a synchronous update using fixed Avro Value arguments.
4149    ///
4150    /// `request_id` is the caller command key (1 to 255 Unicode characters), sent as the
4151    /// `request_id` body field; `None` generates one with
4152    /// [`Client::generate_update_request_id`]. A Server that already retains the
4153    /// key for the same update intent returns the original update's receipt and
4154    /// result instead of admitting a second update; a different intent is
4155    /// refused with [`Error::is_request_id_conflict`].
4156    ///
4157    /// The Server waits for the update to complete. When its wait ends first,
4158    /// this returns [`Error::UpdateStillPending`], never `Null`: read the
4159    /// outcome later with [`Client::update_outcome`] and the pending update's
4160    /// id, or send the update again with the same `request_id`. A handler that
4161    /// returned null is `Ok(Value::Null)`.
4162    pub async fn update_workflow<T: Serialize>(
4163        &self,
4164        workflow_id: &str,
4165        update_name: &str,
4166        input: T,
4167        request_id: Option<&str>,
4168    ) -> Result<Value> {
4169        let response = self
4170            .update_workflow_response(workflow_id, update_name, input, request_id)
4171            .await?;
4172        Self::submitted_update_value(workflow_id, response)
4173    }
4174
4175    /// Send a synchronous update and return the Server's full receipt instead
4176    /// of only its result.
4177    ///
4178    /// The request is the one [`Client::update_workflow`] sends, with the same
4179    /// caller command key rules, and it is sent once. The receipt carries the
4180    /// `request_id`, `update_id`, `run_id`, `update_status` and, on a Server
4181    /// that advertises `capabilities.command_request_keys`, the `retained` and
4182    /// `intent_verified` flags. Use it when the caller must tell a verified
4183    /// retry from a legacy readback: a receipt with `retained: true` and
4184    /// `intent_verified: false` is the original update for a key retained
4185    /// before the Server compared intent, so its result is not proof that this
4186    /// call's name and arguments match the original. A pending update is
4187    /// returned as its receipt (`update_status` is not `completed`), never as
4188    /// an error.
4189    pub async fn update_workflow_receipt<T: Serialize>(
4190        &self,
4191        workflow_id: &str,
4192        update_name: &str,
4193        input: T,
4194        request_id: Option<&str>,
4195    ) -> Result<Value> {
4196        self.update_workflow_response(workflow_id, update_name, input, request_id)
4197            .await
4198    }
4199
4200    /// Send a synchronous update and retain a bytes-capable Avro result.
4201    pub async fn update_workflow_avro_value<T: Serialize>(
4202        &self,
4203        workflow_id: &str,
4204        update_name: &str,
4205        input: T,
4206        request_id: Option<&str>,
4207    ) -> Result<AvroValue> {
4208        let response = self
4209            .update_workflow_response(workflow_id, update_name, input, request_id)
4210            .await?;
4211        Self::submitted_update_avro_value(workflow_id, response)
4212    }
4213
4214    async fn update_workflow_response<T: Serialize>(
4215        &self,
4216        workflow_id: &str,
4217        update_name: &str,
4218        input: T,
4219        request_id: Option<&str>,
4220    ) -> Result<Value> {
4221        let path = format!(
4222            "/workflows/{}/update/{}",
4223            path_segment("workflow_id", workflow_id)?,
4224            path_segment("update_name", update_name)?
4225        );
4226        let request_id = match request_id {
4227            Some(request_id) => {
4228                validate_request_id(request_id)?;
4229                request_id.to_string()
4230            }
4231            None => Self::generate_update_request_id(),
4232        };
4233        let input = normalize_avro_arguments(AvroValue::from_serialize(&input)?);
4234        let body = self.with_observability_context(json!({
4235            "input": encode_typed_envelope(&input, DEFAULT_CODEC)?,
4236            "wait_for": "completed",
4237            "request_id": request_id,
4238        }));
4239        let receipt = self
4240            .request_json(
4241                reqwest::Method::POST,
4242                &path,
4243                RequestProtocol::ControlPlane,
4244                Some(&body),
4245            )
4246            .await
4247            .map_err(|error| error.with_sent_request_id(&request_id))?;
4248        Ok(with_request_id(receipt, &request_id))
4249    }
4250
4251    pub async fn describe_workflow(&self, workflow_id: &str) -> Result<WorkflowDescription> {
4252        let path = format!("/workflows/{}", path_segment("workflow_id", workflow_id)?);
4253        let mut data: WorkflowDescription = self
4254            .request_json(
4255                reqwest::Method::GET,
4256                &path,
4257                RequestProtocol::ControlPlane,
4258                Option::<&Value>::None,
4259            )
4260            .await?;
4261        data.decode_payloads()?;
4262        Ok(data)
4263    }
4264
4265    /// Describe one selected run, including historical terminal runs.
4266    pub async fn describe_workflow_run(
4267        &self,
4268        workflow_id: &str,
4269        run_id: &str,
4270    ) -> Result<WorkflowDescription> {
4271        let path = format!(
4272            "/workflows/{}/runs/{}",
4273            path_segment("workflow_id", workflow_id)?,
4274            path_segment("run_id", run_id)?,
4275        );
4276        let mut data: WorkflowDescription = self
4277            .request_json(
4278                reqwest::Method::GET,
4279                &path,
4280                RequestProtocol::ControlPlane,
4281                Option::<&Value>::None,
4282            )
4283            .await?;
4284        data.decode_payloads()?;
4285        Ok(data)
4286    }
4287
4288    fn workflow_stream_path(
4289        workflow_id: &str,
4290        run_id: &str,
4291        stream_name: Option<&str>,
4292    ) -> Result<String> {
4293        let mut path = format!(
4294            "/workflows/{}/runs/{}/streams",
4295            path_segment("workflow_id", workflow_id)?,
4296            path_segment("run_id", run_id)?,
4297        );
4298        if let Some(stream_name) = stream_name {
4299            path.push('/');
4300            path.push_str(&path_segment("stream_name", stream_name)?);
4301        }
4302        Ok(path)
4303    }
4304
4305    /// List the run-scoped output streams already opened by a workflow.
4306    pub async fn list_workflow_streams(
4307        &self,
4308        workflow_id: &str,
4309        run_id: &str,
4310    ) -> Result<Vec<WorkflowStreamDescription>> {
4311        let response: WorkflowStreamListResponse = self
4312            .request_json(
4313                reqwest::Method::GET,
4314                &Self::workflow_stream_path(workflow_id, run_id, None)?,
4315                RequestProtocol::ControlPlane,
4316                Option::<&Value>::None,
4317            )
4318            .await?;
4319        Ok(response.streams)
4320    }
4321
4322    /// Describe stream lifecycle, offsets, pending count, and terminal error.
4323    pub async fn describe_workflow_stream(
4324        &self,
4325        workflow_id: &str,
4326        run_id: &str,
4327        stream_name: &str,
4328    ) -> Result<WorkflowStreamDescription> {
4329        let response: WorkflowStreamDescriptionResponse = self
4330            .request_json(
4331                reqwest::Method::GET,
4332                &Self::workflow_stream_path(workflow_id, run_id, Some(stream_name))?,
4333                RequestProtocol::ControlPlane,
4334                Option::<&Value>::None,
4335            )
4336            .await?;
4337        Ok(response.stream)
4338    }
4339
4340    /// Read one bounded page beginning at a zero-based offset.
4341    ///
4342    /// Delivery is at least once: persist `next_offset` only after processing
4343    /// the page. The future is cancellation-safe; dropping it cancels the
4344    /// in-flight request. Long polling is capped at 60 seconds by the SDK and
4345    /// service contract.
4346    pub async fn subscribe_workflow_stream(
4347        &self,
4348        workflow_id: &str,
4349        run_id: &str,
4350        stream_name: &str,
4351        from_offset: u64,
4352        max_items: usize,
4353        wait: Duration,
4354    ) -> Result<WorkflowStreamPage> {
4355        let max_items = max_items.clamp(1, 500);
4356        let wait_seconds = wait.as_secs().min(MAX_LONG_POLL_TIMEOUT_SECONDS);
4357        let path = format!(
4358            "{}/items?from={from_offset}&max_items={max_items}&wait_seconds={wait_seconds}",
4359            Self::workflow_stream_path(workflow_id, run_id, Some(stream_name))?,
4360        );
4361        let response: WorkflowStreamPageResponse = self
4362            .request_json_with_timeout(
4363                reqwest::Method::GET,
4364                &path,
4365                RequestProtocol::ControlPlane,
4366                Option::<&Value>::None,
4367                Duration::from_secs(wait_seconds.saturating_add(5).max(5)),
4368            )
4369            .await?;
4370
4371        let items = response
4372            .items
4373            .into_iter()
4374            .map(|raw| {
4375                let offset = raw.get("offset").and_then(Value::as_u64).unwrap_or(0);
4376                let envelope = raw.get("payload").cloned();
4377                let payload = envelope
4378                    .as_ref()
4379                    .filter(|value| value.get("blob").is_some())
4380                    .map(|value| decode_wire_avro_value(value, DEFAULT_CODEC))
4381                    .transpose()?
4382                    .map(AvroValue::into_json)
4383                    .transpose()?;
4384                Ok(WorkflowStreamItem {
4385                    offset,
4386                    payload,
4387                    payload_envelope: envelope,
4388                    payload_reference: raw
4389                        .get("payload_reference")
4390                        .and_then(Value::as_str)
4391                        .map(str::to_string),
4392                    payload_codec: raw
4393                        .get("payload_codec")
4394                        .and_then(Value::as_str)
4395                        .map(str::to_string),
4396                    idempotency_key: raw
4397                        .get("idempotency_key")
4398                        .and_then(Value::as_str)
4399                        .map(str::to_string),
4400                    item_type: raw
4401                        .get("item_type")
4402                        .and_then(Value::as_str)
4403                        .map(str::to_string),
4404                    content_type: raw
4405                        .get("content_type")
4406                        .and_then(Value::as_str)
4407                        .map(str::to_string),
4408                    origin: raw
4409                        .get("origin")
4410                        .and_then(Value::as_str)
4411                        .map(str::to_string),
4412                    origin_reference: raw
4413                        .get("origin_reference")
4414                        .and_then(Value::as_str)
4415                        .map(str::to_string),
4416                    emitted_at: raw
4417                        .get("emitted_at")
4418                        .and_then(Value::as_str)
4419                        .map(str::to_string),
4420                    raw,
4421                })
4422            })
4423            .collect::<Result<Vec<_>>>()?;
4424        Ok(WorkflowStreamPage {
4425            stream: response.stream,
4426            items,
4427            next_offset: response.next_offset,
4428            terminal: response.terminal,
4429        })
4430    }
4431
4432    /// Append inline Avro envelopes or opaque external payload references.
4433    pub async fn append_workflow_stream(
4434        &self,
4435        workflow_id: &str,
4436        run_id: &str,
4437        stream_name: &str,
4438        items: &[WorkflowStreamAppendItem],
4439        max_pending_items: Option<u64>,
4440    ) -> Result<WorkflowStreamAppendResult> {
4441        if items.is_empty() {
4442            return Err(Error::Codec(
4443                "workflow_stream_items_empty: append requires at least one item".to_string(),
4444            ));
4445        }
4446        let mut body = json!({
4447            "items": items
4448                .iter()
4449                .map(|item| item.wire_value(None))
4450                .collect::<Vec<_>>(),
4451        });
4452        if let Some(max_pending_items) = max_pending_items {
4453            if max_pending_items == 0 {
4454                return Err(Error::Codec(
4455                    "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
4456                        .to_string(),
4457                ));
4458            }
4459            body["max_pending_items"] = json!(max_pending_items);
4460        }
4461        let response: WorkflowStreamAppendResponse = self
4462            .request_json(
4463                reqwest::Method::POST,
4464                &format!(
4465                    "{}/items",
4466                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name))?,
4467                ),
4468                RequestProtocol::ControlPlane,
4469                Some(&body),
4470            )
4471            .await?;
4472        Ok(WorkflowStreamAppendResult {
4473            stream: response.stream,
4474            accepted_offsets: response.accepted_offsets,
4475            accepted: response.accepted,
4476            deduped: response.deduped,
4477        })
4478    }
4479
4480    /// Close a stream, or mark it errored when `error_reason` is supplied.
4481    pub async fn close_workflow_stream(
4482        &self,
4483        workflow_id: &str,
4484        run_id: &str,
4485        stream_name: &str,
4486        error_reason: Option<&str>,
4487        retention_seconds: Option<u64>,
4488    ) -> Result<WorkflowStreamDescription> {
4489        let mut body = json!({});
4490        if let Some(error_reason) = error_reason {
4491            body["error_reason"] = json!(error_reason);
4492        }
4493        if let Some(retention_seconds) = retention_seconds {
4494            if retention_seconds == 0 {
4495                return Err(Error::Codec(
4496                    "workflow_stream_retention_invalid: retention_seconds must be positive"
4497                        .to_string(),
4498                ));
4499            }
4500            body["retention_seconds"] = json!(retention_seconds);
4501        }
4502        let response: WorkflowStreamDescriptionResponse = self
4503            .request_json(
4504                reqwest::Method::POST,
4505                &format!(
4506                    "{}/close",
4507                    Self::workflow_stream_path(workflow_id, run_id, Some(stream_name))?,
4508                ),
4509                RequestProtocol::ControlPlane,
4510                Some(&body),
4511            )
4512            .await?;
4513        Ok(response.stream)
4514    }
4515
4516    pub async fn register_worker(
4517        &self,
4518        worker_id: &str,
4519        task_queue: &str,
4520        supported_workflow_types: Vec<String>,
4521        supported_activity_types: Vec<String>,
4522        max_concurrent_workflow_tasks: usize,
4523        max_concurrent_activity_tasks: usize,
4524    ) -> Result<RegisterWorkerResponse> {
4525        self.register_worker_with_capabilities(
4526            worker_id,
4527            task_queue,
4528            supported_workflow_types,
4529            supported_activity_types,
4530            max_concurrent_workflow_tasks,
4531            max_concurrent_activity_tasks,
4532            Vec::new(),
4533        )
4534        .await
4535    }
4536
4537    /// Register a worker and explicitly advertise additive worker capabilities.
4538    // Public signature; bundling the arguments would break callers.
4539    #[allow(clippy::too_many_arguments)]
4540    pub async fn register_worker_with_capabilities(
4541        &self,
4542        worker_id: &str,
4543        task_queue: &str,
4544        supported_workflow_types: Vec<String>,
4545        supported_activity_types: Vec<String>,
4546        max_concurrent_workflow_tasks: usize,
4547        max_concurrent_activity_tasks: usize,
4548        capabilities: Vec<String>,
4549    ) -> Result<RegisterWorkerResponse> {
4550        self.register_worker_with_command_contracts(
4551            worker_id,
4552            task_queue,
4553            supported_workflow_types,
4554            supported_activity_types,
4555            max_concurrent_workflow_tasks,
4556            max_concurrent_activity_tasks,
4557            capabilities,
4558            Value::Object(serde_json::Map::new()),
4559        )
4560        .await
4561    }
4562
4563    /// Register a worker and advertise its named query and update handlers.
4564    ///
4565    /// This Rust SDK cannot execute synchronous pre-accept update validation,
4566    /// so a workflow contract with a non-empty or malformed
4567    /// `update_validators` declaration returns
4568    /// [`Error::UnsupportedUpdateValidators`] before registration transport.
4569    #[allow(clippy::too_many_arguments)]
4570    pub async fn register_worker_with_command_contracts(
4571        &self,
4572        worker_id: &str,
4573        task_queue: &str,
4574        supported_workflow_types: Vec<String>,
4575        supported_activity_types: Vec<String>,
4576        max_concurrent_workflow_tasks: usize,
4577        max_concurrent_activity_tasks: usize,
4578        capabilities: Vec<String>,
4579        workflow_command_contracts: Value,
4580    ) -> Result<RegisterWorkerResponse> {
4581        self.register_worker_with_definition_fingerprints(
4582            worker_id,
4583            task_queue,
4584            supported_workflow_types,
4585            supported_activity_types,
4586            max_concurrent_workflow_tasks,
4587            max_concurrent_activity_tasks,
4588            capabilities,
4589            workflow_command_contracts,
4590            None,
4591        )
4592        .await
4593    }
4594
4595    #[allow(clippy::too_many_arguments)]
4596    async fn register_worker_with_definition_fingerprints(
4597        &self,
4598        worker_id: &str,
4599        task_queue: &str,
4600        supported_workflow_types: Vec<String>,
4601        supported_activity_types: Vec<String>,
4602        max_concurrent_workflow_tasks: usize,
4603        max_concurrent_activity_tasks: usize,
4604        capabilities: Vec<String>,
4605        workflow_command_contracts: Value,
4606        workflow_definition_fingerprints: Option<BTreeMap<String, String>>,
4607    ) -> Result<RegisterWorkerResponse> {
4608        if let Some(contracts) = workflow_command_contracts.as_object() {
4609            for (workflow_type, contract) in contracts {
4610                let Some(update_validators) = contract.get("update_validators") else {
4611                    continue;
4612                };
4613                if !update_validators
4614                    .as_array()
4615                    .is_some_and(|validators| validators.is_empty())
4616                {
4617                    return Err(Error::UnsupportedUpdateValidators {
4618                        workflow_type: workflow_type.clone(),
4619                    });
4620                }
4621            }
4622        }
4623
4624        let mut body = json!({
4625            "worker_id": worker_id,
4626            "task_queue": task_queue,
4627            "runtime": "rust",
4628            "sdk_version": SDK_VERSION,
4629            "supported_workflow_types": supported_workflow_types,
4630            "supported_activity_types": supported_activity_types,
4631            "capabilities": capabilities,
4632            "capability_manifest": portable_worker_affinity_capability_manifest(),
4633            "max_concurrent_workflow_tasks": max_concurrent_workflow_tasks,
4634            "max_concurrent_activity_tasks": max_concurrent_activity_tasks
4635        });
4636        if capabilities
4637            .iter()
4638            .any(|capability| capability == "nexus_cooperative_cancellation")
4639        {
4640            body["capability_manifest"]["nexus_cooperative_cancellation"] = json!({
4641                "supported":true, "minimum_protocol_version":"1.20",
4642                "implementation":"owned_workflow_run_canonical_delivery", "binding_kinds":["workflow_run"],
4643            });
4644        }
4645        if let Some(build_id) = &self.worker_build_id {
4646            if build_id.is_empty() || build_id.len() > 255 {
4647                return Err(Error::WorkerLoop(
4648                    "worker build ID must contain 1 to 255 bytes".into(),
4649                ));
4650            }
4651            body["build_id"] = json!(build_id);
4652        }
4653        if self.sticky_cache.is_some() {
4654            body["capability_manifest"]["sticky_execution"] = json!({"supported":true,
4655                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
4656                "implementation":"bounded_durable_history_cache"});
4657            body["capability_manifest"]["sticky_history_suffix"] = json!({"supported":true,
4658                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION,
4659                "version":1});
4660        }
4661        if self.local_activities_enabled {
4662            body["capability_manifest"]["local_activities"] = json!({"supported":true,
4663                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4664        }
4665        if self.worker_sessions_enabled {
4666            body["capability_manifest"]["worker_sessions"] = json!({"supported":true,
4667                "minimum_protocol_version":PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION});
4668            body["max_concurrent_worker_sessions"] = json!(self.max_concurrent_worker_sessions);
4669        }
4670        if workflow_command_contracts
4671            .as_object()
4672            .is_some_and(|contracts| !contracts.is_empty())
4673        {
4674            body["workflow_command_contracts"] = workflow_command_contracts;
4675        }
4676        if let Some(fingerprints) = workflow_definition_fingerprints {
4677            body["workflow_definition_fingerprints"] = json!(fingerprints);
4678        }
4679
4680        let response: Value = self
4681            .request_json(
4682                reqwest::Method::POST,
4683                "/worker/register",
4684                RequestProtocol::DefaultWorker,
4685                Some(&body),
4686            )
4687            .await?;
4688        if response["registered"] == true && response["worker_id"].as_str() == Some(worker_id) {
4689            self.observe_worker_activity_lease_capabilities(&response["server_capabilities"]);
4690        }
4691        if self.sticky_cache.is_some() {
4692            self.confirm_sticky_registration(&response, worker_id, task_queue)
4693                .await?;
4694        }
4695        if self.local_activities_enabled || self.worker_sessions_enabled {
4696            let compatible = response["registered"].as_bool() == Some(true)
4697                && response["worker_id"].as_str() == Some(worker_id)
4698                && response["namespace"].as_str() == Some(self.namespace.as_str())
4699                && response["task_queue"].as_str() == Some(task_queue)
4700                && response["protocol_version"]
4701                    .as_str()
4702                    .and_then(|version| version.strip_prefix("1."))
4703                    .and_then(|minor| minor.parse::<u64>().ok())
4704                    .is_some_and(|minor| minor >= 18)
4705                && (!self.local_activities_enabled
4706                    || response["capability_manifest"]["local_activities"]["supported"].as_bool()
4707                        == Some(true))
4708                && (!self.worker_sessions_enabled
4709                    || (response["capability_manifest"]["worker_sessions"]["supported"].as_bool()
4710                        == Some(true)
4711                        && response["capabilities"].as_array().is_some_and(|accepted| {
4712                            capabilities.iter().all(|capability| {
4713                                accepted
4714                                    .iter()
4715                                    .any(|value| value.as_str() == Some(capability.as_str()))
4716                            })
4717                        })));
4718            if !compatible {
4719                let error = Error::WorkerLoop(if self.worker_sessions_enabled {
4720                    "worker_session_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and session capabilities".into()
4721                } else {
4722                    "local_activity_registration_unconfirmed: Server must acknowledge this worker, namespace, queue and local capability".into()
4723                });
4724                if response["registered"] == true
4725                    && response["worker_id"].as_str() == Some(worker_id)
4726                {
4727                    if let Err(deregistration) =
4728                        self.deregister_worker_registration(worker_id).await
4729                    {
4730                        return Err(Error::WorkerShutdown {
4731                            primary: Box::new(error),
4732                            deregistration: Box::new(deregistration),
4733                        });
4734                    }
4735                }
4736                return Err(error);
4737            }
4738        }
4739        if self.cooperative_worker_protocol {
4740            let compatible = response["registered"].as_bool() == Some(true)
4741                && response["worker_id"].as_str() == Some(worker_id)
4742                && response["namespace"].as_str() == Some(self.namespace.as_str())
4743                && response["task_queue"].as_str() == Some(task_queue)
4744                && response["protocol_version"]
4745                    .as_str()
4746                    .is_some_and(cooperative_cancellation::supports_protocol)
4747                && response["server_capabilities"]["cooperative_cancellation"].as_bool()
4748                    == Some(true)
4749                && (!capabilities
4750                    .iter()
4751                    .any(|capability| capability == "nexus_cooperative_cancellation")
4752                    || nexus::installed_cooperation(&response["server_capabilities"]))
4753                && response["capabilities"].as_array().is_some_and(|accepted| {
4754                    capabilities.iter().all(|capability| {
4755                        accepted
4756                            .iter()
4757                            .any(|value| value.as_str() == Some(capability.as_str()))
4758                    })
4759                });
4760            if !compatible {
4761                let error = Error::CooperativeCancellationUnavailable(
4762                    "registration must acknowledge this namespace, queue, worker, capabilities and compatible runtime protocol 1.20".into(),
4763                );
4764                if response["registered"].as_bool() == Some(true)
4765                    && response["worker_id"].as_str() == Some(worker_id)
4766                {
4767                    if let Err(deregistration) =
4768                        self.deregister_worker_registration(worker_id).await
4769                    {
4770                        return Err(Error::WorkerShutdown {
4771                            primary: Box::new(error),
4772                            deregistration: Box::new(deregistration),
4773                        });
4774                    }
4775                }
4776                return Err(error);
4777            }
4778        }
4779        Ok(serde_json::from_value(response)?)
4780    }
4781
4782    /// Gracefully remove one worker's registration through the worker plane.
4783    ///
4784    /// This operation is separate from operator-facing worker management. It
4785    /// uses worker-protocol authentication and returns the server's lease
4786    /// recovery result.
4787    pub async fn deregister_worker_registration(
4788        &self,
4789        worker_id: &str,
4790    ) -> Result<WorkerDeregistrationEnvelope> {
4791        let path = format!(
4792            "/worker/registrations/{}",
4793            percent_encode_path_segment(worker_id)
4794        );
4795        self.request_json(
4796            reqwest::Method::DELETE,
4797            &path,
4798            RequestProtocol::DefaultWorker,
4799            Option::<&Value>::None,
4800        )
4801        .await
4802    }
4803
4804    /// Long-poll for an ephemeral, read-only workflow query task.
4805    pub async fn poll_query_task(
4806        &self,
4807        worker_id: &str,
4808        task_queue: &str,
4809        timeout: Duration,
4810    ) -> Result<Option<QueryTask>> {
4811        Ok(self
4812            .poll_query_task_response(worker_id, task_queue, timeout)
4813            .await?
4814            .task)
4815    }
4816
4817    /// Poll a query task while preserving server stop and drain metadata.
4818    pub async fn poll_query_task_response(
4819        &self,
4820        worker_id: &str,
4821        task_queue: &str,
4822        timeout: Duration,
4823    ) -> Result<PollQueryTaskResponse> {
4824        let poll_request_id = unique_request_id("rust-query-poll");
4825        self.poll_query_task_response_with_request_id(
4826            worker_id,
4827            task_queue,
4828            timeout,
4829            &poll_request_id,
4830            1,
4831        )
4832        .await
4833    }
4834
4835    async fn poll_query_task_response_with_request_id(
4836        &self,
4837        worker_id: &str,
4838        task_queue: &str,
4839        timeout: Duration,
4840        poll_request_id: &str,
4841        transport_retries: usize,
4842    ) -> Result<PollQueryTaskResponse> {
4843        let timeout_seconds = long_poll_timeout_seconds(timeout);
4844        let body = json!({
4845            "worker_id": worker_id,
4846            "task_queue": task_queue,
4847            "poll_request_id": poll_request_id,
4848            "timeout_seconds": timeout_seconds,
4849        });
4850        self.poll_request_json(
4851            "/worker/query-tasks/poll",
4852            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4853            &body,
4854            timeout + Duration::from_secs(5),
4855            transport_retries,
4856        )
4857        .await
4858    }
4859
4860    /// Complete a query task without appending workflow history.
4861    pub async fn complete_query_task<T: Serialize>(
4862        &self,
4863        query_task_id: &str,
4864        lease_owner: &str,
4865        query_task_attempt: u64,
4866        result: T,
4867        codec: &str,
4868    ) -> Result<Value> {
4869        let typed_result = AvroValue::from_serialize(&result)?;
4870        let result_envelope = encode_typed_envelope(&typed_result, codec)?;
4871        self.complete_query_task_with_envelope(
4872            query_task_id,
4873            lease_owner,
4874            query_task_attempt,
4875            typed_result.into_json()?,
4876            result_envelope,
4877        )
4878        .await
4879    }
4880
4881    async fn complete_query_task_with_envelope(
4882        &self,
4883        query_task_id: &str,
4884        lease_owner: &str,
4885        query_task_attempt: u64,
4886        result: Value,
4887        result_envelope: Value,
4888    ) -> Result<Value> {
4889        let body = json!({
4890            "lease_owner": lease_owner,
4891            "query_task_attempt": query_task_attempt,
4892            "result": result,
4893            "result_envelope": result_envelope,
4894        });
4895        let path = format!("/worker/query-tasks/{query_task_id}/complete");
4896        let response = self
4897            .request_json(
4898                reqwest::Method::POST,
4899                &path,
4900                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4901                Some(&body),
4902            )
4903            .await;
4904        query_task_response(response)
4905    }
4906
4907    /// Report a stable machine-readable query-task failure.
4908    pub async fn fail_query_task(
4909        &self,
4910        query_task_id: &str,
4911        lease_owner: &str,
4912        query_task_attempt: u64,
4913        message: impl Into<String>,
4914        reason: impl Into<String>,
4915        failure_type: impl Into<String>,
4916    ) -> Result<Value> {
4917        let body = json!({
4918            "lease_owner": lease_owner,
4919            "query_task_attempt": query_task_attempt,
4920            "failure": {
4921                "message": message.into(),
4922                "reason": reason.into(),
4923                "type": failure_type.into(),
4924            }
4925        });
4926        let path = format!("/worker/query-tasks/{query_task_id}/fail");
4927        let response = self
4928            .request_json(
4929                reqwest::Method::POST,
4930                &path,
4931                RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
4932                Some(&body),
4933            )
4934            .await;
4935        query_task_response(response)
4936    }
4937
4938    pub async fn heartbeat_worker(
4939        &self,
4940        worker_id: &str,
4941        workflow_available: usize,
4942        activity_available: usize,
4943    ) -> Result<Value> {
4944        self.heartbeat_worker_with_sessions(worker_id, workflow_available, activity_available, None)
4945            .await
4946    }
4947
4948    async fn heartbeat_worker_with_sessions(
4949        &self,
4950        worker_id: &str,
4951        workflow_available: usize,
4952        activity_available: usize,
4953        session_available: Option<usize>,
4954    ) -> Result<Value> {
4955        let mut body = json!({
4956            "worker_id": worker_id,
4957            "task_slots": {
4958                "workflow_available": workflow_available,
4959                "activity_available": activity_available
4960            },
4961            "process_metrics": {
4962                "process_id": std::process::id(),
4963                "process_uptime_seconds": 0
4964            }
4965        });
4966
4967        if let Some(available) = session_available {
4968            body["task_slots"]["session_available"] = json!(available);
4969        }
4970
4971        self.request_json(
4972            reqwest::Method::POST,
4973            "/worker/heartbeat",
4974            RequestProtocol::DefaultWorker,
4975            Some(&body),
4976        )
4977        .await
4978    }
4979
4980    pub async fn poll_workflow_task(
4981        &self,
4982        worker_id: &str,
4983        task_queue: &str,
4984        timeout: Duration,
4985    ) -> Result<Option<WorkflowTask>> {
4986        Ok(self
4987            .poll_workflow_task_response(worker_id, task_queue, timeout)
4988            .await?
4989            .task)
4990    }
4991
4992    pub async fn poll_workflow_task_response(
4993        &self,
4994        worker_id: &str,
4995        task_queue: &str,
4996        timeout: Duration,
4997    ) -> Result<PollWorkflowTaskResponse> {
4998        let poll_request_id = unique_request_id("rust-workflow-poll");
4999        self.poll_workflow_task_response_with_request_id(
5000            worker_id,
5001            task_queue,
5002            timeout,
5003            &poll_request_id,
5004            1,
5005        )
5006        .await
5007    }
5008
5009    async fn poll_workflow_task_response_with_request_id(
5010        &self,
5011        worker_id: &str,
5012        task_queue: &str,
5013        timeout: Duration,
5014        poll_request_id: &str,
5015        transport_retries: usize,
5016    ) -> Result<PollWorkflowTaskResponse> {
5017        let body = json!({
5018            "worker_id": worker_id,
5019            "task_queue": task_queue,
5020            "poll_request_id": poll_request_id,
5021            "timeout_seconds": long_poll_timeout_seconds(timeout),
5022            "history_page_size": WORKFLOW_HISTORY_PAGE_SIZE,
5023        });
5024        let mut wire: Value = self
5025            .poll_request_json_unresolved(
5026                "/worker/workflow-tasks/poll",
5027                RequestProtocol::DefaultWorker,
5028                &body,
5029                timeout + Duration::from_secs(5),
5030                transport_retries,
5031            )
5032            .await?;
5033        let ready_age = metrics::ready_age_from_poll(&wire);
5034        let claim =
5035            workflow_hydration::HydrationClaim::from_poll(&wire, worker_id, &self.namespace)?;
5036        let (data, _) = workflow_hydration::HydrationClaim::protect(claim, self, async {
5037            self.resolve_runtime_payloads(
5038                &mut wire,
5039                "/worker/workflow-tasks/poll",
5040                RequestProtocol::Worker(self.worker_protocol_version.as_str()),
5041            )
5042            .await?;
5043            let mut data: PollWorkflowTaskResponse = serde_json::from_value(wire)?;
5044            if let Some(task) = data.task.as_mut() {
5045                self.fetch_remaining_workflow_history(worker_id, task)
5046                    .await?;
5047            }
5048            Ok(data)
5049        })
5050        .await?;
5051        if data.task.is_some() {
5052            self.worker_dispatch_metrics
5053                .ready_age("workflow", task_queue, ready_age);
5054        }
5055        Ok(data)
5056    }
5057
5058    async fn fetch_remaining_workflow_history(
5059        &self,
5060        worker_id: &str,
5061        task: &mut WorkflowTask,
5062    ) -> Result<()> {
5063        let mut next_token = task.next_history_page_token.clone();
5064        let mut seen = BTreeSet::new();
5065
5066        while let Some(token) = next_token.take().filter(|token| !token.is_empty()) {
5067            if seen.len() >= 128 || !seen.insert(token.clone()) {
5068                return Err(Error::Codec(
5069                    "workflow history pagination exceeded its page bound or repeated a token"
5070                        .into(),
5071                ));
5072            }
5073            let lease_owner = task
5074                .lease_owner
5075                .clone()
5076                .unwrap_or_else(|| worker_id.to_string());
5077            let page = self
5078                .workflow_task_history_page(
5079                    &task.task_id,
5080                    &lease_owner,
5081                    task.workflow_task_attempt,
5082                    &token,
5083                )
5084                .await?;
5085
5086            task.append_history_page(page);
5087
5088            if task.next_history_page_token.as_deref() == Some(token.as_str()) {
5089                return Err(Error::Codec(
5090                    "workflow history pagination returned the same page token".to_string(),
5091                ));
5092            }
5093
5094            next_token = task.next_history_page_token.clone();
5095        }
5096
5097        Ok(())
5098    }
5099
5100    async fn workflow_task_history_page(
5101        &self,
5102        task_id: &str,
5103        lease_owner: &str,
5104        workflow_task_attempt: u64,
5105        next_history_page_token: &str,
5106    ) -> Result<WorkflowTaskHistoryPage> {
5107        let body = json!({
5108            "lease_owner": lease_owner,
5109            "workflow_task_attempt": workflow_task_attempt,
5110            "next_history_page_token": next_history_page_token
5111        });
5112        let path = format!("/worker/workflow-tasks/{task_id}/history");
5113
5114        self.request_json(
5115            reqwest::Method::POST,
5116            &path,
5117            RequestProtocol::DefaultWorker,
5118            Some(&body),
5119        )
5120        .await
5121    }
5122
5123    pub async fn complete_workflow_task(
5124        &self,
5125        task_id: &str,
5126        lease_owner: &str,
5127        workflow_task_attempt: u64,
5128        commands: Vec<Value>,
5129    ) -> Result<Value> {
5130        self.complete_workflow_task_with_message_streams(
5131            task_id,
5132            lease_owner,
5133            workflow_task_attempt,
5134            commands,
5135            Vec::new(),
5136            Vec::new(),
5137            None,
5138        )
5139        .await
5140    }
5141
5142    #[allow(clippy::too_many_arguments)]
5143    async fn complete_workflow_task_with_message_streams(
5144        &self,
5145        task_id: &str,
5146        lease_owner: &str,
5147        workflow_task_attempt: u64,
5148        commands: Vec<Value>,
5149        message_stream_cursors: Vec<Value>,
5150        message_stream_waits: Vec<Value>,
5151        sticky_cache: Option<Value>,
5152    ) -> Result<Value> {
5153        validate_workflow_task_commands(&commands)?;
5154        let has_message_stream_metadata =
5155            !message_stream_cursors.is_empty() || !message_stream_waits.is_empty();
5156        if has_message_stream_metadata
5157            && !worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
5158        {
5159            return Err(Error::Codec(
5160                "message_streams_unavailable: message stream completion metadata requires worker protocol 1.15 or newer"
5161                    .to_string(),
5162            ));
5163        }
5164        let protocol_version = workflow_completion_protocol_version_with_message_streams(
5165            &commands,
5166            has_message_stream_metadata,
5167        );
5168        let protocol_version = if sticky_cache.is_some()
5169            && protocol_version
5170                .strip_prefix("1.")
5171                .and_then(|minor| minor.parse::<u64>().ok())
5172                .is_some_and(|minor| minor < 18)
5173        {
5174            PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION
5175        } else {
5176            protocol_version
5177        };
5178        let mut body = json!({
5179            "lease_owner": lease_owner,
5180            "workflow_task_attempt": workflow_task_attempt,
5181            "commands": commands
5182        });
5183        #[cfg(feature = "telemetry")]
5184        if self.observability_context_supported.load(Ordering::SeqCst)
5185            && opentelemetry::Context::current()
5186                .get::<telemetry::ExecutionFields>()
5187                .is_some()
5188        {
5189            if let Some(commands) = body["commands"].as_array_mut() {
5190                for command in commands {
5191                    if command.get("observability_context").is_none()
5192                        && matches!(
5193                            command["type"].as_str(),
5194                            Some("start_child_workflow" | "continue_as_new")
5195                        )
5196                    {
5197                        *command = self.with_observability_context(command.take());
5198                    }
5199                }
5200            }
5201        }
5202        if !message_stream_cursors.is_empty() {
5203            body["message_stream_cursors"] = Value::Array(message_stream_cursors);
5204        }
5205        if !message_stream_waits.is_empty() {
5206            body["message_stream_waits"] = Value::Array(message_stream_waits);
5207        }
5208        if let Some(claim) = sticky_cache {
5209            body["sticky_cache"] = claim;
5210        }
5211        let path = format!("/worker/workflow-tasks/{task_id}/complete");
5212        self.request_json(
5213            reqwest::Method::POST,
5214            &path,
5215            RequestProtocol::Worker(protocol_version),
5216            Some(&body),
5217        )
5218        .await
5219    }
5220
5221    pub async fn fail_workflow_task(
5222        &self,
5223        task_id: &str,
5224        lease_owner: &str,
5225        workflow_task_attempt: u64,
5226        message: impl Into<String>,
5227    ) -> Result<Value> {
5228        self.fail_workflow_task_with_type(
5229            task_id,
5230            lease_owner,
5231            workflow_task_attempt,
5232            message,
5233            "RustWorkflowTaskFailure",
5234        )
5235        .await
5236    }
5237
5238    async fn fail_workflow_task_with_type(
5239        &self,
5240        task_id: &str,
5241        lease_owner: &str,
5242        workflow_task_attempt: u64,
5243        message: impl Into<String>,
5244        failure_type: &str,
5245    ) -> Result<Value> {
5246        self.fail_workflow_task_with_failure(
5247            task_id,
5248            lease_owner,
5249            workflow_task_attempt,
5250            json!({"message": message.into(), "type": failure_type}),
5251        )
5252        .await
5253    }
5254
5255    /// Report a workflow-task failure using the existing Server failure schema.
5256    /// The published schema supports `message`, `type`, `reason`, `sequence`
5257    /// and `stack_trace`. Oversized data is bounded before transport; original
5258    /// sizes and omissions are marked in the existing message field.
5259    pub async fn fail_workflow_task_with_failure(
5260        &self,
5261        task_id: &str,
5262        lease_owner: &str,
5263        workflow_task_attempt: u64,
5264        failure: Value,
5265    ) -> Result<Value> {
5266        let body = json!({
5267            "lease_owner": lease_owner,
5268            "workflow_task_attempt": workflow_task_attempt,
5269            "failure": failure,
5270        });
5271        let path = format!("/worker/workflow-tasks/{task_id}/fail");
5272        self.request_json(
5273            reqwest::Method::POST,
5274            &path,
5275            RequestProtocol::DefaultWorker,
5276            Some(&body),
5277        )
5278        .await
5279    }
5280
5281    pub async fn poll_activity_task(
5282        &self,
5283        worker_id: &str,
5284        task_queue: &str,
5285        timeout: Duration,
5286    ) -> Result<Option<ActivityTask>> {
5287        Ok(self
5288            .poll_activity_task_response(worker_id, task_queue, timeout)
5289            .await?
5290            .task)
5291    }
5292
5293    /// Poll an activity task while preserving server stop and drain metadata.
5294    pub async fn poll_activity_task_response(
5295        &self,
5296        worker_id: &str,
5297        task_queue: &str,
5298        timeout: Duration,
5299    ) -> Result<PollActivityTaskResponse> {
5300        let poll_request_id = unique_request_id("rust-activity-poll");
5301        self.poll_activity_task_response_with_request_id(
5302            worker_id,
5303            task_queue,
5304            timeout,
5305            &poll_request_id,
5306            1,
5307        )
5308        .await
5309        .map(worker_session::SessionPollResponse::ordinary)
5310    }
5311
5312    async fn poll_activity_task_response_with_request_id(
5313        &self,
5314        worker_id: &str,
5315        task_queue: &str,
5316        timeout: Duration,
5317        poll_request_id: &str,
5318        transport_retries: usize,
5319    ) -> Result<worker_session::SessionPollResponse> {
5320        let body = json!({
5321            "worker_id": worker_id,
5322            "task_queue": task_queue,
5323            "poll_request_id": poll_request_id,
5324            "timeout_seconds": long_poll_timeout_seconds(timeout),
5325        });
5326        // A delivered lease is measured from the poll's start, not its reply.
5327        let requested = tokio::time::Instant::now();
5328        let mut wire: Value = self
5329            .poll_request_json_unresolved(
5330                "/worker/activity-tasks/poll",
5331                RequestProtocol::DefaultWorker,
5332                &body,
5333                timeout + Duration::from_secs(5),
5334                transport_retries,
5335            )
5336            .await?;
5337        let ready_age = metrics::ready_age_from_poll(&wire);
5338        let lease_deadline = poll_lease_deadline(&wire, requested);
5339        let lease = activity_lease::authority::Lease::confirm(
5340            self, &wire, worker_id, task_queue, requested,
5341        )
5342        .await?;
5343        let observed = self.with_activity_lease_authority(
5344            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
5345        );
5346        let claim = if lease.is_none() {
5347            activity_hydration::HydrationClaim::from_poll(&wire, worker_id, self)?
5348        } else {
5349            None
5350        };
5351        let loading = async {
5352            observed
5353                .resolve_runtime_payloads(
5354                    &mut wire,
5355                    "/worker/activity-tasks/poll",
5356                    RequestProtocol::DefaultWorker,
5357                )
5358                .await?;
5359            if let Some(lease) = &lease {
5360                lease
5361                    .authority
5362                    .refresh_delivery_session(&mut wire["task"])?;
5363            }
5364            let heartbeat_resume =
5365                activity_checkpoint::HeartbeatResume::from_poll(&wire, &self.namespace)?;
5366            let mut data: worker_session::SessionPollResponse = serde_json::from_value(wire)?;
5367            if let Some(task) = data.task.as_mut() {
5368                task.heartbeat_resume = heartbeat_resume;
5369            }
5370            Ok(data)
5371        };
5372        let mut data: worker_session::SessionPollResponse = match lease.as_ref() {
5373            Some(lease) => match lease.authority.protect(loading).await {
5374                Ok(data) => data,
5375                Err(error) => {
5376                    lease.settle_release().await;
5377                    return Err(error);
5378                }
5379            },
5380            None => {
5381                activity_hydration::HydrationClaim::protect(claim.as_ref(), self, loading).await?
5382            }
5383        };
5384        if let Some(task) = data.task.as_mut() {
5385            task.hydration_claim = claim;
5386            task.activity_lease = lease;
5387            task.lease_deadline = lease_deadline;
5388            self.worker_dispatch_metrics
5389                .ready_age("activity", task_queue, ready_age);
5390        }
5391        Ok(data)
5392    }
5393
5394    pub async fn complete_activity_task<T: Serialize>(
5395        &self,
5396        task_id: &str,
5397        activity_attempt_id: &str,
5398        lease_owner: &str,
5399        result: T,
5400        codec: &str,
5401    ) -> Result<Value> {
5402        let result = encode_typed_envelope(&AvroValue::from_serialize(&result)?, codec)?;
5403        let body = json!({
5404            "activity_attempt_id": activity_attempt_id,
5405            "lease_owner": lease_owner,
5406            "result": result
5407        });
5408        let path = format!("/worker/activity-tasks/{task_id}/complete");
5409        activity_task_response(
5410            self.request_json(
5411                reqwest::Method::POST,
5412                &path,
5413                RequestProtocol::DefaultWorker,
5414                Some(&body),
5415            )
5416            .await,
5417            "complete",
5418            task_id,
5419            activity_attempt_id,
5420        )
5421    }
5422
5423    pub async fn fail_activity_task(
5424        &self,
5425        task_id: &str,
5426        activity_attempt_id: &str,
5427        lease_owner: &str,
5428        message: impl Into<String>,
5429        non_retryable: bool,
5430    ) -> Result<Value> {
5431        self.fail_activity_task_with_error(
5432            task_id,
5433            activity_attempt_id,
5434            lease_owner,
5435            &ActivityError::new("RustActivityFailure", message).non_retryable(non_retryable),
5436        )
5437        .await
5438    }
5439
5440    /// Report an activity's application-defined failure type and retry marker.
5441    pub async fn fail_activity_task_with_error(
5442        &self,
5443        task_id: &str,
5444        activity_attempt_id: &str,
5445        lease_owner: &str,
5446        error: &ActivityError,
5447    ) -> Result<Value> {
5448        let error = error.validated();
5449        self.fail_activity_task_with_failure(task_id,activity_attempt_id,lease_owner,json!({
5450            "message":error.message,"type":error.exception_type,"non_retryable":error.non_retryable
5451        })).await
5452    }
5453
5454    /// Report a structured activity failure using existing Server fields such as
5455    /// `message`, `type`, `stack_trace`, `non_retryable` and Avro `details`.
5456    /// The final encoded report is bounded without changing claim identity or
5457    /// retry flags. Invalid or unfit required data is a reporting error.
5458    pub async fn fail_activity_task_with_failure(
5459        &self,
5460        task_id: &str,
5461        activity_attempt_id: &str,
5462        lease_owner: &str,
5463        failure: Value,
5464    ) -> Result<Value> {
5465        let body = json!({
5466            "activity_attempt_id":activity_attempt_id,"lease_owner":lease_owner,"failure":failure
5467        });
5468        let path = format!("/worker/activity-tasks/{task_id}/fail");
5469        activity_task_response(
5470            self.request_json(
5471                reqwest::Method::POST,
5472                &path,
5473                RequestProtocol::DefaultWorker,
5474                Some(&body),
5475            )
5476            .await,
5477            "fail",
5478            task_id,
5479            activity_attempt_id,
5480        )
5481    }
5482
5483    /// Record a flat map of scalar/null activity progress metadata.
5484    ///
5485    /// Heartbeat details use the Server's bounded JSON progress contract.
5486    /// They are not workflow payload envelopes.
5487    pub async fn heartbeat_activity_task<T: Serialize>(
5488        &self,
5489        task_id: &str,
5490        activity_attempt_id: &str,
5491        lease_owner: &str,
5492        details: T,
5493    ) -> Result<ActivityHeartbeatResponse> {
5494        serde_json::from_value(
5495            self.heartbeat_activity_task_value(task_id, activity_attempt_id, lease_owner, details)
5496                .await?,
5497        )
5498        .map_err(Error::from)
5499    }
5500
5501    async fn heartbeat_activity_task_value<T: Serialize>(
5502        &self,
5503        task_id: &str,
5504        activity_attempt_id: &str,
5505        lease_owner: &str,
5506        details: T,
5507    ) -> Result<Value> {
5508        let details = AvroValue::from_serialize(&details)?.into_json()?;
5509        let body = json!({
5510            "activity_attempt_id": activity_attempt_id,
5511            "lease_owner": lease_owner,
5512            "details": details
5513        });
5514        let path = format!("/worker/activity-tasks/{task_id}/heartbeat");
5515        let started = tokio::time::Instant::now();
5516        let response = activity_task_response(
5517            self.request_json(
5518                reqwest::Method::POST,
5519                &path,
5520                RequestProtocol::DefaultWorker,
5521                Some(&body),
5522            )
5523            .await,
5524            "heartbeat",
5525            task_id,
5526            activity_attempt_id,
5527        )?;
5528        if let Some(authority) = &self.activity_lease_authority {
5529            authority.progress(&response, started)?;
5530        }
5531        Ok(response)
5532    }
5533
5534    async fn request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
5535        &self,
5536        method: reqwest::Method,
5537        path: &str,
5538        protocol: RequestProtocol,
5539        body: Option<&B>,
5540    ) -> Result<T> {
5541        self.request_json_with_timeout(method, path, protocol, body, Duration::from_secs(60))
5542            .await
5543    }
5544
5545    async fn request_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
5546        &self,
5547        method: reqwest::Method,
5548        path: &str,
5549        protocol: RequestProtocol,
5550        body: Option<&B>,
5551        timeout: Duration,
5552    ) -> Result<T> {
5553        self.metrics_request(method, path, protocol, body, timeout, true)
5554            .await
5555    }
5556
5557    fn worker_request_protocol(&self, protocol: RequestProtocol) -> Result<RequestProtocol> {
5558        Ok(match protocol {
5559            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
5560                let selected = self.worker_protocol_version.as_str();
5561                if self.cooperative_worker_protocol
5562                    && !cooperative_cancellation::supports_protocol(selected)
5563                {
5564                    return Err(Error::CooperativeCancellationUnavailable(
5565                        "explicit protocol 1.19 cannot enable cooperative cancellation; select protocol 1.20".into(),
5566                    ));
5567                }
5568                if let RequestProtocol::Worker(minimum) = protocol {
5569                    let supported = minimum
5570                        .strip_prefix("1.")
5571                        .and_then(|minor| minor.parse::<u64>().ok())
5572                        .zip(
5573                            selected
5574                                .strip_prefix("1.")
5575                                .and_then(|minor| minor.parse::<u64>().ok()),
5576                        )
5577                        .is_some_and(|(minimum, selected)| selected >= minimum);
5578                    if !supported {
5579                        return Err(Error::WorkerLoop(format!(
5580                            "worker request requires protocol {minimum}; client explicitly selects {selected}"
5581                        )));
5582                    }
5583                }
5584                RequestProtocol::Worker(selected)
5585            }
5586            RequestProtocol::ControlPlane => RequestProtocol::ControlPlane,
5587        })
5588    }
5589
5590    fn check_activity_lease_request(&self, path: &str, body: Option<&Value>) -> Result<()> {
5591        match &self.activity_lease_authority {
5592            Some(authority) => authority.check(path, body),
5593            None => Ok(()),
5594        }
5595    }
5596
5597    async fn request_json_unresolved_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
5598        &self,
5599        method: reqwest::Method,
5600        path: &str,
5601        protocol: RequestProtocol,
5602        body: Option<&B>,
5603        timeout: Duration,
5604    ) -> Result<T> {
5605        self.metrics_request(method, path, protocol, body, timeout, false)
5606            .await
5607    }
5608
5609    async fn send_json_with_timeout<T: DeserializeOwned, B: Serialize + ?Sized>(
5610        &self,
5611        method: reqwest::Method,
5612        path: &str,
5613        protocol: RequestProtocol,
5614        body: Option<&B>,
5615        timeout: Duration,
5616        observation: &metrics::ClientObservation,
5617    ) -> Result<T> {
5618        #[cfg(feature = "telemetry")]
5619        self.begin_observability_discovery(&method, path);
5620        let protocol = self.worker_request_protocol(protocol)?;
5621        let auth_token = self.auth_token(protocol)?;
5622        let mut request = self
5623            .http
5624            .request(method.clone(), format!("{}/api{}", self.base_url, path))
5625            .timeout(timeout)
5626            .header(reqwest::header::ACCEPT, "application/json")
5627            .header(reqwest::header::CONTENT_TYPE, "application/json")
5628            .header("X-Namespace", &self.namespace);
5629
5630        match protocol {
5631            RequestProtocol::DefaultWorker => {
5632                request = request.header(
5633                    "X-Durable-Workflow-Protocol-Version",
5634                    self.worker_protocol_version.as_str(),
5635                );
5636            }
5637            RequestProtocol::Worker(version) => {
5638                request = request.header("X-Durable-Workflow-Protocol-Version", version);
5639            }
5640            RequestProtocol::ControlPlane => {
5641                request = request.header(
5642                    "X-Durable-Workflow-Control-Plane-Version",
5643                    CONTROL_PLANE_VERSION,
5644                );
5645            }
5646        }
5647        // server#1262: a worker request names the capabilities it holds, and
5648        // its answer is restored against exactly that pair (captured here).
5649        let mut capabilities = (!matches!(protocol, RequestProtocol::ControlPlane))
5650            .then(|| self.capabilities_digest.capture());
5651        let mut digest_resent = false;
5652        if let Some(captured) = &capabilities {
5653            request = request.header(
5654                server_capabilities_digest::HEADER,
5655                server_capabilities_digest::Digest::header(captured),
5656            );
5657        }
5658
5659        if let Some(token) = auth_token {
5660            request = request.bearer_auth(token);
5661        }
5662
5663        // A task report before externalization, kept so it can be encoded
5664        // again (once) if the Server refuses it as too large for a policy
5665        // that changed since it was cached.
5666        let mut unexternalized: Option<Value> = None;
5667        if let Some(body) = body {
5668            let mut body = serde_json::to_value(body)?;
5669            self.check_activity_lease_request(path, Some(&body))?;
5670            let mut report = failure_reporting::Prepared::new(
5671                &mut body,
5672                path,
5673                failure_reporting::REQUEST_BYTES,
5674            )?;
5675            if let Some(report) = report.as_mut().filter(|report| report.can_reduce()) {
5676                let limit = self
5677                    .discover_failure_request_limit(&body, path, protocol)
5678                    .await?;
5679                report.encode(&mut body, limit)?;
5680            }
5681            if matches!(
5682                method,
5683                reqwest::Method::POST | reqwest::Method::PUT | reqwest::Method::PATCH
5684            ) {
5685                self.check_activity_lease_request(path, Some(&body))?;
5686                if report.is_none() && is_task_report(path) {
5687                    unexternalized = Some(body.clone());
5688                }
5689                self.externalize_runtime_payloads(&mut body, path, protocol)
5690                    .await?;
5691                self.check_activity_lease_request(path, Some(&body))?;
5692            }
5693            if let Some(mut report) = report {
5694                let limit = self.known_failure_request_limit(protocol)?;
5695                request = request.body(report.encode(&mut body, limit)?);
5696            } else {
5697                request = request.json(&body);
5698            }
5699        }
5700
5701        let mut request = request.build()?;
5702        let request_body = request
5703            .body()
5704            .and_then(reqwest::Body::as_bytes)
5705            .and_then(|body| serde_json::from_slice::<Value>(body).ok());
5706        let poll_request_id = path.ends_with("/poll").then(|| {
5707            request_body
5708                .as_ref()
5709                .and_then(|body| body.get("poll_request_id")?.as_str().map(str::to_owned))
5710                .unwrap_or_default()
5711        });
5712        let request_bytes = request
5713            .body()
5714            .and_then(reqwest::Body::as_bytes)
5715            .map_or(0, |body| body.len() as u64);
5716        let mut storage_retries = 0_usize;
5717        let mut deferred_workflow_completion = false;
5718
5719        loop {
5720            // Keep the serialized body and lease/poll identity across admission pauses.
5721            self.check_activity_lease_request(path, request_body.as_ref())?;
5722            let receive = async {
5723                let response = self
5724                    .http
5725                    .execute(request.try_clone().ok_or_else(|| {
5726                        Error::WorkerLoop("worker request body cannot be retried".to_string())
5727                    })?)
5728                    .await?;
5729                let status = response.status();
5730                observation.status(status);
5731                let body = read_capped_body(response, self.max_response_bytes).await?;
5732                Ok::<_, Error>((status, body))
5733            };
5734            let retry_deadline = self
5735                .worker_storage_admission
5736                .as_ref()
5737                .and_then(|admission| admission.workflow_completion_retry_deadline);
5738            if deferred_workflow_completion
5739                && retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
5740            {
5741                return Err(Error::Timeout);
5742            }
5743            let received = async {
5744                match retry_deadline.filter(|_| deferred_workflow_completion) {
5745                    Some(deadline) => tokio::time::timeout_at(deadline, receive)
5746                        .await
5747                        .map_err(|_| Error::Timeout)?,
5748                    None => receive.await,
5749                }
5750            };
5751            let (status, bytes) = match self
5752                .activity_lease_authority
5753                .as_ref()
5754                .filter(|authority| authority.governs(path))
5755            {
5756                Some(authority) => authority.protect(received).await?,
5757                None => received.await?,
5758            };
5759            // Restore elided capabilities before any reader, success or error.
5760            let bytes = match &capabilities {
5761                Some(captured) => {
5762                    match self
5763                        .capabilities_digest
5764                        .restore(status.as_u16(), &bytes, captured)
5765                    {
5766                        Ok(Some(restored)) => restored,
5767                        Ok(None) => bytes,
5768                        // An answer naming a digest this request did not send
5769                        // is recoverable. Only a task poll, which is
5770                        // idempotent by its poll request ID, is resent asking
5771                        // for full capabilities. Any other request may have
5772                        // committed (a completion's answer can carry the next
5773                        // leased task), so its answer is kept as received and
5774                        // the capabilities are read from cluster info.
5775                        Err(error) if !digest_resent && is_task_poll(path) => {
5776                            tracing::warn!(
5777                                target: "durable_workflow::worker",
5778                                path,
5779                                error = %error,
5780                                "unknown server capabilities digest; resending the poll without it"
5781                            );
5782                            self.capabilities_digest.forget();
5783                            request.headers_mut().insert(
5784                                server_capabilities_digest::HEADER,
5785                                reqwest::header::HeaderValue::from_static("none"),
5786                            );
5787                            capabilities = Some(None);
5788                            digest_resent = true;
5789                            continue;
5790                        }
5791                        Err(error) if !is_task_poll(path) && path != "/cluster/info" => {
5792                            tracing::warn!(
5793                                target: "durable_workflow::worker",
5794                                path,
5795                                error = %error,
5796                                "unknown server capabilities digest; reading capabilities from cluster info"
5797                            );
5798                            self.capabilities_digest.forget();
5799                            // One read-only attempt. It never fails this
5800                            // request: the answer is already received.
5801                            let info = Box::pin(
5802                                self.request_json_unresolved_with_timeout::<Value, Value>(
5803                                    reqwest::Method::GET,
5804                                    "/cluster/info",
5805                                    RequestProtocol::DefaultWorker,
5806                                    None,
5807                                    timeout,
5808                                ),
5809                            )
5810                            .await;
5811                            let full = info.as_ref().ok().and_then(|info| {
5812                                info["worker_protocol"]["server_capabilities"]
5813                                    .as_object()
5814                                    .filter(|full| !full.contains_key("digest"))
5815                                    .cloned()
5816                            });
5817                            if full.is_none() {
5818                                tracing::warn!(
5819                                    target: "durable_workflow::worker",
5820                                    path,
5821                                    "cluster info unavailable; using the answer without its capabilities, which later requests learn again"
5822                                );
5823                            }
5824                            // Without capabilities the unknown copies are
5825                            // dropped from the answer, which is still used.
5826                            let fallback = match &full {
5827                                Some(full) => {
5828                                    server_capabilities_digest::Fallback::Capabilities(full)
5829                                }
5830                                None => server_capabilities_digest::Fallback::Drop,
5831                            };
5832                            let restored = self.capabilities_digest.restore_with(
5833                                status.as_u16(),
5834                                &bytes,
5835                                captured,
5836                                Some(fallback),
5837                            )?;
5838                            // Later requests start again from `none`.
5839                            self.capabilities_digest.forget();
5840                            restored.unwrap_or(bytes)
5841                        }
5842                        Err(error) => return Err(error),
5843                    }
5844                }
5845                None => bytes,
5846            };
5847
5848            if !status.is_success() {
5849                let body = String::from_utf8_lossy(&bytes).to_string();
5850                if let Some(protocol) = protocol_failure(status, &body) {
5851                    return Err(Error::Protocol(protocol));
5852                }
5853                // A typed oversized completion is deterministic: never resend it.
5854                if let Some(refusal) =
5855                    workflow_task_completion_too_large(status, &body, request_bytes)
5856                {
5857                    return Err(Error::WorkflowTaskCompletionTooLarge(refusal));
5858                }
5859                // So is a completion over the history-transaction budget.
5860                if let Some(refusal) = workflow_task_history_limit_exceeded(status, &body, path) {
5861                    return Err(Error::WorkflowTaskHistoryLimitExceeded(refusal));
5862                }
5863                // A report sent inline under a cached payload policy the
5864                // Server has since lowered is refused as too large, and nothing
5865                // was recorded. Rediscover the policy, encode the same report
5866                // again (externalizing what the new limit requires) and resend
5867                // it once. A second refusal is a genuinely too-large report.
5868                if let Some(original) = unexternalized
5869                    .take()
5870                    .filter(|_| report_payload_too_large(status, &body))
5871                {
5872                    tracing::warn!(
5873                        target: "durable_workflow::worker",
5874                        path,
5875                        "report refused as too large; rediscovering the payload policy and resending it once"
5876                    );
5877                    self.forget_runtime_upload_policy(protocol);
5878                    let mut fresh = original;
5879                    self.externalize_runtime_payloads(&mut fresh, path, protocol)
5880                        .await?;
5881                    self.check_activity_lease_request(path, Some(&fresh))?;
5882                    *request.body_mut() = Some(serde_json::to_vec(&fresh)?.into());
5883                    continue;
5884                }
5885                let error = Error::Http { status, body };
5886                deferred_workflow_completion |= worker_deferred_workflow_completion_retry_after(
5887                    &error,
5888                    path,
5889                    request_body.as_ref(),
5890                )
5891                .is_some();
5892                if self
5893                    .wait_for_storage_admission(
5894                        &error,
5895                        protocol,
5896                        Some(path),
5897                        poll_request_id.as_deref(),
5898                        request_body.as_ref(),
5899                        &mut storage_retries,
5900                    )
5901                    .await
5902                {
5903                    continue;
5904                }
5905                return Err(error);
5906            }
5907
5908            if bytes.is_empty() {
5909                return Ok(serde_json::from_value(Value::Null)?);
5910            }
5911
5912            #[cfg(feature = "telemetry")]
5913            return self.decode_observability_response(
5914                &method,
5915                path,
5916                request_body.as_ref(),
5917                &bytes,
5918            );
5919
5920            #[cfg(not(feature = "telemetry"))]
5921            return Ok(serde_json::from_slice(&bytes)?);
5922        }
5923    }
5924
5925    #[cfg(feature = "telemetry")]
5926    fn begin_observability_discovery(&self, method: &reqwest::Method, path: &str) {
5927        if *method == reqwest::Method::GET && path == "/cluster/info" {
5928            self.observability_context_supported
5929                .store(false, Ordering::SeqCst);
5930        }
5931    }
5932
5933    #[cfg(feature = "telemetry")]
5934    fn decode_observability_response<T: DeserializeOwned>(
5935        &self,
5936        method: &reqwest::Method,
5937        path: &str,
5938        request_body: Option<&Value>,
5939        bytes: &[u8],
5940    ) -> Result<T> {
5941        if *method == reqwest::Method::POST
5942            && self.execution_telemetry.is_some()
5943            && matches!(
5944                path,
5945                "/worker/workflow-tasks/poll"
5946                    | "/worker/activity-tasks/poll"
5947                    | "/worker/query-tasks/poll"
5948            )
5949        {
5950            let mut wire: Value = serde_json::from_slice(bytes)?;
5951            telemetry::carrier::retain_poll_observations(
5952                &mut wire,
5953                request_body.unwrap_or(&Value::Null),
5954                path,
5955                &self.namespace,
5956            );
5957            return Ok(serde_json::from_value(wire)?);
5958        }
5959        if *method == reqwest::Method::GET && path == "/cluster/info" {
5960            let info: Value = serde_json::from_slice(bytes)?;
5961            self.observability_context_supported
5962                .store(telemetry::carrier::supported(&info), Ordering::SeqCst);
5963            return Ok(serde_json::from_value(info)?);
5964        }
5965        Ok(serde_json::from_slice(bytes)?)
5966    }
5967
5968    async fn wait_for_storage_admission(
5969        &self,
5970        error: &Error,
5971        protocol: RequestProtocol,
5972        path: Option<&str>,
5973        poll_request_id: Option<&str>,
5974        request_body: Option<&Value>,
5975        retries: &mut usize,
5976    ) -> bool {
5977        let Some(admission) = self
5978            .worker_storage_admission
5979            .as_ref()
5980            .filter(|_| matches!(protocol, RequestProtocol::Worker(_)))
5981        else {
5982            return false;
5983        };
5984        let completion_deferred = path.and_then(|path| {
5985            worker_deferred_workflow_completion_retry_after(error, path, request_body)
5986        });
5987        let Some(advertised_delay) = completion_deferred
5988            .or_else(|| worker_storage_admission_retry_after(error, poll_request_id))
5989            .or_else(|| {
5990                path.and_then(|path| {
5991                    worker_backend_unavailable_retry_after(error, path, poll_request_id)
5992                        .or_else(|| worker_fenced_completion_retry_after(error, path, request_body))
5993                })
5994            })
5995        else {
5996            return false;
5997        };
5998        *retries = retries.saturating_add(1);
5999        let delay = worker_retry_delay(admission.policy, *retries)
6000            .max(advertised_delay)
6001            .min(admission.policy.max_backoff.max(Duration::from_millis(1)));
6002        let delay = if completion_deferred.is_some() {
6003            delay.max(advertised_delay)
6004        } else {
6005            delay
6006        };
6007        let wait_deadline = tokio::time::Instant::now() + delay;
6008        loop {
6009            if admission.stop.load(Ordering::SeqCst) {
6010                return false;
6011            }
6012            let now = tokio::time::Instant::now();
6013            if admission
6014                .workflow_completion_retry_deadline
6015                .is_some_and(|deadline| now >= deadline)
6016            {
6017                return false;
6018            }
6019            let remaining = wait_deadline.saturating_duration_since(now);
6020            if remaining.is_zero() {
6021                return true;
6022            }
6023            tokio::time::sleep(remaining.min(Duration::from_millis(100))).await;
6024        }
6025    }
6026
6027    async fn poll_request_json<T: DeserializeOwned, B: Serialize + ?Sized>(
6028        &self,
6029        path: &str,
6030        protocol: RequestProtocol,
6031        body: &B,
6032        timeout: Duration,
6033        max_retries: usize,
6034    ) -> Result<T> {
6035        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, true)
6036            .await
6037    }
6038
6039    async fn poll_request_json_unresolved<T: DeserializeOwned, B: Serialize + ?Sized>(
6040        &self,
6041        path: &str,
6042        protocol: RequestProtocol,
6043        body: &B,
6044        timeout: Duration,
6045        max_retries: usize,
6046    ) -> Result<T> {
6047        self.poll_request_json_inner(path, protocol, body, timeout, max_retries, false)
6048            .await
6049    }
6050
6051    async fn poll_request_json_inner<T: DeserializeOwned, B: Serialize + ?Sized>(
6052        &self,
6053        path: &str,
6054        protocol: RequestProtocol,
6055        body: &B,
6056        timeout: Duration,
6057        max_retries: usize,
6058        resolve: bool,
6059    ) -> Result<T> {
6060        self.metrics_poll_request(path, protocol, body, timeout, max_retries, resolve)
6061            .await
6062    }
6063
6064    fn auth_token(&self, protocol: RequestProtocol) -> Result<Option<&str>> {
6065        match protocol {
6066            RequestProtocol::DefaultWorker | RequestProtocol::Worker(_) => {
6067                if let Some(token) = self.worker_token.as_deref().or(self.token.as_deref()) {
6068                    return Ok(Some(token));
6069                }
6070                if self.control_token.is_some() {
6071                    return Err(Error::MissingRoleCredentials {
6072                        role: "worker",
6073                        opposite_role: "control",
6074                    });
6075                }
6076                Ok(None)
6077            }
6078            RequestProtocol::ControlPlane => {
6079                if let Some(token) = self.control_token.as_deref().or(self.token.as_deref()) {
6080                    return Ok(Some(token));
6081                }
6082                if self.worker_token.is_some() {
6083                    return Err(Error::MissingRoleCredentials {
6084                        role: "control",
6085                        opposite_role: "worker",
6086                    });
6087                }
6088                Ok(None)
6089            }
6090        }
6091    }
6092}
6093
6094fn query_failure(status: reqwest::StatusCode, raw_body: String) -> QueryFailure {
6095    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
6096    let reason = body
6097        .get("reason")
6098        .and_then(Value::as_str)
6099        .unwrap_or("query_rejected")
6100        .to_string();
6101    let message = body
6102        .get("message")
6103        .or_else(|| body.get("error"))
6104        .and_then(Value::as_str)
6105        .unwrap_or("workflow query was rejected")
6106        .to_string();
6107
6108    QueryFailure {
6109        status: status.as_u16(),
6110        reason,
6111        message,
6112        body,
6113    }
6114}
6115
6116fn workflow_command_result(
6117    command: WorkflowCommandKind,
6118    data: Value,
6119    workflow_id: &str,
6120    run_id: Option<&str>,
6121) -> WorkflowCommandResult {
6122    WorkflowCommandResult {
6123        command,
6124        workflow_id: data
6125            .get("workflow_id")
6126            .and_then(Value::as_str)
6127            .unwrap_or(workflow_id)
6128            .to_string(),
6129        run_id: data
6130            .get("run_id")
6131            .and_then(Value::as_str)
6132            .or(run_id)
6133            .map(str::to_string),
6134        outcome: data
6135            .get("outcome")
6136            .and_then(Value::as_str)
6137            .map(str::to_string),
6138        reason: data
6139            .get("reason")
6140            .and_then(Value::as_str)
6141            .map(str::to_string),
6142        command_status: data
6143            .get("command_status")
6144            .and_then(Value::as_str)
6145            .map(str::to_string),
6146        raw: data,
6147    }
6148}
6149
6150fn workflow_command_rejection(
6151    command: WorkflowCommandKind,
6152    status: reqwest::StatusCode,
6153    raw_body: String,
6154    workflow_id: &str,
6155    run_id: Option<&str>,
6156) -> WorkflowCommandRejection {
6157    let body = serde_json::from_str(&raw_body).unwrap_or_else(|_| json!({"message": raw_body}));
6158    WorkflowCommandRejection {
6159        command,
6160        status: status.as_u16(),
6161        reason: body
6162            .get("reason")
6163            .and_then(Value::as_str)
6164            .unwrap_or("workflow_command_rejected")
6165            .to_string(),
6166        message: body
6167            .get("message")
6168            .or_else(|| body.get("error"))
6169            .and_then(Value::as_str)
6170            .unwrap_or("workflow lifecycle command was rejected")
6171            .to_string(),
6172        workflow_id: body
6173            .get("workflow_id")
6174            .and_then(Value::as_str)
6175            .unwrap_or(workflow_id)
6176            .to_string(),
6177        run_id: body
6178            .get("run_id")
6179            .and_then(Value::as_str)
6180            .or(run_id)
6181            .map(str::to_string),
6182        target_scope: body
6183            .get("target_scope")
6184            .and_then(Value::as_str)
6185            .map(str::to_string),
6186        body,
6187    }
6188}
6189
6190fn query_task_response(response: Result<Value>) -> Result<Value> {
6191    match response {
6192        Err(Error::Http { status, body }) => Err(Error::QueryFailed(query_failure(status, body))),
6193        response => response,
6194    }
6195}
6196
6197fn worker_poll_response<T: DeserializeOwned>(response: Result<T>) -> Result<T> {
6198    match response {
6199        Err(Error::Http { status, body })
6200            if status == reqwest::StatusCode::CONFLICT && worker_poll_body_is_stop(&body) =>
6201        {
6202            Ok(serde_json::from_str(&body)?)
6203        }
6204        response => response,
6205    }
6206}
6207
6208fn worker_poll_body_is_stop(body: &str) -> bool {
6209    serde_json::from_str::<Value>(body)
6210        .ok()
6211        .is_some_and(|body| {
6212            worker_poll_is_stop(
6213                body.get("poll_status").and_then(Value::as_str),
6214                body.get("reason").and_then(Value::as_str),
6215            )
6216        })
6217}
6218
6219fn worker_poll_is_stop(poll_status: Option<&str>, reason: Option<&str>) -> bool {
6220    matches!(poll_status, Some("draining" | "stopped"))
6221        || matches!(reason, Some("worker_draining" | "worker_stopped"))
6222}
6223
6224fn query_task_rejection_is_final(error: &Error) -> bool {
6225    matches!(
6226        error,
6227        Error::QueryFailed(failure)
6228            if QUERY_TASK_FINAL_REJECTION_REASONS.contains(&failure.reason.as_str())
6229    )
6230}
6231
6232fn activity_task_response<T>(
6233    response: Result<T>,
6234    operation: &str,
6235    task_id: &str,
6236    activity_attempt_id: &str,
6237) -> Result<T> {
6238    match response {
6239        Err(Error::Http { status, body }) => {
6240            let body = serde_json::from_str(&body).unwrap_or_else(|_| json!({"message": body}));
6241            Err(Error::ActivityTaskRejected(ActivityTaskRejection {
6242                operation: operation.to_string(),
6243                status: status.as_u16(),
6244                reason: body
6245                    .get("reason")
6246                    .and_then(Value::as_str)
6247                    .unwrap_or("activity_task_rejected")
6248                    .to_string(),
6249                task_id: body
6250                    .get("task_id")
6251                    .and_then(Value::as_str)
6252                    .unwrap_or(task_id)
6253                    .to_string(),
6254                activity_attempt_id: body
6255                    .get("activity_attempt_id")
6256                    .and_then(Value::as_str)
6257                    .unwrap_or(activity_attempt_id)
6258                    .to_string(),
6259                cancel_requested: body
6260                    .get("cancel_requested")
6261                    .and_then(Value::as_bool)
6262                    .unwrap_or(false),
6263                can_continue: body.get("can_continue").and_then(Value::as_bool),
6264                run_closed_reason: body
6265                    .get("run_closed_reason")
6266                    .and_then(Value::as_str)
6267                    .map(str::to_string),
6268                body,
6269            }))
6270        }
6271        response => response,
6272    }
6273}
6274
6275fn activity_task_rejection_is_final(error: &Error) -> bool {
6276    matches!(
6277        error,
6278        Error::ActivityTaskRejected(rejection)
6279            if matches!(
6280                rejection.reason.as_str(),
6281                "run_cancelled"
6282                    | "run_terminated"
6283                    | "attempt_closed"
6284                    | "stale_attempt"
6285                    | "activity_cancelled"
6286                    | "task_cancelled"
6287                    | "run_closed"
6288                    | "activity_not_running"
6289                    | "attempt_not_found"
6290            )
6291    )
6292}
6293
6294/// Which activity outcome a settlement reports.
6295#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6296pub(crate) enum ActivityReport {
6297    Completed,
6298    Failed,
6299}
6300
6301/// How an activity settlement ended.
6302#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6303pub(crate) enum ActivitySettlement {
6304    /// The Server recorded this report, possibly on an earlier copy.
6305    Recorded,
6306    /// The attempt was already closed by something else; nothing recorded.
6307    Closed,
6308    /// Transient failures outlasted the lease; the Server settles it.
6309    LeaseEnded,
6310}
6311
6312/// The Server's answer to a resent settlement whose first copy it already
6313/// recorded. Native Server 3.17 answers a duplicate completion with
6314/// `409 {"reason":"stale_attempt","recorded":false}` naming this task,
6315/// attempt and owner with `activity_status`, `attempt_status` and
6316/// `task_status` all `completed` (a failure: `attempt_status` `failed`). A
6317/// `stale_attempt` in any other state is someone else's outcome.
6318pub(crate) fn activity_report_already_recorded(
6319    error: &Error,
6320    report: ActivityReport,
6321    task_id: &str,
6322    attempt_id: &str,
6323    owner: &str,
6324) -> bool {
6325    let Error::ActivityTaskRejected(rejection) = error else {
6326        return false;
6327    };
6328    let body = &rejection.body;
6329    let field = |name: &str| body.get(name).and_then(Value::as_str);
6330    let own = rejection.status == 409
6331        && rejection.reason == "stale_attempt"
6332        && body.get("recorded").and_then(Value::as_bool) == Some(false)
6333        && field("task_id") == Some(task_id)
6334        && field("activity_attempt_id") == Some(attempt_id)
6335        && field("lease_owner") == Some(owner);
6336    own && match report {
6337        ActivityReport::Completed => ["activity_status", "attempt_status", "task_status"]
6338            .iter()
6339            .all(|name| field(name) == Some("completed")),
6340        ActivityReport::Failed => field("attempt_status") == Some("failed"),
6341    }
6342}
6343
6344/// A workflow-task report the server answered with a non-recorded receipt
6345/// for exactly this task, attempt and run, which settles the managed tick:
6346/// the run's terminal timeout (`run_timed_out` with `run_status=failed`), a
6347/// task this worker no longer holds (`task_not_leased`, for example after the
6348/// run was cancelled or the task was reclaimed), or a run already closed by
6349/// another path (`run_closed` with the terminal state it implies). Nothing was
6350/// recorded, and the server owns any redelivery.
6351fn workflow_task_report_is_settled(
6352    error: &Error,
6353    task_id: &str,
6354    workflow_task_attempt: u64,
6355    run_id: Option<&str>,
6356) -> bool {
6357    let Error::Http { status, body } = error else {
6358        return false;
6359    };
6360    if *status != reqwest::StatusCode::CONFLICT {
6361        return false;
6362    }
6363
6364    let Some(run_id) = run_id else {
6365        return false;
6366    };
6367    let Ok(body) = serde_json::from_str::<Value>(body) else {
6368        return false;
6369    };
6370
6371    let settled = match body.get("reason").and_then(Value::as_str) {
6372        Some("run_timed_out") => body.get("run_status").and_then(Value::as_str) == Some("failed"),
6373        Some("task_not_leased") => true,
6374        Some("run_closed") => run_closed_receipt_is_terminal(&body),
6375        _ => false,
6376    };
6377    settled
6378        && body.get("recorded").and_then(Value::as_bool) == Some(false)
6379        && body.get("run_id").and_then(Value::as_str) == Some(run_id)
6380        && body.get("task_id").and_then(Value::as_str) == Some(task_id)
6381        && body.get("workflow_task_attempt").and_then(Value::as_u64) == Some(workflow_task_attempt)
6382}
6383
6384/// A `run_closed` refusal settles only with the closed run's own state: a
6385/// terminal `run_status`, the `stop_reason` that status implies, and
6386/// `can_continue=false`. Absent or inconsistent state is never inferred.
6387fn run_closed_receipt_is_terminal(body: &Value) -> bool {
6388    let stop_reason = match body.get("run_status").and_then(Value::as_str) {
6389        Some("completed") => "run_completed",
6390        Some("failed") => "run_failed",
6391        Some("cancelled") => "run_cancelled",
6392        Some("terminated") => "run_terminated",
6393        _ => return false,
6394    };
6395    body.get("stop_reason").and_then(Value::as_str) == Some(stop_reason)
6396        && body.get("can_continue").and_then(Value::as_bool) == Some(false)
6397}
6398
6399fn workflow_task_completion_too_large(
6400    status: reqwest::StatusCode,
6401    raw_body: &str,
6402    size: u64,
6403) -> Option<WorkflowTaskCompletionTooLarge> {
6404    if status != reqwest::StatusCode::PAYLOAD_TOO_LARGE {
6405        return None;
6406    }
6407    let body: Value = serde_json::from_str(raw_body).ok()?;
6408    if body.get("reason").and_then(Value::as_str) != Some("payload_too_large")
6409        || body.get("limit_kind").and_then(Value::as_str)
6410            != Some(WORKFLOW_TASK_COMPLETION_BYTES_LIMIT_KIND)
6411    {
6412        return None;
6413    }
6414    Some(WorkflowTaskCompletionTooLarge {
6415        status: status.as_u16(),
6416        limit_kind: WORKFLOW_TASK_COMPLETION_BYTES_LIMIT_KIND.to_string(),
6417        limit: body.get("limit").and_then(Value::as_u64),
6418        size,
6419        message: body
6420            .get("message")
6421            .and_then(Value::as_str)
6422            .unwrap_or_default()
6423            .to_string(),
6424        body,
6425    })
6426}
6427
6428fn workflow_task_history_limit_exceeded(
6429    status: reqwest::StatusCode,
6430    raw_body: &str,
6431    path: &str,
6432) -> Option<WorkflowTaskHistoryLimitExceeded> {
6433    if status != reqwest::StatusCode::CONFLICT {
6434        return None;
6435    }
6436    let task_id = path
6437        .strip_prefix("/worker/workflow-tasks/")?
6438        .strip_suffix("/complete")?;
6439    if task_id.is_empty() || task_id.contains('/') {
6440        return None;
6441    }
6442    let body: Value = serde_json::from_str(raw_body).ok()?;
6443    let reason = body.get("reason").and_then(Value::as_str)?;
6444    if !WORKFLOW_TASK_HISTORY_LIMIT_REASONS.contains(&reason)
6445        || body.get("recorded").and_then(Value::as_bool) == Some(true)
6446    {
6447        return None;
6448    }
6449    let limit_kind = body
6450        .get("limit_kind")
6451        .and_then(Value::as_str)
6452        .filter(|kind| {
6453            !kind.is_empty()
6454                && kind.len() <= 64
6455                && kind
6456                    .bytes()
6457                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
6458        })
6459        .unwrap_or(reason)
6460        .to_string();
6461    Some(WorkflowTaskHistoryLimitExceeded {
6462        status: status.as_u16(),
6463        reason: reason.to_string(),
6464        limit_kind,
6465        current_value: body.get("current_value").and_then(Value::as_u64),
6466        configured_limit: body
6467            .get("configured_limit")
6468            .and_then(Value::as_u64)
6469            .filter(|limit| *limit > 0),
6470        message: body
6471            .get("message")
6472            .and_then(Value::as_str)
6473            .unwrap_or_default()
6474            .to_string(),
6475        body,
6476    })
6477}
6478
6479fn protocol_failure(status: reqwest::StatusCode, raw_body: &str) -> Option<ProtocolFailure> {
6480    let body: Value = serde_json::from_str(raw_body).ok()?;
6481    let reason = body.get("reason")?.as_str()?;
6482    if !matches!(
6483        reason,
6484        "missing_protocol_version"
6485            | "unsupported_protocol_version"
6486            | "missing_control_plane_version"
6487            | "unsupported_control_plane_version"
6488    ) {
6489        return None;
6490    }
6491
6492    Some(ProtocolFailure {
6493        status: status.as_u16(),
6494        reason: reason.to_string(),
6495        message: body
6496            .get("message")
6497            .or_else(|| body.get("error"))
6498            .and_then(Value::as_str)
6499            .unwrap_or("protocol version rejected")
6500            .to_string(),
6501        supported_version: body
6502            .get("supported_version")
6503            .and_then(Value::as_str)
6504            .map(str::to_string),
6505        requested_version: body
6506            .get("requested_version")
6507            .and_then(Value::as_str)
6508            .map(str::to_string),
6509        body,
6510    })
6511}
6512
6513fn long_poll_timeout_seconds(timeout: Duration) -> u64 {
6514    timeout
6515        .as_secs()
6516        .saturating_add(u64::from(timeout.subsec_nanos() > 0))
6517        .min(MAX_LONG_POLL_TIMEOUT_SECONDS)
6518}
6519
6520fn worker_operation_is_retryable(error: &Error) -> bool {
6521    if worker_poll_capacity_retry_after(error).is_some()
6522        || worker_storage_admission_body(error).is_some()
6523        || worker_backend_unavailable_body(error).is_some()
6524        || worker_operation_is_explicitly_non_retryable(error)
6525    {
6526        return false;
6527    }
6528
6529    match error {
6530        Error::Transport(error) => {
6531            error.is_timeout() || error.is_connect() || error.is_request() || error.is_body()
6532        }
6533        Error::Http { status, .. } => {
6534            matches!(
6535                *status,
6536                reqwest::StatusCode::REQUEST_TIMEOUT | reqwest::StatusCode::TOO_MANY_REQUESTS
6537            ) || status.is_server_error()
6538        }
6539        _ => false,
6540    }
6541}
6542
6543/// A failure a running worker outlives (sdk-php#448): a connection refused,
6544/// reset or timed out; an upstream 502/503/504 without a protocol body; a 503
6545/// whose reason is `storage_unavailable` or `backend_unavailable`; or any 5xx
6546/// or 429 that says `retryable: true`. An explicit `retryable: false`, 401,
6547/// 403 and every other protocol refusal stay fatal.
6548pub(crate) fn worker_error_is_transient(error: &Error) -> bool {
6549    let (status, body) = match error {
6550        Error::Timeout => return true,
6551        Error::Transport(error) => {
6552            return error.is_timeout()
6553                || error.is_connect()
6554                || error.is_request()
6555                || error.is_body()
6556        }
6557        Error::Http { status, body } => (status.as_u16(), serde_json::from_str::<Value>(body).ok()),
6558        Error::ActivityTaskRejected(rejection) => (rejection.status, Some(rejection.body.clone())),
6559        _ => return false,
6560    };
6561    let body = body.filter(Value::is_object);
6562    let field = |name: &str| body.as_ref().and_then(|body| body.get(name));
6563    match field("retryable").and_then(Value::as_bool) {
6564        Some(false) => return false,
6565        Some(true) if status >= 500 || status == 429 => return true,
6566        _ => {}
6567    }
6568    matches!(
6569        (status, field("reason").and_then(Value::as_str)),
6570        (503, Some("storage_unavailable" | "backend_unavailable")) | (502..=504, None)
6571    )
6572}
6573
6574/// The shared outage backoff: uniform in `[0, min(4 s, 0.25 s * 2^(n-1))]`
6575/// for the n-th consecutive transient failure (n from 1).
6576pub(crate) fn worker_outage_delay(failures: u32) -> Duration {
6577    let ceiling = Duration::from_millis(250 << failures.saturating_sub(1).min(4));
6578    let (bits, _) = Uuid::new_v4().as_u64_pair();
6579    ceiling.mul_f64((bits >> 11) as f64 / (1_u64 << 53) as f64)
6580}
6581
6582/// Escalates a continuing outage to an ERROR log: once it has lasted 60 s,
6583/// then every 5 minutes while it continues. Callers reset it on success.
6584#[derive(Debug, Default)]
6585pub(crate) struct OutageLog {
6586    started: Option<std::time::Instant>,
6587    reported: Option<std::time::Instant>,
6588}
6589
6590impl OutageLog {
6591    const FIRST_ERROR: Duration = Duration::from_secs(60);
6592    const REPEAT_ERROR: Duration = Duration::from_secs(300);
6593
6594    /// Record a failure at `now`; returns how long the outage has lasted
6595    /// when an ERROR line is due.
6596    pub(crate) fn failed(&mut self, now: std::time::Instant) -> Option<Duration> {
6597        let started = *self.started.get_or_insert(now);
6598        let lasted = now.saturating_duration_since(started);
6599        let due = match self.reported {
6600            None => lasted >= Self::FIRST_ERROR,
6601            Some(last) => now.saturating_duration_since(last) >= Self::REPEAT_ERROR,
6602        };
6603        due.then(|| {
6604            self.reported = Some(now);
6605            lasted
6606        })
6607    }
6608
6609    pub(crate) fn report(&mut self, worker_id: &str, task_queue: &str, error: &Error) {
6610        if let Some(lasted) = self.failed(std::time::Instant::now()) {
6611            tracing::error!(
6612                target: "durable_workflow::worker",
6613                worker_id,
6614                task_queue,
6615                error = %error,
6616                outage_seconds = lasted.as_secs(),
6617                "Server outage continues; the worker is still retrying"
6618            );
6619        }
6620    }
6621}
6622
6623/// Consecutive transient failures in one loop and their escalation state.
6624#[derive(Debug, Default)]
6625pub(crate) struct Outage {
6626    pub(crate) failures: u32,
6627    log: OutageLog,
6628}
6629
6630impl Outage {
6631    pub(crate) fn reset(&mut self) {
6632        *self = Self::default();
6633    }
6634}
6635
6636/// The delivered activity lease's end on the local clock, measured from when
6637/// the poll was sent (`lease_expires_at - server_time`).
6638fn poll_lease_deadline(
6639    wire: &Value,
6640    requested: tokio::time::Instant,
6641) -> Option<tokio::time::Instant> {
6642    let parse = |value: &Value| DateTime::parse_from_rfc3339(value.as_str()?).ok();
6643    let expires = parse(&wire["task"]["lease_expires_at"])?;
6644    let server = parse(&wire["server_time"])?;
6645    requested.checked_add((expires - server).to_std().ok()?)
6646}
6647
6648fn worker_storage_admission_body(error: &Error) -> Option<Value> {
6649    let body: Value = match error {
6650        Error::Http { body, .. } => serde_json::from_str(body).ok()?,
6651        Error::ActivityTaskRejected(rejection) => rejection.body.clone(),
6652        _ => return None,
6653    };
6654    matches!(
6655        body.get("reason").and_then(Value::as_str),
6656        Some("storage_pressure" | "storage_admission_unavailable")
6657    )
6658    .then_some(body)
6659}
6660
6661fn worker_storage_admission_retry_after(
6662    error: &Error,
6663    poll_request_id: Option<&str>,
6664) -> Option<Duration> {
6665    let Error::Http { status, .. } = error else {
6666        return None;
6667    };
6668    let body = worker_storage_admission_body(error)?;
6669    let delay = body.get("retry_after_seconds")?.as_u64()?;
6670    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE
6671        || delay == 0
6672        || body.get("retryable") != Some(&Value::Bool(true))
6673        || !matches!(body.get("storage_state")?.as_str()?, "draining" | "fenced")
6674        || (body["reason"] == "storage_admission_unavailable" && body["storage_state"] != "fenced")
6675        || body
6676            .get("request_admitted")
6677            .is_some_and(|admitted| admitted != &Value::Bool(false))
6678    {
6679        return None;
6680    }
6681    match poll_request_id {
6682        Some(id) => {
6683            if id.is_empty()
6684                || body.get("task") != Some(&Value::Null)
6685                || body.get("poll_request_id").and_then(Value::as_str) != Some(id)
6686                || body.get("poll_status") != body.get("reason")
6687                || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
6688                || body.get("claim_admitted") != Some(&Value::Bool(false))
6689            {
6690                return None;
6691            }
6692        }
6693        None if body.get("request_admitted") != Some(&Value::Bool(false)) => return None,
6694        None => {}
6695    }
6696    Some(Duration::from_secs(delay))
6697}
6698
6699fn worker_backend_unavailable_retry_after(
6700    error: &Error,
6701    path: &str,
6702    poll_request_id: Option<&str>,
6703) -> Option<Duration> {
6704    let operation = match path {
6705        "/worker/register" => "register_worker",
6706        "/worker/heartbeat" => "heartbeat_worker",
6707        "/worker/workflow-tasks/poll" => "poll_workflow_task",
6708        "/worker/activity-tasks/poll" => "poll_activity_task",
6709        "/worker/query-tasks/poll" => "poll_query_task",
6710        "/worker/update-validation-tasks/poll" => "poll_update_validation_task",
6711        _ => return None,
6712    };
6713    let body = worker_backend_unavailable_body(error)?;
6714    let delay = body.get("retry_after_seconds")?.as_u64()?;
6715    if delay == 0
6716        || body.get("operation")?.as_str()? != operation
6717        || body.get("outcome")?.as_str()? != "unknown"
6718        || body.get("retryable") != Some(&Value::Bool(true))
6719        || body.get("worker_id")?.as_str()?.is_empty()
6720    {
6721        return None;
6722    }
6723    if let Some(id) = poll_request_id {
6724        if id.is_empty()
6725            || body.get("task") != Some(&Value::Null)
6726            || body.get("poll_status")?.as_str()? != "backend_unavailable"
6727            || body.get("poll_request_id")?.as_str()? != id
6728            || body.get("retry_same_poll_request_id") != Some(&Value::Bool(true))
6729        {
6730            return None;
6731        }
6732    } else if path.ends_with("/poll") {
6733        return None;
6734    }
6735    Some(Duration::from_secs(delay))
6736}
6737
6738fn worker_fenced_completion_retry_after(
6739    error: &Error,
6740    path: &str,
6741    request_body: Option<&Value>,
6742) -> Option<Duration> {
6743    let (operation, task_id, attempt_field) = if let Some(task_id) = path
6744        .strip_prefix("/worker/workflow-tasks/")
6745        .and_then(|tail| tail.strip_suffix("/complete"))
6746    {
6747        ("complete_workflow_task", task_id, "workflow_task_attempt")
6748    } else {
6749        let task_id = path
6750            .strip_prefix("/worker/activity-tasks/")
6751            .and_then(|tail| tail.strip_suffix("/complete"))?;
6752        ("complete_activity_task", task_id, "activity_attempt_id")
6753    };
6754    if task_id.is_empty() || task_id.contains('/') {
6755        return None;
6756    }
6757
6758    let request = request_body?.as_object()?;
6759    let lease_owner = request.get("lease_owner")?.as_str()?;
6760    if lease_owner.is_empty() {
6761        return None;
6762    }
6763    let attempt = request.get(attempt_field)?;
6764    if (attempt_field == "workflow_task_attempt" && attempt.as_u64().filter(|id| *id > 0).is_none())
6765        || (attempt_field == "activity_attempt_id"
6766            && attempt.as_str().filter(|id| !id.is_empty()).is_none())
6767    {
6768        return None;
6769    }
6770
6771    let body = worker_backend_unavailable_body(error)?;
6772    let delay = body.get("retry_after_seconds")?.as_u64()?;
6773    if delay == 0
6774        || body.get("operation")?.as_str()? != operation
6775        || body.get("outcome")?.as_str()? != "unknown"
6776        || body.get("retryable") != Some(&Value::Bool(true))
6777        || body.get("worker_id")?.as_str()? != lease_owner
6778        || body.get("task_queue") != Some(&Value::Null)
6779        || body.get("task_id")?.as_str()? != task_id
6780        || body.get("lease_owner")?.as_str()? != lease_owner
6781        || body.get(attempt_field) != Some(attempt)
6782    {
6783        return None;
6784    }
6785
6786    Some(Duration::from_secs(delay))
6787}
6788
6789fn worker_deferred_workflow_completion_retry_after(
6790    error: &Error,
6791    path: &str,
6792    request_body: Option<&Value>,
6793) -> Option<Duration> {
6794    let task_id = path
6795        .strip_prefix("/worker/workflow-tasks/")?
6796        .strip_suffix("/complete")?;
6797    if task_id.is_empty() || task_id.contains('/') {
6798        return None;
6799    }
6800    let request = request_body?.as_object()?;
6801    let owner = request.get("lease_owner")?.as_str()?;
6802    let attempt = request.get("workflow_task_attempt")?;
6803    if owner.trim().is_empty() || attempt.as_u64().filter(|attempt| *attempt > 0).is_none() {
6804        return None;
6805    }
6806    let Error::Http { status, body } = error else {
6807        return None;
6808    };
6809    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
6810        return None;
6811    }
6812    let body: Value = serde_json::from_str(body).ok()?;
6813    let delay = body.get("retry_after_seconds")?.as_u64()?;
6814    if !(1..=5).contains(&delay)
6815        || body.get("reason")?.as_str()? != "backend_lock_pressure"
6816        || body.get("operation")?.as_str()? != "complete_workflow_task"
6817        || body.get("outcome")?.as_str()? != "deferred"
6818        || body.get("recorded") != Some(&Value::Bool(false))
6819        || body.get("retryable") != Some(&Value::Bool(true))
6820        || body.get("task_id")?.as_str()? != task_id
6821        || body.get("lease_owner")?.as_str()? != owner
6822        || body.get("workflow_task_attempt") != Some(attempt)
6823        || body.get("backend")?.get("lock_pressure") != Some(&Value::Bool(true))
6824    {
6825        return None;
6826    }
6827    Some(Duration::from_secs(delay))
6828}
6829
6830fn worker_backend_unavailable_body(error: &Error) -> Option<Value> {
6831    let Error::Http { status, body } = error else {
6832        return None;
6833    };
6834    if *status != reqwest::StatusCode::SERVICE_UNAVAILABLE {
6835        return None;
6836    }
6837    let body: Value = serde_json::from_str(body).ok()?;
6838    (body.get("reason")?.as_str()? == "backend_unavailable").then_some(body)
6839}
6840
6841fn worker_operation_is_explicitly_non_retryable(error: &Error) -> bool {
6842    let Error::Http { body, .. } = error else {
6843        return false;
6844    };
6845
6846    serde_json::from_str::<Value>(body)
6847        .ok()
6848        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
6849        == Some(false)
6850}
6851
6852fn worker_poll_capacity_retry_after(error: &Error) -> Option<Duration> {
6853    let Error::Http { status, body } = error else {
6854        return None;
6855    };
6856    if *status != reqwest::StatusCode::TOO_MANY_REQUESTS {
6857        return None;
6858    }
6859
6860    let body = serde_json::from_str::<Value>(body).ok()?;
6861    let capacity_exhausted = body.get("poll_status").and_then(Value::as_str)
6862        == Some("long_poll_capacity_exhausted")
6863        || body.get("reason").and_then(Value::as_str) == Some("long_poll_capacity_exhausted");
6864    if !capacity_exhausted || body.get("retryable").and_then(Value::as_bool) != Some(true) {
6865        return None;
6866    }
6867
6868    Some(Duration::from_secs(
6869        body.get("retry_after_seconds")
6870            .and_then(Value::as_u64)
6871            .unwrap_or_default(),
6872    ))
6873}
6874
6875/// Delay before poll or heartbeat retry `retry` (from 1): the policy's capped
6876/// exponential delay within its budget, then the shared full-jitter outage
6877/// schedule, restarting at its first step, so recovering workers spread out.
6878fn worker_poll_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
6879    if retry <= policy.max_retries {
6880        worker_retry_delay(policy, retry)
6881    } else {
6882        let beyond = retry - policy.max_retries;
6883        worker_outage_delay(u32::try_from(beyond).unwrap_or(u32::MAX))
6884    }
6885    .max(Duration::from_millis(1))
6886}
6887
6888fn worker_retry_delay(policy: WorkerRetryPolicy, retry: usize) -> Duration {
6889    let exponent = retry.saturating_sub(1).min(31) as u32;
6890    policy
6891        .initial_backoff
6892        .saturating_mul(1_u32 << exponent)
6893        .min(policy.max_backoff)
6894}
6895
6896/// A failed read-only cluster-info discovery a running worker waits out: a
6897/// connection or timeout failure, any 5xx or a 429, unless the Server says
6898/// `retryable: false`.
6899pub(crate) fn cluster_info_failure_is_transient(error: &Error) -> bool {
6900    let (status, body) = match error {
6901        Error::Timeout | Error::Transport(_) => return true,
6902        Error::Http { status, body } => (status.as_u16(), body.as_str()),
6903        Error::Protocol(failure) => (failure.status, ""),
6904        _ => return false,
6905    };
6906    let refused = serde_json::from_str::<Value>(body)
6907        .ok()
6908        .and_then(|body| body.get("retryable").and_then(Value::as_bool))
6909        == Some(false);
6910    (status >= 500 || status == 429) && !refused
6911}
6912
6913/// An activity report (completion or failure) whose payloads may be encoded
6914/// again after a too-large refusal. Workflow-task completions keep their own
6915/// typed size refusals unchanged.
6916fn is_task_report(path: &str) -> bool {
6917    path.starts_with("/worker/activity-tasks/")
6918        && (path.ends_with("/complete") || path.ends_with("/fail"))
6919}
6920
6921/// The Server refused the report's size before reading its body.
6922fn report_payload_too_large(status: reqwest::StatusCode, body: &str) -> bool {
6923    status == reqwest::StatusCode::PAYLOAD_TOO_LARGE
6924        && serde_json::from_str::<Value>(body)
6925            .ok()
6926            .and_then(|body| body.get("reason")?.as_str().map(str::to_owned))
6927            .is_some_and(|reason| reason == "payload_too_large")
6928}
6929
6930/// `failure.type` and `failure.class` of an attempt whose result could not be
6931/// delivered because it is too large.
6932pub(crate) const ACTIVITY_RESULT_TOO_LARGE: &str = "ActivityResultTooLarge";
6933
6934/// An activity completion that failed only because its result is too large:
6935/// the Server refused it as too large (after the one re-encode), or it could
6936/// not be externalized (too large to upload, or no payload storage).
6937fn activity_result_too_large(error: &Error) -> bool {
6938    match error {
6939        Error::ActivityTaskRejected(rejection) => {
6940            rejection.status == 413 && rejection.reason == "payload_too_large"
6941        }
6942        Error::Codec(message) => [
6943            "external_payload_oversized:",
6944            "external_payload_unavailable:",
6945            "payload_too_large:",
6946        ]
6947        .iter()
6948        .any(|prefix| message.starts_with(prefix)),
6949        _ => false,
6950    }
6951}
6952
6953/// A worker task poll: idempotent by its poll request ID, so the only
6954/// request that may be resent to recover elided capabilities.
6955fn is_task_poll(path: &str) -> bool {
6956    matches!(
6957        path,
6958        "/worker/workflow-tasks/poll" | "/worker/activity-tasks/poll" | "/worker/query-tasks/poll"
6959    )
6960}
6961
6962/// Default cap on one decoded response body.
6963const DEFAULT_MAX_RESPONSE_BYTES: usize = 128 * 1024 * 1024;
6964
6965/// Read a response body, decoding as it streams, and stop once it exceeds
6966/// `limit` bytes, so a small compressed answer cannot expand without bound.
6967pub(crate) async fn read_capped_body(
6968    mut response: reqwest::Response,
6969    limit: usize,
6970) -> Result<Vec<u8>> {
6971    let mut body = Vec::new();
6972    while let Some(chunk) = response.chunk().await? {
6973        if body.len().saturating_add(chunk.len()) > limit {
6974            return Err(Error::ResponseBodyTooLarge { limit_bytes: limit });
6975        }
6976        body.extend_from_slice(&chunk);
6977    }
6978    Ok(body)
6979}
6980
6981#[derive(Debug)]
6982pub struct ClientBuilder {
6983    metrics: metrics::Metrics,
6984    base_url: String,
6985    token: Option<String>,
6986    control_token: Option<String>,
6987    worker_token: Option<String>,
6988    namespace: String,
6989    timeout: Duration,
6990    max_external_payload_bytes: usize,
6991    max_response_bytes: usize,
6992    worker_protocol_version: WorkerProtocolVersion,
6993    additional_root_certificates: Vec<reqwest::Certificate>,
6994    danger_accept_invalid_certs: bool,
6995}
6996
6997fn validate_static_credential(option: &'static str, value: Option<&str>) -> Result<()> {
6998    let Some(value) = value else {
6999        return Ok(());
7000    };
7001    // The cross-SDK policy fixes Unicode White_Space at the edges and Cc
7002    // anywhere. Do not normalize, trim, or broaden the accepted token alphabet.
7003    let edge_whitespace = |character| {
7004        matches!(
7005            character,
7006            '\u{0009}'..='\u{000d}'
7007                | '\u{0020}'
7008                | '\u{0085}'
7009                | '\u{00a0}'
7010                | '\u{1680}'
7011                | '\u{2000}'..='\u{200a}'
7012                | '\u{2028}'
7013                | '\u{2029}'
7014                | '\u{202f}'
7015                | '\u{205f}'
7016                | '\u{3000}'
7017        )
7018    };
7019    if value.chars().next().is_some_and(edge_whitespace)
7020        || value.chars().next_back().is_some_and(edge_whitespace)
7021        || value
7022            .chars()
7023            .any(|character| matches!(character, '\u{0000}'..='\u{001f}' | '\u{007f}'..='\u{009f}'))
7024    {
7025        return Err(Error::InvalidStaticCredential { option });
7026    }
7027    Ok(())
7028}
7029
7030impl ClientBuilder {
7031    /// Configure stable request metrics. Newly constructed workers inherit this recorder.
7032    pub fn metrics_recorder(mut self, recorder: Arc<dyn metrics::MetricsRecorder>) -> Self {
7033        self.metrics = metrics::Metrics::new(recorder);
7034        self
7035    }
7036    /// Explicitly select 1.19 for an older Server. Cooperation requires 1.20.
7037    pub fn worker_protocol_version(mut self, version: WorkerProtocolVersion) -> Self {
7038        self.worker_protocol_version = version;
7039        self
7040    }
7041
7042    /// Set the shared static token. Build validates every supplied token without
7043    /// trimming it. `None` is absent; `Some("")` remains a supplied empty token.
7044    pub fn token(mut self, token: Option<String>) -> Self {
7045        self.token = token;
7046        self
7047    }
7048
7049    /// Set the control-plane token, which takes precedence over the shared token
7050    /// even when empty. Build also validates tokens for unused roles.
7051    pub fn control_token(mut self, token: Option<String>) -> Self {
7052        self.control_token = token;
7053        self
7054    }
7055
7056    /// Set the worker-plane token, which takes precedence over the shared token
7057    /// even when empty. Build also validates tokens for unused roles.
7058    pub fn worker_token(mut self, token: Option<String>) -> Self {
7059        self.worker_token = token;
7060        self
7061    }
7062
7063    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
7064        self.namespace = namespace.into();
7065        self
7066    }
7067
7068    pub fn timeout(mut self, timeout: Duration) -> Self {
7069        self.timeout = timeout;
7070        self
7071    }
7072
7073    /// Maximum unique external-payload bytes fetched per response (default 64 MiB).
7074    /// References are fetched only from this client's authenticated runtime.
7075    pub fn max_external_payload_bytes(mut self, bytes: usize) -> Self {
7076        self.max_external_payload_bytes = bytes;
7077        self
7078    }
7079
7080    /// Maximum bytes of one decoded (for example gunzipped) response body
7081    /// (default 128 MiB). A larger body stops being read and fails with
7082    /// [`Error::ResponseBodyTooLarge`], so a small compressed answer cannot
7083    /// expand without bound.
7084    pub fn max_response_bytes(mut self, bytes: usize) -> Self {
7085        self.max_response_bytes = bytes;
7086        self
7087    }
7088
7089    pub fn build(self) -> Result<Client> {
7090        validate_static_credential("token", self.token.as_deref())?;
7091        validate_static_credential("control_token", self.control_token.as_deref())?;
7092        validate_static_credential("worker_token", self.worker_token.as_deref())?;
7093        let base_url = self.base_url.trim_end_matches('/').to_string();
7094        let has_sdk_api_suffix = reqwest::Url::parse(&base_url)
7095            .map(|url| url.path().trim_end_matches('/').ends_with("/api"))
7096            .unwrap_or_else(|_| base_url.ends_with("/api"));
7097
7098        if has_sdk_api_suffix {
7099            return Err(Error::InvalidBaseUrl);
7100        }
7101
7102        let mut http = reqwest::Client::builder()
7103            .timeout(self.timeout)
7104            .redirect(reqwest::redirect::Policy::none());
7105        for certificate in self.additional_root_certificates {
7106            http = http.add_root_certificate(certificate);
7107        }
7108        if self.danger_accept_invalid_certs {
7109            tracing::warn!(
7110                target: "durable_workflow::tls",
7111                endpoint = %tls_warning_endpoint(&base_url),
7112                "TLS certificate and hostname verification is disabled for this client"
7113            );
7114            http = http.danger_accept_invalid_certs(true);
7115        }
7116        Ok(Client {
7117            metrics: self.metrics,
7118            worker_dispatch_metrics: metrics::Metrics::default(),
7119            http: http.build()?,
7120            hydration_timeout: self.timeout,
7121            base_url,
7122            token: self.token,
7123            control_token: self.control_token,
7124            worker_token: self.worker_token,
7125            namespace: self.namespace,
7126            max_external_payload_bytes: self.max_external_payload_bytes,
7127            max_response_bytes: self.max_response_bytes,
7128            worker_storage_admission: None,
7129            worker_task_slot: None,
7130            cooperative_worker_protocol: false,
7131            worker_protocol_version: self.worker_protocol_version,
7132            local_activities_enabled: false,
7133            worker_sessions_enabled: false,
7134            max_concurrent_worker_sessions: 10,
7135            worker_build_id: None,
7136            sticky_cache: None,
7137            runtime_upload_policy: Arc::new(Mutex::new([None, None])),
7138            failure_request_limit: Arc::new(AtomicUsize::new(failure_reporting::REQUEST_BYTES)),
7139            activity_lease_renewal_supported: Arc::new(AtomicBool::new(false)),
7140            sticky_history_suffix_supported: Arc::new(AtomicBool::new(false)),
7141            update_outcome_reads_supported: Arc::new(AtomicBool::new(false)),
7142            signal_with_start_supported: Arc::new(AtomicBool::new(false)),
7143            activity_lease_discovery: Arc::new(activity_lease::Discovery::default()),
7144            capabilities_digest: server_capabilities_digest::Digest::default(),
7145            activity_lease_authority: None,
7146            #[cfg(feature = "telemetry")]
7147            execution_telemetry: None,
7148            #[cfg(feature = "telemetry")]
7149            observability_context_supported: Arc::new(AtomicBool::new(false)),
7150        })
7151    }
7152}
7153
7154#[derive(Clone, Debug)]
7155pub struct WorkflowHandle {
7156    client: Client,
7157    pub workflow_id: String,
7158    pub run_id: Option<String>,
7159    pub workflow_type: String,
7160}
7161
7162impl WorkflowHandle {
7163    /// Describe whichever run is current for this stable workflow instance.
7164    pub async fn describe(&self) -> Result<WorkflowDescription> {
7165        self.client.describe_workflow(&self.workflow_id).await
7166    }
7167
7168    /// Describe the run identity originally selected by this handle.
7169    pub async fn describe_selected_run(&self) -> Result<WorkflowDescription> {
7170        let run_id = self.run_id.as_deref().ok_or_else(|| {
7171            Error::Codec("run_id is required for selected-run description".to_string())
7172        })?;
7173        self.client
7174            .describe_workflow_run(&self.workflow_id, run_id)
7175            .await
7176    }
7177
7178    /// Signal this workflow with an SDK-generated caller command key.
7179    pub async fn signal<T: Serialize>(&self, signal_name: &str, input: T) -> Result<Value> {
7180        self.client
7181            .signal_workflow(&self.workflow_id, signal_name, input)
7182            .await
7183    }
7184
7185    /// Signal this workflow with an explicit caller command key (1 to 255 Unicode characters).
7186    pub async fn signal_with_request_id<T: Serialize>(
7187        &self,
7188        signal_name: &str,
7189        input: T,
7190        request_id: &str,
7191    ) -> Result<Value> {
7192        self.client
7193            .signal_workflow_with_request_id(&self.workflow_id, signal_name, input, request_id)
7194            .await
7195    }
7196
7197    pub async fn append_message<T: Serialize>(
7198        &self,
7199        stream_name: &str,
7200        message_id: &str,
7201        input: T,
7202    ) -> Result<Value> {
7203        self.client
7204            .append_message_stream(&self.workflow_id, stream_name, message_id, input)
7205            .await
7206    }
7207
7208    /// Signal only if this handle's selected run is still current, with an
7209    /// SDK-generated caller command key.
7210    pub async fn signal_selected_run<T: Serialize>(
7211        &self,
7212        signal_name: &str,
7213        input: T,
7214    ) -> Result<Value> {
7215        let run_id = self.run_id.as_deref().ok_or_else(|| {
7216            Error::Codec("run_id is required for selected-run signaling".to_string())
7217        })?;
7218        self.client
7219            .signal_workflow_run(&self.workflow_id, run_id, signal_name, input)
7220            .await
7221    }
7222
7223    /// Signal only if this handle's selected run is still current, with an
7224    /// explicit caller command key (1 to 255 Unicode characters).
7225    pub async fn signal_selected_run_with_request_id<T: Serialize>(
7226        &self,
7227        signal_name: &str,
7228        input: T,
7229        request_id: &str,
7230    ) -> Result<Value> {
7231        let run_id = self.run_id.as_deref().ok_or_else(|| {
7232            Error::Codec("run_id is required for selected-run signaling".to_string())
7233        })?;
7234        self.client
7235            .signal_workflow_run_with_request_id(
7236                &self.workflow_id,
7237                run_id,
7238                signal_name,
7239                input,
7240                request_id,
7241            )
7242            .await
7243    }
7244
7245    /// Close whichever run is current as cancelled, without workflow cleanup.
7246    pub async fn cancel(&self, options: WorkflowCommandOptions) -> Result<WorkflowCommandResult> {
7247        self.client
7248            .cancel_workflow(&self.workflow_id, options)
7249            .await
7250    }
7251
7252    /// Request cancellation only if this handle's selected run is still current.
7253    pub async fn cancel_selected_run(
7254        &self,
7255        options: WorkflowCommandOptions,
7256    ) -> Result<WorkflowCommandResult> {
7257        let run_id = self.run_id.as_deref().ok_or_else(|| {
7258            Error::Codec("run_id is required for selected-run cancellation".to_string())
7259        })?;
7260        self.client
7261            .cancel_workflow_run(&self.workflow_id, run_id, options)
7262            .await
7263    }
7264
7265    /// Forcefully terminate whichever run is current.
7266    pub async fn terminate(
7267        &self,
7268        options: WorkflowCommandOptions,
7269    ) -> Result<WorkflowCommandResult> {
7270        self.client
7271            .terminate_workflow(&self.workflow_id, options)
7272            .await
7273    }
7274
7275    /// Terminate only if this handle's selected run is still current.
7276    pub async fn terminate_selected_run(
7277        &self,
7278        options: WorkflowCommandOptions,
7279    ) -> Result<WorkflowCommandResult> {
7280        let run_id = self.run_id.as_deref().ok_or_else(|| {
7281            Error::Codec("run_id is required for selected-run termination".to_string())
7282        })?;
7283        self.client
7284            .terminate_workflow_run(&self.workflow_id, run_id, options)
7285            .await
7286    }
7287
7288    /// Continue this handle's failed run without repeating completed activities.
7289    pub async fn redrive(&self, request_id: Option<&str>) -> Result<WorkflowRedriveResult> {
7290        let run_id = self
7291            .run_id
7292            .as_deref()
7293            .ok_or_else(|| Error::Codec("run_id is required for redrive".to_string()))?;
7294        self.client
7295            .redrive_workflow_run(&self.workflow_id, run_id, request_id)
7296            .await
7297    }
7298
7299    /// Execute a named, read-only query against this workflow.
7300    pub async fn query<T: Serialize>(&self, query_name: &str, input: T) -> Result<Value> {
7301        self.client
7302            .query_workflow(&self.workflow_id, query_name, input)
7303            .await
7304    }
7305
7306    pub async fn query_avro_value<T: Serialize>(
7307        &self,
7308        query_name: &str,
7309        input: T,
7310    ) -> Result<AvroValue> {
7311        self.client
7312            .query_workflow_avro_value(&self.workflow_id, query_name, input)
7313            .await
7314    }
7315
7316    pub async fn update<T: Serialize>(
7317        &self,
7318        update_name: &str,
7319        input: T,
7320        request_id: Option<&str>,
7321    ) -> Result<Value> {
7322        self.client
7323            .update_workflow(&self.workflow_id, update_name, input, request_id)
7324            .await
7325    }
7326
7327    pub async fn update_avro_value<T: Serialize>(
7328        &self,
7329        update_name: &str,
7330        input: T,
7331        request_id: Option<&str>,
7332    ) -> Result<AvroValue> {
7333        self.client
7334            .update_workflow_avro_value(&self.workflow_id, update_name, input, request_id)
7335            .await
7336    }
7337
7338    /// Send an update and return the full receipt; see
7339    /// [`Client::update_workflow_receipt`].
7340    pub async fn update_receipt<T: Serialize>(
7341        &self,
7342        update_name: &str,
7343        input: T,
7344        request_id: Option<&str>,
7345    ) -> Result<Value> {
7346        self.client
7347            .update_workflow_receipt(&self.workflow_id, update_name, input, request_id)
7348            .await
7349    }
7350
7351    /// Query only if this handle's selected run is still current.
7352    pub async fn query_selected_run<T: Serialize>(
7353        &self,
7354        query_name: &str,
7355        input: T,
7356    ) -> Result<Value> {
7357        let run_id = self
7358            .run_id
7359            .as_deref()
7360            .ok_or_else(|| Error::Codec("run_id is required for selected-run query".to_string()))?;
7361        self.client
7362            .query_workflow_run(&self.workflow_id, run_id, query_name, input)
7363            .await
7364    }
7365
7366    /// Await the final terminal outcome of the current continue-as-new chain.
7367    pub async fn result(&self, options: WorkflowResultOptions) -> Result<Value> {
7368        self.result_target(options, None).await
7369    }
7370
7371    /// Await the final result without projecting Avro bytes through JSON.
7372    pub async fn result_avro_value(&self, options: WorkflowResultOptions) -> Result<AvroValue> {
7373        self.result_avro_value_target(options, None).await
7374    }
7375
7376    /// Await the final result and decode it into a Serde application type.
7377    pub async fn result_typed<T: DeserializeOwned>(
7378        &self,
7379        options: WorkflowResultOptions,
7380    ) -> Result<T> {
7381        let result = self.result_avro_value(options).await?;
7382        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
7383    }
7384
7385    /// Await only the run identity originally selected by this handle.
7386    pub async fn result_selected_run(&self, options: WorkflowResultOptions) -> Result<Value> {
7387        let run_id = self.run_id.as_deref().ok_or_else(|| {
7388            Error::Codec("run_id is required for selected-run result".to_string())
7389        })?;
7390        self.result_target(options, Some(run_id)).await
7391    }
7392
7393    /// Await the selected run's result on the lossless Avro Value surface.
7394    pub async fn result_selected_run_avro_value(
7395        &self,
7396        options: WorkflowResultOptions,
7397    ) -> Result<AvroValue> {
7398        let run_id = self.run_id.as_deref().ok_or_else(|| {
7399            Error::Codec("run_id is required for selected-run result".to_string())
7400        })?;
7401        self.result_avro_value_target(options, Some(run_id)).await
7402    }
7403
7404    /// Await the selected run and decode its result into a Serde type.
7405    pub async fn result_selected_run_typed<T: DeserializeOwned>(
7406        &self,
7407        options: WorkflowResultOptions,
7408    ) -> Result<T> {
7409        let result = self.result_selected_run_avro_value(options).await?;
7410        decode_handler_result(result, HandlerKind::Workflow, &self.workflow_type)
7411    }
7412
7413    async fn result_avro_value_target(
7414        &self,
7415        options: WorkflowResultOptions,
7416        selected_run_id: Option<&str>,
7417    ) -> Result<AvroValue> {
7418        let started = Instant::now();
7419
7420        loop {
7421            let description = match selected_run_id {
7422                Some(run_id) => {
7423                    self.client
7424                        .describe_workflow_run(&self.workflow_id, run_id)
7425                        .await?
7426                }
7427                None => self.describe().await?,
7428            };
7429            if description.is_completed() {
7430                return description.output_avro_value.ok_or_else(|| {
7431                    Error::Codec(
7432                        "missing_payload_envelope: typed workflow result requires output_envelope"
7433                            .to_string(),
7434                    )
7435                });
7436            }
7437            if description.is_terminal() {
7438                let description = self
7439                    .client
7440                    .with_terminal_failure_detail(description, &self.workflow_id, selected_run_id)
7441                    .await;
7442                let outcome =
7443                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
7444                return Err(match outcome.kind {
7445                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
7446                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
7447                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
7448                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
7449                });
7450            }
7451            if started.elapsed() >= options.timeout {
7452                return Err(Error::Timeout);
7453            }
7454            tokio::time::sleep(options.poll_interval).await;
7455        }
7456    }
7457
7458    async fn result_target(
7459        &self,
7460        options: WorkflowResultOptions,
7461        selected_run_id: Option<&str>,
7462    ) -> Result<Value> {
7463        let started = Instant::now();
7464
7465        loop {
7466            let description = match selected_run_id {
7467                Some(run_id) => {
7468                    self.client
7469                        .describe_workflow_run(&self.workflow_id, run_id)
7470                        .await?
7471                }
7472                None => self.describe().await?,
7473            };
7474            if description.is_completed() {
7475                return Ok(description.output.unwrap_or(Value::Null));
7476            }
7477
7478            if description.is_terminal() {
7479                let description = self
7480                    .client
7481                    .with_terminal_failure_detail(description, &self.workflow_id, selected_run_id)
7482                    .await;
7483                let outcome =
7484                    workflow_terminal_outcome(&description, &self.workflow_id, selected_run_id);
7485                return Err(match outcome.kind {
7486                    WorkflowTerminalKind::Failed => Error::WorkflowFailed(outcome),
7487                    WorkflowTerminalKind::Cancelled => Error::WorkflowCancelled(outcome),
7488                    WorkflowTerminalKind::Terminated => Error::WorkflowTerminated(outcome),
7489                    WorkflowTerminalKind::TimedOut => Error::WorkflowTimedOut(outcome),
7490                });
7491            }
7492
7493            if started.elapsed() >= options.timeout {
7494                return Err(Error::WorkflowTimedOut(WorkflowTerminalOutcome {
7495                    kind: WorkflowTerminalKind::TimedOut,
7496                    workflow_id: description
7497                        .workflow_id
7498                        .clone()
7499                        .unwrap_or_else(|| self.workflow_id.clone()),
7500                    run_id: description
7501                        .run_id
7502                        .clone()
7503                        .or_else(|| selected_run_id.map(str::to_string)),
7504                    reason: "result_wait_timeout".to_string(),
7505                    failure_category: Some("client_timeout".to_string()),
7506                    failure_id: None,
7507                    exception_type: None,
7508                    exception_class: None,
7509                    non_retryable: None,
7510                    message: Some(format!(
7511                        "workflow result was not terminal within {:?}",
7512                        options.timeout
7513                    )),
7514                    exception: None,
7515                    raw: description.raw_value(),
7516                }));
7517            }
7518
7519            tokio::time::sleep(options.poll_interval).await;
7520        }
7521    }
7522}
7523
7524#[derive(Clone, Copy, Debug)]
7525pub struct WorkflowResultOptions {
7526    pub poll_interval: Duration,
7527    pub timeout: Duration,
7528}
7529
7530impl Default for WorkflowResultOptions {
7531    fn default() -> Self {
7532        Self {
7533            poll_interval: Duration::from_millis(500),
7534            timeout: Duration::from_secs(30),
7535        }
7536    }
7537}
7538
7539#[derive(Clone, Debug, Deserialize)]
7540pub struct WorkflowDescription {
7541    pub workflow_id: Option<String>,
7542    pub run_id: Option<String>,
7543    pub workflow_type: Option<String>,
7544    pub status: Option<String>,
7545    #[serde(default)]
7546    pub closed_reason: Option<String>,
7547    #[serde(default)]
7548    pub error: Option<String>,
7549    #[serde(default)]
7550    pub failure: Option<Value>,
7551    #[serde(default)]
7552    pub exception: Option<Value>,
7553    #[serde(default)]
7554    pub failures: Vec<Value>,
7555    #[serde(default)]
7556    pub output: Option<Value>,
7557    #[serde(default)]
7558    pub output_envelope: Option<Value>,
7559    #[serde(skip)]
7560    pub output_avro_value: Option<AvroValue>,
7561    #[serde(flatten)]
7562    pub raw: HashMap<String, Value>,
7563}
7564
7565/// Lifecycle and backlog metadata for one run-scoped Workflow Stream.
7566#[derive(Clone, Debug, Deserialize)]
7567pub struct WorkflowStreamDescription {
7568    pub stream_name: String,
7569    pub status: String,
7570    pub last_offset: i64,
7571    pub total_items: u64,
7572    pub pending_items: u64,
7573    #[serde(default)]
7574    pub opened_at: Option<String>,
7575    #[serde(default)]
7576    pub last_appended_at: Option<String>,
7577    #[serde(default)]
7578    pub closed_at: Option<String>,
7579    #[serde(default)]
7580    pub error_reason: Option<String>,
7581    #[serde(default)]
7582    pub retention_seconds: Option<u64>,
7583    #[serde(flatten)]
7584    pub raw: HashMap<String, Value>,
7585}
7586
7587impl WorkflowStreamDescription {
7588    pub fn is_terminal(&self) -> bool {
7589        matches!(self.status.as_str(), "closed" | "errored")
7590    }
7591}
7592
7593/// One item for direct or replay-safe append.
7594#[derive(Clone, Debug, Default)]
7595pub struct WorkflowStreamAppendItem {
7596    pub payload_envelope: Option<Value>,
7597    pub payload_reference: Option<String>,
7598    pub item_type: Option<String>,
7599    pub content_type: Option<String>,
7600    pub idempotency_key: Option<String>,
7601}
7602
7603impl WorkflowStreamAppendItem {
7604    /// Encode an inline payload with the SDK's fixed Avro Value envelope.
7605    pub fn new<T: Serialize>(payload: T) -> Result<Self> {
7606        let value = AvroValue::from_serialize(&payload)?;
7607        Ok(Self {
7608            payload_envelope: Some(encode_typed_envelope(&value, DEFAULT_CODEC)?),
7609            ..Self::default()
7610        })
7611    }
7612
7613    /// Preserve an external payload URI as an opaque service-contract reference.
7614    pub fn from_reference(reference: impl Into<String>) -> Self {
7615        Self {
7616            payload_reference: Some(reference.into()),
7617            ..Self::default()
7618        }
7619    }
7620
7621    pub fn item_type(mut self, item_type: impl Into<String>) -> Self {
7622        self.item_type = Some(item_type.into());
7623        self
7624    }
7625
7626    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
7627        self.content_type = Some(content_type.into());
7628        self
7629    }
7630
7631    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
7632        self.idempotency_key = Some(idempotency_key.into());
7633        self
7634    }
7635
7636    fn wire_value(&self, derived_idempotency_key: Option<String>) -> Value {
7637        let mut item = serde_json::Map::new();
7638        if let Some(payload) = &self.payload_envelope {
7639            item.insert("payload".to_string(), payload.clone());
7640            item.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
7641        }
7642        if let Some(reference) = &self.payload_reference {
7643            item.insert("payload_reference".to_string(), json!(reference));
7644        }
7645        if let Some(item_type) = &self.item_type {
7646            item.insert("item_type".to_string(), json!(item_type));
7647        }
7648        if let Some(content_type) = &self.content_type {
7649            item.insert("content_type".to_string(), json!(content_type));
7650        }
7651        if let Some(key) = derived_idempotency_key
7652            .as_ref()
7653            .or(self.idempotency_key.as_ref())
7654        {
7655            item.insert("idempotency_key".to_string(), json!(key));
7656        }
7657        Value::Object(item)
7658    }
7659}
7660
7661/// One durable item at its stable zero-based offset.
7662#[derive(Clone, Debug)]
7663pub struct WorkflowStreamItem {
7664    pub offset: u64,
7665    pub payload: Option<Value>,
7666    pub payload_envelope: Option<Value>,
7667    pub payload_reference: Option<String>,
7668    pub payload_codec: Option<String>,
7669    pub idempotency_key: Option<String>,
7670    pub item_type: Option<String>,
7671    pub content_type: Option<String>,
7672    pub origin: Option<String>,
7673    pub origin_reference: Option<String>,
7674    pub emitted_at: Option<String>,
7675    pub raw: Value,
7676}
7677
7678/// One bounded at-least-once subscription page.
7679#[derive(Clone, Debug)]
7680pub struct WorkflowStreamPage {
7681    pub stream: WorkflowStreamDescription,
7682    pub items: Vec<WorkflowStreamItem>,
7683    pub next_offset: u64,
7684    pub terminal: bool,
7685}
7686
7687/// Durable acceptance and deduplication outcome for an append request.
7688#[derive(Clone, Debug)]
7689pub struct WorkflowStreamAppendResult {
7690    pub stream: WorkflowStreamDescription,
7691    pub accepted_offsets: Vec<u64>,
7692    pub accepted: u64,
7693    pub deduped: u64,
7694}
7695
7696#[derive(Deserialize)]
7697struct WorkflowStreamListResponse {
7698    #[serde(default)]
7699    streams: Vec<WorkflowStreamDescription>,
7700}
7701
7702#[derive(Deserialize)]
7703struct WorkflowStreamDescriptionResponse {
7704    stream: WorkflowStreamDescription,
7705}
7706
7707#[derive(Deserialize)]
7708struct WorkflowStreamPageResponse {
7709    stream: WorkflowStreamDescription,
7710    #[serde(default)]
7711    items: Vec<Value>,
7712    next_offset: u64,
7713    terminal: bool,
7714}
7715
7716#[derive(Deserialize)]
7717struct WorkflowStreamAppendResponse {
7718    stream: WorkflowStreamDescription,
7719    #[serde(default)]
7720    accepted_offsets: Vec<u64>,
7721    accepted: u64,
7722    deduped: u64,
7723}
7724
7725impl WorkflowDescription {
7726    pub fn is_completed(&self) -> bool {
7727        matches!(self.status.as_deref(), Some("completed" | "Completed"))
7728    }
7729
7730    pub fn is_terminal(&self) -> bool {
7731        matches!(
7732            self.status.as_deref(),
7733            Some(
7734                "completed"
7735                    | "Completed"
7736                    | "failed"
7737                    | "Failed"
7738                    | "cancelled"
7739                    | "Cancelled"
7740                    | "terminated"
7741                    | "Terminated"
7742                    | "timed_out"
7743                    | "TimedOut",
7744            )
7745        )
7746    }
7747
7748    fn decode_payloads(&mut self) -> Result<()> {
7749        if let Some(envelope) = &self.output_envelope {
7750            let value = decode_wire_avro_value(envelope, DEFAULT_CODEC)?;
7751            self.output = Some(value.clone().into_json()?);
7752            self.output_avro_value = Some(value);
7753        }
7754
7755        Ok(())
7756    }
7757
7758    fn raw_value(&self) -> Value {
7759        let mut data = self.raw.clone();
7760        data.insert(
7761            "workflow_id".to_string(),
7762            self.workflow_id
7763                .clone()
7764                .map(Value::String)
7765                .unwrap_or(Value::Null),
7766        );
7767        data.insert(
7768            "run_id".to_string(),
7769            self.run_id
7770                .clone()
7771                .map(Value::String)
7772                .unwrap_or(Value::Null),
7773        );
7774        data.insert(
7775            "workflow_type".to_string(),
7776            self.workflow_type
7777                .clone()
7778                .map(Value::String)
7779                .unwrap_or(Value::Null),
7780        );
7781        data.insert(
7782            "status".to_string(),
7783            self.status
7784                .clone()
7785                .map(Value::String)
7786                .unwrap_or(Value::Null),
7787        );
7788        data.insert(
7789            "closed_reason".to_string(),
7790            self.closed_reason
7791                .clone()
7792                .map(Value::String)
7793                .unwrap_or(Value::Null),
7794        );
7795        if let Some(failure) = &self.failure {
7796            data.insert("failure".to_string(), failure.clone());
7797        }
7798        if let Some(exception) = &self.exception {
7799            data.insert("exception".to_string(), exception.clone());
7800        }
7801        Value::Object(data.into_iter().collect())
7802    }
7803}
7804
7805fn workflow_terminal_outcome(
7806    description: &WorkflowDescription,
7807    workflow_id: &str,
7808    run_id: Option<&str>,
7809) -> WorkflowTerminalOutcome {
7810    let terminal_kind = description
7811        .closed_reason
7812        .as_deref()
7813        .or(description.status.as_deref())
7814        .unwrap_or("failed")
7815        .to_ascii_lowercase();
7816    let kind = match terminal_kind.as_str() {
7817        "cancelled" | "canceled" => WorkflowTerminalKind::Cancelled,
7818        "terminated" => WorkflowTerminalKind::Terminated,
7819        "timed_out" | "timedout" => WorkflowTerminalKind::TimedOut,
7820        _ => WorkflowTerminalKind::Failed,
7821    };
7822    let default_reason = match kind {
7823        WorkflowTerminalKind::Failed => "workflow_failed",
7824        WorkflowTerminalKind::Cancelled => "cancelled",
7825        WorkflowTerminalKind::Terminated => "terminated",
7826        WorkflowTerminalKind::TimedOut => "timed_out",
7827    };
7828    let failure = description
7829        .failure
7830        .as_ref()
7831        .filter(|value| value.is_object());
7832    let nested_failure = failure
7833        .and_then(|value| value.get("failures"))
7834        .and_then(Value::as_array)
7835        .and_then(|failures| failures.last())
7836        .or_else(|| description.failures.last());
7837    let exception = description
7838        .exception
7839        .clone()
7840        .or_else(|| failure.and_then(|value| value.get("exception")).cloned())
7841        .or_else(|| {
7842            nested_failure
7843                .and_then(|value| value.get("exception_payload"))
7844                .cloned()
7845        });
7846    let string_field = |name: &str| {
7847        failure
7848            .and_then(|value| value.get(name))
7849            .and_then(Value::as_str)
7850            .or_else(|| {
7851                nested_failure
7852                    .and_then(|value| value.get(name))
7853                    .and_then(Value::as_str)
7854            })
7855            .map(str::to_string)
7856    };
7857    let exception_field = |name: &str| {
7858        exception
7859            .as_ref()
7860            .and_then(|value| value.get(name))
7861            .and_then(Value::as_str)
7862            .map(str::to_string)
7863    };
7864    let message = description
7865        .error
7866        .clone()
7867        .or_else(|| string_field("message"))
7868        .or_else(|| exception_field("message"));
7869    let reason = description
7870        .raw
7871        .get("reason")
7872        .and_then(Value::as_str)
7873        .map(str::to_string)
7874        .or_else(|| {
7875            failure
7876                .and_then(|value| value.get("reason"))
7877                .and_then(Value::as_str)
7878                .map(str::to_string)
7879        })
7880        .or_else(|| description.closed_reason.clone())
7881        .unwrap_or_else(|| default_reason.to_string());
7882    let failure_id = string_field("failure_id").or_else(|| {
7883        nested_failure
7884            .and_then(|value| value.get("id"))
7885            .and_then(Value::as_str)
7886            .map(str::to_string)
7887    });
7888
7889    WorkflowTerminalOutcome {
7890        kind,
7891        workflow_id: description
7892            .workflow_id
7893            .clone()
7894            .unwrap_or_else(|| workflow_id.to_string()),
7895        run_id: description
7896            .run_id
7897            .clone()
7898            .or_else(|| run_id.map(str::to_string)),
7899        reason,
7900        failure_category: string_field("failure_category")
7901            .or_else(|| Some(default_reason.to_string())),
7902        failure_id,
7903        exception_type: string_field("exception_type").or_else(|| exception_field("type")),
7904        exception_class: string_field("exception_class").or_else(|| exception_field("class")),
7905        non_retryable: failure
7906            .and_then(|value| value.get("non_retryable"))
7907            .and_then(Value::as_bool)
7908            .or_else(|| {
7909                nested_failure
7910                    .and_then(|value| value.get("non_retryable"))
7911                    .and_then(Value::as_bool)
7912            }),
7913        message,
7914        exception,
7915        raw: description.raw_value(),
7916    }
7917}
7918
7919#[derive(Clone, Debug, Deserialize)]
7920pub struct RegisterWorkerResponse {
7921    pub worker_id: String,
7922    pub registered: bool,
7923    #[serde(default)]
7924    pub heartbeat_interval_seconds: Option<u64>,
7925    #[serde(default)]
7926    pub protocol_version: Option<String>,
7927    #[serde(default)]
7928    pub server_capabilities: Option<Value>,
7929}
7930
7931/// Result of gracefully removing a worker-plane registration.
7932#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
7933pub struct WorkerDeregistrationEnvelope {
7934    pub worker_id: String,
7935    pub outcome: String,
7936    pub recovered_workflow_task_count: u64,
7937}
7938
7939#[derive(Clone, Debug, Deserialize)]
7940pub struct PollWorkflowTaskResponse {
7941    #[serde(default)]
7942    pub task: Option<WorkflowTask>,
7943    #[serde(default)]
7944    pub poll_status: Option<String>,
7945    #[serde(default)]
7946    pub reason: Option<String>,
7947    #[serde(default)]
7948    pub protocol_version: Option<String>,
7949    #[serde(default)]
7950    pub server_capabilities: Option<Value>,
7951}
7952
7953impl PollWorkflowTaskResponse {
7954    /// Classify this response without parsing server display text.
7955    pub fn outcome(&self) -> WorkerPollOutcome {
7956        worker_poll_outcome(
7957            self.task.is_some(),
7958            self.poll_status.as_deref(),
7959            self.reason.as_deref(),
7960        )
7961    }
7962}
7963
7964fn runtime_supports_workflow_memo_updates(capabilities: Option<&Value>) -> bool {
7965    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
7966        return false;
7967    };
7968    let supported = capabilities
7969        .get("workflow_memo_updates")
7970        .and_then(Value::as_object)
7971        .and_then(|memo| memo.get("supported"))
7972        .and_then(Value::as_bool)
7973        == Some(true);
7974    let command_advertised = capabilities
7975        .get("supported_workflow_task_commands")
7976        .and_then(Value::as_array)
7977        .is_some_and(|commands| {
7978            commands
7979                .iter()
7980                .any(|command| command.as_str() == Some("upsert_memo"))
7981        });
7982    supported && command_advertised
7983}
7984
7985fn commands_use_workflow_memo_updates(commands: &[Value]) -> bool {
7986    commands
7987        .iter()
7988        .any(|command| command.get("type").and_then(Value::as_str) == Some("upsert_memo"))
7989}
7990
7991#[derive(Clone, Debug, Deserialize)]
7992pub struct PollActivityTaskResponse {
7993    #[serde(default)]
7994    pub task: Option<ActivityTask>,
7995    #[serde(default)]
7996    pub poll_status: Option<String>,
7997    #[serde(default)]
7998    pub reason: Option<String>,
7999}
8000
8001impl PollActivityTaskResponse {
8002    /// Classify this response without parsing server display text.
8003    pub fn outcome(&self) -> WorkerPollOutcome {
8004        worker_poll_outcome(
8005            self.task.is_some(),
8006            self.poll_status.as_deref(),
8007            self.reason.as_deref(),
8008        )
8009    }
8010}
8011
8012#[derive(Clone, Debug, Deserialize)]
8013pub struct PollQueryTaskResponse {
8014    #[serde(default)]
8015    pub task: Option<QueryTask>,
8016    #[serde(default)]
8017    pub poll_status: Option<String>,
8018    #[serde(default)]
8019    pub reason: Option<String>,
8020}
8021
8022impl PollQueryTaskResponse {
8023    /// Classify this response without parsing server display text.
8024    pub fn outcome(&self) -> WorkerPollOutcome {
8025        worker_poll_outcome(
8026            self.task.is_some(),
8027            self.poll_status.as_deref(),
8028            self.reason.as_deref(),
8029        )
8030    }
8031}
8032
8033/// Stable classification for worker poll responses.
8034#[derive(Clone, Debug, PartialEq, Eq)]
8035pub enum WorkerPollOutcome {
8036    /// A task was leased and is available on the response.
8037    Task,
8038    /// No task was leased, but the worker should continue polling.
8039    Idle {
8040        poll_status: Option<String>,
8041        reason: Option<String>,
8042    },
8043    /// The server asked this worker to stop claiming new work.
8044    Stop {
8045        poll_status: Option<String>,
8046        reason: Option<String>,
8047    },
8048}
8049
8050impl WorkerPollOutcome {
8051    pub fn should_stop(&self) -> bool {
8052        matches!(self, Self::Stop { .. })
8053    }
8054}
8055
8056fn worker_poll_outcome(
8057    has_task: bool,
8058    poll_status: Option<&str>,
8059    reason: Option<&str>,
8060) -> WorkerPollOutcome {
8061    if worker_poll_is_stop(poll_status, reason) {
8062        return WorkerPollOutcome::Stop {
8063            poll_status: poll_status.map(str::to_string),
8064            reason: reason.map(str::to_string),
8065        };
8066    }
8067
8068    if has_task {
8069        WorkerPollOutcome::Task
8070    } else {
8071        WorkerPollOutcome::Idle {
8072            poll_status: poll_status.map(str::to_string),
8073            reason: reason.map(str::to_string),
8074        }
8075    }
8076}
8077
8078/// An ephemeral server-routed query task.
8079#[derive(Clone, Debug, Deserialize)]
8080pub struct QueryTask {
8081    pub query_task_id: String,
8082    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
8083    #[serde(default)]
8084    pub observability_context: Option<Value>,
8085    #[serde(default)]
8086    pub dispatch_observability_context: Option<Value>,
8087    #[serde(default)]
8088    pub observability_links: Option<Value>,
8089    #[serde(default = "default_workflow_task_attempt")]
8090    pub query_task_attempt: u64,
8091    #[serde(default)]
8092    pub lease_owner: Option<String>,
8093    #[serde(default)]
8094    pub workflow_id: Option<String>,
8095    #[serde(default)]
8096    pub run_id: Option<String>,
8097    pub workflow_type: String,
8098    pub query_name: String,
8099    #[serde(
8100        default = "missing_task_payload_codec",
8101        deserialize_with = "deserialize_task_payload_codec"
8102    )]
8103    pub payload_codec: String,
8104    #[serde(default)]
8105    pub workflow_arguments: Option<Value>,
8106    #[serde(default)]
8107    pub query_arguments: Option<Value>,
8108    #[serde(default)]
8109    pub history_events: Vec<HistoryEvent>,
8110    #[serde(default)]
8111    pub history_export: Option<Value>,
8112    #[serde(default)]
8113    pub run_status: Option<String>,
8114}
8115
8116#[derive(Clone, Debug, Deserialize)]
8117pub struct WorkflowTask {
8118    pub task_id: String,
8119    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
8120    #[serde(default)]
8121    pub observability_context: Option<Value>,
8122    #[serde(default)]
8123    pub dispatch_observability_context: Option<Value>,
8124    #[serde(default)]
8125    pub observability_links: Option<Value>,
8126    #[serde(default)]
8127    pub workflow_command_id: Option<String>,
8128    #[serde(default)]
8129    pub workflow_id: Option<String>,
8130    #[serde(default)]
8131    pub run_id: Option<String>,
8132    pub workflow_type: String,
8133    #[serde(default)]
8134    pub cancel_requested: bool,
8135    #[serde(
8136        default = "missing_task_payload_codec",
8137        deserialize_with = "deserialize_task_payload_codec"
8138    )]
8139    pub payload_codec: String,
8140    #[serde(default)]
8141    pub arguments: Option<Value>,
8142    #[serde(default)]
8143    pub history_events: Vec<HistoryEvent>,
8144    #[serde(default)]
8145    pub total_history_events: Option<u64>,
8146    #[serde(default)]
8147    pub history_size_bytes: Option<u64>,
8148    #[serde(default)]
8149    pub continue_as_new_recommended: Option<bool>,
8150    #[serde(default)]
8151    pub history_budget_pressure: Option<String>,
8152    #[serde(default)]
8153    pub next_history_page_token: Option<String>,
8154    #[serde(default = "default_workflow_task_attempt")]
8155    pub workflow_task_attempt: u64,
8156    #[serde(default)]
8157    pub workflow_signal_id: Option<String>,
8158    #[serde(default)]
8159    pub signal_name: Option<String>,
8160    #[serde(default)]
8161    pub signal_arguments: Option<Value>,
8162    #[serde(default)]
8163    pub workflow_update_id: Option<String>,
8164    #[serde(default)]
8165    pub update_name: Option<String>,
8166    #[serde(default)]
8167    pub lease_owner: Option<String>,
8168}
8169
8170impl WorkflowTask {
8171    fn append_history_page(&mut self, page: WorkflowTaskHistoryPage) {
8172        self.history_events.extend(page.history_events);
8173
8174        if page.total_history_events.is_some() {
8175            self.total_history_events = page.total_history_events;
8176        }
8177
8178        self.next_history_page_token = page
8179            .next_history_page_token
8180            .filter(|token| !token.is_empty());
8181    }
8182}
8183
8184#[derive(Clone, Debug, Deserialize)]
8185struct WorkflowTaskHistoryPage {
8186    #[serde(default)]
8187    history_events: Vec<HistoryEvent>,
8188    #[serde(default)]
8189    total_history_events: Option<u64>,
8190    #[serde(default)]
8191    next_history_page_token: Option<String>,
8192}
8193
8194#[derive(Clone, Debug, Deserialize)]
8195pub struct ActivityTask {
8196    pub task_id: String,
8197    #[serde(default)]
8198    pub workflow_id: Option<String>,
8199    #[serde(default)]
8200    pub run_id: Option<String>,
8201    #[serde(default)]
8202    pub activity_execution_id: Option<String>,
8203    /// Optional, untrusted observability metadata. Receiving it does not authorize execution.
8204    #[serde(default)]
8205    pub observability_context: Option<Value>,
8206    #[serde(default)]
8207    pub dispatch_observability_context: Option<Value>,
8208    #[serde(default)]
8209    pub observability_links: Option<Value>,
8210    #[serde(default)]
8211    pub activity_attempt_id: Option<String>,
8212    #[serde(default)]
8213    pub attempt_id: Option<String>,
8214    pub activity_type: String,
8215    #[serde(
8216        default = "missing_task_payload_codec",
8217        deserialize_with = "deserialize_task_payload_codec"
8218    )]
8219    pub payload_codec: String,
8220    #[serde(default)]
8221    pub arguments: Option<Value>,
8222    #[serde(default = "default_attempt_number")]
8223    pub attempt_number: u64,
8224    #[serde(default)]
8225    pub lease_owner: Option<String>,
8226}
8227
8228#[derive(Clone, Debug, Serialize, Deserialize)]
8229pub struct HistoryEvent {
8230    #[serde(alias = "type")]
8231    pub event_type: String,
8232    #[serde(default)]
8233    pub payload: Value,
8234    #[serde(flatten)]
8235    pub raw: HashMap<String, Value>,
8236}
8237
8238/// One decoded signal in the committed workflow-history snapshot.
8239#[derive(Clone, Debug, PartialEq)]
8240pub struct QuerySignal {
8241    pub id: Option<String>,
8242    pub name: String,
8243    pub arguments: Vec<Value>,
8244    avro_arguments: Vec<AvroValue>,
8245    pub workflow_sequence: Option<u64>,
8246}
8247
8248impl QuerySignal {
8249    /// Lossless fixed Avro Value arguments for this committed signal.
8250    pub fn arguments_avro_value(&self) -> &[AvroValue] {
8251        &self.avro_arguments
8252    }
8253}
8254
8255/// Immutable state supplied to a registered query handler.
8256///
8257/// This context intentionally exposes no activity, signal-wait, or command
8258/// APIs. Query handlers inspect committed history and return a value; query
8259/// completion does not append an event or advance deterministic execution.
8260#[derive(Clone, Debug)]
8261pub struct QueryContext {
8262    pub workflow_id: Option<String>,
8263    pub run_id: Option<String>,
8264    pub workflow_type: String,
8265    pub run_status: Option<String>,
8266    workflow_input: Value,
8267    workflow_input_avro_value: AvroValue,
8268    history_events: Arc<Vec<HistoryEvent>>,
8269    signal_events: Arc<Vec<QuerySignal>>,
8270    replay_time: Option<DateTime<chrono::Utc>>,
8271}
8272
8273impl QueryContext {
8274    /// The normalized argument list used to start the workflow.
8275    pub fn workflow_input(&self) -> &Value {
8276        &self.workflow_input
8277    }
8278
8279    /// The lossless fixed Avro Value argument list used to start the workflow.
8280    pub fn workflow_input_avro_value(&self) -> &AvroValue {
8281        &self.workflow_input_avro_value
8282    }
8283
8284    /// The immutable committed history used for this query snapshot.
8285    pub fn history_events(&self) -> &[HistoryEvent] {
8286        self.history_events.as_slice()
8287    }
8288
8289    /// All decoded signals in committed workflow order.
8290    pub fn signal_events(&self) -> &[QuerySignal] {
8291        self.signal_events.as_slice()
8292    }
8293
8294    /// Decoded argument lists for each committed signal with `signal_name`.
8295    pub fn signals(&self, signal_name: &str) -> Vec<Vec<Value>> {
8296        self.signal_events
8297            .iter()
8298            .filter(|signal| signal.name == signal_name)
8299            .map(|signal| signal.arguments.clone())
8300            .collect()
8301    }
8302
8303    /// Lossless fixed Avro Value arguments for committed signals with `signal_name`.
8304    pub fn signals_avro_value(&self, signal_name: &str) -> Vec<Vec<AvroValue>> {
8305        self.signal_events
8306            .iter()
8307            .filter(|signal| signal.name == signal_name)
8308            .map(|signal| signal.avro_arguments.clone())
8309            .collect()
8310    }
8311}
8312
8313#[derive(Clone, Debug, Deserialize)]
8314pub struct ActivityHeartbeatResponse {
8315    #[serde(default)]
8316    pub cancel_requested: bool,
8317    #[serde(default)]
8318    pub heartbeat_recorded: bool,
8319    #[serde(default)]
8320    pub can_continue: Option<bool>,
8321    #[serde(default)]
8322    pub reason: Option<String>,
8323    #[serde(default)]
8324    pub run_closed_reason: Option<String>,
8325    #[serde(default)]
8326    pub run_closed_at: Option<String>,
8327    #[serde(default)]
8328    pub lease_expires_at: Option<String>,
8329    #[serde(default)]
8330    pub last_heartbeat_at: Option<String>,
8331}
8332
8333impl ActivityHeartbeatResponse {
8334    /// Whether the activity should stop instead of attempting completion.
8335    pub fn should_stop(&self) -> bool {
8336        self.cancel_requested || self.can_continue == Some(false)
8337    }
8338}
8339
8340fn missing_task_payload_codec() -> String {
8341    MISSING_TASK_PAYLOAD_CODEC.to_string()
8342}
8343
8344fn deserialize_task_payload_codec<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
8345where
8346    D: Deserializer<'de>,
8347{
8348    Ok(match Value::deserialize(deserializer)? {
8349        Value::String(codec) => codec,
8350        Value::Null => NULL_TASK_PAYLOAD_CODEC.to_string(),
8351        _ => NON_STRING_TASK_PAYLOAD_CODEC.to_string(),
8352    })
8353}
8354
8355fn default_workflow_task_attempt() -> u64 {
8356    1
8357}
8358
8359fn default_attempt_number() -> u64 {
8360    1
8361}
8362
8363type WorkflowFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
8364type WorkflowHandler =
8365    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<WorkflowFuture> + Send + Sync>;
8366type ErasedWorkflowState = Arc<dyn Any + Send + Sync>;
8367type WorkflowStateSnapshot = Arc<dyn Fn() -> Result<ErasedWorkflowState> + Send + Sync>;
8368type ReplayedWorkflowHandler =
8369    Arc<dyn Fn(WorkflowContext, AvroValue) -> Result<ReplayedWorkflowInvocation> + Send + Sync>;
8370type ActivityFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
8371type ActivityHandler = Arc<dyn Fn(ActivityContext, AvroValue) -> ActivityFuture + Send + Sync>;
8372type QueryFuture = Pin<Box<dyn Future<Output = Result<AvroValue>> + Send + 'static>>;
8373type QueryHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
8374type UpdateHandler = Arc<dyn Fn(QueryContext, AvroValue) -> QueryFuture + Send + Sync>;
8375type ReplayedQueryHandler = Arc<
8376    dyn Fn(QueryContext, ErasedWorkflowState, AvroValue) -> std::result::Result<QueryFuture, String>
8377        + Send
8378        + Sync,
8379>;
8380type WorkerHeartbeatObserver = Arc<dyn Fn(&WorkerHeartbeatObservation) + Send + Sync>;
8381
8382struct ReplayedWorkflowInvocation {
8383    future: WorkflowFuture,
8384    snapshot: WorkflowStateSnapshot,
8385}
8386
8387#[derive(Clone)]
8388struct RegisteredWorkflow {
8389    execute: WorkflowHandler,
8390    replay: Option<ReplayedWorkflowHandler>,
8391    state_type: Option<TypeId>,
8392    definition_fingerprint: Option<String>,
8393}
8394
8395fn argument_vector_contracts(names: &[String]) -> Vec<Value> {
8396    names
8397        .iter()
8398        .map(|name| {
8399            json!({
8400                "name": name,
8401                "parameters": [{
8402                    "name": "args",
8403                    "position": 0,
8404                    "required": false,
8405                    "variadic": true,
8406                    "type": null,
8407                    "allows_null": true,
8408                    "default_available": false,
8409                    "default": null,
8410                }],
8411            })
8412        })
8413        .collect()
8414}
8415
8416#[derive(Debug)]
8417struct WorkflowTaskDecision {
8418    commands: Vec<Value>,
8419    message_stream_cursors: Vec<Value>,
8420    message_stream_waits: Vec<Value>,
8421    cancellation_delivery: Option<CancellationDelivery>,
8422    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
8423    cancellation_scope_delivery: Option<cancellation_scope_replay::ScopeDeliveryIntent>,
8424}
8425
8426enum PreparedWorkflowTask {
8427    Decision(WorkflowTaskDecision),
8428    Execution {
8429        task: WorkflowTask,
8430        context: WorkflowContext,
8431        future: WorkflowFuture,
8432    },
8433}
8434
8435impl WorkflowTaskDecision {
8436    fn without_message_streams(commands: Vec<Value>) -> Self {
8437        Self {
8438            commands,
8439            message_stream_cursors: Vec::new(),
8440            message_stream_waits: Vec::new(),
8441            cancellation_delivery: None,
8442            cancellation_scope_opening: None,
8443            cancellation_scope_delivery: None,
8444        }
8445    }
8446}
8447
8448#[derive(Clone)]
8449enum RegisteredQuery {
8450    Snapshot(QueryHandler),
8451    Replayed {
8452        state_type: TypeId,
8453        handler: ReplayedQueryHandler,
8454    },
8455}
8456
8457#[derive(Clone, Debug)]
8458pub struct WorkerHeartbeatObservation {
8459    pub worker_id: String,
8460    pub task_queue: String,
8461    pub acknowledged_at_unix_millis: u64,
8462    pub acknowledgement: Value,
8463}
8464
8465/// Bounded retry policy for worker poll acquisition and worker heartbeats.
8466///
8467/// Expected empty long polls and explicit Server capacity backpressure are
8468/// normal worker states. Capacity backpressure honors the advertised retry
8469/// delay without consuming this retry budget. Other transport failures,
8470/// retryable HTTP 408/429 responses, and server errors are retried with capped
8471/// exponential backoff. Authentication, protocol, codec, and handler failures
8472/// are never retried by the worker.
8473/// Explicit storage admission pauses also preserve the already-serialized worker
8474/// request without consuming this budget or rerunning its handler. The delay is
8475/// capped by `max_backoff`, except an explicit completion deferral must honor
8476/// the Server's minimum delay. Shutdown interrupts storage waits; cooperative
8477/// completion retries remain bounded by the original cleanup deadline.
8478/// [`Worker::recover_transient_outages`] (on by default) keeps a long-running
8479/// worker retrying transient poll, heartbeat and registration failures beyond
8480/// this budget. `run_once` stays bounded, and `max_retries = 0` disables
8481/// ordinary retries in either mode.
8482#[derive(Clone, Copy, Debug)]
8483pub struct WorkerRetryPolicy {
8484    /// Number of retries after the initial request fails.
8485    pub max_retries: usize,
8486    /// Delay before the first retry.
8487    pub initial_backoff: Duration,
8488    /// Maximum delay between retries.
8489    pub max_backoff: Duration,
8490}
8491
8492impl Default for WorkerRetryPolicy {
8493    fn default() -> Self {
8494        Self {
8495            max_retries: 5,
8496            initial_backoff: Duration::from_millis(100),
8497            max_backoff: Duration::from_secs(5),
8498        }
8499    }
8500}
8501
8502#[derive(Clone, Debug)]
8503struct WorkerStorageAdmission {
8504    policy: WorkerRetryPolicy,
8505    stop: Arc<AtomicBool>,
8506    workflow_completion_retry_deadline: Option<tokio::time::Instant>,
8507}
8508
8509struct StopWorkerOnDrop(Arc<AtomicBool>);
8510
8511impl Drop for StopWorkerOnDrop {
8512    fn drop(&mut self) {
8513        self.0.store(true, Ordering::SeqCst);
8514    }
8515}
8516
8517async fn wait_for_worker_stop(stop: &AtomicBool) {
8518    while !stop.load(Ordering::SeqCst) {
8519        tokio::time::sleep(Duration::from_millis(100)).await;
8520    }
8521}
8522
8523#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8524enum ManagedPollOutcome {
8525    Idle,
8526    Handled,
8527    Stop,
8528}
8529
8530#[derive(Clone)]
8531pub struct Worker {
8532    metrics: metrics::Metrics,
8533    #[cfg(feature = "telemetry")]
8534    telemetry: Option<telemetry::ExecutionTelemetry>,
8535    client: Client,
8536    worker_id: String,
8537    task_queue: String,
8538    workflows: HashMap<String, RegisteredWorkflow>,
8539    activities: HashMap<String, ActivityHandler>,
8540    queries: HashMap<String, HashMap<String, RegisteredQuery>>,
8541    signals: HashMap<String, Vec<String>>,
8542    updates: HashMap<String, HashMap<String, UpdateHandler>>,
8543    registration_definitions:
8544        HashMap<(RegistrationKind, Option<String>, String), HandlerRegistration>,
8545    registration_error: Option<DuplicateRegistrationError>,
8546    max_concurrent_workflow_tasks: usize,
8547    max_concurrent_activity_tasks: usize,
8548    workflow_capacity: Arc<worker_capacity::TaskCapacity>,
8549    activity_capacity: Arc<worker_capacity::TaskCapacity>,
8550    poll_timeout: Duration,
8551    heartbeat_interval: Duration,
8552    retry_policy: WorkerRetryPolicy,
8553    recover_transient_outages: bool,
8554    run_stop: Option<Arc<AtomicBool>>,
8555    heartbeat_observer: Option<WorkerHeartbeatObserver>,
8556    cooperative_cancellation_enabled: bool,
8557    nexus_cooperative_cancellation_enabled: bool,
8558    allow_cancellation_scope_authoring: bool,
8559    allow_cancellation_scope_delivery: bool,
8560    cooperative_registration_confirmed: Arc<AtomicBool>,
8561    nexus_registration_confirmed: Arc<AtomicBool>,
8562    local_registration_confirmed: Arc<AtomicBool>,
8563    session_registration_confirmed: Arc<AtomicBool>,
8564    sticky_registration_confirmed: Arc<AtomicBool>,
8565    require_query_task_authority: bool,
8566    query_authority_confirmed: Arc<AtomicBool>,
8567    resource_capabilities: Vec<String>,
8568    sessions: Arc<Mutex<HashMap<String, WorkerSession>>>,
8569    /// Whether the latest workflow poll's `server_capabilities` advertised
8570    /// the `signal_external_workflow` command.
8571    signal_external_workflow_supported: Arc<AtomicBool>,
8572}
8573
8574impl Worker {
8575    /// Override worker poll/task metrics; client request metrics retain their client's recorder.
8576    pub fn metrics_recorder(mut self, recorder: Arc<dyn metrics::MetricsRecorder>) -> Self {
8577        self.metrics = metrics::Metrics::new(recorder);
8578        self.client.worker_dispatch_metrics = self.metrics.clone();
8579        self
8580    }
8581    pub fn new(mut client: Client, task_queue: impl Into<String>) -> Self {
8582        client.worker_dispatch_metrics = client.metrics.clone();
8583        Self {
8584            metrics: client.metrics.clone(),
8585            #[cfg(feature = "telemetry")]
8586            telemetry: None,
8587            client,
8588            worker_id: default_worker_id(),
8589            task_queue: task_queue.into(),
8590            workflows: HashMap::new(),
8591            activities: HashMap::new(),
8592            queries: HashMap::new(),
8593            signals: HashMap::new(),
8594            updates: HashMap::new(),
8595            registration_definitions: HashMap::new(),
8596            registration_error: None,
8597            max_concurrent_workflow_tasks: 10,
8598            max_concurrent_activity_tasks: 10,
8599            workflow_capacity: worker_capacity::TaskCapacity::new(10),
8600            activity_capacity: worker_capacity::TaskCapacity::new(10),
8601            poll_timeout: Duration::from_secs(30),
8602            heartbeat_interval: Duration::from_secs(60),
8603            retry_policy: WorkerRetryPolicy::default(),
8604            recover_transient_outages: true,
8605            run_stop: None,
8606            heartbeat_observer: None,
8607            cooperative_cancellation_enabled: false,
8608            nexus_cooperative_cancellation_enabled: false,
8609            allow_cancellation_scope_authoring: false,
8610            allow_cancellation_scope_delivery: false,
8611            cooperative_registration_confirmed: Arc::new(AtomicBool::new(false)),
8612            nexus_registration_confirmed: Arc::new(AtomicBool::new(false)),
8613            local_registration_confirmed: Arc::new(AtomicBool::new(false)),
8614            session_registration_confirmed: Arc::new(AtomicBool::new(false)),
8615            sticky_registration_confirmed: Arc::new(AtomicBool::new(false)),
8616            require_query_task_authority: false,
8617            query_authority_confirmed: Arc::new(AtomicBool::new(false)),
8618            resource_capabilities: Vec::new(),
8619            sessions: Arc::new(Mutex::new(HashMap::new())),
8620            signal_external_workflow_supported: Arc::new(AtomicBool::new(false)),
8621        }
8622    }
8623
8624    /// Record the workflow commands the polling Server advertises, so
8625    /// workflow code can refuse an unadvertised command before submitting it.
8626    fn observe_workflow_poll_capabilities(&self, capabilities: Option<&Value>) {
8627        self.signal_external_workflow_supported.store(
8628            external_signal::runtime_supports(capabilities),
8629            Ordering::SeqCst,
8630        );
8631    }
8632
8633    pub fn worker_id(mut self, worker_id: impl Into<String>) -> Self {
8634        self.worker_id = worker_id.into();
8635        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
8636        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
8637        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
8638        self.session_registration_confirmed = Arc::new(AtomicBool::new(false));
8639        self.sticky_registration_confirmed = Arc::new(AtomicBool::new(false));
8640        self.query_authority_confirmed = Arc::new(AtomicBool::new(false));
8641        self.client.reset_sticky_cache();
8642        self.sessions = Arc::new(Mutex::new(HashMap::new()));
8643        self
8644    }
8645
8646    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
8647        self.poll_timeout = timeout;
8648        self
8649    }
8650
8651    /// Opt in to execution spans using application-owned OpenTelemetry providers.
8652    /// No exporter, logging bridge, global provider or Server carrier is installed.
8653    #[cfg(feature = "telemetry")]
8654    pub fn telemetry(mut self, telemetry: telemetry::ExecutionTelemetry) -> Self {
8655        self.client.execution_telemetry = Some(telemetry.clone());
8656        self.telemetry = Some(telemetry);
8657        self
8658    }
8659
8660    pub fn heartbeat_interval(mut self, interval: Duration) -> Self {
8661        self.heartbeat_interval = interval;
8662        self
8663    }
8664
8665    /// Require original query timing and non-renewing runtime observation.
8666    ///
8667    /// Registration refuses before creating a Worker unless protocol 1.20 and
8668    /// the runtime's `query_task_authority` capability are available. By default,
8669    /// older Servers retain their weaker, disclosed local-timing behavior.
8670    pub fn require_query_task_authority(mut self, required: bool) -> Self {
8671        self.require_query_task_authority = required;
8672        self
8673    }
8674
8675    /// Explicitly enable inline local activities in this workflow worker.
8676    ///
8677    /// The worker advertises the capability to Server only when enabled.
8678    /// These callbacks must yield to Tokio and have idempotent side effects.
8679    /// Cooperative prepared local supervision is a separate capability.
8680    pub fn local_activities(mut self, enabled: bool) -> Self {
8681        self.client.local_activities_enabled = enabled;
8682        self.local_registration_confirmed = Arc::new(AtomicBool::new(false));
8683        self
8684    }
8685
8686    /// Opt in to separate cooperative workflow cancellation requests.
8687    ///
8688    /// Registration requires the Server to acknowledge this exact worker,
8689    /// namespace, queue and capabilities with compatible protocol 1.20. Task
8690    /// processing uses canonical delivery and activity ownership fences.
8691    /// Existing terminal cancel and terminate operations remain terminal.
8692    /// The default is disabled. Protocol 1.20 alone does not enable cooperation.
8693    /// Call [`Worker::register`] before [`Worker::run_once`]. [`Worker::run`]
8694    /// and [`Worker::run_until`] register automatically.
8695    pub fn cooperative_cancellation(mut self, enabled: bool) -> Self {
8696        self.cooperative_cancellation_enabled = enabled;
8697        self.client.cooperative_worker_protocol = enabled;
8698        self.cooperative_registration_confirmed = Arc::new(AtomicBool::new(false));
8699        self.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
8700        if !enabled {
8701            self.nexus_cooperative_cancellation_enabled = false;
8702        }
8703        self
8704    }
8705
8706    /// Opt in to cooperative Nexus completion waits on an installed workflow binding.
8707    ///
8708    /// This also enables ordinary cooperative cancellation. Registration checks
8709    /// protocol 1.20 and Server's installed `workflow_run` bridge before advertising.
8710    pub fn nexus_cooperative_cancellation(self, enabled: bool) -> Self {
8711        let mut worker = if enabled {
8712            self.cooperative_cancellation(true)
8713        } else {
8714            self
8715        };
8716        worker.nexus_cooperative_cancellation_enabled = enabled;
8717        worker.nexus_registration_confirmed = Arc::new(AtomicBool::new(false));
8718        worker
8719    }
8720
8721    /// Enable candidate scope authoring without advertising scoped execution.
8722    #[doc(hidden)]
8723    pub fn candidate_cancellation_scope_authoring(mut self, enabled: bool) -> Self {
8724        self.allow_cancellation_scope_authoring = enabled;
8725        self
8726    }
8727
8728    /// Enable the candidate scoped call consumer with canonical authoring.
8729    #[doc(hidden)]
8730    pub fn candidate_cancellation_scope_delivery(mut self, enabled: bool) -> Self {
8731        self.allow_cancellation_scope_delivery = enabled;
8732        self
8733    }
8734
8735    /// Configure bounded retries for task-poll acquisition and worker heartbeats.
8736    pub fn retry_policy(mut self, policy: WorkerRetryPolicy) -> Self {
8737        self.retry_policy = policy;
8738        self
8739    }
8740
8741    /// Keep `run` and `run_until` alive through transient Server outages.
8742    ///
8743    /// Enabled by default. A transient failure is a connection refused, reset
8744    /// or timed out; an upstream 502/503/504 without a protocol body; a 503
8745    /// whose reason is `storage_unavailable` or `backend_unavailable`; or any
8746    /// 5xx or 429 that says `retryable: true`. Poll and heartbeat retries keep
8747    /// going past the [`WorkerRetryPolicy`] budget for these, and a poll keeps
8748    /// its request identity. A transient that still escapes a poll lane or
8749    /// registration (for example a task settlement) is logged with `tracing`
8750    /// and retried after a jittered wait, uniform in
8751    /// `[0, min(4 s, 0.25 s * 2^(n-1))]` for the n-th consecutive failure.
8752    /// Shutdown interrupts every wait. An explicit `retryable: false`, 401,
8753    /// 403, other protocol refusals, codec and handler failures stop the worker
8754    /// with a `tracing` error event and are returned.
8755    ///
8756    /// Activity completions, failures and `worker_lost` releases that hit a
8757    /// transient are resent unchanged while the lease lasts; the Server's
8758    /// answer to a copy it already recorded counts as recorded.
8759    ///
8760    /// Unlike the Python SDK, whose pollers retry 401 and 403 so credentials
8761    /// can rotate, this worker (like PHP's) stops on them after logging.
8762    ///
8763    /// Pass `false` to restore the bounded contract: the worker returns the
8764    /// error once the retry budget is spent. `run_once` always remains bounded.
8765    /// `max_retries = 0` disables retries, even when this option is enabled.
8766    pub fn recover_transient_outages(mut self, enabled: bool) -> Self {
8767        self.recover_transient_outages = enabled;
8768        self
8769    }
8770
8771    pub fn on_worker_heartbeat<F>(mut self, observer: F) -> Self
8772    where
8773        F: Fn(&WorkerHeartbeatObservation) + Send + Sync + 'static,
8774    {
8775        self.heartbeat_observer = Some(Arc::new(observer));
8776        self
8777    }
8778
8779    /// Bound simultaneous claimed workflow tasks, including loading and settlement.
8780    /// Defaults to 10. Use 1 for serial workflow-task execution.
8781    pub fn max_concurrent_workflow_tasks(mut self, count: usize) -> Self {
8782        self.max_concurrent_workflow_tasks = count.clamp(1, tokio::sync::Semaphore::MAX_PERMITS);
8783        self.workflow_capacity =
8784            worker_capacity::TaskCapacity::new(self.max_concurrent_workflow_tasks);
8785        self
8786    }
8787
8788    /// Bound simultaneous remote activity tasks, including loading and settlement.
8789    /// Defaults to 10. Use 1 for serial activity-task execution.
8790    pub fn max_concurrent_activity_tasks(mut self, count: usize) -> Self {
8791        self.max_concurrent_activity_tasks = count.clamp(1, tokio::sync::Semaphore::MAX_PERMITS);
8792        self.activity_capacity =
8793            worker_capacity::TaskCapacity::new(self.max_concurrent_activity_tasks);
8794        self
8795    }
8796
8797    /// Validate local handler admission without making a Server request.
8798    ///
8799    /// Registration methods retain their existing signatures. A duplicate keeps
8800    /// the original handler and makes this Worker invalid, including its clones.
8801    /// `register`, `run`, `run_until` and `run_once` enforce this check before
8802    /// any network request. Build a new Worker to correct an invalid configuration.
8803    pub fn validate_registration(&self) -> std::result::Result<(), DuplicateRegistrationError> {
8804        match &self.registration_error {
8805            Some(error) => Err(error.clone()),
8806            None => Ok(()),
8807        }
8808    }
8809
8810    #[track_caller]
8811    fn admit_registration<F>(
8812        &mut self,
8813        handler_kind: RegistrationKind,
8814        workflow_type: Option<&str>,
8815        handler_name: &str,
8816        method: &'static str,
8817    ) -> bool {
8818        let location = std::panic::Location::caller();
8819        let definition = HandlerRegistration {
8820            method,
8821            handler_type: type_name::<F>(),
8822            file: location.file(),
8823            line: location.line(),
8824            column: location.column(),
8825        };
8826        let key = (
8827            handler_kind,
8828            workflow_type.map(str::to_owned),
8829            handler_name.to_owned(),
8830        );
8831        if let Some(first_definition) = self.registration_definitions.get(&key) {
8832            if self.registration_error.is_none() {
8833                self.registration_error = Some(DuplicateRegistrationError {
8834                    handler_kind,
8835                    workflow_type: key.1.clone(),
8836                    handler_name: key.2.clone(),
8837                    first_definition: first_definition.clone(),
8838                    second_definition: definition,
8839                });
8840            }
8841            return false;
8842        }
8843        self.registration_definitions.insert(key, definition);
8844        true
8845    }
8846
8847    /// Register a workflow handler.
8848    ///
8849    /// An uncaught [`enum@Error`] returned by the handler fails the workflow run and
8850    /// is reported to clients as [`Error::WorkflowFailed`]. Errors that occur
8851    /// while acquiring or decoding a worker task remain worker-operation
8852    /// failures and do not get converted into workflow outcomes.
8853    #[track_caller]
8854    pub fn register_workflow<F, Fut>(&mut self, workflow_type: impl Into<String>, handler: F)
8855    where
8856        F: Fn(WorkflowContext, Value) -> Fut + Send + Sync + 'static,
8857        Fut: Future<Output = Result<Value>> + Send + 'static,
8858    {
8859        let workflow_type = workflow_type.into();
8860        if !self.admit_registration::<F>(
8861            RegistrationKind::Workflow,
8862            None,
8863            &workflow_type,
8864            "register_workflow",
8865        ) {
8866            return;
8867        }
8868        let handler = Arc::new(handler);
8869        self.workflows.insert(
8870            workflow_type,
8871            RegisteredWorkflow {
8872                execute: Arc::new(move |ctx, input| {
8873                    let handler = Arc::clone(&handler);
8874                    Ok(Box::pin(async move {
8875                        let result = handler(ctx, input.into_json()?).await?;
8876                        AvroValue::from_serialize(&result)
8877                    }))
8878                }),
8879                replay: None,
8880                state_type: None,
8881                definition_fingerprint: None,
8882            },
8883        );
8884    }
8885
8886    /// Register a workflow with one Serde request value and a Serde result.
8887    ///
8888    /// This is an ergonomic adapter over the same fixed Avro Value protocol as
8889    /// [`Worker::register_workflow_avro_value`]. It does not create or publish a
8890    /// workflow-specific schema. A task must contain zero arguments for a unit
8891    /// request or exactly one argument for every other request type.
8892    ///
8893    /// See the runnable
8894    /// [`hello_world` example](https://github.com/durable-workflow/sdk-rust/blob/main/examples/hello_world.rs)
8895    /// for typed workflow and activity contracts with retry and timeout policy.
8896    #[track_caller]
8897    pub fn register_typed_workflow<I, O, F, Fut>(
8898        &mut self,
8899        workflow_type: impl Into<String>,
8900        handler: F,
8901    ) where
8902        I: DeserializeOwned + Send + 'static,
8903        O: Serialize + Send + 'static,
8904        F: Fn(WorkflowContext, I) -> Fut + Send + Sync + 'static,
8905        Fut: Future<Output = Result<O>> + Send + 'static,
8906    {
8907        let workflow_type = workflow_type.into();
8908        if !self.admit_registration::<F>(
8909            RegistrationKind::Workflow,
8910            None,
8911            &workflow_type,
8912            "register_typed_workflow",
8913        ) {
8914            return;
8915        }
8916        let handler_name = workflow_type.clone();
8917        let handler = Arc::new(handler);
8918        self.workflows.insert(
8919            workflow_type,
8920            RegisteredWorkflow {
8921                execute: Arc::new(move |ctx, input| {
8922                    let input = decode_workflow_entry::<I>(input, &handler_name)?;
8923                    let handler = Arc::clone(&handler);
8924                    let handler_name = handler_name.clone();
8925                    Ok(Box::pin(async move {
8926                        let result = handler(ctx, input).await?;
8927                        encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
8928                    }))
8929                }),
8930                replay: None,
8931                state_type: None,
8932                definition_fingerprint: None,
8933            },
8934        );
8935    }
8936
8937    /// Register a workflow on the lossless fixed Avro Value surface.
8938    #[track_caller]
8939    pub fn register_workflow_avro_value<F, Fut>(
8940        &mut self,
8941        workflow_type: impl Into<String>,
8942        handler: F,
8943    ) where
8944        F: Fn(WorkflowContext, AvroValue) -> Fut + Send + Sync + 'static,
8945        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
8946    {
8947        let workflow_type = workflow_type.into();
8948        if !self.admit_registration::<F>(
8949            RegistrationKind::Workflow,
8950            None,
8951            &workflow_type,
8952            "register_workflow_avro_value",
8953        ) {
8954            return;
8955        }
8956        self.workflows.insert(
8957            workflow_type,
8958            RegisteredWorkflow {
8959                execute: Arc::new(move |ctx, input| Ok(Box::pin(handler(ctx, input)))),
8960                replay: None,
8961                state_type: None,
8962                definition_fingerprint: None,
8963            },
8964        );
8965    }
8966
8967    /// Register a workflow whose typed instance state can be reconstructed for queries.
8968    ///
8969    /// `state_factory` creates a fresh instance for every normal workflow task and
8970    /// query replay. The workflow handler is the single source of truth for state
8971    /// transitions: it updates [`WorkflowInstance`] after activities and signals
8972    /// resolve. Query replay runs this same handler over committed history and
8973    /// discards any commands it would emit.
8974    #[track_caller]
8975    pub fn register_replayed_workflow<S, Factory, F, Fut>(
8976        &mut self,
8977        workflow_type: impl Into<String>,
8978        state_factory: Factory,
8979        handler: F,
8980    ) where
8981        S: Clone + Send + Sync + 'static,
8982        Factory: Fn() -> S + Send + Sync + 'static,
8983        F: Fn(WorkflowContext, Value, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
8984        Fut: Future<Output = Result<Value>> + Send + 'static,
8985    {
8986        let workflow_type = workflow_type.into();
8987        if !self.admit_registration::<F>(
8988            RegistrationKind::Workflow,
8989            None,
8990            &workflow_type,
8991            "register_replayed_workflow",
8992        ) {
8993            return;
8994        }
8995        let state_factory = Arc::new(state_factory);
8996        let handler = Arc::new(handler);
8997
8998        let execute_factory = Arc::clone(&state_factory);
8999        let execute_handler = Arc::clone(&handler);
9000        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
9001            let state = WorkflowInstance::new(execute_factory());
9002            let handler = Arc::clone(&execute_handler);
9003            Ok(Box::pin(async move {
9004                let result = handler(ctx, input.into_json()?, state).await?;
9005                AvroValue::from_serialize(&result)
9006            }) as WorkflowFuture)
9007        });
9008
9009        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
9010            let state = WorkflowInstance::new(state_factory());
9011            let snapshot_state = state.clone();
9012            let snapshot: WorkflowStateSnapshot =
9013                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
9014            let replay_handler = Arc::clone(&handler);
9015            let future = async move {
9016                let result = replay_handler(ctx, input.into_json()?, state).await?;
9017                AvroValue::from_serialize(&result)
9018            };
9019            Ok(ReplayedWorkflowInvocation {
9020                future: Box::pin(future),
9021                snapshot,
9022            })
9023        });
9024
9025        self.workflows.insert(
9026            workflow_type,
9027            RegisteredWorkflow {
9028                execute,
9029                replay: Some(replay),
9030                state_type: Some(TypeId::of::<S>()),
9031                definition_fingerprint: None,
9032            },
9033        );
9034    }
9035
9036    /// Register a replayable workflow with one Serde request value and result.
9037    ///
9038    /// Normal task execution and instance-state query replay both decode and
9039    /// encode through the fixed Avro Value codec. The state factory and handler
9040    /// otherwise follow [`Worker::register_replayed_workflow`].
9041    #[track_caller]
9042    pub fn register_typed_replayed_workflow<I, O, S, Factory, F, Fut>(
9043        &mut self,
9044        workflow_type: impl Into<String>,
9045        state_factory: Factory,
9046        handler: F,
9047    ) where
9048        I: DeserializeOwned + Send + 'static,
9049        O: Serialize + Send + 'static,
9050        S: Clone + Send + Sync + 'static,
9051        Factory: Fn() -> S + Send + Sync + 'static,
9052        F: Fn(WorkflowContext, I, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
9053        Fut: Future<Output = Result<O>> + Send + 'static,
9054    {
9055        let workflow_type = workflow_type.into();
9056        if !self.admit_registration::<F>(
9057            RegistrationKind::Workflow,
9058            None,
9059            &workflow_type,
9060            "register_typed_replayed_workflow",
9061        ) {
9062            return;
9063        }
9064        let state_factory = Arc::new(state_factory);
9065        let handler = Arc::new(handler);
9066
9067        let execute_name = workflow_type.clone();
9068        let execute_factory = Arc::clone(&state_factory);
9069        let execute_handler = Arc::clone(&handler);
9070        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
9071            let input = decode_workflow_entry::<I>(input, &execute_name)?;
9072            let state = WorkflowInstance::new(execute_factory());
9073            let handler = Arc::clone(&execute_handler);
9074            let handler_name = execute_name.clone();
9075            Ok(Box::pin(async move {
9076                let result = handler(ctx, input, state).await?;
9077                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
9078            }) as WorkflowFuture)
9079        });
9080
9081        let replay_name = workflow_type.clone();
9082        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
9083            let input = decode_workflow_entry::<I>(input, &replay_name)?;
9084            let state = WorkflowInstance::new(state_factory());
9085            let snapshot_state = state.clone();
9086            let snapshot: WorkflowStateSnapshot =
9087                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
9088            let handler = Arc::clone(&handler);
9089            let handler_name = replay_name.clone();
9090            let future = async move {
9091                let result = handler(ctx, input, state).await?;
9092                encode_handler_result(&result, HandlerKind::Workflow, &handler_name)
9093            };
9094            Ok(ReplayedWorkflowInvocation {
9095                future: Box::pin(future),
9096                snapshot,
9097            })
9098        });
9099
9100        self.workflows.insert(
9101            workflow_type,
9102            RegisteredWorkflow {
9103                execute,
9104                replay: Some(replay),
9105                state_type: Some(TypeId::of::<S>()),
9106                definition_fingerprint: None,
9107            },
9108        );
9109    }
9110
9111    /// Declare the signal names consumed by a registered workflow.
9112    ///
9113    /// Call this after registering the workflow and before starting the worker.
9114    /// Names read through `wait_signal` or `signals` need a declaration for
9115    /// Server command admission. Arguments remain arbitrary positional values,
9116    /// including lossless Avro values. This replaces the previous declaration;
9117    /// an empty slice declares no signals. Names are sorted and deduplicated.
9118    /// Existing runs retain the declarations captured when they started.
9119    pub fn declare_workflow_signals(
9120        &mut self,
9121        workflow_type: &str,
9122        signal_names: &[&str],
9123    ) -> Result<()> {
9124        if !self.workflows.contains_key(workflow_type) {
9125            return Err(Error::Codec(format!(
9126                "workflow type {workflow_type:?} is not registered"
9127            )));
9128        }
9129        if signal_names
9130            .iter()
9131            .any(|name| name.is_empty() || *name != name.trim())
9132        {
9133            return Err(Error::Codec(
9134                "signal names must be non-empty and have no surrounding whitespace".into(),
9135            ));
9136        }
9137        let mut names = signal_names
9138            .iter()
9139            .map(|name| (*name).to_string())
9140            .collect::<Vec<_>>();
9141        names.sort();
9142        names.dedup();
9143        self.signals.insert(workflow_type.to_string(), names);
9144        Ok(())
9145    }
9146
9147    /// Bind a registered workflow to compile-time embedded source for safe redrive.
9148    ///
9149    /// Supply `include_str!` values for the workflow body and every helper whose
9150    /// behavior can affect replay. Register the workflow once, then set its
9151    /// identity before starting the worker. Duplicate registrations are invalid. The server
9152    /// rejects reusing a worker ID when its prior fingerprint disappears.
9153    /// Workflows without source identity remain runnable but cannot be safely redriven.
9154    /// For example, pass `&[include_str!("workflows.rs")]` when the handler and
9155    /// replay-sensitive helpers are in a sibling `workflows.rs` file.
9156    pub fn set_workflow_definition_sources(
9157        &mut self,
9158        workflow_type: &str,
9159        sources: &[&str],
9160    ) -> Result<()> {
9161        if sources.is_empty() || sources.iter().any(|source| source.is_empty()) {
9162            return Err(Error::Codec(
9163                "workflow definition sources must be non-empty".to_string(),
9164            ));
9165        }
9166        let workflow = self.workflows.get_mut(workflow_type).ok_or_else(|| {
9167            Error::Codec(format!("workflow type {workflow_type:?} is not registered"))
9168        })?;
9169        let mut hasher = Sha256::new();
9170        hasher.update(b"durable-workflow-rust.workflow-definition.v1\0");
9171        hasher.update((workflow_type.len() as u64).to_be_bytes());
9172        hasher.update(workflow_type.as_bytes());
9173        for source in sources {
9174            hasher.update((source.len() as u64).to_be_bytes());
9175            hasher.update(source.as_bytes());
9176        }
9177        workflow.definition_fingerprint = Some(format!("sha256:{:x}", hasher.finalize()));
9178        Ok(())
9179    }
9180
9181    /// Register a replayable workflow on the lossless fixed Avro Value surface.
9182    #[track_caller]
9183    pub fn register_replayed_workflow_avro_value<S, Factory, F, Fut>(
9184        &mut self,
9185        workflow_type: impl Into<String>,
9186        state_factory: Factory,
9187        handler: F,
9188    ) where
9189        S: Clone + Send + Sync + 'static,
9190        Factory: Fn() -> S + Send + Sync + 'static,
9191        F: Fn(WorkflowContext, AvroValue, WorkflowInstance<S>) -> Fut + Send + Sync + 'static,
9192        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
9193    {
9194        let workflow_type = workflow_type.into();
9195        if !self.admit_registration::<F>(
9196            RegistrationKind::Workflow,
9197            None,
9198            &workflow_type,
9199            "register_replayed_workflow_avro_value",
9200        ) {
9201            return;
9202        }
9203        let state_factory = Arc::new(state_factory);
9204        let handler = Arc::new(handler);
9205
9206        let execute_factory = Arc::clone(&state_factory);
9207        let execute_handler = Arc::clone(&handler);
9208        let execute = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
9209            let state = WorkflowInstance::new(execute_factory());
9210            Ok(Box::pin(execute_handler(ctx, input, state)) as WorkflowFuture)
9211        });
9212
9213        let replay = Arc::new(move |ctx: WorkflowContext, input: AvroValue| {
9214            let state = WorkflowInstance::new(state_factory());
9215            let snapshot_state = state.clone();
9216            let snapshot: WorkflowStateSnapshot =
9217                Arc::new(move || Ok(Arc::new(snapshot_state.snapshot()?) as ErasedWorkflowState));
9218            Ok(ReplayedWorkflowInvocation {
9219                future: Box::pin(handler(ctx, input, state)),
9220                snapshot,
9221            })
9222        });
9223
9224        self.workflows.insert(
9225            workflow_type,
9226            RegisteredWorkflow {
9227                execute,
9228                replay: Some(replay),
9229                state_type: Some(TypeId::of::<S>()),
9230                definition_fingerprint: None,
9231            },
9232        );
9233    }
9234
9235    #[track_caller]
9236    pub fn register_activity<F, Fut>(&mut self, activity_type: impl Into<String>, handler: F)
9237    where
9238        F: Fn(ActivityContext, Value) -> Fut + Send + Sync + 'static,
9239        Fut: Future<Output = Result<Value>> + Send + 'static,
9240    {
9241        let activity_type = activity_type.into();
9242        if !self.admit_registration::<F>(
9243            RegistrationKind::Activity,
9244            None,
9245            &activity_type,
9246            "register_activity",
9247        ) {
9248            return;
9249        }
9250        let handler = Arc::new(handler);
9251        self.activities.insert(
9252            activity_type,
9253            Arc::new(move |ctx, args| {
9254                let handler = Arc::clone(&handler);
9255                Box::pin(async move {
9256                    let result = handler(ctx, args.into_json()?).await?;
9257                    AvroValue::from_serialize(&result)
9258                })
9259            }),
9260        );
9261    }
9262
9263    /// Register an activity with one Serde request value and a Serde result.
9264    ///
9265    /// Inputs and results use the platform's fixed Avro Value schema. Shape
9266    /// mismatches and unsupported Serde values return [`Error::HandlerType`]
9267    /// with the activity name and Rust type.
9268    #[track_caller]
9269    pub fn register_typed_activity<I, O, F, Fut>(
9270        &mut self,
9271        activity_type: impl Into<String>,
9272        handler: F,
9273    ) where
9274        I: DeserializeOwned + Send + 'static,
9275        O: Serialize + Send + 'static,
9276        F: Fn(ActivityContext, I) -> Fut + Send + Sync + 'static,
9277        Fut: Future<Output = Result<O>> + Send + 'static,
9278    {
9279        let activity_type = activity_type.into();
9280        if !self.admit_registration::<F>(
9281            RegistrationKind::Activity,
9282            None,
9283            &activity_type,
9284            "register_typed_activity",
9285        ) {
9286            return;
9287        }
9288        let handler_name = activity_type.clone();
9289        let handler = Arc::new(handler);
9290        self.activities.insert(
9291            activity_type,
9292            Arc::new(move |ctx, input| {
9293                let handler = Arc::clone(&handler);
9294                let handler_name = handler_name.clone();
9295                Box::pin(async move {
9296                    let input =
9297                        decode_handler_input::<I>(input, HandlerKind::Activity, &handler_name)?;
9298                    let result = handler(ctx, input).await?;
9299                    encode_handler_result(&result, HandlerKind::Activity, &handler_name)
9300                })
9301            }),
9302        );
9303    }
9304
9305    /// Register an activity on the lossless fixed Avro Value surface.
9306    #[track_caller]
9307    pub fn register_activity_avro_value<F, Fut>(
9308        &mut self,
9309        activity_type: impl Into<String>,
9310        handler: F,
9311    ) where
9312        F: Fn(ActivityContext, AvroValue) -> Fut + Send + Sync + 'static,
9313        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
9314    {
9315        let activity_type = activity_type.into();
9316        if !self.admit_registration::<F>(
9317            RegistrationKind::Activity,
9318            None,
9319            &activity_type,
9320            "register_activity_avro_value",
9321        ) {
9322            return;
9323        }
9324        self.activities.insert(
9325            activity_type,
9326            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
9327        );
9328    }
9329
9330    /// Register a named, read-only query handler for a workflow type.
9331    ///
9332    /// The workflow type must also be registered with [`Worker::register_workflow`]
9333    /// before the worker runs. The handler receives only an immutable committed
9334    /// state snapshot and normalized query arguments.
9335    #[track_caller]
9336    pub fn register_query<F, Fut>(
9337        &mut self,
9338        workflow_type: impl Into<String>,
9339        query_name: impl Into<String>,
9340        handler: F,
9341    ) where
9342        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
9343        Fut: Future<Output = Result<Value>> + Send + 'static,
9344    {
9345        let workflow_type = workflow_type.into();
9346        let query_name = query_name.into();
9347        if !self.admit_registration::<F>(
9348            RegistrationKind::Query,
9349            Some(&workflow_type),
9350            &query_name,
9351            "register_query",
9352        ) {
9353            return;
9354        }
9355        let handler = Arc::new(handler);
9356        self.queries.entry(workflow_type).or_default().insert(
9357            query_name,
9358            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| {
9359                let handler = Arc::clone(&handler);
9360                Box::pin(async move {
9361                    let result = handler(ctx, args.into_json()?).await?;
9362                    AvroValue::from_serialize(&result)
9363                })
9364            })),
9365        );
9366    }
9367
9368    /// Register a query handler on the lossless fixed Avro Value surface.
9369    #[track_caller]
9370    pub fn register_query_avro_value<F, Fut>(
9371        &mut self,
9372        workflow_type: impl Into<String>,
9373        query_name: impl Into<String>,
9374        handler: F,
9375    ) where
9376        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
9377        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
9378    {
9379        let workflow_type = workflow_type.into();
9380        let query_name = query_name.into();
9381        if !self.admit_registration::<F>(
9382            RegistrationKind::Query,
9383            Some(&workflow_type),
9384            &query_name,
9385            "register_query_avro_value",
9386        ) {
9387            return;
9388        }
9389        self.queries.entry(workflow_type).or_default().insert(
9390            query_name,
9391            RegisteredQuery::Snapshot(Arc::new(move |ctx, args| Box::pin(handler(ctx, args)))),
9392        );
9393    }
9394
9395    /// Register a named query against deterministically replayed instance state.
9396    ///
9397    /// The workflow type must use [`Worker::register_replayed_workflow`] with the
9398    /// same state type `S`. The handler receives an immutable, detached state
9399    /// clone, so successful and failed queries cannot affect workflow execution
9400    /// or the state reconstructed by a later query.
9401    #[track_caller]
9402    pub fn register_replayed_query<S, F, Fut>(
9403        &mut self,
9404        workflow_type: impl Into<String>,
9405        query_name: impl Into<String>,
9406        handler: F,
9407    ) where
9408        S: Clone + Send + Sync + 'static,
9409        F: Fn(QueryContext, Arc<S>, Value) -> Fut + Send + Sync + 'static,
9410        Fut: Future<Output = Result<Value>> + Send + 'static,
9411    {
9412        let workflow_type = workflow_type.into();
9413        let query_name = query_name.into();
9414        if !self.admit_registration::<F>(
9415            RegistrationKind::Query,
9416            Some(&workflow_type),
9417            &query_name,
9418            "register_replayed_query",
9419        ) {
9420            return;
9421        }
9422        let handler = Arc::new(handler);
9423        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
9424            let state = state.downcast::<S>().map_err(|_| {
9425                "registered query state type does not match the replayed workflow state".to_string()
9426            })?;
9427            let handler = Arc::clone(&handler);
9428            Ok(Box::pin(async move {
9429                let result = handler(ctx, state, args.into_json()?).await?;
9430                AvroValue::from_serialize(&result)
9431            }))
9432        });
9433
9434        self.queries.entry(workflow_type).or_default().insert(
9435            query_name,
9436            RegisteredQuery::Replayed {
9437                state_type: TypeId::of::<S>(),
9438                handler: erased_handler,
9439            },
9440        );
9441    }
9442
9443    /// Register a replayed-state query on the lossless fixed Avro Value surface.
9444    #[track_caller]
9445    pub fn register_replayed_query_avro_value<S, F, Fut>(
9446        &mut self,
9447        workflow_type: impl Into<String>,
9448        query_name: impl Into<String>,
9449        handler: F,
9450    ) where
9451        S: Clone + Send + Sync + 'static,
9452        F: Fn(QueryContext, Arc<S>, AvroValue) -> Fut + Send + Sync + 'static,
9453        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
9454    {
9455        let workflow_type = workflow_type.into();
9456        let query_name = query_name.into();
9457        if !self.admit_registration::<F>(
9458            RegistrationKind::Query,
9459            Some(&workflow_type),
9460            &query_name,
9461            "register_replayed_query_avro_value",
9462        ) {
9463            return;
9464        }
9465        let handler = Arc::new(handler);
9466        let erased_handler: ReplayedQueryHandler = Arc::new(move |ctx, state, args| {
9467            let state = state.downcast::<S>().map_err(|_| {
9468                "registered query state type does not match the replayed workflow state".to_string()
9469            })?;
9470            Ok(Box::pin(handler(ctx, state, args)))
9471        });
9472
9473        self.queries.entry(workflow_type).or_default().insert(
9474            query_name,
9475            RegisteredQuery::Replayed {
9476                state_type: TypeId::of::<S>(),
9477                handler: erased_handler,
9478            },
9479        );
9480    }
9481
9482    /// Register a synchronous workflow update handler.
9483    #[track_caller]
9484    pub fn register_update<F, Fut>(
9485        &mut self,
9486        workflow_type: impl Into<String>,
9487        update_name: impl Into<String>,
9488        handler: F,
9489    ) where
9490        F: Fn(QueryContext, Value) -> Fut + Send + Sync + 'static,
9491        Fut: Future<Output = Result<Value>> + Send + 'static,
9492    {
9493        let workflow_type = workflow_type.into();
9494        let update_name = update_name.into();
9495        if !self.admit_registration::<F>(
9496            RegistrationKind::Update,
9497            Some(&workflow_type),
9498            &update_name,
9499            "register_update",
9500        ) {
9501            return;
9502        }
9503        let handler = Arc::new(handler);
9504        self.updates.entry(workflow_type).or_default().insert(
9505            update_name,
9506            Arc::new(move |ctx, args| {
9507                let handler = Arc::clone(&handler);
9508                Box::pin(async move {
9509                    let result = handler(ctx, args.into_json()?).await?;
9510                    AvroValue::from_serialize(&result)
9511                })
9512            }),
9513        );
9514    }
9515
9516    /// Register an update handler on the lossless fixed Avro Value surface.
9517    #[track_caller]
9518    pub fn register_update_avro_value<F, Fut>(
9519        &mut self,
9520        workflow_type: impl Into<String>,
9521        update_name: impl Into<String>,
9522        handler: F,
9523    ) where
9524        F: Fn(QueryContext, AvroValue) -> Fut + Send + Sync + 'static,
9525        Fut: Future<Output = Result<AvroValue>> + Send + 'static,
9526    {
9527        let workflow_type = workflow_type.into();
9528        let update_name = update_name.into();
9529        if !self.admit_registration::<F>(
9530            RegistrationKind::Update,
9531            Some(&workflow_type),
9532            &update_name,
9533            "register_update_avro_value",
9534        ) {
9535            return;
9536        }
9537        self.updates.entry(workflow_type).or_default().insert(
9538            update_name,
9539            Arc::new(move |ctx, args| Box::pin(handler(ctx, args))),
9540        );
9541    }
9542
9543    pub async fn register(&self) -> Result<RegisterWorkerResponse> {
9544        self.validate_registration()?;
9545        self.nexus_registration_confirmed
9546            .store(false, Ordering::SeqCst);
9547        self.query_authority_confirmed
9548            .store(false, Ordering::SeqCst);
9549        if self.nexus_cooperative_cancellation_enabled {
9550            let info: Value = self
9551                .client
9552                .retry_cluster_info(|| {
9553                    self.client.request_json(
9554                        reqwest::Method::GET,
9555                        "/cluster/info",
9556                        RequestProtocol::Worker("1.20"),
9557                        Option::<&Value>::None,
9558                    )
9559                })
9560                .await?;
9561            if !nexus::installed_cooperation(&info["worker_protocol"]["server_capabilities"]) {
9562                return Err(Error::CooperativeCancellationUnavailable(
9563                    "nexus_cooperative_cancellation_not_supported: Server must advertise the installed workflow_run bridge".into(),
9564                ));
9565            }
9566        }
9567        if self.require_query_task_authority {
9568            if self.client.worker_protocol_version != WorkerProtocolVersion::V120 {
9569                return Err(Error::WorkerLoop(
9570                    "query authority requires worker protocol 1.20".into(),
9571                ));
9572            }
9573            // Discovery uses the Worker credential, including worker-only Clients.
9574            let discovery: Value = self
9575                .client
9576                .retry_cluster_info(|| {
9577                    self.client
9578                        .request_json_unresolved_with_timeout::<Value, Value>(
9579                            reqwest::Method::GET,
9580                            "/cluster/info",
9581                            RequestProtocol::Worker("1.20"),
9582                            None,
9583                            Duration::from_secs(5),
9584                        )
9585                })
9586                .await?;
9587            if discovery["worker_protocol"]["server_capabilities"]["query_task_authority"] != true {
9588                return Err(Error::WorkerLoop(
9589                    "runtime does not advertise query_task_authority".into(),
9590                ));
9591            }
9592        }
9593        self.sticky_registration_confirmed
9594            .store(false, Ordering::SeqCst);
9595        self.session_registration_confirmed
9596            .store(false, Ordering::SeqCst);
9597        for capability in &self.resource_capabilities {
9598            worker_session::validate_resource_capability(capability)?;
9599        }
9600        self.local_registration_confirmed
9601            .store(false, Ordering::SeqCst);
9602        if self.client.local_activities_enabled && self.cooperative_cancellation_enabled {
9603            return Err(Error::CooperativeCancellationUnavailable(
9604                "inline local activities cannot advertise prepared local supervision; use a separate ordinary worker for inline local callbacks".into(),
9605            ));
9606        }
9607        let mut command_contracts = serde_json::Map::new();
9608        for workflow_type in self.workflows.keys() {
9609            let mut queries = self
9610                .queries
9611                .get(workflow_type)
9612                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
9613                .unwrap_or_default();
9614            queries.sort();
9615            let mut updates = self
9616                .updates
9617                .get(workflow_type)
9618                .map(|handlers| handlers.keys().cloned().collect::<Vec<_>>())
9619                .unwrap_or_default();
9620            updates.sort();
9621            let signals = self.signals.get(workflow_type).cloned().unwrap_or_default();
9622            command_contracts.insert(
9623                workflow_type.clone(),
9624                json!({
9625                    "queries": queries,
9626                    "query_contracts": argument_vector_contracts(&queries),
9627                    "signals": signals,
9628                    "signal_contracts": argument_vector_contracts(&signals),
9629                    "updates": updates,
9630                    "update_contracts": argument_vector_contracts(&updates),
9631                    "update_validators": [],
9632                }),
9633            );
9634        }
9635
9636        self.cooperative_registration_confirmed
9637            .store(false, Ordering::SeqCst);
9638        #[cfg(feature = "telemetry")]
9639        if self
9640            .telemetry
9641            .as_ref()
9642            .is_some_and(telemetry::ExecutionTelemetry::is_enabled)
9643            && !self
9644                .client
9645                .observability_context_supported
9646                .load(Ordering::SeqCst)
9647        {
9648            // Optional startup discovery is bounded and cached. Its failure
9649            // cannot refuse registration or add retries to a business command.
9650            let _ = self
9651                .client
9652                .request_json_unresolved_with_timeout::<Value, Value>(
9653                    reqwest::Method::GET,
9654                    "/cluster/info",
9655                    RequestProtocol::DefaultWorker,
9656                    None,
9657                    Duration::from_secs(5),
9658                )
9659                .await;
9660        }
9661        let response = self
9662            .client
9663            .register_worker_with_definition_fingerprints(
9664                &self.worker_id,
9665                &self.task_queue,
9666                self.workflows.keys().cloned().collect(),
9667                self.activities.keys().cloned().collect(),
9668                self.max_concurrent_workflow_tasks,
9669                self.max_concurrent_activity_tasks,
9670                [
9671                    Some(CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY.to_string()),
9672                    Some("workflow_entry_arguments_validation".to_string()),
9673                    Some(DURABLE_SELECTION_CAPABILITY.to_string()),
9674                    Some(MEMO_UPSERTS_CAPABILITY.to_string()),
9675                    Some(TYPED_SEARCH_ATTRIBUTES_CAPABILITY.to_string()),
9676                    Some(activity_checkpoint::CAPABILITY.to_string()),
9677                    self.client
9678                        .local_activities_enabled
9679                        .then(|| "local_activities".to_string()),
9680                    self.client
9681                        .worker_sessions_enabled
9682                        .then(|| "worker_sessions".to_string()),
9683                    self.client
9684                        .sticky_cache
9685                        .is_some()
9686                        .then(|| "sticky_execution".to_string()),
9687                    self.client
9688                        .sticky_cache
9689                        .is_some()
9690                        .then(|| "sticky_history_suffix".to_string()),
9691                    self.cooperative_cancellation_enabled
9692                        .then(|| "cooperative_cancellation".to_string()),
9693                    self.nexus_cooperative_cancellation_enabled
9694                        .then(|| "nexus_cooperative_cancellation".to_string()),
9695                    (!self.queries.is_empty()).then(|| QUERY_TASKS_CAPABILITY.to_string()),
9696                    (!self.updates.is_empty()).then(|| WORKFLOW_UPDATES_CAPABILITY.to_string()),
9697                    worker_protocol_supports_message_streams(WORKER_PROTOCOL_VERSION)
9698                        .then(|| MESSAGE_STREAMS_CAPABILITY.to_string()),
9699                ]
9700                .into_iter()
9701                .flatten()
9702                .chain(self.resource_capabilities.iter().cloned())
9703                .collect(),
9704                Value::Object(command_contracts),
9705                Some(
9706                    self.workflows
9707                        .iter()
9708                        .filter_map(|(workflow_type, workflow)| {
9709                            workflow
9710                                .definition_fingerprint
9711                                .as_ref()
9712                                .map(|fingerprint| (workflow_type.clone(), fingerprint.clone()))
9713                        })
9714                        .collect(),
9715                ),
9716            )
9717            .await?;
9718        if self.cooperative_cancellation_enabled && response.registered {
9719            self.cooperative_registration_confirmed
9720                .store(true, Ordering::SeqCst);
9721        }
9722        if self.nexus_cooperative_cancellation_enabled && response.registered {
9723            self.nexus_registration_confirmed
9724                .store(true, Ordering::SeqCst);
9725        }
9726        if self.client.local_activities_enabled && response.registered {
9727            self.local_registration_confirmed
9728                .store(true, Ordering::SeqCst);
9729        }
9730        if self.client.worker_sessions_enabled && response.registered {
9731            self.session_registration_confirmed
9732                .store(true, Ordering::SeqCst);
9733        }
9734        if self.client.sticky_cache.is_some() && response.registered {
9735            self.sticky_registration_confirmed
9736                .store(true, Ordering::SeqCst);
9737        }
9738        self.query_authority_confirmed.store(
9739            response.registered
9740                && self.client.worker_protocol_version == WorkerProtocolVersion::V120
9741                && response
9742                    .server_capabilities
9743                    .as_ref()
9744                    .is_some_and(|capabilities| capabilities["query_task_authority"] == true),
9745            Ordering::SeqCst,
9746        );
9747        Ok(response)
9748    }
9749
9750    /// Run until shutdown or a terminal worker error occurs.
9751    ///
9752    /// Empty long-poll expirations do not stop the worker. Retryable poll and
9753    /// heartbeat failures use [`WorkerRetryPolicy`] independently. Transient
9754    /// Server outages never stop it while [`Worker::recover_transient_outages`]
9755    /// is on (the default); authentication, protocol and other non-retryable
9756    /// failures are logged and returned.
9757    pub async fn run(&self) -> Result<()> {
9758        self.run_until(std::future::pending::<()>()).await
9759    }
9760
9761    /// Run until `shutdown` resolves or a terminal worker error occurs.
9762    ///
9763    /// This has the same liveness and terminal-error contract as [`Worker::run`].
9764    pub async fn run_until<F>(&self, shutdown: F) -> Result<()>
9765    where
9766        F: Future<Output = ()>,
9767    {
9768        let _clear_cache_on_drop =
9769            sticky_worker::ClearCacheOnDrop(self.client.sticky_cache.clone());
9770        let stop = Arc::new(AtomicBool::new(false));
9771        let _stop_on_drop = StopWorkerOnDrop(Arc::clone(&stop));
9772        let mut worker = self.with_storage_admission(Arc::clone(&stop));
9773        worker.run_stop = Some(Arc::clone(&stop));
9774        let run = worker.run_with_storage_admission(Arc::clone(&stop));
9775        tokio::pin!(run);
9776        tokio::pin!(shutdown);
9777        tokio::select! {
9778            result = &mut run => result,
9779            _ = &mut shutdown => {
9780                stop.store(true, Ordering::SeqCst);
9781                run.await
9782            }
9783        }
9784    }
9785
9786    fn with_storage_admission(&self, stop: Arc<AtomicBool>) -> Self {
9787        let mut worker = self.clone();
9788        worker.client.worker_storage_admission = Some(WorkerStorageAdmission {
9789            policy: self.retry_policy,
9790            stop,
9791            workflow_completion_retry_deadline: None,
9792        });
9793        worker
9794    }
9795
9796    async fn run_with_storage_admission(&self, stop: Arc<AtomicBool>) -> Result<()> {
9797        let mut outage = Outage::default();
9798        let registration = loop {
9799            match self.register().await {
9800                Ok(registration) => break registration,
9801                Err(error) => {
9802                    // Shutdown during the wait still reports the refusal: the
9803                    // worker was never registered.
9804                    if !self.outlive_transient(&error, &mut outage, &stop).await {
9805                        return Err(error);
9806                    }
9807                }
9808            }
9809        };
9810        if !registration.registered {
9811            return Err(Error::WorkerLoop(format!(
9812                "worker registration for {:?} was not accepted",
9813                self.worker_id
9814            )));
9815        }
9816        let registered_worker_id = registration.worker_id.clone();
9817        let primary = self.run_registered_until(stop, registration).await;
9818        let primary = match (primary, self.close_worker_sessions().await) {
9819            (Ok(()), result) => result,
9820            (Err(error), Ok(())) => Err(error),
9821            (Err(primary), Err(close)) => Err(Error::WorkerShutdown {
9822                primary: Box::new(primary),
9823                deregistration: Box::new(close),
9824            }),
9825        };
9826        self.session_registration_confirmed
9827            .store(false, Ordering::SeqCst);
9828        self.cooperative_registration_confirmed
9829            .store(false, Ordering::SeqCst);
9830        self.local_registration_confirmed
9831            .store(false, Ordering::SeqCst);
9832        let deregistration = self
9833            .client
9834            .deregister_worker_registration(&registered_worker_id)
9835            .await;
9836        self.sticky_registration_confirmed
9837            .store(false, Ordering::SeqCst);
9838        self.client.clear_sticky_cache()?;
9839
9840        match (primary, deregistration) {
9841            (Ok(()), Ok(_)) => Ok(()),
9842            (Ok(()), Err(deregistration)) => Err(deregistration),
9843            (Err(primary), Ok(_)) => Err(primary),
9844            (Err(primary), Err(deregistration)) => Err(Error::WorkerShutdown {
9845                primary: Box::new(primary),
9846                deregistration: Box::new(deregistration),
9847            }),
9848        }
9849    }
9850
9851    async fn run_registered_until(
9852        &self,
9853        stop: Arc<AtomicBool>,
9854        registration: RegisterWorkerResponse,
9855    ) -> Result<()> {
9856        if self.require_query_task_authority
9857            && !self.query_authority_confirmed.load(Ordering::SeqCst)
9858        {
9859            return Err(Error::WorkerLoop(
9860                "registration did not confirm query_task_authority".into(),
9861            ));
9862        }
9863        let heartbeat_interval = Duration::from_secs(
9864            registration
9865                .heartbeat_interval_seconds
9866                .unwrap_or(self.heartbeat_interval.as_secs().max(1)),
9867        );
9868        // The first heartbeat is immediate. Subsequent heartbeats are scheduled
9869        // from the completion of the preceding attempt, including its bounded
9870        // retries. A fixed-epoch interval can leave an already-due tick queued
9871        // while an acknowledgement is slow, producing a catch-up heartbeat as
9872        // soon as that request completes.
9873        let heartbeat = tokio::time::sleep(Duration::ZERO);
9874        tokio::pin!(heartbeat);
9875        // Poll responses may already have leased server-side work by the time
9876        // they become ready, so each poller owns its responses through
9877        // completion or failure instead of racing raw polls in this select.
9878        let mut workflow_poller = (!self.workflows.is_empty()).then(|| {
9879            let worker = self.clone();
9880            let stop = Arc::clone(&stop);
9881            tokio::spawn(async move { worker.poll_workflows_until_stopped(stop).await })
9882        });
9883        let mut activity_poller = (!self.activities.is_empty()).then(|| {
9884            let worker = self.clone();
9885            let stop = Arc::clone(&stop);
9886            tokio::spawn(async move { worker.poll_activities_until_stopped(stop).await })
9887        });
9888        let mut query_poller = (!self.queries.is_empty()).then(|| {
9889            let worker = self.clone();
9890            let stop = Arc::clone(&stop);
9891            tokio::spawn(async move { worker.poll_queries_until_stopped(stop).await })
9892        });
9893
9894        loop {
9895            tokio::select! {
9896                _ = wait_for_worker_stop(&stop) => {
9897                    stop.store(true, Ordering::SeqCst);
9898                    break;
9899                }
9900                _ = &mut heartbeat => {
9901                    let result = self.retry_worker_operation(|| {
9902                        self.client.heartbeat_worker_with_sessions(
9903                            &self.worker_id,
9904                            self.workflow_capacity.available(),
9905                            self.activity_capacity.available(),
9906                            self.client.worker_sessions_enabled.then(|| self.session_available()),
9907                        )
9908                    }).await;
9909                    heartbeat
9910                        .as_mut()
9911                        .reset(tokio::time::Instant::now() + heartbeat_interval);
9912                    match result {
9913                        Ok(Some(acknowledgement)) => {
9914                            if let Some(observer) = &self.heartbeat_observer {
9915                                observer(&WorkerHeartbeatObservation {
9916                                    worker_id: self.worker_id.clone(),
9917                                    task_queue: self.task_queue.clone(),
9918                                    acknowledged_at_unix_millis: SystemTime::now()
9919                                        .duration_since(UNIX_EPOCH)
9920                                        .unwrap_or_default()
9921                                        .as_millis()
9922                                        .min(u64::MAX as u128)
9923                                        as u64,
9924                                    acknowledgement,
9925                                });
9926                            }
9927                        }
9928                        Ok(None) => break,
9929                        Err(error) => {
9930                            tracing::error!(
9931                                target: "durable_workflow::worker",
9932                                worker_id = %self.worker_id,
9933                                task_queue = %self.task_queue,
9934                                error = %error,
9935                                "worker stopping: heartbeat failed with a non-retryable failure"
9936                            );
9937                            stop.store(true, Ordering::SeqCst);
9938                            join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await?;
9939                            return Err(error);
9940                        }
9941                    }
9942                }
9943                result = OptionFuture::from(workflow_poller.as_mut()), if workflow_poller.is_some() => {
9944                    workflow_poller = None;
9945                    let stopped_by_server = stop.load(Ordering::SeqCst);
9946                    stop.store(true, Ordering::SeqCst);
9947                    let poller_result = optional_poller_result("workflow", result);
9948                    let join_result =
9949                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
9950                    poller_result?;
9951                    join_result?;
9952                    if stopped_by_server {
9953                        return Ok(());
9954                    }
9955                    return Err(Error::WorkerLoop(
9956                        "workflow poller stopped unexpectedly".to_string(),
9957                    ));
9958                }
9959                result = OptionFuture::from(activity_poller.as_mut()), if activity_poller.is_some() => {
9960                    activity_poller = None;
9961                    let stopped_by_server = stop.load(Ordering::SeqCst);
9962                    stop.store(true, Ordering::SeqCst);
9963                    let poller_result = optional_poller_result("activity", result);
9964                    let join_result =
9965                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
9966                    poller_result?;
9967                    join_result?;
9968                    if stopped_by_server {
9969                        return Ok(());
9970                    }
9971                    return Err(Error::WorkerLoop(
9972                        "activity poller stopped unexpectedly".to_string(),
9973                    ));
9974                }
9975                result = OptionFuture::from(query_poller.as_mut()), if query_poller.is_some() => {
9976                    query_poller = None;
9977                    let stopped_by_server = stop.load(Ordering::SeqCst);
9978                    stop.store(true, Ordering::SeqCst);
9979                    let poller_result = optional_poller_result("query", result);
9980                    let join_result =
9981                        join_pollers(workflow_poller.take(), activity_poller.take(), query_poller.take()).await;
9982                    poller_result?;
9983                    join_result?;
9984                    if stopped_by_server {
9985                        return Ok(());
9986                    }
9987                    return Err(Error::WorkerLoop(
9988                        "query poller stopped unexpectedly".to_string(),
9989                    ));
9990                }
9991            }
9992        }
9993
9994        join_pollers(
9995            workflow_poller.take(),
9996            activity_poller.take(),
9997            query_poller.take(),
9998        )
9999        .await
10000    }
10001
10002    /// Poll and settle at most one task from each enabled task family.
10003    ///
10004    /// A workflow may reach its server-enforced run deadline while this worker
10005    /// holds a task. When a completion or workflow-task failure endpoint rejects that
10006    /// selected task and run with `recorded=false`, `reason=run_timed_out`, and
10007    /// terminal `run_status=failed`, the workflow tick is considered settled:
10008    /// the late command was not recorded and cannot replace the terminal run.
10009    /// A `recorded=false`, `reason=task_not_leased` receipt for the same task,
10010    /// attempt and run settles the tick the same way: this worker no longer
10011    /// holds the task, and the server owns any redelivery.
10012    /// A `recorded=false`, `reason=run_closed` receipt for the same task,
10013    /// attempt and run also settles the tick when it carries the closed run's
10014    /// terminal `run_status`, the matching `stop_reason` and
10015    /// `can_continue=false`, for example after the run was cancelled while the
10016    /// report was in flight.
10017    /// Every other rejection remains an error. This worker-level
10018    /// race handling is distinct from [`WorkflowResultOptions::timeout`], which
10019    /// only bounds how long a client waits for a result.
10020    ///
10021    /// Direct callers of [`Client::complete_workflow_task`] and
10022    /// [`Client::fail_workflow_task`] continue to receive the original
10023    /// [`Error::Http`] status and response body.
10024    ///
10025    /// A completion the Server refuses as larger than its aggregate completion
10026    /// limit (native Server 3.6.0: HTTP 413 with
10027    /// `limit_kind: "workflow_task_completion_bytes"`) is never resent. The
10028    /// worker completes the same task once with a non-retryable `fail_workflow`
10029    /// command whose message starts with `Structural limit exceeded:`, so the
10030    /// run fails with failure category `structural_limit`. Direct callers of
10031    /// [`Client::complete_workflow_task`] receive
10032    /// [`Error::WorkflowTaskCompletionTooLarge`] for that refusal.
10033    ///
10034    /// A completion the Server refuses because recording it would exceed its
10035    /// history-transaction budget (native Server 3.13.0: HTTP 409
10036    /// `history_transaction_limit_exceeded` with `limit_kind`, `current_value`
10037    /// and `configured_limit`) is handled the same way, and direct callers
10038    /// receive [`Error::WorkflowTaskHistoryLimitExceeded`].
10039    pub async fn run_once(&self) -> Result<usize> {
10040        self.validate_registration()?;
10041        if self.client.worker_sessions_enabled {
10042            self.require_session_registration()?;
10043        }
10044        if self.cooperative_cancellation_enabled
10045            && !self
10046                .cooperative_registration_confirmed
10047                .load(Ordering::SeqCst)
10048        {
10049            return Err(Error::CooperativeCancellationUnavailable(
10050                "register this cooperative worker before polling tasks".into(),
10051            ));
10052        }
10053        let worker = self.with_storage_admission(Arc::new(AtomicBool::new(false)));
10054        let mut handled = 0;
10055        // Keep optional telemetry/cooperative poller state off the caller's
10056        // stack, including callers that await several run_once turns.
10057        match Box::pin(worker.poll_workflow_once()).await? {
10058            ManagedPollOutcome::Handled => handled += 1,
10059            ManagedPollOutcome::Stop => return Ok(handled),
10060            ManagedPollOutcome::Idle => {}
10061        }
10062        match Box::pin(worker.poll_activity_once()).await? {
10063            ManagedPollOutcome::Handled => handled += 1,
10064            ManagedPollOutcome::Stop => return Ok(handled),
10065            ManagedPollOutcome::Idle => {}
10066        }
10067        if !self.queries.is_empty() {
10068            match Box::pin(worker.poll_query_once()).await? {
10069                ManagedPollOutcome::Handled => handled += 1,
10070                ManagedPollOutcome::Stop => return Ok(handled),
10071                ManagedPollOutcome::Idle => {}
10072            }
10073        }
10074        Ok(handled)
10075    }
10076
10077    async fn poll_workflow_once_reserved(&self) -> Result<ManagedPollOutcome> {
10078        if self.client.sticky_cache.is_some()
10079            && !self.sticky_registration_confirmed.load(Ordering::SeqCst)
10080        {
10081            return Err(Error::WorkerLoop("sticky_registration_unconfirmed: register the sticky-capable worker before polling".into()));
10082        }
10083        if self.client.local_activities_enabled
10084            && !self.local_registration_confirmed.load(Ordering::SeqCst)
10085        {
10086            return Err(Error::WorkerLoop("local_activity_registration_unconfirmed: register this local-capable worker before polling workflow tasks".into()));
10087        }
10088        if self.cooperative_cancellation_enabled {
10089            return self.poll_cooperative_workflow_once().await;
10090        }
10091        let mut poll_metrics = self.metrics.worker(false, "workflow", &self.task_queue);
10092        let poll_request_id = unique_request_id("rust-workflow-poll");
10093        let response = self
10094            .retry_worker_operation(|| self.poll_workflow_with_sticky_cache(&poll_request_id))
10095            .await;
10096        poll_metrics.poll(&response, |value| value.0.outcome());
10097        drop(poll_metrics);
10098        let Some((response, snapshot)) = self.settle_worker_poll_response(response).await? else {
10099            return Ok(ManagedPollOutcome::Idle);
10100        };
10101        if response.outcome().should_stop() {
10102            return Ok(ManagedPollOutcome::Stop);
10103        }
10104        let memo_updates_supported =
10105            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
10106        self.observe_workflow_poll_capabilities(response.server_capabilities.as_ref());
10107        let Some(task) = response.task else {
10108            return Ok(ManagedPollOutcome::Idle);
10109        };
10110
10111        self.client.release_worker_poll();
10112
10113        let mut task_metrics = self.metrics.worker(true, "workflow", &self.task_queue);
10114        task_metrics.outcome("failed");
10115        let task_id = task.task_id.clone();
10116        let attempt = task.workflow_task_attempt;
10117        let run_id = task.run_id.clone();
10118        let lease_owner = task
10119            .lease_owner
10120            .clone()
10121            .unwrap_or_else(|| self.worker_id.clone());
10122
10123        let decision = match self.execute_workflow_with_local_activities(task).await {
10124            Ok(Some(decision)) => Ok(decision),
10125            Ok(None) => {
10126                task_metrics.outcome("expired");
10127                return Ok(ManagedPollOutcome::Handled);
10128            }
10129            Err(error) => Err(error),
10130        };
10131        let task_outcome = metrics::workflow_task_outcome(decision.as_ref().ok());
10132        let settled = self
10133            .settle_workflow_task_decision(
10134                &task_id,
10135                &lease_owner,
10136                attempt,
10137                run_id.as_deref(),
10138                decision,
10139                memo_updates_supported,
10140                snapshot,
10141            )
10142            .await;
10143        if settled.is_ok() {
10144            task_metrics.outcome(task_outcome);
10145        }
10146        settled
10147    }
10148
10149    /// Answer a typed oversized-completion refusal (Server 3.6.0
10150    /// `workflow_task_completion_bytes`) without resending the completion:
10151    /// complete the same task once with a non-retryable structural-limit
10152    /// `fail_workflow` command. A failed task would be retried into the same
10153    /// refusal, or park the run. If this small completion is not recorded
10154    /// either, the original refusal is returned (or the report's settled
10155    /// receipt), and nothing is resent.
10156    ///
10157    /// A completion refused over the Server's history-transaction budget
10158    /// ([`Error::WorkflowTaskHistoryLimitExceeded`], HTTP 409) takes the same
10159    /// path: its transaction rolled back, and replay produces the same commands.
10160    async fn fail_oversized_workflow_task(
10161        &self,
10162        task_id: &str,
10163        lease_owner: &str,
10164        attempt: u64,
10165        run_id: Option<&str>,
10166        error: Error,
10167    ) -> Result<Value> {
10168        tracing::warn!(
10169            target: "durable_workflow::worker",
10170            task_id,
10171            workflow_task_attempt = attempt,
10172            run_id,
10173            error = %error,
10174            "the Server refused the workflow task completion over a structural limit; failing the run with a structural-limit failure"
10175        );
10176        let command = workflow_failure_command(&error, None);
10177        match self
10178            .client
10179            .complete_workflow_task(task_id, lease_owner, attempt, vec![command])
10180            .await
10181        {
10182            Ok(receipt) => Ok(receipt),
10183            Err(report) if workflow_task_report_is_settled(&report, task_id, attempt, run_id) => {
10184                Err(report)
10185            }
10186            Err(report) => {
10187                tracing::warn!(
10188                    target: "durable_workflow::worker",
10189                    task_id,
10190                    workflow_task_attempt = attempt,
10191                    run_id,
10192                    error = %report,
10193                    "the structural-limit workflow failure was not recorded"
10194                );
10195                Err(error)
10196            }
10197        }
10198    }
10199
10200    #[allow(clippy::too_many_arguments)]
10201    async fn settle_workflow_task_decision(
10202        &self,
10203        task_id: &str,
10204        lease_owner: &str,
10205        attempt: u64,
10206        run_id: Option<&str>,
10207        decision: Result<WorkflowTaskDecision>,
10208        memo_updates_supported: bool,
10209        snapshot: Option<sticky_worker::StickySnapshot>,
10210    ) -> Result<ManagedPollOutcome> {
10211        let reported = match decision {
10212            Ok(decision)
10213                if decision.cancellation_delivery.is_some()
10214                    || decision.cancellation_scope_delivery.is_some()
10215                    || decision.cancellation_scope_opening.is_some() =>
10216            {
10217                return Err(Error::CooperativeCancellationUnavailable(
10218                    "worker cancellation delivery has not been negotiated".into(),
10219                ));
10220            }
10221            Ok(decision)
10222                if commands_use_workflow_memo_updates(&decision.commands)
10223                    && !memo_updates_supported =>
10224            {
10225                self.client
10226                    .fail_workflow_task(
10227                        task_id,
10228                        lease_owner,
10229                        attempt,
10230                        Error::WorkflowMemoUpdatesUnavailable.to_string(),
10231                    )
10232                    .await
10233            }
10234            Ok(decision) if decision.commands.is_empty() => {
10235                // A replay can consume a recorded pending durable command
10236                // without producing a new command. The standalone protocol
10237                // acknowledges that state through the typed waiting outcome;
10238                // an empty completion is rejected by servers that require at
10239                // least one executable command.
10240                self.client
10241                    .fail_workflow_task_with_type(
10242                        task_id,
10243                        lease_owner,
10244                        attempt,
10245                        WORKFLOW_TASK_WAITING_FOR_HISTORY_MESSAGE,
10246                        WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE,
10247                    )
10248                    .await
10249            }
10250            Ok(decision) => {
10251                let sticky_claim = self.sticky_claim(snapshot.as_ref(), &decision.commands)?;
10252                match self
10253                    .client
10254                    .complete_workflow_task_with_message_streams(
10255                        task_id,
10256                        lease_owner,
10257                        attempt,
10258                        decision.commands,
10259                        decision.message_stream_cursors,
10260                        decision.message_stream_waits,
10261                        sticky_claim,
10262                    )
10263                    .await
10264                {
10265                    Err(
10266                        error @ (Error::WorkflowTaskCompletionTooLarge(_)
10267                        | Error::WorkflowTaskHistoryLimitExceeded(_)),
10268                    ) => {
10269                        // The refused commands were never recorded.
10270                        self.discard_sticky_snapshot(snapshot.as_ref())?;
10271                        self.fail_oversized_workflow_task(
10272                            task_id,
10273                            lease_owner,
10274                            attempt,
10275                            run_id,
10276                            error,
10277                        )
10278                        .await
10279                    }
10280                    reported => reported,
10281                }
10282            }
10283            Err(error @ Error::CancellationScopeExecutionUnavailable) => return Err(error),
10284            Err(error @ Error::FailureReporting(_)) => {
10285                self.discard_sticky_snapshot(snapshot.as_ref())?;
10286                return Err(error);
10287            }
10288            Err(error) => {
10289                self.discard_sticky_snapshot(snapshot.as_ref())?;
10290                if matches!(
10291                    error,
10292                    Error::HandlerType {
10293                        handler_kind: HandlerKind::Workflow,
10294                        value_kind: HandlerValueKind::Input,
10295                        ..
10296                    }
10297                ) {
10298                    self.client
10299                        .fail_workflow_task_with_failure(
10300                            task_id,
10301                            lease_owner,
10302                            attempt,
10303                            json!({
10304                                "message": error.to_string(),
10305                                "type": "WorkflowEntryArgumentsMismatch",
10306                                "reason": "workflow_entry_arguments_mismatch",
10307                            }),
10308                        )
10309                        .await
10310                } else {
10311                    self.client
10312                        .fail_workflow_task(task_id, lease_owner, attempt, error.to_string())
10313                        .await
10314                }
10315            }
10316        };
10317
10318        // A run may expire or close, or the task may be reclaimed, while a
10319        // completion or failure report is in flight. Settle only the matching
10320        // task's non-recorded receipt.
10321        if let Err(error) = reported {
10322            self.discard_sticky_snapshot(snapshot.as_ref())?;
10323            if !workflow_task_report_is_settled(&error, task_id, attempt, run_id) {
10324                return Err(error);
10325            }
10326            #[cfg(feature = "telemetry")]
10327            tracing::debug!(
10328                task_id,
10329                workflow_task_attempt = attempt,
10330                run_id,
10331                error = %error,
10332                "settled a non-recorded workflow-task receipt"
10333            );
10334        }
10335
10336        Ok(ManagedPollOutcome::Handled)
10337    }
10338
10339    async fn poll_activity_once_reserved(&self) -> Result<ManagedPollOutcome> {
10340        if self.client.worker_sessions_enabled {
10341            self.require_session_registration()?;
10342        }
10343        let mut poll_metrics = self.metrics.worker(false, "activity", &self.task_queue);
10344        let poll_request_id = unique_request_id("rust-activity-poll");
10345        let response = self
10346            .retry_worker_operation(|| {
10347                self.client.poll_activity_task_response_with_request_id(
10348                    &self.worker_id,
10349                    &self.task_queue,
10350                    self.poll_timeout,
10351                    &poll_request_id,
10352                    0,
10353                )
10354            })
10355            .await;
10356        poll_metrics.poll(&response, |value| value.outcome());
10357        drop(poll_metrics);
10358        let response = match response {
10359            Err(Error::ActivityExecutionAbandoned(_)) => return Ok(ManagedPollOutcome::Handled),
10360            response => response,
10361        };
10362        let Some(response) = self.settle_worker_poll_response(response).await? else {
10363            return Ok(ManagedPollOutcome::Idle);
10364        };
10365        if response.outcome().should_stop() {
10366            return Ok(ManagedPollOutcome::Stop);
10367        }
10368        let Some(task) = response.task else {
10369            return Ok(ManagedPollOutcome::Idle);
10370        };
10371
10372        self.client.release_worker_poll();
10373        self.settle_polled_activity(task).await
10374    }
10375
10376    async fn settle_polled_activity(
10377        &self,
10378        task: worker_session::SessionActivityTask,
10379    ) -> Result<ManagedPollOutcome> {
10380        let mut task_metrics = self.metrics.worker(true, "activity", &self.task_queue);
10381        task_metrics.outcome("failed");
10382        let lease = task.activity_lease.clone();
10383        let mut worker = self.clone();
10384        worker.client = self.client.with_activity_lease_authority(
10385            lease.as_ref().map(|lease| Arc::clone(&lease.authority)),
10386        );
10387        let operation = worker.execute_polled_activity(task, &mut task_metrics);
10388        let result = match lease.as_ref() {
10389            Some(lease) => lease.authority.protect(operation).await,
10390            None => operation.await,
10391        };
10392        match result {
10393            Err(Error::ActivityExecutionAbandoned(_)) => {
10394                if let Some(lease) = &lease {
10395                    lease.settle_release().await;
10396                }
10397                task_metrics.outcome("expired");
10398                Ok(ManagedPollOutcome::Handled)
10399            }
10400            result => result,
10401        }
10402    }
10403
10404    async fn execute_polled_activity(
10405        &self,
10406        task: worker_session::SessionActivityTask,
10407        task_metrics: &mut metrics::WorkerObservation,
10408    ) -> Result<ManagedPollOutcome> {
10409        if self.cooperative_cancellation_enabled {
10410            return self.settle_cooperative_activity(task, task_metrics).await;
10411        }
10412        let session = self.track_session_task(task.worker_session.as_ref())?;
10413        let lease_deadline = task.lease_deadline;
10414        let invocation = task.invocation(session);
10415        let task = task.task;
10416
10417        let task_id = task.task_id.clone();
10418        let attempt_id = task
10419            .activity_attempt_id
10420            .clone()
10421            .or(task.attempt_id.clone())
10422            .unwrap_or_default();
10423        let lease_owner = task
10424            .lease_owner
10425            .clone()
10426            .unwrap_or_else(|| self.worker_id.clone());
10427        let codec = task.payload_codec.clone();
10428        let result = self.execute_session_activity_task(task, invocation).await;
10429        let mut task_outcome = if result.is_ok() {
10430            "completed"
10431        } else if matches!(result, Err(Error::ActivityExecutionAbandoned(_))) {
10432            "expired"
10433        } else {
10434            "failed"
10435        };
10436        let settled = match result {
10437            Err(Error::ActivityExecutionAbandoned(_)) => ActivitySettlement::Recorded,
10438            Err(error) if activity_hydration::stopped(&error) => ActivitySettlement::Recorded,
10439            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
10440            Ok(value) => {
10441                let (settlement, too_large) = self
10442                    .settle_activity_completion(
10443                        &task_id,
10444                        &attempt_id,
10445                        &lease_owner,
10446                        lease_deadline,
10447                        &value,
10448                        &codec,
10449                    )
10450                    .await?;
10451                if too_large {
10452                    task_outcome = "failed";
10453                }
10454                settlement
10455            }
10456            Err(error) => {
10457                let failure = ActivityError::from_error(&error, "RustActivityFailure");
10458                self.settle_activity_report(
10459                    ActivityReport::Failed,
10460                    &task_id,
10461                    &attempt_id,
10462                    &lease_owner,
10463                    lease_deadline,
10464                    || {
10465                        self.client.fail_activity_task_with_error(
10466                            &task_id,
10467                            &attempt_id,
10468                            &lease_owner,
10469                            &failure,
10470                        )
10471                    },
10472                )
10473                .await?
10474            }
10475        };
10476        match settled {
10477            ActivitySettlement::Recorded => {}
10478            // A stale attempt someone else closed is not this worker's outcome.
10479            ActivitySettlement::Closed if task_outcome == "completed" => task_outcome = "expired",
10480            ActivitySettlement::Closed => {}
10481            ActivitySettlement::LeaseEnded => task_outcome = "expired",
10482        }
10483
10484        task_metrics.outcome(task_outcome);
10485        Ok(ManagedPollOutcome::Handled)
10486    }
10487
10488    /// Send one activity settlement (complete or fail), resending the same
10489    /// report after a transient failure with the shared jittered backoff while
10490    /// the lease lasts. A maintained lease authority bounds this too: it ends
10491    /// the publication when the claim is lost. The resend is idempotent: the
10492    /// Server's answer to a copy it already recorded counts as recorded.
10493    #[allow(clippy::too_many_arguments)]
10494    pub(crate) async fn settle_activity_report<F, Fut>(
10495        &self,
10496        report: ActivityReport,
10497        task_id: &str,
10498        attempt_id: &str,
10499        owner: &str,
10500        lease_deadline: Option<tokio::time::Instant>,
10501        mut send: F,
10502    ) -> Result<ActivitySettlement>
10503    where
10504        F: FnMut() -> Fut,
10505        Fut: Future<Output = Result<Value>>,
10506    {
10507        let mut failures = 0_u32;
10508        let mut outage = OutageLog::default();
10509        loop {
10510            let error = match send().await {
10511                Ok(_) => return Ok(ActivitySettlement::Recorded),
10512                Err(error)
10513                    if activity_report_already_recorded(
10514                        &error, report, task_id, attempt_id, owner,
10515                    ) =>
10516                {
10517                    return Ok(ActivitySettlement::Recorded)
10518                }
10519                Err(error) if activity_task_rejection_is_final(&error) => {
10520                    return Ok(ActivitySettlement::Closed)
10521                }
10522                Err(error) => error,
10523            };
10524            let stopping = self
10525                .run_stop
10526                .as_ref()
10527                .is_some_and(|stop| stop.load(Ordering::SeqCst));
10528            if !worker_error_is_transient(&error) || self.retry_policy.max_retries == 0 || stopping
10529            {
10530                return Err(error);
10531            }
10532            failures = failures.saturating_add(1);
10533            outage.report(&self.worker_id, &self.task_queue, &error);
10534            let delay = worker_outage_delay(failures);
10535            let lease_left = self
10536                .client
10537                .activity_lease_authority
10538                .as_ref()
10539                .and_then(|authority| authority.lease_left())
10540                .or_else(|| {
10541                    lease_deadline.map(|deadline| {
10542                        deadline.saturating_duration_since(tokio::time::Instant::now())
10543                    })
10544                });
10545            let out_of_time = match lease_left {
10546                Some(left) => delay >= left,
10547                // No known lease: keep the ordinary bounded budget.
10548                None => failures as usize > self.retry_policy.max_retries,
10549            };
10550            if out_of_time {
10551                tracing::error!(
10552                    target: "durable_workflow::worker",
10553                    worker_id = %self.worker_id,
10554                    task_id,
10555                    error = %error,
10556                    "activity outcome not delivered before its lease ended; the Server settles the attempt"
10557                );
10558                return Ok(ActivitySettlement::LeaseEnded);
10559            }
10560            tracing::warn!(
10561                target: "durable_workflow::worker",
10562                worker_id = %self.worker_id,
10563                task_id,
10564                error = %error,
10565                retry_in_ms = delay.as_millis() as u64,
10566                "transient failure reporting an activity outcome; resending it"
10567            );
10568            match &self.run_stop {
10569                Some(stop) => {
10570                    tokio::select! {
10571                        _ = tokio::time::sleep(delay) => {}
10572                        _ = wait_for_worker_stop(stop) => return Err(error),
10573                    }
10574                }
10575                None => tokio::time::sleep(delay).await,
10576            }
10577        }
10578    }
10579
10580    /// Complete an activity. When its result cannot be delivered because it is
10581    /// too large (still refused after the payload policy was rediscovered, or
10582    /// too large to externalize), report the attempt as a non-retryable
10583    /// `ActivityResultTooLarge` failure instead, so the worker keeps running.
10584    /// Returns the settlement and whether it was that failure.
10585    #[allow(clippy::too_many_arguments)]
10586    pub(crate) async fn settle_activity_completion<T: Serialize + Clone>(
10587        &self,
10588        task_id: &str,
10589        attempt_id: &str,
10590        owner: &str,
10591        lease_deadline: Option<tokio::time::Instant>,
10592        value: &T,
10593        codec: &str,
10594    ) -> Result<(ActivitySettlement, bool)> {
10595        let completion = self
10596            .settle_activity_report(
10597                ActivityReport::Completed,
10598                task_id,
10599                attempt_id,
10600                owner,
10601                lease_deadline,
10602                || {
10603                    self.client.complete_activity_task(
10604                        task_id,
10605                        attempt_id,
10606                        owner,
10607                        value.clone(),
10608                        codec,
10609                    )
10610                },
10611            )
10612            .await;
10613        let error = match completion {
10614            Ok(settlement) => return Ok((settlement, false)),
10615            Err(error) if activity_result_too_large(&error) => error,
10616            Err(error) => return Err(error),
10617        };
10618        tracing::error!(
10619            target: "durable_workflow::worker",
10620            worker_id = %self.worker_id,
10621            task_id,
10622            error = %error,
10623            "activity result is too large to deliver; reporting a non-retryable ActivityResultTooLarge failure"
10624        );
10625        let failure = json!({
10626            "type": ACTIVITY_RESULT_TOO_LARGE,
10627            "class": ACTIVITY_RESULT_TOO_LARGE,
10628            "non_retryable": true,
10629            "message": format!("activity result is too large to deliver: {error}"),
10630        });
10631        let settlement = self
10632            .settle_activity_report(
10633                ActivityReport::Failed,
10634                task_id,
10635                attempt_id,
10636                owner,
10637                lease_deadline,
10638                || {
10639                    self.client.fail_activity_task_with_failure(
10640                        task_id,
10641                        attempt_id,
10642                        owner,
10643                        failure.clone(),
10644                    )
10645                },
10646            )
10647            .await?;
10648        Ok((settlement, true))
10649    }
10650
10651    async fn poll_query_once(&self) -> Result<ManagedPollOutcome> {
10652        let mut poll_metrics = self.metrics.worker(false, "query", &self.task_queue);
10653        let poll_request_id = unique_request_id("rust-query-poll");
10654        let response = self
10655            .retry_worker_operation(|| {
10656                let body = json!({"worker_id":self.worker_id,"task_queue":self.task_queue,
10657                    "poll_request_id":poll_request_id,
10658                    "timeout_seconds":long_poll_timeout_seconds(self.poll_timeout)});
10659                async move {
10660                    self.client
10661                        .poll_request_json_unresolved::<Value, Value>(
10662                            "/worker/query-tasks/poll",
10663                            RequestProtocol::Worker(QUERY_TASK_MINIMUM_WORKER_PROTOCOL_VERSION),
10664                            &body,
10665                            self.poll_timeout + Duration::from_secs(5),
10666                            0,
10667                        )
10668                        .await
10669                }
10670            })
10671            .await;
10672        poll_metrics.poll(&response, |value| {
10673            worker_poll_outcome(
10674                value.get("task").is_some_and(|task| !task.is_null()),
10675                value.get("poll_status").and_then(Value::as_str),
10676                value.get("reason").and_then(Value::as_str),
10677            )
10678        });
10679        drop(poll_metrics);
10680        let Some(mut wire) = self.settle_worker_poll_response(response).await? else {
10681            return Ok(ManagedPollOutcome::Idle);
10682        };
10683        let authority = if wire.get("task").is_some_and(|task| !task.is_null()) {
10684            match query_authority::Authority::capture(&wire["task"], self) {
10685                Ok(authority) => authority,
10686                Err(_) => return Ok(ManagedPollOutcome::Handled),
10687            }
10688        } else {
10689            None
10690        };
10691        let loading = self.client.resolve_runtime_payloads(
10692            &mut wire,
10693            "/worker/query-tasks/poll",
10694            RequestProtocol::Worker(self.client.worker_protocol_version.as_str()),
10695        );
10696        match query_authority::Authority::protect(authority.as_ref(), self, loading).await {
10697            Err(_) => return Ok(ManagedPollOutcome::Handled),
10698            Ok(result) => result?,
10699        }
10700        let response: PollQueryTaskResponse = serde_json::from_value(wire)?;
10701        if response.outcome().should_stop() {
10702            return Ok(ManagedPollOutcome::Stop);
10703        }
10704        let Some(task) = response.task else {
10705            return Ok(ManagedPollOutcome::Idle);
10706        };
10707
10708        let mut task_metrics = self.metrics.worker(true, "query", &self.task_queue);
10709        task_metrics.outcome("failed");
10710        let query_task_id = task.query_task_id.clone();
10711        let attempt = task.query_task_attempt;
10712        let lease_owner = task
10713            .lease_owner
10714            .clone()
10715            .unwrap_or_else(|| self.worker_id.clone());
10716        let codec = task.payload_codec.clone();
10717
10718        let execution = query_authority::Authority::protect(
10719            authority.as_ref(),
10720            self,
10721            self.execute_query_task_with_authority(task, authority.as_ref()),
10722        )
10723        .await;
10724        let execution = match execution {
10725            Err(_) => return Ok(ManagedPollOutcome::Handled),
10726            Ok(Err(failure)) if failure.reason == "query_authority_lost" => {
10727                return Ok(ManagedPollOutcome::Handled)
10728            }
10729            Ok(result) => result,
10730        };
10731        let task_outcome = if execution.is_ok() {
10732            "completed"
10733        } else {
10734            "failed"
10735        };
10736        match execution {
10737            Ok(value) => {
10738                let result_envelope = match encode_typed_envelope(&value, &codec) {
10739                    Ok(result_envelope) => result_envelope,
10740                    Err(error) => {
10741                        let failure = query_authority::Authority::protect(
10742                            authority.as_ref(),
10743                            self,
10744                            self.client.fail_query_task(
10745                                &query_task_id,
10746                                &lease_owner,
10747                                attempt,
10748                                error.to_string(),
10749                                "query_result_encode_failed",
10750                                "QueryResultEncodeFailed",
10751                            ),
10752                        )
10753                        .await;
10754                        let Ok(failure) = failure else {
10755                            return Ok(ManagedPollOutcome::Handled);
10756                        };
10757                        if let Err(error) = failure {
10758                            if !query_task_rejection_is_final(&error) {
10759                                return Err(error);
10760                            }
10761                        }
10762                        return Ok(ManagedPollOutcome::Handled);
10763                    }
10764                };
10765
10766                let completion = query_authority::Authority::protect(
10767                    authority.as_ref(),
10768                    self,
10769                    self.client.complete_query_task_with_envelope(
10770                        &query_task_id,
10771                        &lease_owner,
10772                        attempt,
10773                        value.clone().into_json()?,
10774                        result_envelope,
10775                    ),
10776                )
10777                .await;
10778                let Ok(completion) = completion else {
10779                    return Ok(ManagedPollOutcome::Handled);
10780                };
10781                if let Err(error) = completion {
10782                    if !query_task_rejection_is_final(&error) {
10783                        return Err(error);
10784                    }
10785                }
10786            }
10787            Err(failure) => {
10788                let result = query_authority::Authority::protect(
10789                    authority.as_ref(),
10790                    self,
10791                    self.client.fail_query_task(
10792                        &query_task_id,
10793                        &lease_owner,
10794                        attempt,
10795                        failure.message,
10796                        failure.reason,
10797                        failure.failure_type,
10798                    ),
10799                )
10800                .await;
10801                let Ok(result) = result else {
10802                    return Ok(ManagedPollOutcome::Handled);
10803                };
10804                if let Err(error) = result {
10805                    if !query_task_rejection_is_final(&error) {
10806                        return Err(error);
10807                    }
10808                }
10809            }
10810        }
10811
10812        task_metrics.outcome(task_outcome);
10813        Ok(ManagedPollOutcome::Handled)
10814    }
10815
10816    async fn poll_queries_until_stopped(self, stop: Arc<AtomicBool>) -> Result<()> {
10817        let mut outage = Outage::default();
10818        while !stop.load(Ordering::SeqCst) {
10819            match self.poll_query_once().await {
10820                Ok(ManagedPollOutcome::Stop) => {
10821                    stop.store(true, Ordering::SeqCst);
10822                    break;
10823                }
10824                Err(error) => {
10825                    if !self.outlive_transient(&error, &mut outage, &stop).await {
10826                        stop.store(true, Ordering::SeqCst);
10827                        return Err(error);
10828                    }
10829                }
10830                _ => outage.reset(),
10831            }
10832        }
10833
10834        Ok(())
10835    }
10836
10837    /// A running worker (not `run_once`) outlives transient failures unless
10838    /// recovery or retries are disabled.
10839    pub(crate) fn outlives(&self, error: &Error) -> bool {
10840        self.run_stop.is_some()
10841            && self.recover_transient_outages
10842            && self.retry_policy.max_retries > 0
10843            && worker_error_is_transient(error)
10844    }
10845
10846    /// Whether a running worker keeps going after `error`, which escaped a
10847    /// poll lane: a transient waits out the shared jittered backoff; anything
10848    /// else is logged as fatal. Shutdown before or during the wait returns the
10849    /// error as before, so a refused operation never looks acknowledged.
10850    pub(crate) async fn outlive_transient(
10851        &self,
10852        error: &Error,
10853        outage: &mut Outage,
10854        stop: &AtomicBool,
10855    ) -> bool {
10856        if stop.load(Ordering::SeqCst) {
10857            return false;
10858        }
10859        if !self.outlives(error) {
10860            tracing::error!(
10861                target: "durable_workflow::worker",
10862                worker_id = %self.worker_id,
10863                task_queue = %self.task_queue,
10864                error = %error,
10865                "worker stopping on a non-retryable failure"
10866            );
10867            return false;
10868        }
10869        outage.failures = outage.failures.saturating_add(1);
10870        outage.log.report(&self.worker_id, &self.task_queue, error);
10871        let delay = worker_outage_delay(outage.failures);
10872        tracing::warn!(
10873            target: "durable_workflow::worker",
10874            worker_id = %self.worker_id,
10875            task_queue = %self.task_queue,
10876            error = %error,
10877            retry_in_ms = delay.as_millis() as u64,
10878            "transient Server failure; the worker keeps running"
10879        );
10880        tokio::select! {
10881            _ = tokio::time::sleep(delay) => true,
10882            _ = wait_for_worker_stop(stop) => false,
10883        }
10884    }
10885
10886    async fn retry_worker_operation<T, F, Fut>(&self, mut operation: F) -> Result<Option<T>>
10887    where
10888        F: FnMut() -> Fut,
10889        Fut: Future<Output = Result<T>>,
10890    {
10891        let mut retries = 0;
10892        let mut outage = OutageLog::default();
10893
10894        loop {
10895            if self
10896                .run_stop
10897                .as_ref()
10898                .is_some_and(|stop| stop.load(Ordering::SeqCst))
10899            {
10900                return Ok(None);
10901            }
10902            match operation().await {
10903                Err(error)
10904                    if (workflow_hydration::stopped(&error)
10905                        || activity_hydration::stopped(&error))
10906                        && self
10907                            .run_stop
10908                            .as_ref()
10909                            .is_some_and(|stop| stop.load(Ordering::SeqCst)) =>
10910                {
10911                    return Ok(None);
10912                }
10913                Err(error)
10914                    if worker_operation_is_retryable(&error)
10915                        && (retries < self.retry_policy.max_retries
10916                            || (self.recover_transient_outages
10917                                && self.run_stop.is_some()
10918                                && self.retry_policy.max_retries > 0
10919                                && worker_error_is_transient(&error))) =>
10920                {
10921                    retries = retries.saturating_add(1);
10922                    outage.report(&self.worker_id, &self.task_queue, &error);
10923                    // Within the budget the policy's capped exponential delay
10924                    // applies. Beyond it, every worker draws from the shared
10925                    // full-jitter schedule so a fleet does not retry in step
10926                    // when the Server comes back.
10927                    let delay = worker_poll_retry_delay(self.retry_policy, retries);
10928                    if let Some(stop) = &self.run_stop {
10929                        tokio::select! {
10930                            _ = tokio::time::sleep(delay) => {}
10931                            _ = wait_for_worker_stop(stop) => return Ok(None),
10932                        }
10933                    } else {
10934                        tokio::time::sleep(delay).await;
10935                    }
10936                }
10937                result => return result.map(Some),
10938            }
10939        }
10940    }
10941
10942    async fn settle_worker_poll_response<T>(
10943        &self,
10944        response: Result<Option<T>>,
10945    ) -> Result<Option<T>> {
10946        match response {
10947            Ok(response) => Ok(response),
10948            Err(error) => {
10949                let Some(advertised_delay) = worker_poll_capacity_retry_after(&error) else {
10950                    return Err(error);
10951                };
10952                let minimum_delay = self
10953                    .retry_policy
10954                    .initial_backoff
10955                    .max(Duration::from_millis(1));
10956                let maximum_delay = self.retry_policy.max_backoff.max(minimum_delay);
10957                let delay = advertised_delay.max(minimum_delay).min(maximum_delay);
10958                if let Some(stop) = &self.run_stop {
10959                    tokio::select! {
10960                        biased;
10961                        _ = wait_for_worker_stop(stop) => {},
10962                        _ = tokio::time::sleep(delay) => {},
10963                    }
10964                } else {
10965                    tokio::time::sleep(delay).await;
10966                }
10967                Ok(None)
10968            }
10969        }
10970    }
10971
10972    #[cfg(test)]
10973    async fn execute_query_task(
10974        &self,
10975        task: QueryTask,
10976    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
10977        self.execute_query_task_with_authority(task, None).await
10978    }
10979
10980    async fn execute_query_task_with_authority(
10981        &self,
10982        task: QueryTask,
10983        authority: Option<&query_authority::Authority>,
10984    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
10985        #[cfg(feature = "telemetry")]
10986        if let Some(telemetry) = &self.telemetry {
10987            return telemetry
10988                .run_observed(
10989                    "durable.query.task",
10990                    self.query_telemetry_fields(&task),
10991                    false,
10992                    authority.and_then(|_| self.query_observations(&task)),
10993                    self.execute_query_task_inner(task, authority),
10994                )
10995                .await;
10996        }
10997        self.execute_query_task_inner(task, authority).await
10998    }
10999
11000    async fn execute_query_task_inner(
11001        &self,
11002        mut task: QueryTask,
11003        authority: Option<&query_authority::Authority>,
11004    ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure> {
11005        validate_query_task_payloads(&task).map_err(|error| {
11006            QueryTaskExecutionFailure::new(
11007                "query_payload_decode_failed",
11008                error.to_string(),
11009                "QueryPayloadDecodeFailed",
11010            )
11011        })?;
11012
11013        if !self.workflows.contains_key(&task.workflow_type) {
11014            return Err(QueryTaskExecutionFailure::new(
11015                "query_workflow_type_not_registered",
11016                format!("no workflow registered for type {:?}", task.workflow_type),
11017                "WorkflowTypeNotRegistered",
11018            ));
11019        }
11020
11021        let Some(handlers) = self.queries.get(&task.workflow_type) else {
11022            return Err(QueryTaskExecutionFailure::new(
11023                "query_handler_unavailable",
11024                format!(
11025                    "query handlers are unavailable for workflow type {:?}",
11026                    task.workflow_type
11027                ),
11028                "QueryHandlerUnavailable",
11029            ));
11030        };
11031        let Some(query) = handlers.get(&task.query_name) else {
11032            return Err(QueryTaskExecutionFailure::new(
11033                "rejected_unknown_query",
11034                format!("unknown query {:?}", task.query_name),
11035                "QueryFailed",
11036            ));
11037        };
11038
11039        let args = decode_task_avro_arguments(task.query_arguments.as_ref(), &task.payload_codec)
11040            .map_err(|error| {
11041            QueryTaskExecutionFailure::new(
11042                "query_payload_decode_failed",
11043                format!("cannot decode query arguments: {error}"),
11044                "QueryPayloadDecodeFailed",
11045            )
11046        })?;
11047        let workflow_input_typed =
11048            decode_task_avro_arguments(task.workflow_arguments.as_ref(), &task.payload_codec)
11049                .map_err(|error| {
11050                    QueryTaskExecutionFailure::new(
11051                        "query_workflow_state_unavailable",
11052                        format!("cannot decode workflow start input: {error}"),
11053                        "QueryWorkflowStateUnavailable",
11054                    )
11055                })?;
11056        let workflow_input = workflow_input_typed.clone().into_json().map_err(|error| {
11057            QueryTaskExecutionFailure::new(
11058                "query_workflow_state_unavailable",
11059                format!("cannot project workflow start input: {error}"),
11060                "QueryWorkflowStateUnavailable",
11061            )
11062        })?;
11063        hydrate_query_history_from_export(&mut task).map_err(|error| {
11064            QueryTaskExecutionFailure::new(
11065                "query_workflow_state_unavailable",
11066                format!("cannot restore query history snapshot: {error}"),
11067                "QueryWorkflowStateUnavailable",
11068            )
11069        })?;
11070        enrich_query_history_from_export(&mut task).map_err(|error| {
11071            QueryTaskExecutionFailure::new(
11072                "query_workflow_state_unavailable",
11073                format!("cannot restore compact query history payloads: {error}"),
11074                "QueryWorkflowStateUnavailable",
11075            )
11076        })?;
11077        let signal_events = query_signal_events(&task).map_err(|error| {
11078            QueryTaskExecutionFailure::new(
11079                "query_workflow_state_unavailable",
11080                format!("cannot decode committed workflow signals: {error}"),
11081                "QueryWorkflowStateUnavailable",
11082            )
11083        })?;
11084        let history_events = Arc::new(std::mem::take(&mut task.history_events));
11085        let mut context = QueryContext {
11086            workflow_id: task.workflow_id,
11087            run_id: task.run_id,
11088            workflow_type: task.workflow_type.clone(),
11089            run_status: task.run_status,
11090            workflow_input,
11091            workflow_input_avro_value: workflow_input_typed.clone(),
11092            replay_time: replay_clock::snapshot_time(&history_events, &task.payload_codec),
11093            history_events: Arc::clone(&history_events),
11094            signal_events: Arc::new(signal_events),
11095        };
11096
11097        let future = match query {
11098            RegisteredQuery::Snapshot(handler) => {
11099                query_authority::before_handler(authority, &self.client).await?;
11100                handler(context, args)
11101            }
11102            RegisteredQuery::Replayed {
11103                state_type,
11104                handler,
11105            } => {
11106                let workflow = self
11107                    .workflows
11108                    .get(&task.workflow_type)
11109                    .expect("workflow registration was checked above");
11110                if workflow.state_type != Some(*state_type) {
11111                    return Err(QueryTaskExecutionFailure::new(
11112                        "query_workflow_state_unavailable",
11113                        "replayed query state type does not match its workflow registration",
11114                        "QueryWorkflowStateUnavailable",
11115                    ));
11116                }
11117                let replay = workflow.replay.as_ref().ok_or_else(|| {
11118                    QueryTaskExecutionFailure::new(
11119                        "query_workflow_state_unavailable",
11120                        format!(
11121                            "workflow type {:?} is not registered for instance-state replay",
11122                            task.workflow_type
11123                        ),
11124                        "QueryWorkflowStateUnavailable",
11125                    )
11126                })?;
11127                let mut replayed_state = WorkflowState::new_with_identity(
11128                    history_events.as_ref().clone(),
11129                    context.workflow_id.clone(),
11130                    context.run_id.clone(),
11131                    self.task_queue.clone(),
11132                    task.payload_codec,
11133                    None,
11134                )
11135                .map_err(|error| {
11136                    QueryTaskExecutionFailure::new(
11137                        "query_workflow_state_unavailable",
11138                        format!("workflow replay failed before query: {error}"),
11139                        "QueryWorkflowStateUnavailable",
11140                    )
11141                })?;
11142                // Query replay never submits commands, so an external signal
11143                // past the recorded history waits like any new command.
11144                replayed_state.signal_external_workflow_supported = true;
11145                let workflow_state = Arc::new(Mutex::new(replayed_state));
11146                let workflow_context = WorkflowContext {
11147                    state: workflow_state,
11148                    cancellation_scope_id: "root".into(),
11149                };
11150                query_authority::before_handler(authority, &self.client).await?;
11151                let mut invocation = {
11152                    let _clock = replay_clock::Guard::query(&workflow_context);
11153                    replay(workflow_context.clone(), workflow_input_typed.clone())
11154                }
11155                .map_err(|error| {
11156                    QueryTaskExecutionFailure::new(
11157                        "query_workflow_state_unavailable",
11158                        error.to_string(),
11159                        "QueryWorkflowStateUnavailable",
11160                    )
11161                })?;
11162                let outcome = {
11163                    let mut cx = TaskContext::from_waker(noop_waker_ref());
11164                    let _clock = replay_clock::Guard::query(&workflow_context);
11165                    let _replay = cancellation_replay_clock::ReplayGuard::enter(&workflow_context)
11166                        .map_err(|error| {
11167                            QueryTaskExecutionFailure::new(
11168                                "query_workflow_state_unavailable",
11169                                error.to_string(),
11170                                "QueryWorkflowStateUnavailable",
11171                            )
11172                        })?;
11173                    invocation.future.as_mut().poll(&mut cx)
11174                };
11175                match outcome {
11176                    Poll::Ready(Ok(_)) => {
11177                        workflow_context
11178                            .ensure_history_consumed()
11179                            .map_err(|error| {
11180                                QueryTaskExecutionFailure::new(
11181                                    "query_workflow_state_unavailable",
11182                                    format!("workflow replay failed before query: {error}"),
11183                                    "QueryWorkflowStateUnavailable",
11184                                )
11185                            })?;
11186                    }
11187                    Poll::Ready(Err(error)) => {
11188                        return Err(QueryTaskExecutionFailure::new(
11189                            "query_workflow_state_unavailable",
11190                            format!("workflow replay failed before query: {error}"),
11191                            "QueryWorkflowStateUnavailable",
11192                        ));
11193                    }
11194                    Poll::Pending => {
11195                        let commands = workflow_context.take_commands().map_err(|error| {
11196                            QueryTaskExecutionFailure::new(
11197                                "query_workflow_state_unavailable",
11198                                format!("workflow replay failed before query: {error}"),
11199                                "QueryWorkflowStateUnavailable",
11200                            )
11201                        })?;
11202                        if commands.is_empty()
11203                            && !workflow_context
11204                                .matched_recorded_pending()
11205                                .map_err(|error| {
11206                                    QueryTaskExecutionFailure::new(
11207                                        "query_workflow_state_unavailable",
11208                                        format!("workflow replay failed before query: {error}"),
11209                                        "QueryWorkflowStateUnavailable",
11210                                    )
11211                                })?
11212                        {
11213                            return Err(QueryTaskExecutionFailure::new(
11214                                "query_workflow_state_unavailable",
11215                                "workflow replay yielded without a durable command",
11216                                "QueryWorkflowStateUnavailable",
11217                            ));
11218                        }
11219                    }
11220                }
11221                let state = (invocation.snapshot)().map_err(|error| {
11222                    QueryTaskExecutionFailure::new(
11223                        "query_workflow_state_unavailable",
11224                        format!("cannot snapshot replayed workflow state: {error}"),
11225                        "QueryWorkflowStateUnavailable",
11226                    )
11227                })?;
11228                query_authority::before_handler(authority, &self.client).await?;
11229                context.replay_time = workflow_context
11230                    .state
11231                    .lock()
11232                    .map_err(|_| {
11233                        QueryTaskExecutionFailure::new(
11234                            "query_workflow_state_unavailable",
11235                            "workflow state poisoned",
11236                            "QueryWorkflowStateUnavailable",
11237                        )
11238                    })?
11239                    .replay_time()
11240                    .ok();
11241                handler(context, state, args).map_err(|message| {
11242                    QueryTaskExecutionFailure::new(
11243                        "query_workflow_state_unavailable",
11244                        message,
11245                        "QueryWorkflowStateUnavailable",
11246                    )
11247                })?
11248            }
11249        };
11250
11251        future.await.map_err(|error| {
11252            QueryTaskExecutionFailure::new("query_rejected", error.to_string(), "QueryFailed")
11253        })
11254    }
11255
11256    #[cfg(test)]
11257    fn execute_workflow_task(&self, task: WorkflowTask) -> Result<Vec<Value>> {
11258        Ok(self.execute_workflow_task_decision(task)?.commands)
11259    }
11260
11261    fn execute_workflow_task_decision(&self, task: WorkflowTask) -> Result<WorkflowTaskDecision> {
11262        self.execute_workflow_task_decision_with_cancellation(task, None)
11263    }
11264
11265    fn execute_workflow_task_decision_with_cancellation(
11266        &self,
11267        task: WorkflowTask,
11268        observation: Option<&CancellationRequest>,
11269    ) -> Result<WorkflowTaskDecision> {
11270        #[cfg(feature = "telemetry")]
11271        if let Some(telemetry) = &self.telemetry {
11272            return telemetry.run_sync_observed(
11273                "durable.workflow.task",
11274                self.workflow_telemetry_fields(&task),
11275                self.workflow_observations(&task),
11276                || {
11277                    let mut decision =
11278                        self.execute_workflow_task_decision_inner(task, observation)?;
11279                    self.stamp_observability_commands(&mut decision.commands);
11280                    Ok(decision)
11281                },
11282            );
11283        }
11284        self.execute_workflow_task_decision_inner(task, observation)
11285    }
11286
11287    fn execute_workflow_task_decision_inner(
11288        &self,
11289        task: WorkflowTask,
11290        observation: Option<&CancellationRequest>,
11291    ) -> Result<WorkflowTaskDecision> {
11292        match self.prepare_workflow_task_execution(task, observation)? {
11293            PreparedWorkflowTask::Decision(decision) => Ok(decision),
11294            PreparedWorkflowTask::Execution {
11295                task,
11296                context,
11297                mut future,
11298            } => {
11299                let outcome = Self::poll_workflow_future(&context, &mut future)?;
11300                self.finish_workflow_task_execution(&task, &context, outcome)
11301            }
11302        }
11303    }
11304
11305    fn prepare_workflow_task_execution(
11306        &self,
11307        task: WorkflowTask,
11308        observation: Option<&CancellationRequest>,
11309    ) -> Result<PreparedWorkflowTask> {
11310        if (self.allow_cancellation_scope_authoring || self.allow_cancellation_scope_delivery)
11311            && !self.cooperative_cancellation_enabled
11312        {
11313            return Err(Error::CancellationScopeExecutionUnavailable);
11314        }
11315        validate_workflow_task_payloads(&task)?;
11316        cooperative_cancellation::assert_cancellation_scope_replay_supported(
11317            &task.history_events,
11318            self.allow_cancellation_scope_authoring,
11319            self.allow_cancellation_scope_delivery,
11320        )?;
11321        let cancellation_history = if let Some(observation) = observation {
11322            observation.validate_observation()?;
11323            cooperative_cancellation::cancellation_claim(&task)?;
11324            let canonical = CancellationHistory::from_events(
11325                &task.history_events,
11326                task.run_id.as_deref().unwrap_or_default(),
11327                Some(observation),
11328            )?;
11329            if canonical.request_index >= task.history_events.len() {
11330                return Err(Error::InvalidCooperativeCancellation(
11331                    "workflow replay requires the observed canonical request".into(),
11332                ));
11333            }
11334            Some(canonical)
11335        } else {
11336            None
11337        };
11338        if let Some(update_id) = task
11339            .workflow_update_id
11340            .as_deref()
11341            .filter(|update_id| !update_id.is_empty())
11342        {
11343            if self.allow_cancellation_scope_delivery {
11344                return Err(Error::CancellationScopeExecutionUnavailable);
11345            }
11346            CancellationHistory::from_events(
11347                &task.history_events,
11348                task.run_id.as_deref().unwrap_or_default(),
11349                None,
11350            )?;
11351            return self
11352                .execute_update_task(&task, update_id)
11353                .map(WorkflowTaskDecision::without_message_streams)
11354                .map(PreparedWorkflowTask::Decision);
11355        }
11356
11357        let workflow = self
11358            .workflows
11359            .get(&task.workflow_type)
11360            .ok_or_else(|| Error::WorkflowNotRegistered(task.workflow_type.clone()))?;
11361        let input = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
11362        let resume_signal = decode_resume_signal(&task)?;
11363        let history_budget = WorkflowHistoryBudget {
11364            event_count: task
11365                .total_history_events
11366                .unwrap_or_else(|| u64::try_from(task.history_events.len()).unwrap_or(u64::MAX)),
11367            size_bytes: task.history_size_bytes,
11368            continue_as_new_recommended: task.continue_as_new_recommended.unwrap_or(false),
11369            pressure: task.history_budget_pressure.clone(),
11370        };
11371        let workflow_command_identity = task
11372            .workflow_command_id
11373            .clone()
11374            .filter(|identity| !identity.is_empty())
11375            .or_else(|| (!task.task_id.is_empty()).then(|| task.task_id.clone()))
11376            .unwrap_or_default();
11377        let mut workflow_state = WorkflowState::new_with_identity_and_scope_delivery(
11378            task.history_events.clone(),
11379            task.workflow_id.clone(),
11380            task.run_id.clone(),
11381            self.task_queue.clone(),
11382            task.payload_codec.clone(),
11383            resume_signal,
11384            CancellationScopeAllowance {
11385                authoring: self.allow_cancellation_scope_authoring,
11386                delivery: self.allow_cancellation_scope_delivery,
11387            },
11388        )?;
11389        workflow_state.observation_namespace = Some(self.client.namespace.clone());
11390        workflow_state.signal_external_workflow_supported = self
11391            .signal_external_workflow_supported
11392            .load(Ordering::SeqCst);
11393        workflow_state.history_budget = history_budget;
11394        workflow_state.workflow_command_identity = workflow_command_identity;
11395        if let Some(canonical) = cancellation_history {
11396            workflow_state.cancellation_history = canonical;
11397            workflow_state.cancellation_delivery_enabled = true;
11398        }
11399        if workflow_state.cancellation_history.request.is_none() {
11400            workflow_state.cancel_requested = task.cancel_requested;
11401        }
11402        let state = Arc::new(Mutex::new(workflow_state));
11403        let ctx = WorkflowContext {
11404            state,
11405            cancellation_scope_id: "root".into(),
11406        };
11407        let future = {
11408            let _clock = replay_clock::Guard::enter(&ctx);
11409            (workflow.execute)(ctx.clone(), input)?
11410        };
11411        Ok(PreparedWorkflowTask::Execution {
11412            task,
11413            context: ctx,
11414            future,
11415        })
11416    }
11417
11418    fn poll_workflow_future(
11419        ctx: &WorkflowContext,
11420        future: &mut WorkflowFuture,
11421    ) -> Result<Poll<Result<AvroValue>>> {
11422        let mut cx = TaskContext::from_waker(noop_waker_ref());
11423        let _clock = replay_clock::Guard::enter(ctx);
11424        let _replay = cancellation_replay_clock::ReplayGuard::enter(ctx)?;
11425        Ok(future.as_mut().poll(&mut cx))
11426    }
11427
11428    fn finish_workflow_task_execution(
11429        &self,
11430        task: &WorkflowTask,
11431        ctx: &WorkflowContext,
11432        outcome: Poll<Result<AvroValue>>,
11433    ) -> Result<WorkflowTaskDecision> {
11434        if !ctx
11435            .state
11436            .lock()
11437            .map_err(|_| Error::WorkflowStatePoisoned)?
11438            .local_activity_requests
11439            .is_empty()
11440        {
11441            return Err(Error::CooperativeCancellationUnavailable(
11442                "local_activity_execution_unavailable: unresolved inline local calls require an ordinary workflow worker executor; cooperative execution requires prepared local supervision".into(),
11443            ));
11444        }
11445        let awaiting_canonical_boundary = {
11446            let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
11447            state.cancellation_delivery_intent.is_some()
11448                || state.cancellation_scope_opening.is_some()
11449                || state
11450                    .scope_delivery
11451                    .as_ref()
11452                    .is_some_and(|replay| replay.intent.is_some())
11453        };
11454        if awaiting_canonical_boundary {
11455            // A private delivery intent never becomes an application error.
11456            // Even a custom future which ignores a pending durable call cannot
11457            // publish terminal commands before canonical delivery and replay.
11458            if let Poll::Ready(Err(error)) = outcome {
11459                if workflow_task_integrity_error(&error) {
11460                    return Err(error);
11461                }
11462            }
11463            return self.message_stream_decision(ctx, ctx.take_commands()?);
11464        }
11465
11466        match outcome {
11467            Poll::Ready(Ok(result)) => {
11468                ctx.ensure_history_consumed()?;
11469                let result = encode_typed_envelope(&result, &task.payload_codec)?;
11470                let mut commands = ctx.take_commands()?;
11471                commands.push(json!({
11472                    "type": "complete_workflow",
11473                    "result": result
11474                }));
11475                self.message_stream_decision(ctx, commands)
11476            }
11477            Poll::Ready(Err(error)) => {
11478                if let Error::ContinueAsNew(request) = error {
11479                    let mut commands = ctx.take_commands()?;
11480                    if let Some(command) = ctx.continue_as_new_command(request)? {
11481                        commands.push(command);
11482                    }
11483                    ctx.ensure_history_consumed()?;
11484                    return self.message_stream_decision(ctx, commands);
11485                }
11486                if workflow_task_integrity_error(&error) {
11487                    // Replay and protocol failures describe the workflow-task
11488                    // decision itself. Preserve their specific failure reason
11489                    // instead of replacing it with the derivative fact that
11490                    // recorded commands remain unconsumed.
11491                    return Err(error);
11492                }
11493                // A handler error must not hide a committed durable command that
11494                // upgraded workflow code no longer consumes.
11495                ctx.ensure_history_consumed()?;
11496                let mut commands = ctx.take_commands()?;
11497                commands.push(workflow_failure_command(
11498                    &error,
11499                    recorded_activity_failure_boundary(ctx, &error),
11500                ));
11501                self.message_stream_decision(ctx, commands)
11502            }
11503            Poll::Pending => {
11504                let commands = ctx.take_commands()?;
11505                if commands.is_empty() && !ctx.matched_recorded_pending()? {
11506                    Err(Error::WorkflowYieldedWithoutCommand)
11507                } else {
11508                    self.message_stream_decision(ctx, commands)
11509                }
11510            }
11511        }
11512    }
11513
11514    fn message_stream_decision(
11515        &self,
11516        ctx: &WorkflowContext,
11517        commands: Vec<Value>,
11518    ) -> Result<WorkflowTaskDecision> {
11519        if !self.cooperative_cancellation_enabled
11520            && commands.iter().any(|command| {
11521                command["type"] == "schedule_activity"
11522                    && command.get("cancellation_policy").is_some()
11523            })
11524        {
11525            return Err(Error::CooperativeCancellationUnavailable(format!(
11526                "activity_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
11527                self.worker_id,
11528            )));
11529        }
11530        if !self.cooperative_cancellation_enabled
11531            && commands.iter().any(|command| {
11532                command["type"] == "start_child_workflow"
11533                    && (command["parent_close_policy"] == "request_cancellation"
11534                        || matches!(
11535                            command["cancellation_policy"].as_str(),
11536                            Some("try_cancel" | "wait_cancellation_completed")
11537                        ))
11538            })
11539        {
11540            return Err(Error::CooperativeCancellationUnavailable(format!(
11541                "child_cancellation_policy_not_supported: Rust worker {} must enable cooperative cancellation with worker protocol 1.20 and a compatible Server/Native backend",
11542                self.worker_id,
11543            )));
11544        }
11545        let (message_stream_cursors, message_stream_waits) = ctx.message_stream_metadata()?;
11546        let state = ctx.state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
11547        let scope_delivery = state
11548            .scope_delivery
11549            .as_ref()
11550            .and_then(|replay| replay.intent.clone());
11551        if scope_delivery
11552            .as_ref()
11553            .is_some_and(|intent| commands.len() != intent.command_count)
11554        {
11555            return Err(invalid_recorded_history(
11556                "cancellation_scope_pending_call_escaped",
11557                scope_delivery.as_ref().unwrap().boundary.sequence,
11558                "commands preceding the pending scoped call",
11559                "commands after suspension",
11560                "workflow cannot publish beyond an uncommitted scope delivery",
11561            ));
11562        }
11563        if let Some(opening) = &state.cancellation_scope_opening {
11564            if commands.len() != opening.command_count {
11565                return Err(invalid_recorded_history(
11566                    "cancellation_scope_pending_call_escaped",
11567                    opening.sequence,
11568                    "commands before original scope opening",
11569                    "commands after suspended opening",
11570                    "workflow cannot publish beyond an uncommitted scope opening",
11571                ));
11572            }
11573        }
11574        if let Some(intent) = state
11575            .cancellation_delivery_intent
11576            .as_ref()
11577            .filter(|_| commands.len() != state.cancellation_delivery_command_count)
11578        {
11579            return Err(invalid_recorded_history(
11580                "cooperative_cancellation_pending_call_escaped",
11581                intent.sequence,
11582                "only commands preceding the pending cancellation call",
11583                "commands authored after a suspended call",
11584                "workflow code cannot publish work beyond an uncommitted cancellation boundary",
11585            ));
11586        }
11587        Ok(WorkflowTaskDecision {
11588            commands,
11589            message_stream_cursors,
11590            message_stream_waits,
11591            cancellation_delivery: state.cancellation_delivery_intent.clone(),
11592            cancellation_scope_opening: state.cancellation_scope_opening.clone(),
11593            cancellation_scope_delivery: scope_delivery,
11594        })
11595    }
11596
11597    fn execute_update_task(&self, task: &WorkflowTask, update_id: &str) -> Result<Vec<Value>> {
11598        if !self.workflows.contains_key(&task.workflow_type) {
11599            return Err(Error::WorkflowNotRegistered(task.workflow_type.clone()));
11600        }
11601
11602        let accepted = task.history_events.iter().rev().find_map(|event| {
11603            (event.event_type == "UpdateAccepted"
11604                && event.payload.get("update_id").and_then(Value::as_str) == Some(update_id))
11605            .then_some(&event.payload)
11606        });
11607        let update_name = accepted
11608            .and_then(|payload| payload.get("update_name"))
11609            .and_then(Value::as_str)
11610            .or(task.update_name.as_deref())
11611            .unwrap_or_default();
11612        let Some(handler) = self
11613            .updates
11614            .get(&task.workflow_type)
11615            .and_then(|handlers| handlers.get(update_name))
11616        else {
11617            return Ok(vec![json!({
11618                "type": "fail_update",
11619                "update_id": update_id,
11620                "message": format!(
11621                    "no update handler is registered for {}.{update_name}",
11622                    task.workflow_type
11623                ),
11624                "exception_type": "UnknownUpdate",
11625                "non_retryable": true,
11626            })]);
11627        };
11628        let arguments = accepted
11629            .and_then(|payload| payload.get("arguments"))
11630            .or(task.arguments.as_ref());
11631        let arguments = decode_task_avro_arguments(arguments, &task.payload_codec)?;
11632        let workflow_input_avro_value =
11633            decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
11634        let workflow_input = workflow_input_avro_value.clone().into_json()?;
11635        let signal_events = history_signal_events(&task.history_events, None, &task.payload_codec)?;
11636        let context = QueryContext {
11637            workflow_id: task.workflow_id.clone(),
11638            run_id: task.run_id.clone(),
11639            workflow_type: task.workflow_type.clone(),
11640            run_status: Some("running".to_string()),
11641            workflow_input,
11642            workflow_input_avro_value,
11643            replay_time: replay_clock::update_time(&task.history_events, update_id),
11644            history_events: Arc::new(task.history_events.clone()),
11645            signal_events: Arc::new(signal_events),
11646        };
11647        let mut future = handler(context, arguments);
11648        let mut cx = TaskContext::from_waker(noop_waker_ref());
11649
11650        match future.as_mut().poll(&mut cx) {
11651            Poll::Ready(Ok(result)) => Ok(vec![json!({
11652                "type": "complete_update",
11653                "update_id": update_id,
11654                "result": encode_typed_envelope(&result, &task.payload_codec)?,
11655            })]),
11656            Poll::Ready(Err(error)) => Ok(vec![json!({
11657                "type": "fail_update",
11658                "update_id": update_id,
11659                "message": error.to_string(),
11660                "exception_type": "UpdateFailed",
11661                "non_retryable": true,
11662            })]),
11663            Poll::Pending => Err(Error::WorkflowYieldedWithoutCommand),
11664        }
11665    }
11666
11667    #[cfg(test)]
11668    async fn execute_activity_task(&self, task: ActivityTask) -> Result<AvroValue> {
11669        let invocation = worker_session::ActivityInvocation::unknown(task.attempt_number);
11670        self.execute_session_activity_task(task, invocation).await
11671    }
11672
11673    async fn execute_session_activity_task(
11674        &self,
11675        task: ActivityTask,
11676        invocation: worker_session::ActivityInvocation,
11677    ) -> Result<AvroValue> {
11678        #[cfg(feature = "telemetry")]
11679        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
11680            !self
11681                .client
11682                .observability_context_supported
11683                .load(Ordering::SeqCst)
11684        }) {
11685            return telemetry
11686                .run(
11687                    "durable.activity.task",
11688                    self.activity_telemetry_fields(&task),
11689                    false,
11690                    self.execute_session_activity_task_inner(task, invocation),
11691                )
11692                .await;
11693        }
11694        self.execute_session_activity_task_inner(task, invocation)
11695            .await
11696    }
11697
11698    async fn execute_session_activity_task_inner(
11699        &self,
11700        task: ActivityTask,
11701        invocation: worker_session::ActivityInvocation,
11702    ) -> Result<AvroValue> {
11703        let worker_session::ActivityInvocation {
11704            worker_session,
11705            hydration_claim,
11706            retry_info,
11707            heartbeat_resume,
11708        } = invocation;
11709        validate_activity_task_payloads(&task)?;
11710        if worker_session.is_some()
11711            && (task.lease_owner.as_deref() != Some(self.worker_id.as_str())
11712                || task
11713                    .activity_attempt_id
11714                    .as_deref()
11715                    .or(task.attempt_id.as_deref())
11716                    .is_none_or(str::is_empty)
11717                || matches!((&task.activity_attempt_id,&task.attempt_id),(Some(a),Some(b)) if a != b))
11718        {
11719            return Err(Error::ActivityExecutionAbandoned(
11720                "session activity requires this worker's exact immutable claim".into(),
11721            ));
11722        }
11723
11724        let handler = self
11725            .activities
11726            .get(&task.activity_type)
11727            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
11728        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
11729        let attempt_id = task
11730            .activity_attempt_id
11731            .clone()
11732            .or(task.attempt_id.clone())
11733            .unwrap_or_default();
11734        let lease_owner = task
11735            .lease_owner
11736            .clone()
11737            .unwrap_or_else(|| self.worker_id.clone());
11738        let session = worker_session.clone();
11739        if let Some(claim) = &hydration_claim {
11740            claim.confirm(&self.client).await?;
11741        }
11742        #[cfg(feature = "telemetry")]
11743        let observations = self.activity_observations(&task);
11744        #[cfg(feature = "telemetry")]
11745        let fields = self.activity_telemetry_fields(&task);
11746        let ctx = ActivityContext {
11747            client: self.client.clone(),
11748            task_id: task.task_id,
11749            activity_attempt_id: attempt_id,
11750            lease_owner,
11751            activity_type: task.activity_type,
11752            attempt_number: task.attempt_number,
11753            retry_info,
11754            heartbeat_resume,
11755            activity_execution_id: task.activity_execution_id,
11756            workflow_id: task.workflow_id,
11757            run_id: task.run_id,
11758            task_queue: self.task_queue.clone(),
11759            worker_id: self.worker_id.clone(),
11760            claim_guard: None,
11761            local_heartbeats: None,
11762            worker_session,
11763        };
11764
11765        let operation = async {
11766            let callback = self.activity_callback(handler, ctx, args, false);
11767            if let Some(session) = session {
11768                tokio::select! {
11769                    biased;
11770                    _ = session.wait_until_unavailable() => Err(Error::ActivityExecutionAbandoned("worker-session lease or TTL expired, closed or became uncertain".into())),
11771                    result = callback => if session.active() { result } else {
11772                        Err(Error::ActivityExecutionAbandoned("worker-session authority ended before callback settlement".into()))
11773                    },
11774                }
11775            } else {
11776                callback.await
11777            }
11778        };
11779        #[cfg(feature = "telemetry")]
11780        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
11781            self.client
11782                .observability_context_supported
11783                .load(Ordering::SeqCst)
11784        }) {
11785            return telemetry
11786                .run_observed(
11787                    "durable.activity.task",
11788                    fields,
11789                    false,
11790                    observations,
11791                    operation,
11792                )
11793                .await;
11794        }
11795        operation.await
11796    }
11797
11798    fn activity_callback(
11799        &self,
11800        handler: &ActivityHandler,
11801        context: ActivityContext,
11802        args: AvroValue,
11803        local: bool,
11804    ) -> ActivityFuture {
11805        #[cfg(feature = "telemetry")]
11806        if let Some(telemetry) = &self.telemetry {
11807            let telemetry = telemetry.clone();
11808            let fields = self.callback_telemetry_fields(&context, local);
11809            let handler = handler.clone();
11810            let name = if local {
11811                "durable.local_activity.attempt"
11812            } else {
11813                "durable.activity.attempt"
11814            };
11815            return Box::pin(async move {
11816                telemetry
11817                    .run(
11818                        name,
11819                        fields,
11820                        true,
11821                        async move { handler(context, args).await },
11822                    )
11823                    .await
11824            });
11825        }
11826        #[cfg(not(feature = "telemetry"))]
11827        let _ = local;
11828        handler(context, args)
11829    }
11830}
11831
11832fn poller_result(
11833    kind: &str,
11834    result: std::result::Result<Result<()>, tokio::task::JoinError>,
11835) -> Result<()> {
11836    match result {
11837        Ok(result) => result,
11838        Err(error) => Err(Error::WorkerLoop(format!(
11839            "{kind} poller join error: {error}"
11840        ))),
11841    }
11842}
11843
11844fn optional_poller_result(
11845    kind: &str,
11846    result: Option<std::result::Result<Result<()>, tokio::task::JoinError>>,
11847) -> Result<()> {
11848    match result {
11849        Some(result) => poller_result(kind, result),
11850        None => Ok(()),
11851    }
11852}
11853
11854async fn join_pollers(
11855    workflow_poller: Option<tokio::task::JoinHandle<Result<()>>>,
11856    activity_poller: Option<tokio::task::JoinHandle<Result<()>>>,
11857    query_poller: Option<tokio::task::JoinHandle<Result<()>>>,
11858) -> Result<()> {
11859    let mut first_error = None;
11860
11861    if let Some(handle) = workflow_poller {
11862        if let Err(error) = poller_result("workflow", handle.await) {
11863            first_error.get_or_insert(error);
11864        }
11865    }
11866
11867    if let Some(handle) = activity_poller {
11868        if let Err(error) = poller_result("activity", handle.await) {
11869            first_error.get_or_insert(error);
11870        }
11871    }
11872
11873    if let Some(handle) = query_poller {
11874        if let Err(error) = poller_result("query", handle.await) {
11875            first_error.get_or_insert(error);
11876        }
11877    }
11878
11879    if let Some(error) = first_error {
11880        Err(error)
11881    } else {
11882        Ok(())
11883    }
11884}
11885
11886fn default_worker_id() -> String {
11887    let millis = SystemTime::now()
11888        .duration_since(UNIX_EPOCH)
11889        .unwrap_or_default()
11890        .as_millis();
11891    format!("rust-worker-{}-{millis}", std::process::id())
11892}
11893
11894/// Only the endpoint origin, since base paths can contain namespace identities
11895/// or proxy credentials that must not appear in logs.
11896fn tls_warning_endpoint(base_url: &str) -> String {
11897    match reqwest::Url::parse(base_url) {
11898        Ok(url) => url.origin().ascii_serialization(),
11899        Err(_) => "<unparseable base URL>".to_string(),
11900    }
11901}
11902
11903fn percent_encode_path_segment(segment: &str) -> String {
11904    const HEX: &[u8; 16] = b"0123456789ABCDEF";
11905    let mut encoded = String::with_capacity(segment.len());
11906
11907    for byte in segment.bytes() {
11908        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
11909            encoded.push(char::from(byte));
11910        } else {
11911            encoded.push('%');
11912            encoded.push(char::from(HEX[(byte >> 4) as usize]));
11913            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
11914        }
11915    }
11916
11917    encoded
11918}
11919
11920fn unique_request_id(prefix: &str) -> String {
11921    let nanos = SystemTime::now()
11922        .duration_since(UNIX_EPOCH)
11923        .unwrap_or_default()
11924        .as_nanos();
11925    format!("{prefix}-{}-{nanos}", std::process::id())
11926}
11927
11928#[derive(Debug)]
11929struct QueryTaskExecutionFailure {
11930    reason: String,
11931    message: String,
11932    failure_type: String,
11933}
11934
11935impl QueryTaskExecutionFailure {
11936    fn new(
11937        reason: impl Into<String>,
11938        message: impl Into<String>,
11939        failure_type: impl Into<String>,
11940    ) -> Self {
11941        Self {
11942            reason: reason.into(),
11943            message: message.into(),
11944            failure_type: failure_type.into(),
11945        }
11946    }
11947}
11948
11949/// Typed local state owned by one deterministic workflow invocation.
11950///
11951/// Use [`WorkflowInstance::update`] for the same state transitions during
11952/// ordinary execution and replay. A replayed query receives a detached
11953/// immutable `Arc<S>` rather than this mutation-capable handle.
11954#[derive(Clone, Debug)]
11955pub struct WorkflowInstance<S> {
11956    state: Arc<Mutex<S>>,
11957}
11958
11959impl<S> WorkflowInstance<S> {
11960    fn new(state: S) -> Self {
11961        Self {
11962            state: Arc::new(Mutex::new(state)),
11963        }
11964    }
11965
11966    /// Read the current workflow-instance state without changing it.
11967    pub fn read<R>(&self, reader: impl FnOnce(&S) -> R) -> Result<R> {
11968        let state = self
11969            .state
11970            .lock()
11971            .map_err(|_| Error::WorkflowStatePoisoned)?;
11972        Ok(reader(&state))
11973    }
11974
11975    /// Apply one deterministic workflow-instance state transition.
11976    pub fn update<R>(&self, transition: impl FnOnce(&mut S) -> R) -> Result<R> {
11977        let mut state = self
11978            .state
11979            .lock()
11980            .map_err(|_| Error::WorkflowStatePoisoned)?;
11981        Ok(transition(&mut state))
11982    }
11983}
11984
11985impl<S: Clone> WorkflowInstance<S> {
11986    fn snapshot(&self) -> Result<S> {
11987        self.read(Clone::clone)
11988    }
11989}
11990
11991#[derive(Clone, Debug, PartialEq)]
11992pub struct MessageStreamMessage {
11993    pub stream_name: String,
11994    pub message_id: String,
11995    pub position: u64,
11996    pub arguments: Vec<AvroValue>,
11997}
11998
11999#[derive(Clone, Debug)]
12000pub struct MessageStream {
12001    ctx: WorkflowContext,
12002    name: String,
12003}
12004
12005impl MessageStream {
12006    /// Wait for one message, then return a bounded currently-available batch.
12007    pub async fn receive(&self, max_items: usize) -> Result<Vec<MessageStreamMessage>> {
12008        if !(1..=MESSAGE_STREAM_MAX_BATCH).contains(&max_items) {
12009            return Err(Error::Codec(format!(
12010                "message stream max_items must be between 1 and {MESSAGE_STREAM_MAX_BATCH}"
12011            )));
12012        }
12013        loop {
12014            if let Some(batch) = self.ctx.take_message_stream_batch(&self.name, max_items)? {
12015                return Ok(batch);
12016            }
12017
12018            self.ctx.record_message_stream_wait(&self.name)?;
12019            let replay_wait_sequence = self.ctx.next_message_stream_wait_sequence()?;
12020            let arguments = self.ctx.wait_runtime_signal(MESSAGE_STREAM_SIGNAL).await?;
12021            self.ctx.buffer_message_stream_delivery(arguments)?;
12022            if let Some(sequence) = replay_wait_sequence {
12023                self.ctx.buffer_message_stream_history_for_wait(sequence)?;
12024            }
12025        }
12026    }
12027
12028    pub async fn receive_one(&self) -> Result<MessageStreamMessage> {
12029        self.receive(1)
12030            .await?
12031            .into_iter()
12032            .next()
12033            .ok_or_else(|| Error::Codec("message stream resumed without a message".to_string()))
12034    }
12035}
12036
12037#[derive(Clone, Debug)]
12038pub struct WorkflowContext {
12039    state: Arc<Mutex<WorkflowState>>,
12040    cancellation_scope_id: String,
12041}
12042
12043fn valid_memo_key(key: &str) -> bool {
12044    let numeric_candidate = key.strip_prefix('-').unwrap_or(key);
12045
12046    !key.is_empty()
12047        && key.len() <= 64
12048        && (numeric_candidate.is_empty()
12049            || !numeric_candidate.bytes().all(|byte| byte.is_ascii_digit()))
12050        && key
12051            .bytes()
12052            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b':' | b'-'))
12053}
12054
12055fn avro_encoded_size(value: &AvroValue) -> Result<usize> {
12056    BASE64
12057        .decode(encode_avro_value(value)?.blob)
12058        .map(|bytes| bytes.len())
12059        .map_err(|error| Error::Codec(format!("memo Avro encoding was not strict base64: {error}")))
12060}
12061
12062fn canonical_memo_entries(value: AvroValue, require_entries: bool) -> Result<AvroValue> {
12063    let AvroValue::Map(entries) = value else {
12064        return Err(Error::InvalidMemoUpdate(
12065            "entries must serialize to an Avro string-keyed map".to_string(),
12066        ));
12067    };
12068    if require_entries && entries.is_empty() {
12069        return Err(Error::InvalidMemoUpdate(
12070            "at least one entry is required".to_string(),
12071        ));
12072    }
12073    if entries.len() > MAX_MEMO_ENTRIES {
12074        return Err(Error::InvalidMemoUpdate(format!(
12075            "at most {MAX_MEMO_ENTRIES} entries are allowed"
12076        )));
12077    }
12078
12079    for (key, value) in &entries {
12080        if !valid_memo_key(key) {
12081            return Err(Error::InvalidMemoUpdate(
12082                "keys must match ^(?!-?[0-9]+$)[A-Za-z0-9_.:-]{1,64}$".to_string(),
12083            ));
12084        }
12085        if avro_encoded_size(value)? > MAX_MEMO_VALUE_SIZE_BYTES {
12086            return Err(Error::InvalidMemoUpdate(format!(
12087                "value {key:?} exceeds the {MAX_MEMO_VALUE_SIZE_BYTES}-byte limit"
12088            )));
12089        }
12090    }
12091
12092    let value = AvroValue::Map(entries);
12093    if avro_encoded_size(&value)? > MAX_MEMO_TOTAL_SIZE_BYTES {
12094        return Err(Error::InvalidMemoUpdate(format!(
12095            "update exceeds the {MAX_MEMO_TOTAL_SIZE_BYTES}-byte total limit"
12096        )));
12097    }
12098    Ok(value)
12099}
12100
12101fn decode_memo_history_map(envelope: &Value, require_entries: bool) -> Result<AvroValue> {
12102    let object = envelope.as_object().ok_or_else(|| {
12103        Error::InvalidMemoUpdate(
12104            "history field must use the public {codec, blob} payload envelope".to_string(),
12105        )
12106    })?;
12107    if object.len() != 2 || !object.contains_key("codec") || !object.contains_key("blob") {
12108        return Err(Error::InvalidMemoUpdate(
12109            "history field must use exactly the public {codec, blob} payload envelope".to_string(),
12110        ));
12111    }
12112
12113    canonical_memo_entries(
12114        decode_wire_avro_value(envelope, DEFAULT_CODEC)?,
12115        require_entries,
12116    )
12117}
12118
12119impl WorkflowContext {
12120    pub fn message_stream(&self, name: impl Into<String>) -> Result<MessageStream> {
12121        let name = name.into();
12122        if name.is_empty()
12123            || name.len() > 128
12124            || !name.bytes().all(|byte| {
12125                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
12126            })
12127        {
12128            return Err(Error::Codec(
12129                "message stream names must contain 1-128 letters, numbers, periods, underscores, colons, or hyphens"
12130                    .to_string(),
12131            ));
12132        }
12133        Ok(MessageStream {
12134            ctx: self.clone(),
12135            name,
12136        })
12137    }
12138
12139    fn record_message_stream_wait(&self, name: &str) -> Result<()> {
12140        let mut state = self
12141            .state
12142            .lock()
12143            .map_err(|_| Error::WorkflowStatePoisoned)?;
12144        let position = state.message_stream_cursors.get(name).copied().unwrap_or(0);
12145        state
12146            .message_stream_waits
12147            .insert(name.to_string(), position);
12148        Ok(())
12149    }
12150
12151    fn buffer_message_stream(&self, message: MessageStreamMessage) -> Result<()> {
12152        let mut state = self
12153            .state
12154            .lock()
12155            .map_err(|_| Error::WorkflowStatePoisoned)?;
12156        let cursor = state
12157            .message_stream_cursors
12158            .get(&message.stream_name)
12159            .copied()
12160            .unwrap_or(0);
12161        if message.position <= cursor {
12162            return Ok(());
12163        }
12164        let pending = state
12165            .message_stream_messages
12166            .entry(message.stream_name.clone())
12167            .or_default();
12168        if pending.iter().any(|candidate| {
12169            candidate.position == message.position || candidate.message_id == message.message_id
12170        }) {
12171            return Ok(());
12172        }
12173        pending.push(message);
12174        pending.sort_by_key(|candidate| candidate.position);
12175        Ok(())
12176    }
12177
12178    fn buffer_message_stream_delivery(&self, arguments: Vec<Value>) -> Result<Option<String>> {
12179        if let Some(delivery) = decode_message_stream_delivery(arguments)? {
12180            match delivery {
12181                MessageStreamDelivery::Message(message) => {
12182                    let stream_name = message.stream_name.clone();
12183                    self.buffer_message_stream(message)?;
12184                    return Ok(Some(stream_name));
12185                }
12186                MessageStreamDelivery::Cursor {
12187                    stream_name,
12188                    through_position,
12189                } => self.apply_message_stream_cursor(&stream_name, through_position)?,
12190            }
12191        }
12192        Ok(None)
12193    }
12194
12195    fn next_message_stream_wait_sequence(&self) -> Result<Option<u64>> {
12196        let state = self
12197            .state
12198            .lock()
12199            .map_err(|_| Error::WorkflowStatePoisoned)?;
12200        Ok(match state.recorded_commands.get(state.command_cursor) {
12201            Some(RecordedCommand::SignalWait {
12202                sequence,
12203                signal_name,
12204                ..
12205            }) if signal_name == MESSAGE_STREAM_SIGNAL => Some(*sequence),
12206            _ => None,
12207        })
12208    }
12209
12210    fn buffer_message_stream_history_for_wait(&self, wait_sequence: u64) -> Result<()> {
12211        let (history, payload_codec) = {
12212            let state = self
12213                .state
12214                .lock()
12215                .map_err(|_| Error::WorkflowStatePoisoned)?;
12216            (
12217                Arc::clone(&state.history_events),
12218                state.payload_codec.clone(),
12219            )
12220        };
12221
12222        let Some(opened_index) = history.iter().position(|event| {
12223            event.event_type == "SignalWaitOpened"
12224                && durable_event_sequence(event) == Some(wait_sequence)
12225                && event.payload.get("signal_name").and_then(Value::as_str)
12226                    == Some(MESSAGE_STREAM_SIGNAL)
12227        }) else {
12228            return Ok(());
12229        };
12230        let boundary_index = history
12231            .iter()
12232            .enumerate()
12233            .skip(opened_index + 1)
12234            .find_map(|(index, event)| {
12235                (durable_event_sequence(event).is_some_and(|sequence| sequence > wait_sequence)
12236                    && is_authored_command_open_event(event))
12237                .then_some(index)
12238            })
12239            .unwrap_or(history.len());
12240
12241        for event in history[opened_index + 1..boundary_index]
12242            .iter()
12243            .filter(|event| {
12244                event.event_type == "SignalReceived"
12245                    && event.payload.get("signal_name").and_then(Value::as_str)
12246                        == Some(MESSAGE_STREAM_SIGNAL)
12247            })
12248        {
12249            let arguments = decode_signal_event_arguments(event, &payload_codec)?
12250                .into_iter()
12251                .map(AvroValue::into_json)
12252                .collect::<Result<Vec<_>>>()?;
12253            self.buffer_message_stream_delivery(arguments)?;
12254        }
12255        Ok(())
12256    }
12257
12258    fn apply_message_stream_cursor(&self, name: &str, through_position: u64) -> Result<()> {
12259        let mut state = self
12260            .state
12261            .lock()
12262            .map_err(|_| Error::WorkflowStatePoisoned)?;
12263        let cursor = state
12264            .message_stream_cursors
12265            .entry(name.to_string())
12266            .or_default();
12267        *cursor = (*cursor).max(through_position);
12268        if let Some(pending) = state.message_stream_messages.get_mut(name) {
12269            pending.retain(|message| message.position > through_position);
12270        }
12271        Ok(())
12272    }
12273
12274    fn take_message_stream_batch(
12275        &self,
12276        name: &str,
12277        max_items: usize,
12278    ) -> Result<Option<Vec<MessageStreamMessage>>> {
12279        let mut state = self
12280            .state
12281            .lock()
12282            .map_err(|_| Error::WorkflowStatePoisoned)?;
12283        let cursor = state.message_stream_cursors.get(name).copied().unwrap_or(0);
12284        let pending = state
12285            .message_stream_messages
12286            .entry(name.to_string())
12287            .or_default();
12288        let count = contiguous_message_stream_count(pending, cursor, max_items);
12289        if count == 0 {
12290            return Ok(None);
12291        }
12292        let batch = pending.drain(..count).collect::<Vec<_>>();
12293        let position = batch.last().map(|message| message.position).unwrap_or(0);
12294        state
12295            .message_stream_cursors
12296            .insert(name.to_string(), position);
12297        state.message_stream_waits.remove(name);
12298        Ok(Some(batch))
12299    }
12300
12301    fn message_stream_metadata(&self) -> Result<(Vec<Value>, Vec<Value>)> {
12302        let state = self
12303            .state
12304            .lock()
12305            .map_err(|_| Error::WorkflowStatePoisoned)?;
12306        let mut cursors = state.message_stream_cursors.iter().collect::<Vec<_>>();
12307        cursors.sort_by_key(|(name, _)| *name);
12308        let mut waits = state.message_stream_waits.iter().collect::<Vec<_>>();
12309        waits.sort_by_key(|(name, _)| *name);
12310        Ok((
12311            cursors
12312                .into_iter()
12313                .map(|(name, position)| json!({"stream_name": name, "through_position": position}))
12314                .collect(),
12315            waits
12316                .into_iter()
12317                .map(|(name, position)| json!({"stream_name": name, "after_position": position}))
12318                .collect(),
12319        ))
12320    }
12321    /// The schedule fire that started this run, or `None` if no schedule did.
12322    ///
12323    /// It comes from the run's recorded `ScheduleTriggered` history event, so
12324    /// it is available on the first workflow task and identical on replay.
12325    pub fn schedule_origin(&self) -> Result<Option<ScheduleOrigin>> {
12326        let state = self
12327            .state
12328            .lock()
12329            .map_err(|_| Error::WorkflowStatePoisoned)?;
12330        Ok(ScheduleOrigin::from_history(&state.history_events))
12331    }
12332
12333    /// Identity of the parent workflow currently being replayed.
12334    pub fn workflow_identity(&self) -> Result<WorkflowIdentity> {
12335        let state = self
12336            .state
12337            .lock()
12338            .map_err(|_| Error::WorkflowStatePoisoned)?;
12339        Ok(WorkflowIdentity {
12340            workflow_id: state.workflow_id.clone(),
12341            run_id: state.run_id.clone(),
12342        })
12343    }
12344
12345    /// Return the server-published history budget for this workflow task.
12346    pub fn history_budget(&self) -> Result<WorkflowHistoryBudget> {
12347        let state = self
12348            .state
12349            .lock()
12350            .map_err(|_| Error::WorkflowStatePoisoned)?;
12351        Ok(state.history_budget.clone())
12352    }
12353
12354    /// Continue this workflow instance as a fresh run with replacement arguments.
12355    ///
12356    /// Return this value directly from the workflow handler. The worker converts
12357    /// it to the terminal protocol command only after replay has consumed every
12358    /// recorded durable command.
12359    pub fn continue_as_new<T: Serialize>(&self, args: T) -> Result<Value> {
12360        self.continue_as_new_with_options(ContinueAsNewOptions::new(), args)
12361    }
12362
12363    /// Continue as new with optional workflow-type and task-queue overrides.
12364    pub fn continue_as_new_with_options<T: Serialize>(
12365        &self,
12366        options: ContinueAsNewOptions,
12367        args: T,
12368    ) -> Result<Value> {
12369        options.validate()?;
12370        Err(Error::ContinueAsNew(ContinueAsNewRequest {
12371            arguments: normalize_avro_arguments(AvroValue::from_serialize(&args)?),
12372            options,
12373        }))
12374    }
12375
12376    #[track_caller]
12377    pub fn activity<T: Serialize>(
12378        &self,
12379        activity_type: impl Into<String>,
12380        args: T,
12381    ) -> ActivityCall {
12382        self.activity_with_options(activity_type, ActivityOptions::new(), args)
12383    }
12384
12385    #[track_caller]
12386    pub fn activity_on_queue<T, Q>(
12387        &self,
12388        activity_type: impl Into<String>,
12389        task_queue: Option<Q>,
12390        args: T,
12391    ) -> ActivityCall
12392    where
12393        T: Serialize,
12394        Q: Into<String>,
12395    {
12396        let mut options = ActivityOptions::new();
12397        options.task_queue = task_queue.map(Into::into);
12398        self.activity_with_options(activity_type, options, args)
12399    }
12400
12401    /// Schedule one durable activity with retry, routing, and timeout options.
12402    ///
12403    /// Options are validated before the command is emitted. Once the command is
12404    /// recorded, replay consumes the same activity lifecycle at this command
12405    /// position and never emits a duplicate schedule.
12406    ///
12407    /// ```no_run
12408    /// # use durable_workflow::{json, ActivityOptions, ActivityRetryPolicy, Error, Result, WorkflowContext};
12409    /// # use std::time::Duration;
12410    /// # async fn run(ctx: WorkflowContext) -> Result<durable_workflow::Value> {
12411    /// let result = ctx
12412    ///     .activity_with_options(
12413    ///         "charge-card",
12414    ///         ActivityOptions::new()
12415    ///             .task_queue("payments")
12416    ///             .retry_policy(
12417    ///                 ActivityRetryPolicy::new(4).exponential_backoff(
12418    ///                     Duration::from_secs(1),
12419    ///                     2,
12420    ///                     Some(Duration::from_secs(30)),
12421    ///                 ),
12422    ///             )
12423    ///             .start_to_close_timeout(Duration::from_secs(60))
12424    ///             .schedule_to_close_timeout(Duration::from_secs(180))
12425    ///             .heartbeat_timeout(Duration::from_secs(15)),
12426    ///         json!([{"order_id": "order-42"}]),
12427    ///     )
12428    ///     .await;
12429    /// match result {
12430    ///     Err(Error::ActivityFailed(failure)) => Ok(json!({
12431    ///         "reason": failure.reason,
12432    ///         "timeout_kind": failure.timeout_kind,
12433    ///     })),
12434    ///     other => other,
12435    /// }
12436    /// # }
12437    /// ```
12438    #[track_caller]
12439    pub fn activity_with_options<T: Serialize>(
12440        &self,
12441        activity_type: impl Into<String>,
12442        options: ActivityOptions,
12443        args: T,
12444    ) -> ActivityCall {
12445        self.activity_with_options_at(activity_type, options, args, Some(Location::caller()))
12446    }
12447
12448    fn activity_with_options_at<T: Serialize>(
12449        &self,
12450        activity_type: impl Into<String>,
12451        options: ActivityOptions,
12452        args: T,
12453        source: Option<&'static Location<'static>>,
12454    ) -> ActivityCall {
12455        ActivityCall {
12456            source,
12457            ctx: self.clone(),
12458            activity_type: activity_type.into(),
12459            options,
12460            worker_session: None,
12461            args: Some(AvroValue::from_serialize(&args)),
12462            scheduled: false,
12463            local: false,
12464            local_result: None,
12465            parallel_group_path: Vec::new(),
12466        }
12467    }
12468
12469    pub async fn activity_avro_value<T: Serialize>(
12470        &self,
12471        activity_type: impl Into<String>,
12472        args: T,
12473    ) -> Result<AvroValue> {
12474        let mut call =
12475            self.activity_with_options_at(activity_type, ActivityOptions::new(), args, None);
12476        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
12477    }
12478
12479    pub async fn activity_avro_value_with_options<T: Serialize>(
12480        &self,
12481        activity_type: impl Into<String>,
12482        options: ActivityOptions,
12483        args: T,
12484    ) -> Result<AvroValue> {
12485        let mut call = self.activity_with_options_at(activity_type, options, args, None);
12486        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
12487    }
12488
12489    /// Schedule an activity with a Serde request and decode its Serde result.
12490    pub async fn activity_typed<I, O>(&self, activity_type: impl Into<String>, args: I) -> Result<O>
12491    where
12492        I: Serialize,
12493        O: DeserializeOwned,
12494    {
12495        self.activity_typed_with_options(activity_type, ActivityOptions::new(), args)
12496            .await
12497    }
12498
12499    /// Schedule an activity with options and decode its result into `O`.
12500    ///
12501    /// Both directions use the fixed Avro Value codec. In particular, this
12502    /// method does not deserialize the JSON-safe inspection projection returned
12503    /// by the dynamic [`ActivityCall`] future.
12504    pub async fn activity_typed_with_options<I, O>(
12505        &self,
12506        activity_type: impl Into<String>,
12507        options: ActivityOptions,
12508        args: I,
12509    ) -> Result<O>
12510    where
12511        I: Serialize,
12512        O: DeserializeOwned,
12513    {
12514        let activity_type = activity_type.into();
12515        let encoded = AvroValue::from_serialize(&args).map_err(|error| {
12516            handler_type_error::<I>(
12517                HandlerKind::Activity,
12518                &activity_type,
12519                HandlerValueKind::Input,
12520                error.to_string(),
12521            )
12522        });
12523        let mut call = ActivityCall {
12524            source: None,
12525            ctx: self.clone(),
12526            activity_type: activity_type.clone(),
12527            options,
12528            worker_session: None,
12529            args: Some(encoded),
12530            scheduled: false,
12531            local: false,
12532            local_result: None,
12533            parallel_group_path: Vec::new(),
12534        };
12535        let result = std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await?;
12536        decode_handler_result(result, HandlerKind::Activity, &activity_type)
12537    }
12538
12539    /// Schedule and join a deterministic activity/child/timer group.
12540    ///
12541    /// Nested groups retain their input shape. Every durable leaf is scheduled
12542    /// before this future yields, results are assembled by declaration order,
12543    /// and a failure returns [`Error::ParallelFailed`] with typed cause,
12544    /// declaration path, stable group metadata, and completed siblings.
12545    pub fn parallel(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
12546        ParallelCall::new(self.clone(), operations)
12547    }
12548
12549    /// Alias for [`WorkflowContext::parallel`].
12550    pub fn join(&self, operations: Vec<ParallelOperation>) -> ParallelCall {
12551        self.parallel(operations)
12552    }
12553
12554    /// Lossless fixed-Avro variant of [`WorkflowContext::parallel`].
12555    pub async fn parallel_avro_value(
12556        &self,
12557        operations: Vec<ParallelOperation>,
12558    ) -> Result<Vec<ParallelAvroResult>> {
12559        let mut call = self.parallel(operations);
12560        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
12561    }
12562
12563    /// Start every durable operation and resume from the one winner persisted
12564    /// by Server. Non-winning operations continue and remain addressable.
12565    pub fn select(&self, operations: Vec<ParallelOperation>) -> SelectCall {
12566        let operations = operations
12567            .into_iter()
12568            .enumerate()
12569            .map(|(index, operation)| (SelectionKey::Index(index), operation))
12570            .collect();
12571        SelectCall::new(self.clone(), operations)
12572    }
12573
12574    /// Named-key variant of [`WorkflowContext::select`].
12575    pub fn select_keyed<K>(&self, operations: Vec<(K, ParallelOperation)>) -> SelectCall
12576    where
12577        K: Into<SelectionKey>,
12578    {
12579        SelectCall::new(
12580            self.clone(),
12581            operations
12582                .into_iter()
12583                .map(|(key, operation)| (key.into(), operation))
12584                .collect(),
12585        )
12586    }
12587
12588    /// Create a workflow-local deterministic compensation registry.
12589    pub fn saga(&self) -> Saga {
12590        Saga::new(self.clone())
12591    }
12592
12593    /// Whether cancellation has reached this replay's authored boundary.
12594    ///
12595    /// Server's current `/cancel` route is terminal and does not set this flag.
12596    /// A canonical service request remains pending until its committed delivery
12597    /// is consumed. Request observation alone does not authorize an exception.
12598    pub fn is_cancellation_requested(&self) -> Result<bool> {
12599        let state = self
12600            .state
12601            .lock()
12602            .map_err(|_| Error::WorkflowStatePoisoned)?;
12603        if let Some(delivery) = state
12604            .scope_delivery
12605            .as_ref()
12606            .filter(|_| self.cancellation_scope_id != "root")
12607        {
12608            return Ok(delivery.contexts.contains_key(&self.cancellation_scope_id));
12609        }
12610        Ok(state.cancel_requested
12611            || state
12612                .scope_delivery
12613                .as_ref()
12614                .is_some_and(|replay| replay.contexts.contains_key(&self.cancellation_scope_id)))
12615    }
12616
12617    /// Raise a typed cooperative cancellation at an author-controlled point.
12618    ///
12619    /// Passing this result to [`Saga::finish`] compensates already registered
12620    /// forward steps before the cancellation remains the initiating outcome.
12621    pub fn throw_if_cancellation_requested(&self) -> Result<()> {
12622        let mut state = self
12623            .state
12624            .lock()
12625            .map_err(|_| Error::WorkflowStatePoisoned)?;
12626        if state.cancellation_shield_depth == 0 {
12627            if let Some(replay) = &state.scope_delivery {
12628                if let Some((context, _)) = replay.contexts.get(&self.cancellation_scope_id) {
12629                    let delivered = replay
12630                        .consumed_delivery_for_scope(&self.cancellation_scope_id)
12631                        .ok_or_else(|| {
12632                            Error::InvalidCooperativeCancellation(
12633                                "scoped request lacks its consumed original delivery".into(),
12634                            )
12635                        })?;
12636                    return Err(Error::CancellationScopeRequested(
12637                        CancellationScopeRequested {
12638                            context: context
12639                                .clone()
12640                                .with_replay(Some(Arc::downgrade(&self.state))),
12641                            delivery: delivered.boundary.clone(),
12642                        },
12643                    ));
12644                }
12645            }
12646        }
12647        if state.cancel_requested && state.cancellation_shield_depth == 0 {
12648            if self.cancellation_scope_id != "root" && state.scope_delivery.is_some() {
12649                return Ok(());
12650            }
12651            return Err(state.cancellation_error());
12652        }
12653        Ok(())
12654    }
12655
12656    pub fn wait_signal(&self, signal_name: impl Into<String>) -> SignalCall {
12657        SignalCall {
12658            ctx: self.clone(),
12659            signal_name: signal_name.into(),
12660            runtime_reserved_allowed: false,
12661            opened_wait: false,
12662            matched_pending: false,
12663            parallel_group_path: Vec::new(),
12664        }
12665    }
12666
12667    fn wait_runtime_signal(&self, signal_name: impl Into<String>) -> SignalCall {
12668        SignalCall {
12669            ctx: self.clone(),
12670            signal_name: signal_name.into(),
12671            runtime_reserved_allowed: true,
12672            opened_wait: false,
12673            matched_pending: false,
12674            parallel_group_path: Vec::new(),
12675        }
12676    }
12677
12678    pub async fn wait_signal_avro_value(
12679        &self,
12680        signal_name: impl Into<String>,
12681    ) -> Result<Vec<AvroValue>> {
12682        let mut call = self.wait_signal(signal_name);
12683        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
12684    }
12685
12686    /// Return every committed signal argument list with the given name.
12687    ///
12688    /// This history-backed view is deterministic and is intended for
12689    /// condition predicates that must be re-evaluated after a signal while the
12690    /// workflow is blocked on [`WorkflowContext::wait_condition`].
12691    pub fn signals(&self, signal_name: &str) -> Result<Vec<Vec<Value>>> {
12692        self.signals_avro_value(signal_name)?
12693            .into_iter()
12694            .map(|arguments| {
12695                arguments
12696                    .into_iter()
12697                    .map(AvroValue::into_json)
12698                    .collect::<Result<Vec<_>>>()
12699            })
12700            .collect()
12701    }
12702
12703    /// Lossless fixed Avro Value view of committed signals with the given name.
12704    pub fn signals_avro_value(&self, signal_name: &str) -> Result<Vec<Vec<AvroValue>>> {
12705        let state = self
12706            .state
12707            .lock()
12708            .map_err(|_| Error::WorkflowStatePoisoned)?;
12709        state
12710            .history_events
12711            .iter()
12712            .filter(|event| {
12713                event.event_type == "SignalReceived"
12714                    && event.payload.get("signal_name").and_then(Value::as_str) == Some(signal_name)
12715            })
12716            .map(|event| decode_signal_event_arguments(event, &state.payload_codec))
12717            .collect()
12718    }
12719
12720    /// Return every committed update argument list with the given name.
12721    ///
12722    /// Accepted and applied records for the same update ID are de-duplicated.
12723    /// A Server task created after an update therefore replays the workflow and
12724    /// re-evaluates an open condition without application polling.
12725    pub fn updates(&self, update_name: &str) -> Result<Vec<Vec<Value>>> {
12726        self.updates_avro_value(update_name)?
12727            .into_iter()
12728            .map(|arguments| {
12729                arguments
12730                    .into_iter()
12731                    .map(AvroValue::into_json)
12732                    .collect::<Result<Vec<_>>>()
12733            })
12734            .collect()
12735    }
12736
12737    /// Lossless fixed Avro Value view of committed updates with the given name.
12738    pub fn updates_avro_value(&self, update_name: &str) -> Result<Vec<Vec<AvroValue>>> {
12739        let state = self
12740            .state
12741            .lock()
12742            .map_err(|_| Error::WorkflowStatePoisoned)?;
12743        let mut seen = Vec::new();
12744        let mut updates = Vec::new();
12745        for event in state.history_events.iter() {
12746            if !matches!(
12747                event.event_type.as_str(),
12748                "UpdateAccepted" | "UpdateApplied"
12749            ) || event.payload.get("update_name").and_then(Value::as_str) != Some(update_name)
12750                || event.payload.get("arguments").is_none()
12751            {
12752                continue;
12753            }
12754            if let Some(update_id) = event.payload.get("update_id").and_then(Value::as_str) {
12755                if seen.iter().any(|recorded| recorded == update_id) {
12756                    continue;
12757                }
12758                seen.push(update_id.to_string());
12759            }
12760            updates.push(decode_update_event_arguments(event, &state.payload_codec)?);
12761        }
12762        Ok(updates)
12763    }
12764
12765    /// Wait for a deterministic predicate to become true or for its durable
12766    /// timeout to elapse.
12767    ///
12768    /// The timeout runs from the first time the wait opens. A signal or update
12769    /// that leaves the predicate false does not restart it.
12770    ///
12771    /// Prefer [`wait_condition!`] for inline predicates so changes to the Rust
12772    /// predicate tokens automatically change the recorded definition
12773    /// fingerprint. Direct callers must provide an equally stable identity in
12774    /// [`ConditionWaitOptions`].
12775    pub fn wait_condition<F>(
12776        &self,
12777        options: ConditionWaitOptions,
12778        predicate: F,
12779    ) -> ConditionWaitCall
12780    where
12781        F: Fn() -> Result<bool> + Send + 'static,
12782    {
12783        ConditionWaitCall {
12784            ctx: self.clone(),
12785            options,
12786            predicate: Box::new(predicate),
12787            occurrence_id: None,
12788            opened_wait: false,
12789            parallel_group_path: Vec::new(),
12790        }
12791    }
12792
12793    /// Wait for server-backed durable time without blocking the worker executor.
12794    ///
12795    /// Polling this future emits one `start_timer` command and yields. The
12796    /// server records the deadline, so neither worker nor server restarts reset
12797    /// the wait. Replay resolves the future only from a `TimerScheduled` and
12798    /// `TimerFired` pair at the same position in the shared durable-command
12799    /// stream, with matching sequence, timer identity, and delay. Sub-second
12800    /// durations round up because protocol deadlines use whole seconds.
12801    ///
12802    /// ```no_run
12803    /// # use durable_workflow::{json, Client, Worker};
12804    /// # use std::time::Duration;
12805    /// # fn configure(client: Client) {
12806    /// let mut worker = Worker::new(client, "rust-workers");
12807    /// worker.register_workflow("delayed-greeting", |ctx, _input| async move {
12808    ///     ctx.sleep(Duration::from_secs(5)).await?;
12809    ///     Ok(json!({"status": "timer fired"}))
12810    /// });
12811    /// # }
12812    /// ```
12813    #[track_caller]
12814    pub fn sleep(&self, duration: Duration) -> TimerCall {
12815        let delay_seconds = duration
12816            .as_secs()
12817            .checked_add(u64::from(duration.subsec_nanos() > 0));
12818        TimerCall {
12819            source: Some(Location::caller()),
12820            ctx: self.clone(),
12821            delay_seconds,
12822            scheduled: false,
12823            matched_pending: false,
12824            parallel_group_path: Vec::new(),
12825        }
12826    }
12827
12828    /// Alias for [`WorkflowContext::sleep`] for timer-oriented workflow code.
12829    #[track_caller]
12830    pub fn start_timer(&self, duration: Duration) -> TimerCall {
12831        self.sleep(duration)
12832    }
12833
12834    /// Evaluate a non-deterministic callback once and durably record its typed value.
12835    ///
12836    /// On replay the callback is not invoked: the value is decoded from the
12837    /// sequence-matched `SideEffectRecorded` event using the workflow's payload
12838    /// codec. Use this for UUIDs, wall-clock snapshots, random values, and other
12839    /// small values that must remain fixed for the lifetime of a workflow run.
12840    pub fn side_effect<T, F>(&self, callback: F) -> Result<T>
12841    where
12842        T: Serialize + DeserializeOwned,
12843        F: FnOnce() -> T,
12844    {
12845        {
12846            let mut state = self
12847                .state
12848                .lock()
12849                .map_err(|_| Error::WorkflowStatePoisoned)?;
12850            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
12851                return match recorded {
12852                    RecordedCommand::SideEffect { sequence, value } => {
12853                        state.replay_clock.unavailable();
12854                        state.command_cursor += 1;
12855                        value.deserialize().map_err(|error| {
12856                            Error::NonDeterministicReplay(ReplayFailure::new(
12857                                "side_effect_type_mismatch",
12858                                Some(sequence),
12859                                Some(std::any::type_name::<T>().to_string()),
12860                                Some(error.to_string()),
12861                                "recorded side-effect value is incompatible with the requested Rust type",
12862                            ))
12863                        })
12864                    }
12865                    other => Err(command_mismatch(&other, "side effect")),
12866                };
12867            }
12868        }
12869
12870        let value = callback();
12871        let avro_value = AvroValue::from_serialize(&value)?;
12872        let mut state = self
12873            .state
12874            .lock()
12875            .map_err(|_| Error::WorkflowStatePoisoned)?;
12876        let result = encode_typed_envelope(&avro_value, &state.payload_codec)?;
12877        state.replay_clock.unavailable();
12878        state.commands.push(json!({
12879            "type": "record_side_effect",
12880            "result": result,
12881        }));
12882        Ok(value)
12883    }
12884
12885    /// Record or replay a lossless fixed Avro Value side effect.
12886    pub fn side_effect_avro_value<F>(&self, callback: F) -> Result<AvroValue>
12887    where
12888        F: FnOnce() -> AvroValue,
12889    {
12890        {
12891            let mut state = self
12892                .state
12893                .lock()
12894                .map_err(|_| Error::WorkflowStatePoisoned)?;
12895            if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
12896                return match recorded {
12897                    RecordedCommand::SideEffect { value, .. } => {
12898                        state.replay_clock.unavailable();
12899                        state.command_cursor += 1;
12900                        Ok(value)
12901                    }
12902                    other => Err(command_mismatch(&other, "side effect")),
12903                };
12904            }
12905        }
12906
12907        let value = callback();
12908        let mut state = self
12909            .state
12910            .lock()
12911            .map_err(|_| Error::WorkflowStatePoisoned)?;
12912        let result = encode_typed_envelope(&value, &state.payload_codec)?;
12913        state.replay_clock.unavailable();
12914        state.commands.push(json!({
12915            "type": "record_side_effect",
12916            "result": result,
12917        }));
12918        Ok(value)
12919    }
12920
12921    /// Append output items at a deterministic workflow command boundary.
12922    ///
12923    /// Stable idempotency keys are derived from the server-provided durable
12924    /// workflow command identity, command ordinal, and item index. Replay
12925    /// consumes the recorded side effect and never emits another append.
12926    pub fn append_workflow_stream(
12927        &self,
12928        stream_name: impl Into<String>,
12929        items: &[WorkflowStreamAppendItem],
12930        max_pending_items: Option<u64>,
12931    ) -> Result<()> {
12932        if items.is_empty() {
12933            return Err(Error::Codec(
12934                "workflow_stream_items_empty: append requires at least one item".to_string(),
12935            ));
12936        }
12937        if max_pending_items == Some(0) {
12938            return Err(Error::Codec(
12939                "workflow_stream_pending_limit_invalid: max_pending_items must be positive"
12940                    .to_string(),
12941            ));
12942        }
12943        let stream_name = stream_name.into();
12944        if stream_name.is_empty() {
12945            return Err(Error::Codec(
12946                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
12947            ));
12948        }
12949
12950        let mut state = self
12951            .state
12952            .lock()
12953            .map_err(|_| Error::WorkflowStatePoisoned)?;
12954        let command_ordinal = state.workflow_stream_command_counter;
12955        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
12956            state.workflow_stream_command_counter += 1;
12957            return match recorded {
12958                RecordedCommand::SideEffect { .. } => {
12959                    state.replay_clock.unavailable();
12960                    state.command_cursor += 1;
12961                    Ok(())
12962                }
12963                other => Err(command_mismatch(&other, "workflow stream append")),
12964            };
12965        }
12966
12967        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
12968        state.workflow_stream_command_counter += 1;
12969        let wire_items = items
12970            .iter()
12971            .enumerate()
12972            .map(|(item_index, item)| {
12973                item.wire_value(Some(format!(
12974                    "dw-stream:{identity}:{command_ordinal}:{item_index}"
12975                )))
12976            })
12977            .collect::<Vec<_>>();
12978        let mut directive = json!({
12979            "operation": "append",
12980            "stream_name": stream_name,
12981            "command_identity": identity,
12982            "command_ordinal": command_ordinal,
12983            "items": wire_items,
12984        });
12985        if let Some(max_pending_items) = max_pending_items {
12986            directive["max_pending_items"] = json!(max_pending_items);
12987        }
12988        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
12989        state.replay_clock.unavailable();
12990        state.commands.push(json!({
12991            "type": "record_side_effect",
12992            "result": result,
12993            "workflow_stream": directive,
12994        }));
12995        Ok(())
12996    }
12997
12998    /// Close a run-scoped output stream at a deterministic command boundary.
12999    pub fn close_workflow_stream(
13000        &self,
13001        stream_name: impl Into<String>,
13002        retention_seconds: Option<u64>,
13003    ) -> Result<()> {
13004        self.finish_workflow_stream(stream_name.into(), None, retention_seconds)
13005    }
13006
13007    /// Mark a run-scoped output stream errored at a deterministic command boundary.
13008    pub fn error_workflow_stream(
13009        &self,
13010        stream_name: impl Into<String>,
13011        error_reason: impl Into<String>,
13012        retention_seconds: Option<u64>,
13013    ) -> Result<()> {
13014        let error_reason = error_reason.into();
13015        if error_reason.is_empty() {
13016            return Err(Error::Codec(
13017                "workflow_stream_error_invalid: error reason must not be empty".to_string(),
13018            ));
13019        }
13020        self.finish_workflow_stream(stream_name.into(), Some(error_reason), retention_seconds)
13021    }
13022
13023    fn finish_workflow_stream(
13024        &self,
13025        stream_name: String,
13026        error_reason: Option<String>,
13027        retention_seconds: Option<u64>,
13028    ) -> Result<()> {
13029        if stream_name.is_empty() {
13030            return Err(Error::Codec(
13031                "workflow_stream_name_invalid: stream name must not be empty".to_string(),
13032            ));
13033        }
13034        if retention_seconds == Some(0) {
13035            return Err(Error::Codec(
13036                "workflow_stream_retention_invalid: retention_seconds must be positive".to_string(),
13037            ));
13038        }
13039        let mut state = self
13040            .state
13041            .lock()
13042            .map_err(|_| Error::WorkflowStatePoisoned)?;
13043        let command_ordinal = state.workflow_stream_command_counter;
13044        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
13045            state.workflow_stream_command_counter += 1;
13046            return match recorded {
13047                RecordedCommand::SideEffect { .. } => {
13048                    state.replay_clock.unavailable();
13049                    state.command_cursor += 1;
13050                    Ok(())
13051                }
13052                other => Err(command_mismatch(&other, "workflow stream close")),
13053            };
13054        }
13055        let identity = Self::workflow_stream_command_identity(&state)?.to_string();
13056        state.workflow_stream_command_counter += 1;
13057        let mut directive = json!({
13058            "operation": if error_reason.is_some() { "error" } else { "close" },
13059            "stream_name": stream_name,
13060            "command_identity": identity,
13061            "command_ordinal": command_ordinal,
13062        });
13063        if let Some(error_reason) = error_reason {
13064            directive["error_reason"] = json!(error_reason);
13065        }
13066        if let Some(retention_seconds) = retention_seconds {
13067            directive["retention_seconds"] = json!(retention_seconds);
13068        }
13069        let result = encode_typed_envelope(&AvroValue::Null, &state.payload_codec)?;
13070        state.replay_clock.unavailable();
13071        state.commands.push(json!({
13072            "type": "record_side_effect",
13073            "result": result,
13074            "workflow_stream": directive,
13075        }));
13076        Ok(())
13077    }
13078
13079    fn workflow_stream_command_identity(state: &WorkflowState) -> Result<&str> {
13080        let identity = state.workflow_command_identity.as_str();
13081        if identity.is_empty() {
13082            return Err(Error::MissingWorkflowCommandIdentity);
13083        }
13084        Ok(identity)
13085    }
13086
13087    /// Validate, emit, or replay a typed workflow search-attribute update.
13088    ///
13089    /// The command is non-blocking within a workflow decision, but its
13090    /// `SearchAttributesUpserted` event occupies the same deterministic command
13091    /// stream as activities, timers, conditions, and other durable operations.
13092    pub fn upsert_search_attributes(&self, update: SearchAttributeUpdate) -> Result<()> {
13093        update.validate()?;
13094        let (attributes, attribute_types) = update.into_wire_parts();
13095        let mut state = self
13096            .state
13097            .lock()
13098            .map_err(|_| Error::WorkflowStatePoisoned)?;
13099
13100        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
13101            return match recorded {
13102                RecordedCommand::SearchAttributes {
13103                    sequence,
13104                    attributes: recorded_attributes,
13105                    attribute_types: recorded_attribute_types,
13106                } => {
13107                    if recorded_attributes != attributes {
13108                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13109                            "search_attribute_value_mismatch",
13110                            Some(sequence),
13111                            Some(recorded_attributes.to_string()),
13112                            Some(attributes.to_string()),
13113                            "search-attribute values differ from the recorded durable command",
13114                        )));
13115                    }
13116                    if let RecordedSnapshotValue::Known(recorded_types) = recorded_attribute_types {
13117                        if recorded_types != attribute_types {
13118                            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13119                                "search_attribute_type_mismatch",
13120                                Some(sequence),
13121                                Some(json!(recorded_types).to_string()),
13122                                Some(json!(attribute_types).to_string()),
13123                                "search-attribute declared types differ from the recorded durable command",
13124                            )));
13125                        }
13126                    }
13127                    state.replay_clock.unavailable();
13128                    state.command_cursor += 1;
13129                    Ok(())
13130                }
13131                other => Err(command_mismatch(&other, "search-attribute update")),
13132            };
13133        }
13134
13135        let mut command = serde_json::Map::from_iter([
13136            ("type".to_string(), json!("upsert_search_attributes")),
13137            ("attributes".to_string(), attributes),
13138        ]);
13139        if !attribute_types.is_empty() {
13140            command.insert("attribute_types".to_string(), json!(attribute_types));
13141        }
13142        state.replay_clock.unavailable();
13143        state.commands.push(Value::Object(command));
13144        Ok(())
13145    }
13146
13147    /// Record a UUIDv4 once and return the same UUID on every replay.
13148    pub fn uuid_v4(&self) -> Result<Uuid> {
13149        self.side_effect(Uuid::new_v4)
13150    }
13151
13152    /// Select the newest supported version for a change, or replay the version
13153    /// already committed for that stable change ID.
13154    ///
13155    /// An unmarked old history that reached its next durable operation, or
13156    /// already completed, selects `-1` when that version is supported. This
13157    /// leaves the original operation available and writes no additional marker.
13158    /// Consistent markers written by older workers retain their original ordered
13159    /// positions. Repeated calls consume a matching marker at the current cursor.
13160    /// Conflicting recorded decisions and unsupported ranges remain replay faults.
13161    pub fn get_version(
13162        &self,
13163        change_id: impl Into<String>,
13164        min_supported: i32,
13165        max_supported: i32,
13166    ) -> Result<i32> {
13167        let change_id = change_id.into();
13168        if change_id.trim().is_empty() {
13169            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13170                "version_change_id_invalid",
13171                None,
13172                Some("non-empty change ID".to_string()),
13173                Some(change_id),
13174                "version markers require a stable non-empty change ID",
13175            )));
13176        }
13177        if min_supported > max_supported {
13178            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13179                "version_range_invalid",
13180                None,
13181                Some("min_supported <= max_supported".to_string()),
13182                Some(format!("{min_supported}..={max_supported}")),
13183                "version marker supported range is invalid",
13184            )));
13185        }
13186
13187        let mut state = self
13188            .state
13189            .lock()
13190            .map_err(|_| Error::WorkflowStatePoisoned)?;
13191        if let Some((version, sequence)) = state.version_markers.get(&change_id).copied() {
13192            if let Some(RecordedCommand::VersionMarker {
13193                sequence: alias_sequence,
13194                change_id: alias_change_id,
13195                version: alias_version,
13196            }) = state.recorded_commands.get(state.command_cursor)
13197            {
13198                if alias_change_id == &change_id {
13199                    if *alias_version != version {
13200                        return Err(invalid_recorded_history(
13201                            "version_marker_conflict",
13202                            *alias_sequence,
13203                            &format!("selected version {version} for change ID {change_id:?}"),
13204                            &format!("recorded version {alias_version}"),
13205                            "recorded marker conflicts with the decision already selected during replay",
13206                        ));
13207                    }
13208                    ensure_version_supported(
13209                        &change_id,
13210                        version,
13211                        min_supported,
13212                        max_supported,
13213                        *alias_sequence,
13214                    )?;
13215                    // Older workers could record the same decision again. Keep
13216                    // each physical boundary without skipping intervening work.
13217                    state.replay_clock.unavailable();
13218                    state.command_cursor += 1;
13219                    return Ok(version);
13220                }
13221            }
13222            ensure_version_supported(&change_id, version, min_supported, max_supported, sequence)?;
13223            return Ok(version);
13224        }
13225
13226        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
13227            return match recorded {
13228                RecordedCommand::VersionMarker {
13229                    sequence,
13230                    change_id: recorded_change_id,
13231                    version,
13232                    ..
13233                } => {
13234                    if recorded_change_id != change_id {
13235                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13236                            "version_change_id_mismatch",
13237                            Some(sequence),
13238                            Some(recorded_change_id),
13239                            Some(change_id),
13240                            "recorded version marker change ID differs from current workflow code",
13241                        )));
13242                    }
13243                    ensure_version_supported(
13244                        &change_id,
13245                        version,
13246                        min_supported,
13247                        max_supported,
13248                        sequence,
13249                    )?;
13250                    state.replay_clock.unavailable();
13251                    state.command_cursor += 1;
13252                    state.version_markers.insert(change_id, (version, sequence));
13253                    Ok(version)
13254                }
13255                other => {
13256                    let version = -1;
13257                    let sequence = other.sequence();
13258                    ensure_version_supported(
13259                        &change_id,
13260                        version,
13261                        min_supported,
13262                        max_supported,
13263                        sequence,
13264                    )?;
13265                    // The existing operation proves this patch site was reached
13266                    // before its marker existed. Keep its original cursor.
13267                    state.version_markers.insert(change_id, (version, sequence));
13268                    Ok(version)
13269                }
13270            };
13271        }
13272
13273        if state
13274            .history_events
13275            .iter()
13276            .any(|event| event.event_type == "WorkflowCompleted")
13277        {
13278            let version = -1;
13279            ensure_version_supported(&change_id, version, min_supported, max_supported, 0)?;
13280            state.version_markers.insert(change_id, (version, 0));
13281            return Ok(version);
13282        }
13283
13284        let version = max_supported;
13285        state.replay_clock.unavailable();
13286        state.commands.push(json!({
13287            "type": "record_version_marker",
13288            "change_id": change_id,
13289            "version": version,
13290            "min_supported": min_supported,
13291            "max_supported": max_supported,
13292        }));
13293        // Sequence numbers are assigned by the server. Zero identifies a marker
13294        // selected in this uncommitted decision batch for duplicate-call checks.
13295        state.version_markers.insert(change_id, (version, 0));
13296        Ok(version)
13297    }
13298
13299    /// Record or replay the standard `-1` (legacy) / `1` (patched) marker.
13300    pub fn patched(&self, change_id: impl Into<String>) -> Result<bool> {
13301        Ok(self.get_version(change_id, -1, 1)? == 1)
13302    }
13303
13304    /// Keep a patch marker in history after the legacy branch has been removed.
13305    pub fn deprecate_patch(&self, change_id: impl Into<String>) -> Result<()> {
13306        self.get_version(change_id, -1, 1).map(|_| ())
13307    }
13308
13309    /// Merge non-indexed workflow memo metadata through durable history.
13310    ///
13311    /// Avro `null` deletes a key. The SDK encodes the complete patch in the
13312    /// public Avro payload envelope consumed by Server and Cloud runtimes.
13313    pub fn upsert_memo<T: Serialize>(&self, entries: T) -> Result<()> {
13314        let entries = canonical_memo_entries(AvroValue::from_serialize(&entries)?, true)?;
13315        let mut state = self
13316            .state
13317            .lock()
13318            .map_err(|_| Error::WorkflowStatePoisoned)?;
13319
13320        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
13321            return match recorded {
13322                RecordedCommand::Memo {
13323                    sequence,
13324                    entries: recorded_entries,
13325                } => {
13326                    if recorded_entries != entries {
13327                        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13328                            "memo_update_mismatch",
13329                            Some(sequence),
13330                            Some(format!("{recorded_entries:?}")),
13331                            Some(format!("{entries:?}")),
13332                            "recorded memo entries differ from the current workflow update",
13333                        )));
13334                    }
13335                    state.replay_clock.unavailable();
13336                    state.command_cursor += 1;
13337                    Ok(())
13338                }
13339                other => Err(command_mismatch(&other, "memo upsert")),
13340            };
13341        }
13342
13343        let entries_envelope = encode_typed_envelope(&entries, DEFAULT_CODEC)?;
13344        state.replay_clock.unavailable();
13345        state.commands.push(json!({
13346            "type": "upsert_memo",
13347            "entries": entries_envelope,
13348        }));
13349        Ok(())
13350    }
13351
13352    /// Start a named durable child on an explicit queue and await its result.
13353    ///
13354    /// The command is recorded in the parent's sequence-ordered durable command
13355    /// stream. Replay keeps a scheduled child pending without emitting another
13356    /// start, or consumes its matching terminal `ChildRun*` outcome. Successful
13357    /// values preserve the history payload codec and include both sides of the
13358    /// durable relationship; failures are returned as
13359    /// [`Error::ChildWorkflowFailed`].
13360    ///
13361    /// ```no_run
13362    /// # use durable_workflow::{json, ChildWorkflowOptions, Client, ParentClosePolicy, Worker};
13363    /// # fn configure(client: Client) {
13364    /// let mut worker = Worker::new(client, "parent-workers");
13365    /// worker.register_workflow("order-parent", |ctx, _input| async move {
13366    ///     let child = ctx
13367    ///         .start_child_workflow(
13368    ///             "fulfil-order",
13369    ///             ChildWorkflowOptions::new("fulfilment-workers")
13370    ///                 .parent_close_policy(ParentClosePolicy::RequestCancel),
13371    ///             json!([{"order_id": "order-42"}]),
13372    ///         )
13373    ///         .await?;
13374    ///     Ok(child.result)
13375    /// });
13376    /// # }
13377    /// ```
13378    pub fn start_child_workflow<T: Serialize>(
13379        &self,
13380        workflow_type: impl Into<String>,
13381        options: ChildWorkflowOptions,
13382        args: T,
13383    ) -> ChildWorkflowCall {
13384        ChildWorkflowCall {
13385            ctx: self.clone(),
13386            workflow_type: workflow_type.into(),
13387            options,
13388            args: Some(AvroValue::from_serialize(&args)),
13389            scheduled: false,
13390            matched_pending: false,
13391            parallel_group_path: Vec::new(),
13392        }
13393    }
13394
13395    pub async fn start_child_workflow_avro_value<T: Serialize>(
13396        &self,
13397        workflow_type: impl Into<String>,
13398        options: ChildWorkflowOptions,
13399        args: T,
13400    ) -> Result<ChildWorkflowAvroResult> {
13401        let mut call = self.start_child_workflow(workflow_type, options, args);
13402        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
13403    }
13404
13405    fn take_commands(&self) -> Result<Vec<Value>> {
13406        let mut state = self
13407            .state
13408            .lock()
13409            .map_err(|_| Error::WorkflowStatePoisoned)?;
13410        Ok(std::mem::take(&mut state.commands))
13411    }
13412
13413    fn continue_as_new_command(&self, request: ContinueAsNewRequest) -> Result<Option<Value>> {
13414        let mut state = self
13415            .state
13416            .lock()
13417            .map_err(|_| Error::WorkflowStatePoisoned)?;
13418
13419        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
13420            return Err(command_mismatch(&recorded, "continue as new"));
13421        }
13422        if state.recorded_continue_as_new_sequence.is_some() {
13423            state.continue_as_new_consumed = true;
13424            return Ok(None);
13425        }
13426
13427        let arguments = encode_typed_envelope(&request.arguments, &state.payload_codec)?;
13428        let mut command = serde_json::Map::from_iter([
13429            ("type".to_string(), json!("continue_as_new")),
13430            ("arguments".to_string(), arguments),
13431            ("queue".to_string(), json!(state.task_queue.clone())),
13432        ]);
13433        if let Some(workflow_type) = request.options.workflow_type {
13434            command.insert("workflow_type".to_string(), json!(workflow_type));
13435        }
13436        if let Some(task_queue) = request.options.task_queue {
13437            command.insert("queue".to_string(), json!(task_queue));
13438        }
13439        Ok(Some(Value::Object(command)))
13440    }
13441
13442    fn matched_recorded_pending(&self) -> Result<bool> {
13443        let state = self
13444            .state
13445            .lock()
13446            .map_err(|_| Error::WorkflowStatePoisoned)?;
13447        Ok(state.matched_recorded_pending)
13448    }
13449
13450    fn ensure_history_consumed(&self) -> Result<()> {
13451        let state = self
13452            .state
13453            .lock()
13454            .map_err(|_| Error::WorkflowStatePoisoned)?;
13455        if let Some(replay) = &state.scope_delivery {
13456            if let Some((&sequence, _)) = replay
13457                .canonical
13458                .deliveries
13459                .iter()
13460                .find(|(sequence, _)| !replay.consumed.contains(sequence))
13461            {
13462                return Err(invalid_recorded_history(
13463                    "cancellation_scope_delivery_unconsumed",
13464                    sequence,
13465                    "original scoped delivery",
13466                    "workflow completion",
13467                    "workflow completed without consuming its committed scope delivery",
13468                ));
13469            }
13470        }
13471        if let Some(command) = state.recorded_commands.get(state.command_cursor) {
13472            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13473                "recorded_commands_unconsumed",
13474                Some(command.sequence()),
13475                Some(command.shape().to_string()),
13476                Some("workflow completion".to_string()),
13477                "workflow completed before consuming all recorded durable commands",
13478            )));
13479        }
13480        if let Some(delivery) = state
13481            .cancellation_history
13482            .delivery
13483            .as_ref()
13484            .filter(|_| !state.cancellation_consumed)
13485        {
13486            return Err(invalid_recorded_history(
13487                "cooperative_cancellation_unconsumed",
13488                delivery.sequence,
13489                "committed cancellation call",
13490                "workflow completion",
13491                "workflow completed without reaching its committed cancellation boundary",
13492            ));
13493        }
13494        if let Some(sequence) = state
13495            .recorded_continue_as_new_sequence
13496            .filter(|_| !state.continue_as_new_consumed)
13497        {
13498            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
13499                "recorded_continue_as_new_unconsumed",
13500                Some(sequence),
13501                Some("continue as new".to_string()),
13502                Some("workflow completion".to_string()),
13503                "workflow completed without consuming its recorded continue-as-new transition",
13504            )));
13505        }
13506        Ok(())
13507    }
13508}
13509
13510fn contiguous_message_stream_count(
13511    pending: &[MessageStreamMessage],
13512    cursor: u64,
13513    max_items: usize,
13514) -> usize {
13515    pending
13516        .iter()
13517        .take(max_items)
13518        .enumerate()
13519        .take_while(|(offset, message)| {
13520            u64::try_from(*offset)
13521                .ok()
13522                .and_then(|offset| cursor.checked_add(offset + 1))
13523                == Some(message.position)
13524        })
13525        .count()
13526}
13527
13528fn is_authored_command_open_event(event: &HistoryEvent) -> bool {
13529    matches!(
13530        event.event_type.as_str(),
13531        "ActivityScheduled"
13532            | "TimerScheduled"
13533            | "ChildWorkflowScheduled"
13534            | "SignalWaitOpened"
13535            | "ConditionWaitOpened"
13536            | "SearchAttributesUpserted"
13537            | "SideEffectRecorded"
13538            | "VersionMarkerRecorded"
13539            | "MemoUpserted"
13540            | "ExternalSignalRequested"
13541            | "WorkflowContinuedAsNew"
13542    )
13543}
13544
13545/// Which cancellation-scope features a workflow state may use.
13546#[derive(Clone, Copy)]
13547struct CancellationScopeAllowance {
13548    authoring: bool,
13549    delivery: bool,
13550}
13551
13552#[derive(Debug)]
13553struct WorkflowState {
13554    observation_namespace: Option<String>,
13555    observation_terminal: bool,
13556    // A pending recorded call consumes its descriptor before yielding. Cursor
13557    // exhaustion alone therefore cannot make the surrounding poll live.
13558    observation_pending: bool,
13559    workflow_id: Option<String>,
13560    run_id: Option<String>,
13561    task_queue: String,
13562    payload_codec: String,
13563    history_events: Arc<Vec<HistoryEvent>>,
13564    history_budget: WorkflowHistoryBudget,
13565    cancel_requested: bool,
13566    cancellation_history: CancellationHistory,
13567    cancellation_consumed: bool,
13568    cancellation_clock: Option<cancellation_replay_clock::ReplayClock>,
13569    replay_clock: replay_clock::Clock,
13570    cancellation_shield_depth: u64,
13571    cancellation_delivery_enabled: bool,
13572    cancellation_delivery_intent: Option<CancellationDelivery>,
13573    cancellation_delivery_command_count: usize,
13574    allow_cancellation_scope_authoring: bool,
13575    cancellation_scope_opening: Option<cancellation_scope::CancellationScopeOpening>,
13576    cancellation_scope_memberships: BTreeMap<u64, String>,
13577    scope_delivery: Option<cancellation_scope_replay::ScopeReplay>,
13578    resume_signal: Option<ResumeSignal>,
13579    recorded_commands: Vec<RecordedCommand>,
13580    selection_markers: Vec<SelectionMarker>,
13581    selection_marker_cursor: usize,
13582    cancelled_selection_members: Vec<SelectionCancellation>,
13583    recorded_continue_as_new_sequence: Option<u64>,
13584    continue_as_new_consumed: bool,
13585    command_cursor: usize,
13586    condition_wait_occurrence_counter: u64,
13587    matched_recorded_pending: bool,
13588    version_markers: HashMap<String, (i32, u64)>,
13589    workflow_command_identity: String,
13590    workflow_stream_command_counter: u64,
13591    commands: Vec<Value>,
13592    local_activity_requests: Vec<local_activity::Request>,
13593    message_stream_messages: HashMap<String, Vec<MessageStreamMessage>>,
13594    message_stream_cursors: HashMap<String, u64>,
13595    message_stream_waits: HashMap<String, u64>,
13596    /// Whether the Server that delivered this task advertises the
13597    /// `signal_external_workflow` command.
13598    signal_external_workflow_supported: bool,
13599}
13600
13601/// `cancellation_reason` of an `ActivityCancelled` that the run's own close
13602/// recorded for an activity it never awaited, such as a `select()` loser
13603/// (workflow#1117, server#1193).
13604const RUN_CLOSED_CANCELLATION_REASON: &str = "run_closed";
13605
13606/// Whether this history event is an activity cancellation recorded by its
13607/// run's close rather than an outcome the workflow could have observed.
13608///
13609/// The close appends it in the closing transaction, after the workflow had
13610/// already moved past the operation, so replay never treats it as a
13611/// selection winner, an `all()` member failure or an awaited outcome.
13612fn settled_at_run_close(event: &HistoryEvent) -> bool {
13613    event.event_type == "ActivityCancelled"
13614        && event
13615            .payload
13616            .get("cancellation_reason")
13617            .and_then(Value::as_str)
13618            == Some(RUN_CLOSED_CANCELLATION_REASON)
13619}
13620
13621/// History as the workflow observed it: run-close cancellations are left
13622/// out, so each such activity replays as still open.
13623fn history_observed_by_workflow(mut history: Vec<HistoryEvent>) -> Vec<HistoryEvent> {
13624    history.retain(|event| !settled_at_run_close(event));
13625    history
13626}
13627
13628impl WorkflowState {
13629    #[cfg(test)]
13630    fn new(
13631        history: Vec<HistoryEvent>,
13632        task_queue: String,
13633        payload_codec: String,
13634        resume_signal: Option<ResumeSignal>,
13635    ) -> Result<Self> {
13636        Self::new_with_identity(
13637            history,
13638            None,
13639            None,
13640            task_queue,
13641            payload_codec,
13642            resume_signal,
13643        )
13644    }
13645
13646    fn new_with_identity(
13647        history: Vec<HistoryEvent>,
13648        workflow_id: Option<String>,
13649        run_id: Option<String>,
13650        task_queue: String,
13651        payload_codec: String,
13652        resume_signal: Option<ResumeSignal>,
13653    ) -> Result<Self> {
13654        Self::new_with_identity_and_scopes(
13655            history,
13656            workflow_id,
13657            run_id,
13658            task_queue,
13659            payload_codec,
13660            resume_signal,
13661            false,
13662        )
13663    }
13664
13665    fn new_with_identity_and_scopes(
13666        history: Vec<HistoryEvent>,
13667        workflow_id: Option<String>,
13668        run_id: Option<String>,
13669        task_queue: String,
13670        payload_codec: String,
13671        resume_signal: Option<ResumeSignal>,
13672        allow_cancellation_scope_authoring: bool,
13673    ) -> Result<Self> {
13674        Self::new_with_identity_and_scope_delivery(
13675            history,
13676            workflow_id,
13677            run_id,
13678            task_queue,
13679            payload_codec,
13680            resume_signal,
13681            CancellationScopeAllowance {
13682                authoring: allow_cancellation_scope_authoring,
13683                delivery: false,
13684            },
13685        )
13686    }
13687
13688    fn new_with_identity_and_scope_delivery(
13689        history: Vec<HistoryEvent>,
13690        workflow_id: Option<String>,
13691        run_id: Option<String>,
13692        task_queue: String,
13693        payload_codec: String,
13694        resume_signal: Option<ResumeSignal>,
13695        scopes: CancellationScopeAllowance,
13696    ) -> Result<Self> {
13697        let CancellationScopeAllowance {
13698            authoring: allow_cancellation_scope_authoring,
13699            delivery: allow_cancellation_scope_delivery,
13700        } = scopes;
13701        // The history budget counts every committed event, including any
13702        // the run's close recorded.
13703        let event_count = u64::try_from(history.len()).unwrap_or(u64::MAX);
13704        let history = history_observed_by_workflow(history);
13705        cooperative_cancellation::assert_cancellation_scope_replay_supported(
13706            &history,
13707            allow_cancellation_scope_authoring,
13708            allow_cancellation_scope_delivery,
13709        )?;
13710        let scopes = if allow_cancellation_scope_authoring {
13711            cancellation_scope::CancellationScopeHistory::read(
13712                &history,
13713                run_id.as_deref().unwrap_or_default(),
13714            )?
13715        } else {
13716            cancellation_scope::CancellationScopeHistory::default()
13717        };
13718        let cancellation_history = CancellationHistory::from_events(
13719            &history,
13720            run_id.as_deref().unwrap_or_default(),
13721            None,
13722        )?;
13723        if allow_cancellation_scope_authoring
13724            && cancellation_history.request.is_some()
13725            && !allow_cancellation_scope_delivery
13726        {
13727            return Err(Error::CancellationScopeExecutionUnavailable);
13728        }
13729        let scope_delivery = if allow_cancellation_scope_delivery {
13730            Some(cancellation_scope_replay::ScopeReplay::read(
13731                &history,
13732                &scopes,
13733                run_id.as_deref().unwrap_or_default(),
13734                workflow_id.as_deref().unwrap_or_default(),
13735            )?)
13736        } else {
13737            None
13738        };
13739        let mut recorded_commands = cancellation_history.bind_commands(recorded_commands(
13740            &history,
13741            &payload_codec,
13742            WorkflowIdentity {
13743                workflow_id: workflow_id.clone(),
13744                run_id: run_id.clone(),
13745            },
13746        )?)?;
13747        for (sequence, opening) in &scopes.openings {
13748            if recorded_commands
13749                .iter()
13750                .any(|command| command.sequence() == *sequence)
13751            {
13752                return Err(invalid_recorded_history(
13753                    "invalid_cancellation_scope_history",
13754                    *sequence,
13755                    "distinct authored scope opening",
13756                    "operation collision",
13757                    "scope opening collides with a command",
13758                ));
13759            }
13760            recorded_commands.push(RecordedCommand::CancellationScope {
13761                sequence: *sequence,
13762                scope_id: opening.scope_id.clone(),
13763                parent_scope_id: opening.parent_scope_id.clone(),
13764                shield_parent: opening.shield_parent,
13765            });
13766        }
13767        recorded_commands.sort_by_key(RecordedCommand::sequence);
13768        if let Some(replay) = &scope_delivery {
13769            replay.bind_commands(&mut recorded_commands)?;
13770        }
13771        let recorded_commands = group_condition_reopens_by_member(recorded_commands);
13772        let selection_markers = recorded_selection_markers(&history)?;
13773        let cancelled_selection_members = recorded_selection_cancellations(&history)?;
13774        let recorded_continue_as_new = history
13775            .iter()
13776            .filter(|event| event.event_type == "WorkflowContinuedAsNew")
13777            .collect::<Vec<_>>();
13778        if recorded_continue_as_new.len() > 1 {
13779            return Err(invalid_recorded_history(
13780                "duplicate_continue_as_new_transition",
13781                recorded_continue_as_new
13782                    .last()
13783                    .and_then(|event| durable_event_sequence(event))
13784                    .unwrap_or(0),
13785                "one WorkflowContinuedAsNew event",
13786                &format!(
13787                    "{} WorkflowContinuedAsNew events",
13788                    recorded_continue_as_new.len()
13789                ),
13790                "workflow history records one continue-as-new transition more than once",
13791            ));
13792        }
13793        let recorded_continue_as_new_sequence = recorded_continue_as_new
13794            .first()
13795            .map(|event| {
13796                durable_event_sequence(event).ok_or_else(|| {
13797                    Error::NonDeterministicReplay(ReplayFailure::new(
13798                        "continue_as_new_sequence_missing",
13799                        None,
13800                        Some("recorded transition sequence".to_string()),
13801                        Some("missing sequence".to_string()),
13802                        "WorkflowContinuedAsNew history is missing its recorded sequence",
13803                    ))
13804                })
13805            })
13806            .transpose()?;
13807        let mut message_stream_cursors = HashMap::new();
13808        for event in &history {
13809            if !matches!(
13810                event.event_type.as_str(),
13811                "SignalReceived" | "SignalApplied"
13812            ) || event.payload.get("signal_name").and_then(Value::as_str)
13813                != Some(MESSAGE_STREAM_SIGNAL)
13814            {
13815                continue;
13816            }
13817            let arguments = decode_signal_event_arguments(event, &payload_codec)?;
13818            if arguments.len() != 1 {
13819                continue;
13820            }
13821            let envelope = arguments[0].clone().into_json()?;
13822            let Some(envelope) = envelope.as_object() else {
13823                continue;
13824            };
13825            if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_CURSOR_SCHEMA)
13826            {
13827                continue;
13828            }
13829            let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
13830                continue;
13831            };
13832            let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
13833            else {
13834                continue;
13835            };
13836            let cursor = message_stream_cursors
13837                .entry(stream_name.to_string())
13838                .or_insert(0);
13839            *cursor = (*cursor).max(through_position);
13840        }
13841        let cancel_requested = history.iter().any(|event| {
13842            matches!(
13843                event.event_type.as_str(),
13844                "WorkflowCancellationRequested" | "WorkflowCancelRequested"
13845            )
13846        });
13847        let cancellation_clock = cancellation_history
13848            .request
13849            .as_ref()
13850            .and_then(|request| request.context.as_ref())
13851            .map(|_| {
13852                cancellation_replay_clock::ReplayClock::new(
13853                    &history,
13854                    &recorded_commands,
13855                    cancellation_history.delivery_index,
13856                )
13857            })
13858            .or_else(|| {
13859                scope_delivery.as_ref().map(|_| {
13860                    cancellation_replay_clock::ReplayClock::new(&history, &recorded_commands, None)
13861                })
13862            });
13863        Ok(Self {
13864            observation_namespace: None,
13865            observation_terminal: history.iter().any(|event| {
13866                matches!(
13867                    event.event_type.as_str(),
13868                    "WorkflowCompleted"
13869                        | "WorkflowFailed"
13870                        | "WorkflowCancelled"
13871                        | "WorkflowTerminated"
13872                        | "WorkflowTimedOut"
13873                        | "WorkflowContinuedAsNew"
13874                )
13875            }),
13876            observation_pending: false,
13877            workflow_command_identity: String::new(),
13878            workflow_stream_command_counter: 0,
13879            workflow_id,
13880            run_id,
13881            task_queue,
13882            payload_codec,
13883            replay_clock: replay_clock::Clock::new(&history, &recorded_commands),
13884            history_events: Arc::new(history),
13885            history_budget: WorkflowHistoryBudget {
13886                event_count,
13887                ..WorkflowHistoryBudget::default()
13888            },
13889            cancel_requested,
13890            cancellation_history,
13891            cancellation_consumed: false,
13892            cancellation_clock,
13893            cancellation_shield_depth: 0,
13894            cancellation_delivery_enabled: false,
13895            cancellation_delivery_intent: None,
13896            cancellation_delivery_command_count: 0,
13897            allow_cancellation_scope_authoring,
13898            cancellation_scope_opening: None,
13899            cancellation_scope_memberships: scopes.memberships,
13900            scope_delivery,
13901            resume_signal,
13902            recorded_commands,
13903            selection_markers,
13904            selection_marker_cursor: 0,
13905            cancelled_selection_members,
13906            recorded_continue_as_new_sequence,
13907            continue_as_new_consumed: false,
13908            command_cursor: 0,
13909            condition_wait_occurrence_counter: 0,
13910            matched_recorded_pending: false,
13911            version_markers: HashMap::new(),
13912            commands: Vec::new(),
13913            local_activity_requests: Vec::new(),
13914            message_stream_messages: HashMap::new(),
13915            message_stream_cursors,
13916            message_stream_waits: HashMap::new(),
13917            signal_external_workflow_supported: false,
13918        })
13919    }
13920}
13921
13922enum MessageStreamDelivery {
13923    Message(MessageStreamMessage),
13924    Cursor {
13925        stream_name: String,
13926        through_position: u64,
13927    },
13928}
13929
13930fn decode_message_stream_delivery(arguments: Vec<Value>) -> Result<Option<MessageStreamDelivery>> {
13931    if arguments.len() != 1 {
13932        return Ok(None);
13933    }
13934    let envelope = arguments
13935        .into_iter()
13936        .next()
13937        .expect("one argument was checked");
13938    let Some(envelope) = envelope.as_object() else {
13939        return Ok(None);
13940    };
13941    let Some(stream_name) = envelope.get("stream_name").and_then(Value::as_str) else {
13942        return Ok(None);
13943    };
13944    if envelope.get("schema").and_then(Value::as_str) == Some(MESSAGE_STREAM_CURSOR_SCHEMA) {
13945        let Some(through_position) = envelope.get("through_position").and_then(Value::as_u64)
13946        else {
13947            return Ok(None);
13948        };
13949        return Ok(Some(MessageStreamDelivery::Cursor {
13950            stream_name: stream_name.to_string(),
13951            through_position,
13952        }));
13953    }
13954    if envelope.get("schema").and_then(Value::as_str) != Some(MESSAGE_STREAM_SCHEMA) {
13955        return Ok(None);
13956    }
13957    let Some(message_id) = envelope.get("message_id").and_then(Value::as_str) else {
13958        return Ok(None);
13959    };
13960    let Some(position) = envelope
13961        .get("position")
13962        .and_then(Value::as_u64)
13963        .filter(|value| *value > 0)
13964    else {
13965        return Ok(None);
13966    };
13967    let Some(payload_envelope) = envelope.get("payload_envelope") else {
13968        return Ok(None);
13969    };
13970    let Ok(payload_envelope) = serde_json::from_value::<PayloadEnvelope>(payload_envelope.clone())
13971    else {
13972        return Ok(None);
13973    };
13974    let decoded = decode_avro_value(&payload_envelope)?;
13975    let AvroValue::Array(values) = decoded else {
13976        return Ok(None);
13977    };
13978    Ok(Some(MessageStreamDelivery::Message(MessageStreamMessage {
13979        stream_name: stream_name.to_string(),
13980        message_id: message_id.to_string(),
13981        position,
13982        arguments: values,
13983    })))
13984}
13985
13986#[derive(Clone, Debug)]
13987enum RecordedCommand {
13988    ServiceOperation {
13989        sequence: u64,
13990        call: nexus::RecordedServiceCall,
13991    },
13992    CancellationScope {
13993        sequence: u64,
13994        scope_id: String,
13995        parent_scope_id: String,
13996        shield_parent: bool,
13997    },
13998    CancellationGroup {
13999        sequence: u64,
14000        span: u64,
14001        original: Vec<RecordedCommand>,
14002    },
14003    CancellationBoundary {
14004        sequence: u64,
14005        call_kind: CancellationCallKind,
14006        original: Option<Box<RecordedCommand>>,
14007    },
14008    Activity {
14009        sequence: u64,
14010        activity_type: Option<String>,
14011        cancellation_policy: String,
14012        options: Option<RecordedActivityOptions>,
14013        outcome: Option<ActivityOutcome>,
14014        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
14015    },
14016    Timer {
14017        sequence: u64,
14018        delay_seconds: u64,
14019        fired: bool,
14020        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
14021    },
14022    ChildWorkflow {
14023        sequence: u64,
14024        workflow_type: Option<String>,
14025        policies: RecordedChildPolicies,
14026        outcome: Option<ChildWorkflowOutcome>,
14027        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
14028    },
14029    SignalWait {
14030        sequence: u64,
14031        signal_name: String,
14032        value: Option<Vec<AvroValue>>,
14033        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
14034    },
14035    ConditionWait {
14036        sequence: u64,
14037        occurrence_id: String,
14038        condition_key: Option<String>,
14039        predicate_identity: String,
14040        timeout_seconds: Option<u64>,
14041        result: Option<ConditionWaitResult>,
14042        parallel_group_path: Option<Vec<ParallelGroupMetadata>>,
14043    },
14044    SearchAttributes {
14045        sequence: u64,
14046        attributes: Value,
14047        attribute_types: RecordedSnapshotValue<BTreeMap<String, String>>,
14048    },
14049    SideEffect {
14050        sequence: u64,
14051        value: AvroValue,
14052    },
14053    VersionMarker {
14054        sequence: u64,
14055        change_id: String,
14056        version: i32,
14057    },
14058    Memo {
14059        sequence: u64,
14060        entries: AvroValue,
14061    },
14062    ExternalSignal {
14063        sequence: u64,
14064        request: external_signal::RecordedRequest,
14065        outcome: Option<ExternalSignalResult>,
14066    },
14067}
14068
14069#[derive(Clone, Debug, PartialEq, Eq)]
14070struct SelectionMarker {
14071    selection_group_id: String,
14072    selection_group_base_sequence: u64,
14073    selection_group_size: usize,
14074    member_key: SelectionKey,
14075    member_index: usize,
14076    member_base_sequence: u64,
14077    member_size: usize,
14078    operation_kind: String,
14079    operation_identity: String,
14080    outcome: String,
14081    resolution_event_id: String,
14082    resolution_event_type: String,
14083}
14084
14085#[derive(Clone, Debug, PartialEq, Eq)]
14086struct SelectionCancellation {
14087    selection_group_id: String,
14088    member_key: SelectionKey,
14089    member_index: usize,
14090    member_base_sequence: u64,
14091    member_size: usize,
14092    operation_kind: String,
14093    operation_identity: String,
14094}
14095
14096// Left byte-identical in a lint-only change; equivalent to `saturating_add`.
14097#[allow(clippy::manual_saturating_arithmetic)]
14098fn recorded_selection_markers(events: &[HistoryEvent]) -> Result<Vec<SelectionMarker>> {
14099    let mut markers: Vec<SelectionMarker> = Vec::new();
14100    for event in events
14101        .iter()
14102        .filter(|event| event.event_type == "SelectionResolved")
14103    {
14104        let payload = &event.payload;
14105        let base_sequence = required_selection_u64(payload, "selection_group_base_sequence")?;
14106        let group_size = required_selection_usize(payload, "selection_group_size")?;
14107        let member_base_sequence = required_selection_u64(payload, "member_base_sequence")?;
14108        let member_size = required_selection_usize(payload, "member_size")?;
14109        let member_index = required_selection_usize_allow_zero(payload, "member_index")?;
14110        let group_id = payload_string(payload, "selection_group_id").ok_or_else(|| {
14111            invalid_recorded_history(
14112                "selection_marker_invalid",
14113                base_sequence,
14114                "non-empty selection_group_id",
14115                &payload.to_string(),
14116                "selection winner history is missing its durable group identity",
14117            )
14118        })?;
14119        let expected_group_id = format!("select-calls:{base_sequence}:{group_size}");
14120        if group_id != expected_group_id {
14121            return Err(invalid_recorded_history(
14122                "selection_marker_invalid",
14123                base_sequence,
14124                &expected_group_id,
14125                &group_id,
14126                "selection winner history contains an incompatible group identity",
14127            ));
14128        }
14129        let group_end = base_sequence
14130            .checked_add(u64::try_from(group_size).unwrap_or(u64::MAX))
14131            .unwrap_or(u64::MAX);
14132        let member_end = member_base_sequence
14133            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
14134            .unwrap_or(u64::MAX);
14135        if member_index >= group_size
14136            || member_base_sequence < base_sequence
14137            || member_end > group_end
14138        {
14139            return Err(invalid_recorded_history(
14140                "selection_marker_invalid",
14141                base_sequence,
14142                "winner member within selection group bounds",
14143                &payload.to_string(),
14144                "selection winner history contains an invalid member range",
14145            ));
14146        }
14147        let operation_kind = payload_string(payload, "operation_kind").ok_or_else(|| {
14148            invalid_recorded_history(
14149                "selection_marker_invalid",
14150                base_sequence,
14151                "selection operation kind",
14152                &payload.to_string(),
14153                "selection winner history is missing its operation kind",
14154            )
14155        })?;
14156        if !matches!(
14157            operation_kind.as_str(),
14158            "activity" | "child" | "timer" | "signal" | "condition" | "group"
14159        ) {
14160            return Err(invalid_recorded_history(
14161                "selection_marker_invalid",
14162                base_sequence,
14163                "activity, child, timer, signal, condition, or group",
14164                &operation_kind,
14165                "selection winner history contains an unsupported operation kind",
14166            ));
14167        }
14168        let operation_identity =
14169            payload_string(payload, "operation_identity").ok_or_else(|| {
14170                invalid_recorded_history(
14171                    "selection_marker_invalid",
14172                    base_sequence,
14173                    "non-empty operation identity",
14174                    &payload.to_string(),
14175                    "selection winner history is missing its durable operation identity",
14176                )
14177            })?;
14178        let outcome = payload_string(payload, "outcome").ok_or_else(|| {
14179            invalid_recorded_history(
14180                "selection_marker_invalid",
14181                base_sequence,
14182                "completed or failed selection outcome",
14183                &payload.to_string(),
14184                "selection winner history is missing its outcome",
14185            )
14186        })?;
14187        if !matches!(outcome.as_str(), "completed" | "failed") {
14188            return Err(invalid_recorded_history(
14189                "selection_marker_invalid",
14190                base_sequence,
14191                "completed or failed selection outcome",
14192                &outcome,
14193                "selection winner history contains an unsupported outcome",
14194            ));
14195        }
14196        let marker = SelectionMarker {
14197            selection_group_id: group_id,
14198            selection_group_base_sequence: base_sequence,
14199            selection_group_size: group_size,
14200            member_key: selection_key_from_value(payload.get("member_key"), base_sequence)?,
14201            member_index,
14202            member_base_sequence,
14203            member_size,
14204            operation_kind,
14205            operation_identity,
14206            outcome,
14207            resolution_event_id: payload_string(payload, "resolution_event_id").ok_or_else(
14208                || {
14209                    invalid_recorded_history(
14210                        "selection_marker_invalid",
14211                        base_sequence,
14212                        "durable resolution_event_id",
14213                        &payload.to_string(),
14214                        "selection winner history is missing its terminal event identity",
14215                    )
14216                },
14217            )?,
14218            resolution_event_type: payload_string(payload, "resolution_event_type").ok_or_else(
14219                || {
14220                    invalid_recorded_history(
14221                        "selection_marker_invalid",
14222                        base_sequence,
14223                        "durable resolution_event_type",
14224                        &payload.to_string(),
14225                        "selection winner history is missing its terminal event type",
14226                    )
14227                },
14228            )?,
14229        };
14230        if let Some(existing) = markers
14231            .iter()
14232            .find(|existing| existing.selection_group_id == marker.selection_group_id)
14233        {
14234            if existing != &marker {
14235                return Err(invalid_recorded_history(
14236                    "selection_marker_conflict",
14237                    base_sequence,
14238                    &format!("one winner for {}", marker.selection_group_id),
14239                    &payload.to_string(),
14240                    "selection history records conflicting winners for one durable group",
14241                ));
14242            }
14243            continue;
14244        }
14245        markers.push(marker);
14246    }
14247    Ok(markers)
14248}
14249
14250fn recorded_selection_cancellations(events: &[HistoryEvent]) -> Result<Vec<SelectionCancellation>> {
14251    let mut cancelled: Vec<SelectionCancellation> = Vec::new();
14252    for event in events
14253        .iter()
14254        .filter(|event| event.event_type == "SelectionOperationCancelled")
14255    {
14256        let group_id = payload_string(&event.payload, "selection_group_id").ok_or_else(|| {
14257            invalid_recorded_history(
14258                "selection_cancellation_invalid",
14259                0,
14260                "non-empty selection_group_id",
14261                &event.payload.to_string(),
14262                "selection cancellation history is missing its group identity",
14263            )
14264        })?;
14265        let member_base_sequence = required_selection_u64(&event.payload, "member_base_sequence")?;
14266        let marker = SelectionCancellation {
14267            selection_group_id: group_id,
14268            member_key: selection_key_from_value(
14269                event.payload.get("member_key"),
14270                member_base_sequence,
14271            )?,
14272            member_index: required_selection_usize_allow_zero(&event.payload, "member_index")?,
14273            member_base_sequence,
14274            member_size: required_selection_usize(&event.payload, "member_size")?,
14275            operation_kind: payload_string(&event.payload, "operation_kind").ok_or_else(|| {
14276                invalid_recorded_history(
14277                    "selection_cancellation_invalid",
14278                    member_base_sequence,
14279                    "selection operation kind",
14280                    &event.payload.to_string(),
14281                    "selection cancellation is missing its operation kind",
14282                )
14283            })?,
14284            operation_identity: payload_string(&event.payload, "operation_identity").ok_or_else(
14285                || {
14286                    invalid_recorded_history(
14287                        "selection_cancellation_invalid",
14288                        member_base_sequence,
14289                        "selection operation identity",
14290                        &event.payload.to_string(),
14291                        "selection cancellation is missing its operation identity",
14292                    )
14293                },
14294            )?,
14295        };
14296        if let Some(existing) = cancelled.iter().find(|recorded| {
14297            recorded.selection_group_id == marker.selection_group_id
14298                && recorded.member_base_sequence == marker.member_base_sequence
14299        }) {
14300            if existing != &marker {
14301                return Err(invalid_recorded_history(
14302                    "selection_cancellation_conflict",
14303                    member_base_sequence,
14304                    "one stable SelectionOperationCancelled marker",
14305                    &event.payload.to_string(),
14306                    "selection cancellation history contains conflicting member metadata",
14307                ));
14308            }
14309        } else {
14310            cancelled.push(marker);
14311        }
14312    }
14313    Ok(cancelled)
14314}
14315
14316fn required_selection_u64(payload: &Value, field: &str) -> Result<u64> {
14317    payload
14318        .get(field)
14319        .and_then(value_as_u64)
14320        .filter(|value| *value > 0)
14321        .ok_or_else(|| {
14322            invalid_recorded_history(
14323                "selection_marker_invalid",
14324                0,
14325                &format!("positive integer {field}"),
14326                &payload.to_string(),
14327                "selection history contains invalid durable identity metadata",
14328            )
14329        })
14330}
14331
14332fn required_selection_usize(payload: &Value, field: &str) -> Result<usize> {
14333    required_selection_usize_allow_zero(payload, field).and_then(|value| {
14334        if value > 0 {
14335            Ok(value)
14336        } else {
14337            Err(invalid_recorded_history(
14338                "selection_marker_invalid",
14339                0,
14340                &format!("positive integer {field}"),
14341                &payload.to_string(),
14342                "selection history contains invalid durable identity metadata",
14343            ))
14344        }
14345    })
14346}
14347
14348fn required_selection_usize_allow_zero(payload: &Value, field: &str) -> Result<usize> {
14349    payload
14350        .get(field)
14351        .and_then(value_as_u64)
14352        .and_then(|value| usize::try_from(value).ok())
14353        .ok_or_else(|| {
14354            invalid_recorded_history(
14355                "selection_marker_invalid",
14356                0,
14357                &format!("non-negative integer {field}"),
14358                &payload.to_string(),
14359                "selection history contains invalid durable identity metadata",
14360            )
14361        })
14362}
14363
14364#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
14365struct RecordedActivityOptions {
14366    task_queue: RecordedSnapshotValue<Option<String>>,
14367    execution_mode: RecordedSnapshotValue<Option<String>>,
14368    retry_policy: ActivityRetrySnapshot,
14369    worker_session: Option<Value>,
14370}
14371
14372#[derive(Clone, Debug)]
14373struct RecordedChildPolicies {
14374    parent_close_policy: String,
14375    cancellation_policy: String,
14376}
14377
14378fn recorded_activity_cancellation_policy(
14379    events: &[&HistoryEvent],
14380    sequence: u64,
14381) -> Result<String> {
14382    let mut policy: Option<String> = None;
14383    for event in events.iter().filter(|event| {
14384        matches!(
14385            event.event_type.as_str(),
14386            "ActivityScheduled"
14387                | "ActivityStarted"
14388                | "ActivityCompleted"
14389                | "ActivityFailed"
14390                | "ActivityTimedOut"
14391                | "ActivityCancelled"
14392        )
14393    }) {
14394        for source in [Some(&event.payload), event.payload.get("activity")]
14395            .into_iter()
14396            .flatten()
14397        {
14398            let Some(value) = source.get("cancellation_policy") else {
14399                continue;
14400            };
14401            let Some(incoming @ ("try_cancel" | "wait_cancellation_completed" | "abandon")) =
14402                value.as_str()
14403            else {
14404                return Err(invalid_recorded_history(
14405                    "invalid_activity_cancellation_policy_history",
14406                    sequence,
14407                    "supported Activity cancellation policy",
14408                    &value.to_string(),
14409                    "Activity history contains an invalid cancellation policy",
14410                ));
14411            };
14412            if let Some(previous) = policy.as_deref() {
14413                if previous != incoming {
14414                    return Err(invalid_recorded_history(
14415                        "activity_cancellation_policy_history_conflict",
14416                        sequence,
14417                        previous,
14418                        incoming,
14419                        "Activity cancellation policy changed between history events",
14420                    ));
14421                }
14422            }
14423            policy = Some(incoming.to_string());
14424        }
14425        policy.get_or_insert_with(|| "try_cancel".to_string());
14426    }
14427    Ok(policy.unwrap_or_else(|| "try_cancel".to_string()))
14428}
14429
14430fn recorded_child_policy_value<'a>(
14431    payload: &'a Value,
14432    field: &str,
14433    sequence: u64,
14434) -> Result<Option<&'a str>> {
14435    let Some(value) = payload.get(field).filter(|value| !value.is_null()) else {
14436        return Ok(None);
14437    };
14438    let valid = matches!(
14439        (field, value.as_str()),
14440        (
14441            "parent_close_policy",
14442            Some("abandon" | "request_cancel" | "request_cancellation" | "terminate"),
14443        ) | (
14444            "cancellation_policy",
14445            Some("abandon" | "try_cancel" | "wait_cancellation_completed")
14446        )
14447    );
14448    if !valid {
14449        return Err(invalid_recorded_history(
14450            "invalid_child_workflow_policy_history",
14451            sequence,
14452            "supported child workflow policy",
14453            &value.to_string(),
14454            "child workflow history contains an invalid policy",
14455        ));
14456    }
14457    Ok(value.as_str())
14458}
14459
14460fn recorded_child_policies(
14461    events: &[&HistoryEvent],
14462    scheduled: &HistoryEvent,
14463    sequence: u64,
14464) -> Result<RecordedChildPolicies> {
14465    let parent_close_policy =
14466        recorded_child_policy_value(&scheduled.payload, "parent_close_policy", sequence)?
14467            .unwrap_or("abandon")
14468            .to_string();
14469    let cancellation_policy =
14470        recorded_child_policy_value(&scheduled.payload, "cancellation_policy", sequence)?
14471            .unwrap_or("abandon")
14472            .to_string();
14473    for event in events {
14474        for (field, expected) in [
14475            ("parent_close_policy", parent_close_policy.as_str()),
14476            ("cancellation_policy", cancellation_policy.as_str()),
14477        ] {
14478            if let Some(actual) = recorded_child_policy_value(&event.payload, field, sequence)? {
14479                if actual != expected {
14480                    return Err(invalid_recorded_history(
14481                        "child_workflow_policy_history_conflict",
14482                        sequence,
14483                        expected,
14484                        actual,
14485                        "child workflow policy changed between history events",
14486                    ));
14487                }
14488            }
14489        }
14490    }
14491    Ok(RecordedChildPolicies {
14492        parent_close_policy,
14493        cancellation_policy,
14494    })
14495}
14496
14497fn ensure_child_policies_match(
14498    sequence: u64,
14499    recorded: &RecordedChildPolicies,
14500    current: &ChildWorkflowOptions,
14501) -> Result<()> {
14502    for (field, expected, actual) in [
14503        (
14504            "parent_close_policy",
14505            recorded.parent_close_policy.as_str(),
14506            current.parent_close_policy.as_str(),
14507        ),
14508        (
14509            "cancellation_policy",
14510            recorded.cancellation_policy.as_str(),
14511            current.cancellation_policy.as_str(),
14512        ),
14513    ] {
14514        if expected != actual {
14515            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
14516                "child_workflow_policy_changed",
14517                Some(sequence),
14518                Some(expected.to_string()),
14519                Some(actual.to_string()),
14520                format!("child workflow {field} changed during replay"),
14521            )));
14522        }
14523    }
14524    Ok(())
14525}
14526
14527#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
14528enum RecordedSnapshotValue<T> {
14529    /// Older history did not persist this field, so it cannot constrain replay.
14530    Unknown,
14531    Known(T),
14532}
14533
14534impl<T: PartialEq> RecordedSnapshotValue<T> {
14535    fn matches_current(&self, current: &Self) -> bool {
14536        match self {
14537            Self::Unknown => true,
14538            Self::Known(recorded) => matches!(current, Self::Known(value) if value == recorded),
14539        }
14540    }
14541}
14542
14543#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
14544struct ActivityRetrySnapshot {
14545    snapshot_version: RecordedSnapshotValue<Option<u64>>,
14546    max_attempts: RecordedSnapshotValue<Option<u64>>,
14547    backoff_seconds: RecordedSnapshotValue<Vec<u64>>,
14548    start_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
14549    schedule_to_start_timeout: RecordedSnapshotValue<Option<u64>>,
14550    schedule_to_close_timeout: RecordedSnapshotValue<Option<u64>>,
14551    heartbeat_timeout: RecordedSnapshotValue<Option<u64>>,
14552    non_retryable_error_types: RecordedSnapshotValue<Vec<String>>,
14553}
14554
14555impl ActivityRetrySnapshot {
14556    fn matches_current(&self, current: &Self) -> bool {
14557        self.snapshot_version
14558            .matches_current(&current.snapshot_version)
14559            && self.max_attempts.matches_current(&current.max_attempts)
14560            && self
14561                .backoff_seconds
14562                .matches_current(&current.backoff_seconds)
14563            && self
14564                .start_to_close_timeout
14565                .matches_current(&current.start_to_close_timeout)
14566            && self
14567                .schedule_to_start_timeout
14568                .matches_current(&current.schedule_to_start_timeout)
14569            && self
14570                .schedule_to_close_timeout
14571                .matches_current(&current.schedule_to_close_timeout)
14572            && self
14573                .heartbeat_timeout
14574                .matches_current(&current.heartbeat_timeout)
14575            && self
14576                .non_retryable_error_types
14577                .matches_current(&current.non_retryable_error_types)
14578    }
14579}
14580
14581fn recorded_optional_u64(
14582    object: Option<&serde_json::Map<String, Value>>,
14583    field: &str,
14584) -> RecordedSnapshotValue<Option<u64>> {
14585    match object.and_then(|object| object.get(field)) {
14586        None => RecordedSnapshotValue::Unknown,
14587        Some(Value::Null) => RecordedSnapshotValue::Known(None),
14588        Some(value) => RecordedSnapshotValue::Known(value_as_u64(value)),
14589    }
14590}
14591
14592fn recorded_optional_string(
14593    object: &serde_json::Map<String, Value>,
14594    field: &str,
14595) -> RecordedSnapshotValue<Option<String>> {
14596    match object.get(field) {
14597        None => RecordedSnapshotValue::Unknown,
14598        Some(Value::Null) => RecordedSnapshotValue::Known(None),
14599        Some(value) => RecordedSnapshotValue::Known(value.as_str().map(str::to_string)),
14600    }
14601}
14602
14603fn recorded_activity_execution_mode(
14604    events: &[&HistoryEvent],
14605    sequence: u64,
14606) -> Result<RecordedSnapshotValue<Option<String>>> {
14607    let mut recorded = RecordedSnapshotValue::Unknown;
14608    for event in events {
14609        for object in [
14610            event.payload.as_object(),
14611            event.payload.get("activity").and_then(Value::as_object),
14612        ]
14613        .into_iter()
14614        .flatten()
14615        {
14616            let mode = match object.get("execution_mode") {
14617                None => None,
14618                Some(Value::Null) => Some(None),
14619                Some(Value::String(mode)) if !mode.is_empty() => Some(Some(mode.clone())),
14620                Some(_) => {
14621                    return Err(invalid_recorded_history(
14622                        "activity_execution_mode_invalid",
14623                        sequence,
14624                        "null or a non-empty execution mode",
14625                        "invalid execution_mode",
14626                        "activity history contains an invalid execution mode",
14627                    ))
14628                }
14629            };
14630            let legacy_mode = match object.get("local_activity") {
14631                None => None,
14632                Some(Value::Bool(local)) => Some(local.then(|| "local".to_string())),
14633                Some(_) => {
14634                    return Err(invalid_recorded_history(
14635                        "activity_execution_mode_invalid",
14636                        sequence,
14637                        "boolean local_activity",
14638                        "invalid local_activity",
14639                        "activity history contains an invalid local-activity marker",
14640                    ))
14641                }
14642            };
14643            for mode in [mode, legacy_mode].into_iter().flatten() {
14644                if matches!(&recorded, RecordedSnapshotValue::Known(previous) if previous != &mode)
14645                {
14646                    return Err(invalid_recorded_history(
14647                        "activity_execution_mode_conflict", sequence, "one activity execution mode", "conflicting execution modes",
14648                        "activity lifecycle events at one workflow sequence disagree on execution mode",
14649                    ));
14650                }
14651                recorded = RecordedSnapshotValue::Known(mode);
14652            }
14653        }
14654    }
14655    Ok(recorded)
14656}
14657
14658fn recorded_activity_retry_snapshot(policy: Option<&Value>) -> ActivityRetrySnapshot {
14659    let policy = policy.and_then(Value::as_object);
14660    let backoff_seconds = policy
14661        .and_then(|policy| policy.get("backoff_seconds"))
14662        .and_then(Value::as_array)
14663        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
14664        .map_or(RecordedSnapshotValue::Unknown, RecordedSnapshotValue::Known);
14665    let mut non_retryable_error_types = Vec::new();
14666    for error_type in policy
14667        .and_then(|policy| policy.get("non_retryable_error_types"))
14668        .and_then(Value::as_array)
14669        .into_iter()
14670        .flatten()
14671        .filter_map(Value::as_str)
14672        .map(str::trim)
14673        .filter(|error_type| !error_type.is_empty())
14674    {
14675        if !non_retryable_error_types
14676            .iter()
14677            .any(|recorded| recorded == error_type)
14678        {
14679            non_retryable_error_types.push(error_type.to_string());
14680        }
14681    }
14682
14683    ActivityRetrySnapshot {
14684        snapshot_version: recorded_optional_u64(policy, "snapshot_version"),
14685        max_attempts: recorded_optional_u64(policy, "max_attempts"),
14686        backoff_seconds,
14687        start_to_close_timeout: recorded_optional_u64(policy, "start_to_close_timeout"),
14688        schedule_to_start_timeout: recorded_optional_u64(policy, "schedule_to_start_timeout"),
14689        schedule_to_close_timeout: recorded_optional_u64(policy, "schedule_to_close_timeout"),
14690        heartbeat_timeout: recorded_optional_u64(policy, "heartbeat_timeout"),
14691        non_retryable_error_types: if policy
14692            .is_some_and(|policy| policy.contains_key("non_retryable_error_types"))
14693        {
14694            RecordedSnapshotValue::Known(non_retryable_error_types)
14695        } else {
14696            RecordedSnapshotValue::Unknown
14697        },
14698    }
14699}
14700
14701fn current_activity_retry_snapshot(options: &ValidatedActivityOptions) -> ActivityRetrySnapshot {
14702    let policy = options.retry_policy.as_ref();
14703    let max_attempts = match policy.and_then(|policy| policy.get("max_attempts")) {
14704        Some(Value::Null) => None,
14705        Some(value) => value_as_u64(value),
14706        None => Some(1),
14707    };
14708    let backoff_seconds = policy
14709        .and_then(|policy| policy.get("backoff_seconds"))
14710        .and_then(Value::as_array)
14711        .map(|intervals| intervals.iter().filter_map(value_as_u64).collect())
14712        .unwrap_or_default();
14713    let non_retryable_error_types = policy
14714        .and_then(|policy| policy.get("non_retryable_error_types"))
14715        .and_then(Value::as_array)
14716        .into_iter()
14717        .flatten()
14718        .filter_map(Value::as_str)
14719        .map(str::to_string)
14720        .collect();
14721
14722    ActivityRetrySnapshot {
14723        snapshot_version: RecordedSnapshotValue::Known(Some(1)),
14724        max_attempts: RecordedSnapshotValue::Known(max_attempts),
14725        backoff_seconds: RecordedSnapshotValue::Known(backoff_seconds),
14726        start_to_close_timeout: RecordedSnapshotValue::Known(options.start_to_close_timeout),
14727        schedule_to_start_timeout: RecordedSnapshotValue::Known(options.schedule_to_start_timeout),
14728        schedule_to_close_timeout: RecordedSnapshotValue::Known(options.schedule_to_close_timeout),
14729        heartbeat_timeout: RecordedSnapshotValue::Known(options.heartbeat_timeout),
14730        non_retryable_error_types: RecordedSnapshotValue::Known(non_retryable_error_types),
14731    }
14732}
14733
14734fn activity_options_description(options: &RecordedActivityOptions) -> String {
14735    serde_json::to_string(options).unwrap_or_else(|_| format!("{options:?}"))
14736}
14737
14738impl RecordedCommand {
14739    fn sequence(&self) -> u64 {
14740        match self {
14741            Self::CancellationGroup { sequence, .. }
14742            | Self::CancellationScope { sequence, .. }
14743            | Self::CancellationBoundary { sequence, .. }
14744            | Self::Activity { sequence, .. }
14745            | Self::Timer { sequence, .. }
14746            | Self::ChildWorkflow { sequence, .. }
14747            | Self::SignalWait { sequence, .. }
14748            | Self::ConditionWait { sequence, .. }
14749            | Self::SearchAttributes { sequence, .. }
14750            | Self::SideEffect { sequence, .. }
14751            | Self::VersionMarker { sequence, .. }
14752            | Self::Memo { sequence, .. }
14753            | Self::ExternalSignal { sequence, .. } => *sequence,
14754            Self::ServiceOperation { sequence, .. } => *sequence,
14755        }
14756    }
14757
14758    fn shape(&self) -> &'static str {
14759        match self {
14760            Self::CancellationScope { .. } => "cancellation scope",
14761            Self::CancellationBoundary { .. } | Self::CancellationGroup { .. } => {
14762                "cooperative cancellation"
14763            }
14764            Self::Activity { .. } => "activity",
14765            Self::Timer { .. } => "timer",
14766            Self::ChildWorkflow { .. } => "child workflow",
14767            Self::SignalWait { .. } => "signal wait",
14768            Self::ConditionWait { .. } => "condition wait",
14769            Self::SearchAttributes { .. } => "search-attribute update",
14770            Self::SideEffect { .. } => "side effect",
14771            Self::VersionMarker { .. } => "version marker",
14772            Self::Memo { .. } => "memo upsert",
14773            Self::ExternalSignal { .. } => "external signal",
14774            Self::ServiceOperation { .. } => "service operation",
14775        }
14776    }
14777}
14778
14779fn ensure_version_supported(
14780    change_id: &str,
14781    version: i32,
14782    min_supported: i32,
14783    max_supported: i32,
14784    sequence: u64,
14785) -> Result<()> {
14786    if (min_supported..=max_supported).contains(&version) {
14787        return Ok(());
14788    }
14789    Err(Error::NonDeterministicReplay(ReplayFailure::new(
14790        "version_marker_incompatible_range",
14791        (sequence != 0).then_some(sequence),
14792        Some(format!("{min_supported}..={max_supported}")),
14793        Some(format!("{change_id}:{version}")),
14794        "recorded workflow version is outside the range supported by current code",
14795    )))
14796}
14797
14798#[derive(Clone, Debug)]
14799struct ResumeSignal {
14800    signal_name: String,
14801    arguments: Vec<AvroValue>,
14802}
14803
14804const MAX_PARALLEL_OPERATIONS: usize = 1000;
14805
14806fn parallel_group_prefix(kind: &str) -> &'static str {
14807    match kind {
14808        "activity" => "parallel-activities",
14809        "child" => "parallel-children",
14810        "timer" => "parallel-timers",
14811        _ => "parallel-calls",
14812    }
14813}
14814
14815fn parallel_group_entry(
14816    base_sequence: u64,
14817    size: usize,
14818    index: usize,
14819    kind: &str,
14820) -> ParallelGroupMetadata {
14821    ParallelGroupMetadata {
14822        parallel_group_id: format!("{}:{base_sequence}:{size}", parallel_group_prefix(kind)),
14823        parallel_group_kind: kind.to_string(),
14824        parallel_group_base_sequence: base_sequence,
14825        parallel_group_size: size,
14826        parallel_group_index: index,
14827        parallel_group_mode: None,
14828        selection_member_key: None,
14829        selection_member_index: None,
14830        selection_member_base_sequence: None,
14831        selection_member_size: None,
14832        selection_member_kind: None,
14833    }
14834}
14835
14836struct SelectionMemberMetadata {
14837    key: SelectionKey,
14838    index: usize,
14839    base_sequence: u64,
14840    size: usize,
14841    kind: String,
14842}
14843
14844fn selection_group_entry(
14845    base_sequence: u64,
14846    size: usize,
14847    index: usize,
14848    kind: &str,
14849    member: &SelectionMemberMetadata,
14850) -> ParallelGroupMetadata {
14851    ParallelGroupMetadata {
14852        parallel_group_id: format!("select-calls:{base_sequence}:{size}"),
14853        parallel_group_kind: kind.to_string(),
14854        parallel_group_base_sequence: base_sequence,
14855        parallel_group_size: size,
14856        parallel_group_index: index,
14857        parallel_group_mode: Some("select".to_string()),
14858        selection_member_key: Some(member.key.clone()),
14859        selection_member_index: Some(member.index),
14860        selection_member_base_sequence: Some(member.base_sequence),
14861        selection_member_size: Some(member.size),
14862        selection_member_kind: Some(member.kind.clone()),
14863    }
14864}
14865
14866fn apply_parallel_group_path(
14867    command: &mut serde_json::Map<String, Value>,
14868    path: &[ParallelGroupMetadata],
14869) {
14870    let Some(inner) = path.last() else {
14871        return;
14872    };
14873    command.insert(
14874        "parallel_group_id".to_string(),
14875        json!(inner.parallel_group_id),
14876    );
14877    command.insert(
14878        "parallel_group_kind".to_string(),
14879        json!(inner.parallel_group_kind),
14880    );
14881    command.insert(
14882        "parallel_group_base_sequence".to_string(),
14883        json!(inner.parallel_group_base_sequence),
14884    );
14885    command.insert(
14886        "parallel_group_size".to_string(),
14887        json!(inner.parallel_group_size),
14888    );
14889    command.insert(
14890        "parallel_group_index".to_string(),
14891        json!(inner.parallel_group_index),
14892    );
14893    if let Some(mode) = &inner.parallel_group_mode {
14894        command.insert("parallel_group_mode".to_string(), json!(mode));
14895    }
14896    if let Some(key) = &inner.selection_member_key {
14897        command.insert("selection_member_key".to_string(), json!(key));
14898    }
14899    if let Some(index) = inner.selection_member_index {
14900        command.insert("selection_member_index".to_string(), json!(index));
14901    }
14902    if let Some(base_sequence) = inner.selection_member_base_sequence {
14903        command.insert(
14904            "selection_member_base_sequence".to_string(),
14905            json!(base_sequence),
14906        );
14907    }
14908    if let Some(size) = inner.selection_member_size {
14909        command.insert("selection_member_size".to_string(), json!(size));
14910    }
14911    if let Some(kind) = &inner.selection_member_kind {
14912        command.insert("selection_member_kind".to_string(), json!(kind));
14913    }
14914    command.insert("parallel_group_path".to_string(), json!(path));
14915}
14916
14917fn ensure_parallel_path_matches(
14918    sequence: u64,
14919    recorded: Option<&[ParallelGroupMetadata]>,
14920    expected: &[ParallelGroupMetadata],
14921) -> Result<()> {
14922    match (recorded, expected.is_empty()) {
14923        (None, true) => Ok(()),
14924        (Some(recorded), false) if recorded == expected => Ok(()),
14925        (None, false) => Err(invalid_recorded_history(
14926            "parallel_group_metadata_missing",
14927            sequence,
14928            &serde_json::to_string(expected).unwrap_or_default(),
14929            "<missing>",
14930            "recorded parallel member is missing its durable group path",
14931        )),
14932        (Some(recorded), true) => Err(invalid_recorded_history(
14933            "parallel_group_shape_mismatch",
14934            sequence,
14935            "sequential command",
14936            &serde_json::to_string(recorded).unwrap_or_default(),
14937            "recorded command belonged to a parallel group but current code schedules it sequentially",
14938        )),
14939        (Some(recorded), false) => Err(invalid_recorded_history(
14940            "parallel_group_shape_mismatch",
14941            sequence,
14942            &serde_json::to_string(recorded).unwrap_or_default(),
14943            &serde_json::to_string(expected).unwrap_or_default(),
14944            "recorded parallel-group identity or path changed during replay",
14945        )),
14946    }
14947}
14948
14949#[derive(Clone, Debug)]
14950enum ParallelShape {
14951    Leaf,
14952    Group(Vec<ParallelShape>),
14953}
14954
14955struct ParallelDescriptor {
14956    operation: ParallelOperation,
14957    offset: usize,
14958    member_path: Vec<usize>,
14959    group_path: Vec<ParallelGroupMetadata>,
14960}
14961
14962fn parallel_leaf_count(operations: &[ParallelOperation]) -> usize {
14963    operations
14964        .iter()
14965        .map(|operation| match operation {
14966            ParallelOperation::Group(children) => parallel_leaf_count(children),
14967            _ => 1,
14968        })
14969        .sum()
14970}
14971
14972fn parallel_operation_kind(operation: &ParallelOperation) -> Option<&'static str> {
14973    match operation {
14974        ParallelOperation::Activity { .. } => Some("activity"),
14975        ParallelOperation::ChildWorkflow { .. } => Some("child"),
14976        ParallelOperation::Timer(_) => Some("timer"),
14977        ParallelOperation::Signal(_) => Some("signal"),
14978        ParallelOperation::Condition { .. } => Some("condition"),
14979        ParallelOperation::Group(children) => parallel_group_kind(children),
14980    }
14981}
14982
14983fn parallel_group_kind(operations: &[ParallelOperation]) -> Option<&'static str> {
14984    let mut kind = None;
14985    for operation in operations {
14986        let Some(operation_kind) = parallel_operation_kind(operation) else {
14987            continue;
14988        };
14989        match kind {
14990            None => kind = Some(operation_kind),
14991            Some(current) if current == operation_kind => {}
14992            Some(_) => return Some("mixed"),
14993        }
14994    }
14995    kind
14996}
14997
14998fn validate_parallel_operations(
14999    operations: &[ParallelOperation],
15000    member_path: &mut Vec<usize>,
15001    root: bool,
15002) -> Result<()> {
15003    let leaves = parallel_leaf_count(operations);
15004    if leaves > MAX_PARALLEL_OPERATIONS {
15005        return Err(Error::InvalidParallelGroup(ParallelGroupError {
15006            reason: "fan_out_limit_exceeded",
15007            member_path: member_path.clone(),
15008            message: format!(
15009                "group contains {leaves} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
15010            ),
15011        }));
15012    }
15013    if !root && operations.is_empty() {
15014        return Err(Error::InvalidParallelGroup(ParallelGroupError {
15015            reason: "nested_group_empty",
15016            member_path: member_path.clone(),
15017            message: "a nested group must contain at least one durable leaf".to_string(),
15018        }));
15019    }
15020
15021    for (index, operation) in operations.iter().enumerate() {
15022        member_path.push(index);
15023        match operation {
15024            ParallelOperation::Activity {
15025                options, arguments, ..
15026            } => {
15027                options.validate().map_err(Error::InvalidActivityOptions)?;
15028                if let Err(error) = arguments {
15029                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
15030                        reason: "arguments_invalid",
15031                        member_path: member_path.clone(),
15032                        message: error.to_string(),
15033                    }));
15034                }
15035            }
15036            ParallelOperation::ChildWorkflow {
15037                options, arguments, ..
15038            } => {
15039                validate_parallel_child_options(options)?;
15040                if let Err(error) = arguments {
15041                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
15042                        reason: "arguments_invalid",
15043                        member_path: member_path.clone(),
15044                        message: error.to_string(),
15045                    }));
15046                }
15047            }
15048            ParallelOperation::Timer(duration)
15049                if duration.as_secs() == u64::MAX && duration.subsec_nanos() > 0 =>
15050            {
15051                return Err(Error::TimerDurationOverflow);
15052            }
15053            ParallelOperation::Timer(_) => {}
15054            ParallelOperation::Signal(signal_name) => {
15055                validate_user_signal_name(signal_name)?;
15056                if signal_name.trim().is_empty() {
15057                    return Err(Error::InvalidParallelGroup(ParallelGroupError {
15058                        reason: "signal_name_empty",
15059                        member_path: member_path.clone(),
15060                        message: "signal wait name must not be empty".to_string(),
15061                    }));
15062                }
15063            }
15064            ParallelOperation::Condition { options, .. } => {
15065                options.validate()?;
15066            }
15067            ParallelOperation::Group(children) => {
15068                validate_parallel_operations(children, member_path, false)?;
15069            }
15070        }
15071        member_path.pop();
15072    }
15073    Ok(())
15074}
15075
15076fn validate_parallel_child_options(options: &ChildWorkflowOptions) -> Result<()> {
15077    if options.task_queue.trim().is_empty() {
15078        return Err(Error::InvalidChildWorkflowOptions(
15079            "task_queue must not be empty".to_string(),
15080        ));
15081    }
15082    for (name, value) in [
15083        (
15084            "execution_timeout_seconds",
15085            options.execution_timeout_seconds,
15086        ),
15087        ("run_timeout_seconds", options.run_timeout_seconds),
15088    ] {
15089        if value == Some(0) {
15090            return Err(Error::InvalidChildWorkflowOptions(format!(
15091                "{name} must be at least 1"
15092            )));
15093        }
15094    }
15095    if options
15096        .retry_policy
15097        .as_ref()
15098        .is_some_and(|policy| policy.max_attempts == Some(0))
15099    {
15100        return Err(Error::InvalidChildWorkflowOptions(
15101            "retry_policy.max_attempts must be at least 1".to_string(),
15102        ));
15103    }
15104    Ok(())
15105}
15106
15107fn parallel_shape(operations: &[ParallelOperation]) -> ParallelShape {
15108    ParallelShape::Group(
15109        operations
15110            .iter()
15111            .map(|operation| match operation {
15112                ParallelOperation::Group(children) => parallel_shape(children),
15113                _ => ParallelShape::Leaf,
15114            })
15115            .collect(),
15116    )
15117}
15118
15119fn parallel_descriptors(
15120    operations: Vec<ParallelOperation>,
15121    base_sequence: u64,
15122) -> Result<Vec<ParallelDescriptor>> {
15123    let size = parallel_leaf_count(&operations);
15124    let kind = parallel_group_kind(&operations).unwrap_or("activity");
15125    let mut descriptors = Vec::with_capacity(size);
15126    let mut cursor = 0;
15127
15128    for (index, operation) in operations.into_iter().enumerate() {
15129        match operation {
15130            ParallelOperation::Group(children) => {
15131                let child_base = base_sequence
15132                    .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
15133                    .ok_or(Error::TimerDurationOverflow)?;
15134                for mut descriptor in parallel_descriptors(children, child_base)? {
15135                    let outer_index = cursor + descriptor.offset;
15136                    descriptor.group_path.insert(
15137                        0,
15138                        parallel_group_entry(base_sequence, size, outer_index, kind),
15139                    );
15140                    descriptor.member_path.insert(0, index);
15141                    descriptor.offset = outer_index;
15142                    descriptors.push(descriptor);
15143                }
15144                cursor = descriptors.len();
15145            }
15146            operation => {
15147                descriptors.push(ParallelDescriptor {
15148                    operation,
15149                    offset: cursor,
15150                    member_path: vec![index],
15151                    group_path: vec![parallel_group_entry(base_sequence, size, cursor, kind)],
15152                });
15153                cursor += 1;
15154            }
15155        }
15156    }
15157    Ok(descriptors)
15158}
15159
15160enum ParallelLeafCall {
15161    Activity(ActivityCall),
15162    ChildWorkflow(ChildWorkflowCall),
15163    Timer(TimerCall),
15164    Signal(SignalCall),
15165    Condition(ConditionWaitCall),
15166}
15167
15168fn parallel_leaf_call(
15169    ctx: &WorkflowContext,
15170    operation: ParallelOperation,
15171    parallel_group_path: Vec<ParallelGroupMetadata>,
15172) -> ParallelLeafCall {
15173    match operation {
15174        ParallelOperation::Activity {
15175            activity_type,
15176            options,
15177            arguments,
15178        } => ParallelLeafCall::Activity(ActivityCall {
15179            source: None,
15180            ctx: ctx.clone(),
15181            activity_type,
15182            options,
15183            worker_session: None,
15184            args: Some(arguments),
15185            scheduled: false,
15186            local: false,
15187            local_result: None,
15188            parallel_group_path,
15189        }),
15190        ParallelOperation::ChildWorkflow {
15191            workflow_type,
15192            options,
15193            arguments,
15194        } => ParallelLeafCall::ChildWorkflow(ChildWorkflowCall {
15195            ctx: ctx.clone(),
15196            workflow_type,
15197            options,
15198            args: Some(arguments),
15199            scheduled: false,
15200            matched_pending: false,
15201            parallel_group_path,
15202        }),
15203        ParallelOperation::Timer(duration) => {
15204            let delay_seconds = duration
15205                .as_secs()
15206                .checked_add(u64::from(duration.subsec_nanos() > 0));
15207            ParallelLeafCall::Timer(TimerCall {
15208                source: None,
15209                ctx: ctx.clone(),
15210                delay_seconds,
15211                scheduled: false,
15212                matched_pending: false,
15213                parallel_group_path,
15214            })
15215        }
15216        ParallelOperation::Signal(signal_name) => ParallelLeafCall::Signal(SignalCall {
15217            ctx: ctx.clone(),
15218            signal_name,
15219            runtime_reserved_allowed: false,
15220            opened_wait: false,
15221            matched_pending: false,
15222            parallel_group_path,
15223        }),
15224        ParallelOperation::Condition { options, predicate } => {
15225            ParallelLeafCall::Condition(ConditionWaitCall {
15226                ctx: ctx.clone(),
15227                options,
15228                predicate,
15229                occurrence_id: None,
15230                opened_wait: false,
15231                parallel_group_path,
15232            })
15233        }
15234        ParallelOperation::Group(_) => {
15235            unreachable!("parallel descriptors contain only durable leaves")
15236        }
15237    }
15238}
15239
15240impl ParallelLeafCall {
15241    fn poll_avro_value(&mut self, cx: &mut TaskContext<'_>) -> Poll<Result<ParallelAvroResult>> {
15242        match self {
15243            Self::Activity(call) => Pin::new(call)
15244                .poll_avro_value(cx)
15245                .map_ok(ParallelAvroResult::Activity),
15246            Self::ChildWorkflow(call) => Pin::new(call)
15247                .poll_avro_value(cx)
15248                .map_ok(ParallelAvroResult::ChildWorkflow),
15249            Self::Timer(call) => Pin::new(call)
15250                .poll(cx)
15251                .map_ok(|()| ParallelAvroResult::Timer),
15252            Self::Signal(call) => Pin::new(call)
15253                .poll_avro_value(cx)
15254                .map_ok(ParallelAvroResult::Signal),
15255            Self::Condition(call) => Pin::new(call)
15256                .poll(cx)
15257                .map_ok(ParallelAvroResult::Condition),
15258        }
15259    }
15260}
15261
15262struct ParallelLeaf {
15263    call: ParallelLeafCall,
15264    sequence: u64,
15265    member_path: Vec<usize>,
15266    group_path: Vec<ParallelGroupMetadata>,
15267    result: Option<ParallelAvroResult>,
15268}
15269
15270/// Future returned by [`WorkflowContext::parallel`].
15271pub struct ParallelCall {
15272    ctx: WorkflowContext,
15273    operations: Option<Vec<ParallelOperation>>,
15274    shape: Option<ParallelShape>,
15275    leaves: Vec<ParallelLeaf>,
15276    pending_scope_delivery: bool,
15277    worker_session: Option<WorkerSessionOptions>,
15278}
15279
15280impl ParallelCall {
15281    fn new(ctx: WorkflowContext, operations: Vec<ParallelOperation>) -> Self {
15282        Self {
15283            ctx,
15284            operations: Some(operations),
15285            shape: None,
15286            leaves: Vec::new(),
15287            pending_scope_delivery: false,
15288            worker_session: None,
15289        }
15290    }
15291
15292    fn initialize(&mut self) -> Result<()> {
15293        if let Some(session) = &self.worker_session {
15294            session.to_wire()?;
15295        }
15296        let operations = self.operations.take().unwrap_or_default();
15297        validate_parallel_operations(&operations, &mut Vec::new(), true)?;
15298        self.shape = Some(parallel_shape(&operations));
15299        if operations.is_empty() {
15300            return Ok(());
15301        }
15302
15303        let base_sequence = {
15304            let state = self
15305                .ctx
15306                .state
15307                .lock()
15308                .map_err(|_| Error::WorkflowStatePoisoned)?;
15309            if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
15310                recorded.sequence()
15311            } else {
15312                let last = state.max_recorded_sequence();
15313                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
15314                    .and_then(|sequence| sequence.checked_add(1))
15315                    .ok_or_else(|| {
15316                        Error::InvalidParallelGroup(ParallelGroupError {
15317                            reason: "sequence_overflow",
15318                            member_path: Vec::new(),
15319                            message: "parallel group sequence identity overflowed u64".to_string(),
15320                        })
15321                    })?
15322            }
15323        };
15324
15325        let descriptors = parallel_descriptors(operations, base_sequence)?;
15326        {
15327            let mut state = self
15328                .ctx
15329                .state
15330                .lock()
15331                .map_err(|_| Error::WorkflowStatePoisoned)?;
15332            let cursor = state.command_cursor;
15333            self.ctx.validate_scope_membership(&mut state, cursor)?;
15334            if state.prepare_parallel_scope_cancellation(&descriptors)? {
15335                self.pending_scope_delivery = true;
15336                return Ok(());
15337            }
15338            state.expand_cancellation_group(&descriptors)?;
15339            state.prepare_group_cancellation(&descriptors)?;
15340        }
15341        self.leaves = descriptors
15342            .into_iter()
15343            .map(|descriptor| {
15344                let mut call = parallel_leaf_call(
15345                    &self.ctx,
15346                    descriptor.operation,
15347                    descriptor.group_path.clone(),
15348                );
15349                if let (Some(session), ParallelLeafCall::Activity(activity)) =
15350                    (&self.worker_session, &mut call)
15351                {
15352                    activity.worker_session = Some(session.clone());
15353                }
15354                ParallelLeaf {
15355                    call,
15356                    sequence: base_sequence + descriptor.offset as u64,
15357                    member_path: descriptor.member_path,
15358                    group_path: descriptor.group_path,
15359                    result: None,
15360                }
15361            })
15362            .collect();
15363        Ok(())
15364    }
15365
15366    fn poll_avro_value(
15367        mut self: Pin<&mut Self>,
15368        cx: &mut TaskContext<'_>,
15369    ) -> Poll<Result<Vec<ParallelAvroResult>>> {
15370        if self.operations.is_some() {
15371            if let Err(error) = self.initialize() {
15372                return Poll::Ready(Err(error));
15373            }
15374        }
15375        if self.pending_scope_delivery {
15376            return Poll::Pending;
15377        }
15378        if self.leaves.is_empty() {
15379            return Poll::Ready(Ok(Vec::new()));
15380        }
15381
15382        let mut failures = Vec::new();
15383        let mut pending = false;
15384        for (index, leaf) in self.leaves.iter_mut().enumerate() {
15385            if leaf.result.is_some() {
15386                continue;
15387            }
15388            match leaf.call.poll_avro_value(cx) {
15389                Poll::Ready(Ok(result)) => leaf.result = Some(result),
15390                Poll::Ready(Err(error)) => failures.push((index, error)),
15391                Poll::Pending => pending = true,
15392            }
15393        }
15394
15395        if !failures.is_empty() {
15396            if let Some(position) = failures
15397                .iter()
15398                .position(|(_, error)| workflow_task_integrity_error(error))
15399            {
15400                return Poll::Ready(Err(failures.remove(position).1));
15401            }
15402            if self
15403                .ctx
15404                .state
15405                .lock()
15406                .map_err(|_| Error::WorkflowStatePoisoned)?
15407                .cancellation_delivery_intent
15408                .is_some()
15409            {
15410                return Poll::Pending;
15411            }
15412            if let Some(position) = failures
15413                .iter()
15414                .position(|(_, error)| matches!(error, Error::CooperativeCancellationRequested(_)))
15415            {
15416                return Poll::Ready(Err(failures.remove(position).1));
15417            }
15418            failures.sort_by_key(|(index, _)| *index);
15419            let (failed_index, cause) = failures.remove(0);
15420            let failed = &self.leaves[failed_index];
15421            let completed = self
15422                .leaves
15423                .iter()
15424                .filter_map(|leaf| {
15425                    leaf.result
15426                        .clone()
15427                        .and_then(|result| result.into_json_result().ok())
15428                        .map(|result| ParallelCompletion {
15429                            member_path: leaf.member_path.clone(),
15430                            result,
15431                        })
15432                })
15433                .collect();
15434            let group_id = failed
15435                .group_path
15436                .first()
15437                .map(|entry| entry.parallel_group_id.clone())
15438                .unwrap_or_default();
15439            let sequences = self
15440                .leaves
15441                .iter()
15442                .map(|leaf| leaf.sequence)
15443                .collect::<Vec<_>>();
15444            self.ctx
15445                .state
15446                .lock()
15447                .map_err(|_| Error::WorkflowStatePoisoned)?
15448                .consume_replay_group(&sequences, Some(failed.sequence));
15449            return Poll::Ready(Err(Error::ParallelFailed(ParallelFailure {
15450                group_id,
15451                member_path: failed.member_path.clone(),
15452                group_path: failed.group_path.clone(),
15453                completed,
15454                cause: Box::new(cause),
15455            })));
15456        }
15457        if pending
15458            || self
15459                .ctx
15460                .state
15461                .lock()
15462                .map_err(|_| Error::WorkflowStatePoisoned)?
15463                .cancellation_delivery_intent
15464                .is_some()
15465        {
15466            return Poll::Pending;
15467        }
15468
15469        let mut flat_results = self
15470            .leaves
15471            .iter_mut()
15472            .map(|leaf| leaf.result.take().expect("completed parallel leaf"))
15473            .collect::<Vec<_>>()
15474            .into_iter();
15475        let results = parallel_results_for_shape(
15476            self.shape.as_ref().expect("initialized parallel shape"),
15477            &mut flat_results,
15478        );
15479        let sequences = self
15480            .leaves
15481            .iter()
15482            .map(|leaf| leaf.sequence)
15483            .collect::<Vec<_>>();
15484        self.ctx
15485            .state
15486            .lock()
15487            .map_err(|_| Error::WorkflowStatePoisoned)?
15488            .consume_replay_group(&sequences, None);
15489        Poll::Ready(Ok(match results {
15490            ParallelAvroResult::Group(results) => results,
15491            ParallelAvroResult::Activity(_)
15492            | ParallelAvroResult::ChildWorkflow(_)
15493            | ParallelAvroResult::Timer
15494            | ParallelAvroResult::Signal(_)
15495            | ParallelAvroResult::Condition(_) => {
15496                unreachable!("root parallel shape is a group")
15497            }
15498        }))
15499    }
15500}
15501
15502fn parallel_results_for_shape(
15503    shape: &ParallelShape,
15504    flat_results: &mut impl Iterator<Item = ParallelAvroResult>,
15505) -> ParallelAvroResult {
15506    match shape {
15507        ParallelShape::Leaf => flat_results.next().expect("one result per parallel leaf"),
15508        ParallelShape::Group(children) => ParallelAvroResult::Group(
15509            children
15510                .iter()
15511                .map(|child| parallel_results_for_shape(child, flat_results))
15512                .collect(),
15513        ),
15514    }
15515}
15516
15517impl Future for ParallelCall {
15518    type Output = Result<Vec<ParallelResult>>;
15519
15520    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15521        self.poll_avro_value(cx)
15522            .map_ok(|results| {
15523                results
15524                    .into_iter()
15525                    .map(ParallelAvroResult::into_json_result)
15526                    .collect::<Result<Vec<_>>>()
15527            })
15528            .map_ok(|result| result)
15529            .flatten_result()
15530    }
15531}
15532
15533#[derive(Clone, Debug)]
15534struct SelectionMemberPlan {
15535    key: SelectionKey,
15536    index: usize,
15537    base_sequence: u64,
15538    size: usize,
15539    kind: String,
15540    shape: ParallelShape,
15541    leaf_start: usize,
15542}
15543
15544fn selection_operation_kind(operation: &ParallelOperation) -> &'static str {
15545    match operation {
15546        ParallelOperation::Activity { .. } => "activity",
15547        ParallelOperation::ChildWorkflow { .. } => "child",
15548        ParallelOperation::Timer(_) => "timer",
15549        ParallelOperation::Signal(_) => "signal",
15550        ParallelOperation::Condition { .. } => "condition",
15551        ParallelOperation::Group(_) => "group",
15552    }
15553}
15554
15555fn selection_operation_shape(operation: &ParallelOperation) -> ParallelShape {
15556    match operation {
15557        ParallelOperation::Group(children) => parallel_shape(children),
15558        _ => ParallelShape::Leaf,
15559    }
15560}
15561
15562fn selection_descriptors(
15563    operations: Vec<(SelectionKey, ParallelOperation)>,
15564    base_sequence: u64,
15565) -> Result<(Vec<ParallelDescriptor>, Vec<SelectionMemberPlan>)> {
15566    if operations.is_empty() {
15567        return Err(Error::InvalidParallelGroup(ParallelGroupError {
15568            reason: "selection_empty",
15569            member_path: Vec::new(),
15570            message: "durable selection requires at least one operation".to_string(),
15571        }));
15572    }
15573    let operation_refs = operations
15574        .iter()
15575        .map(|(_, operation)| operation)
15576        .collect::<Vec<_>>();
15577    let total_size = operation_refs
15578        .iter()
15579        .map(|operation| match operation {
15580            ParallelOperation::Group(children) => parallel_leaf_count(children),
15581            _ => 1,
15582        })
15583        .sum::<usize>();
15584    if total_size > MAX_PARALLEL_OPERATIONS {
15585        return Err(Error::InvalidParallelGroup(ParallelGroupError {
15586            reason: "fan_out_limit_exceeded",
15587            member_path: Vec::new(),
15588            message: format!(
15589                "selection contains {total_size} durable leaves; the limit is {MAX_PARALLEL_OPERATIONS}"
15590            ),
15591        }));
15592    }
15593    let group_kind = {
15594        let mut kind = None;
15595        for operation in &operation_refs {
15596            let operation_kind = parallel_operation_kind(operation).unwrap_or("mixed");
15597            match kind {
15598                None => kind = Some(operation_kind),
15599                Some(current) if current == operation_kind => {}
15600                Some(_) => {
15601                    kind = Some("mixed");
15602                    break;
15603                }
15604            }
15605        }
15606        kind.unwrap_or("mixed")
15607    };
15608
15609    let mut descriptors = Vec::with_capacity(total_size);
15610    let mut members = Vec::with_capacity(operations.len());
15611    let mut cursor = 0usize;
15612    let mut seen_keys: Vec<SelectionKey> = Vec::new();
15613    for (member_index, (key, operation)) in operations.into_iter().enumerate() {
15614        if matches!(&key, SelectionKey::Name(value) if value.is_empty()) {
15615            return Err(Error::InvalidParallelGroup(ParallelGroupError {
15616                reason: "selection_key_invalid",
15617                member_path: vec![member_index],
15618                message: "selection member keys must be non-empty strings or non-negative integers"
15619                    .to_string(),
15620            }));
15621        }
15622        if seen_keys.contains(&key) {
15623            return Err(Error::InvalidParallelGroup(ParallelGroupError {
15624                reason: "selection_key_duplicate",
15625                member_path: vec![member_index],
15626                message: format!("selection member key {key:?} is duplicated"),
15627            }));
15628        }
15629        seen_keys.push(key.clone());
15630        let member_size = match &operation {
15631            ParallelOperation::Group(children) => parallel_leaf_count(children),
15632            _ => 1,
15633        };
15634        if member_size == 0 {
15635            return Err(Error::InvalidParallelGroup(ParallelGroupError {
15636                reason: "selection_member_empty",
15637                member_path: vec![member_index],
15638                message: "a selection member must contain at least one durable leaf".to_string(),
15639            }));
15640        }
15641        let member_base = base_sequence
15642            .checked_add(u64::try_from(cursor).unwrap_or(u64::MAX))
15643            .ok_or(Error::TimerDurationOverflow)?;
15644        let member_kind = selection_operation_kind(&operation).to_string();
15645        let member_shape = selection_operation_shape(&operation);
15646        let leaf_start = descriptors.len();
15647        match operation {
15648            ParallelOperation::Group(children) => {
15649                validate_parallel_operations(&children, &mut vec![member_index], false)?;
15650                for mut descriptor in parallel_descriptors(children, member_base)? {
15651                    let flat_index = cursor + descriptor.offset;
15652                    descriptor.group_path.insert(
15653                        0,
15654                        selection_group_entry(
15655                            base_sequence,
15656                            total_size,
15657                            flat_index,
15658                            group_kind,
15659                            &SelectionMemberMetadata {
15660                                key: key.clone(),
15661                                index: member_index,
15662                                base_sequence: member_base,
15663                                size: member_size,
15664                                kind: member_kind.clone(),
15665                            },
15666                        ),
15667                    );
15668                    descriptor.member_path.insert(0, member_index);
15669                    descriptor.offset = flat_index;
15670                    descriptors.push(descriptor);
15671                }
15672            }
15673            operation => {
15674                validate_parallel_operations(
15675                    std::slice::from_ref(&operation),
15676                    &mut Vec::new(),
15677                    true,
15678                )?;
15679                descriptors.push(ParallelDescriptor {
15680                    operation,
15681                    offset: cursor,
15682                    member_path: vec![member_index],
15683                    group_path: vec![selection_group_entry(
15684                        base_sequence,
15685                        total_size,
15686                        cursor,
15687                        group_kind,
15688                        &SelectionMemberMetadata {
15689                            key: key.clone(),
15690                            index: member_index,
15691                            base_sequence: member_base,
15692                            size: member_size,
15693                            kind: member_kind.clone(),
15694                        },
15695                    )],
15696                });
15697            }
15698        }
15699        members.push(SelectionMemberPlan {
15700            key,
15701            index: member_index,
15702            base_sequence: member_base,
15703            size: member_size,
15704            kind: member_kind,
15705            shape: member_shape,
15706            leaf_start,
15707        });
15708        cursor += member_size;
15709    }
15710    Ok((descriptors, members))
15711}
15712
15713struct SelectionLeaf {
15714    call: ParallelLeafCall,
15715    outcome: Option<Result<ParallelAvroResult>>,
15716}
15717
15718/// Stable reference to one member of a durable selection group.
15719#[derive(Clone)]
15720pub struct DurableOperationHandle {
15721    ctx: WorkflowContext,
15722    pub key: SelectionKey,
15723    pub index: usize,
15724    pub kind: String,
15725    pub identity: String,
15726    pub base_sequence: u64,
15727    pub size: usize,
15728    pub selection_group_id: String,
15729    shape: ParallelShape,
15730}
15731
15732impl std::fmt::Debug for DurableOperationHandle {
15733    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15734        formatter
15735            .debug_struct("DurableOperationHandle")
15736            .field("key", &self.key)
15737            .field("index", &self.index)
15738            .field("kind", &self.kind)
15739            .field("identity", &self.identity)
15740            .field("base_sequence", &self.base_sequence)
15741            .field("size", &self.size)
15742            .field("selection_group_id", &self.selection_group_id)
15743            .finish()
15744    }
15745}
15746
15747impl DurableOperationHandle {
15748    /// Await this member after another member has already won the selection.
15749    pub fn await_result(&self) -> DurableOperationAwaitCall {
15750        DurableOperationAwaitCall {
15751            handle: self.clone(),
15752        }
15753    }
15754
15755    /// Request cancellation without affecting siblings. The future resolves
15756    /// to unit; only `SelectionOperationCancelled` history proves cancellation
15757    /// beat a concurrently committed terminal result.
15758    pub fn cancel(&self) -> CancelDurableOperationCall {
15759        CancelDurableOperationCall {
15760            handle: self.clone(),
15761            emitted: false,
15762        }
15763    }
15764}
15765
15766/// The one winner committed for a durable selection group.
15767#[derive(Debug)]
15768pub struct SelectionResult {
15769    pub key: SelectionKey,
15770    pub index: usize,
15771    pub kind: String,
15772    pub identity: String,
15773    pub value: Option<ParallelResult>,
15774    pub failure: Option<Error>,
15775    pub winner: DurableOperationHandle,
15776    pub handles: Vec<DurableOperationHandle>,
15777}
15778
15779impl SelectionResult {
15780    pub fn succeeded(&self) -> bool {
15781        self.failure.is_none()
15782    }
15783
15784    pub fn handle(&self, key: &SelectionKey) -> Option<&DurableOperationHandle> {
15785        self.handles.iter().find(|handle| &handle.key == key)
15786    }
15787
15788    pub fn remaining(&self) -> Vec<&DurableOperationHandle> {
15789        self.handles
15790            .iter()
15791            .filter(|handle| handle.index != self.index)
15792            .collect()
15793    }
15794
15795    pub fn into_result(self) -> Result<ParallelResult> {
15796        match (self.value, self.failure) {
15797            (Some(value), None) => Ok(value),
15798            (_, Some(error)) => Err(error),
15799            _ => Err(Error::WorkerLoop(
15800                "selection result contained neither a value nor a failure".to_string(),
15801            )),
15802        }
15803    }
15804}
15805
15806/// Future returned by [`WorkflowContext::select`].
15807pub struct SelectCall {
15808    ctx: WorkflowContext,
15809    operations: Option<Vec<(SelectionKey, ParallelOperation)>>,
15810    members: Vec<SelectionMemberPlan>,
15811    leaves: Vec<SelectionLeaf>,
15812    group_id: Option<String>,
15813}
15814
15815impl SelectCall {
15816    fn new(ctx: WorkflowContext, operations: Vec<(SelectionKey, ParallelOperation)>) -> Self {
15817        Self {
15818            ctx,
15819            operations: Some(operations),
15820            members: Vec::new(),
15821            leaves: Vec::new(),
15822            group_id: None,
15823        }
15824    }
15825
15826    fn initialize(&mut self) -> Result<()> {
15827        let operations = self.operations.take().unwrap_or_default();
15828        let base_sequence = {
15829            let state = self
15830                .ctx
15831                .state
15832                .lock()
15833                .map_err(|_| Error::WorkflowStatePoisoned)?;
15834            if let Some(RecordedCommand::CancellationGroup { sequence, .. }) =
15835                state.recorded_commands.get(state.command_cursor)
15836            {
15837                *sequence
15838            } else if let Some(marker) = state.selection_markers.get(state.selection_marker_cursor)
15839            {
15840                marker.selection_group_base_sequence
15841            } else if let Some(recorded) = state.recorded_commands.get(state.command_cursor) {
15842                recorded.sequence()
15843            } else {
15844                let last = state.max_recorded_sequence();
15845                last.checked_add(u64::try_from(state.commands.len()).unwrap_or(u64::MAX))
15846                    .and_then(|sequence| sequence.checked_add(1))
15847                    .ok_or(Error::TimerDurationOverflow)?
15848            }
15849        };
15850        let (descriptors, members) = selection_descriptors(operations, base_sequence)?;
15851        let group_id = format!("select-calls:{base_sequence}:{}", descriptors.len());
15852        {
15853            let mut state = self
15854                .ctx
15855                .state
15856                .lock()
15857                .map_err(|_| Error::WorkflowStatePoisoned)?;
15858            state.expand_cancellation_group(&descriptors)?;
15859            state.prepare_group_cancellation(&descriptors)?;
15860        }
15861        self.leaves = descriptors
15862            .into_iter()
15863            .map(|descriptor| SelectionLeaf {
15864                call: parallel_leaf_call(&self.ctx, descriptor.operation, descriptor.group_path),
15865                outcome: None,
15866            })
15867            .collect();
15868        self.members = members;
15869        self.group_id = Some(group_id);
15870        Ok(())
15871    }
15872}
15873
15874impl Future for SelectCall {
15875    type Output = Result<SelectionResult>;
15876
15877    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
15878        if self.operations.is_some() {
15879            if let Err(error) = self.initialize() {
15880                return Poll::Ready(Err(error));
15881            }
15882        }
15883
15884        for leaf in &mut self.leaves {
15885            if leaf.outcome.is_some() {
15886                continue;
15887            }
15888            if let Poll::Ready(outcome) = leaf.call.poll_avro_value(cx) {
15889                if outcome
15890                    .as_ref()
15891                    .err()
15892                    .is_some_and(workflow_task_integrity_error)
15893                {
15894                    return Poll::Ready(outcome.map(|_| unreachable!()));
15895                }
15896                leaf.outcome = Some(outcome);
15897            }
15898        }
15899
15900        if self
15901            .ctx
15902            .state
15903            .lock()
15904            .map_err(|_| Error::WorkflowStatePoisoned)?
15905            .cancellation_delivery_intent
15906            .is_some()
15907        {
15908            return Poll::Pending;
15909        }
15910
15911        if let Some(leaf) = self.leaves.iter_mut().find(|leaf| {
15912            matches!(
15913                leaf.outcome,
15914                Some(Err(Error::CooperativeCancellationRequested(_)))
15915            )
15916        }) {
15917            return Poll::Ready(
15918                leaf.outcome
15919                    .take()
15920                    .expect("matched cancellation")
15921                    .map(|_| unreachable!()),
15922            );
15923        }
15924
15925        let all_members_terminal = self.leaves.iter().all(|leaf| leaf.outcome.is_some());
15926        let selection_member_range = self
15927            .members
15928            .first()
15929            .map(|member| member.base_sequence)
15930            .zip(self.leaves.len().try_into().ok())
15931            .map(|(base_sequence, size): (u64, u64)| {
15932                base_sequence..base_sequence.saturating_add(size)
15933            });
15934        let marker = {
15935            let mut state = match self.ctx.state.lock() {
15936                Ok(state) => state,
15937                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
15938            };
15939            let marker = state
15940                .selection_markers
15941                .get(state.selection_marker_cursor)
15942                .cloned();
15943            if marker.is_none()
15944                && all_members_terminal
15945                && selection_member_range.as_ref().is_some_and(|member_range| {
15946                    state
15947                        .recorded_commands
15948                        .iter()
15949                        .any(|command| member_range.contains(&command.sequence()))
15950                })
15951            {
15952                // Terminal member history can be committed before the server's
15953                // SelectionResolved marker becomes visible to this task. That
15954                // marker is the durable barrier the selection is still waiting
15955                // on, so an otherwise commandless replay remains legitimately
15956                // pending instead of failing as an untracked yield.
15957                state.matched_recorded_pending = true;
15958                state.observation_pending = true;
15959            }
15960            marker
15961        };
15962        let Some(marker) = marker else {
15963            return Poll::Pending;
15964        };
15965        if self.group_id.as_deref() != Some(marker.selection_group_id.as_str())
15966            || marker.selection_group_size != self.leaves.len()
15967            || self.members.first().map(|member| member.base_sequence)
15968                != Some(marker.selection_group_base_sequence)
15969        {
15970            return Poll::Ready(Err(invalid_recorded_history(
15971                "selection_group_shape_mismatch",
15972                marker.selection_group_base_sequence,
15973                self.group_id
15974                    .as_deref()
15975                    .unwrap_or("initialized selection group"),
15976                &marker.selection_group_id,
15977                "recorded selection group differs from current workflow code",
15978            )));
15979        }
15980        let Some(member_position) = self.members.iter().position(|member| {
15981            member.key == marker.member_key
15982                && member.index == marker.member_index
15983                && member.base_sequence == marker.member_base_sequence
15984                && member.size == marker.member_size
15985                && member.kind == marker.operation_kind
15986        }) else {
15987            return Poll::Ready(Err(invalid_recorded_history(
15988                "selection_member_shape_mismatch",
15989                marker.member_base_sequence,
15990                "winner member matching current workflow code",
15991                &format!("{:?}", marker.member_key),
15992                "recorded selection winner differs from the authored member identity",
15993            )));
15994        };
15995        let member = self.members[member_position].clone();
15996        let (handles, resolution_sequence) = {
15997            let mut state = match self.ctx.state.lock() {
15998                Ok(state) => state,
15999                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16000            };
16001            let identities = self
16002                .members
16003                .iter()
16004                .map(|candidate| {
16005                    selection_operation_identity(
16006                        &state,
16007                        &candidate.kind,
16008                        candidate.base_sequence,
16009                        candidate.size,
16010                    )
16011                })
16012                .collect::<Vec<_>>();
16013            if let Some((position, missing)) = identities
16014                .iter()
16015                .enumerate()
16016                .find(|(_, identity)| identity.is_empty())
16017                .map(|(position, identity)| (position, identity.clone()))
16018            {
16019                let candidate = &self.members[position];
16020                return Poll::Ready(Err(invalid_recorded_history(
16021                    "selection_operation_identity_missing",
16022                    candidate.base_sequence,
16023                    &format!(
16024                        "durable {} resource identity from scheduled/open history",
16025                        candidate.kind
16026                    ),
16027                    &missing,
16028                    "selection member history is missing its canonical durable identity",
16029                )));
16030            }
16031            let expected_winner_identity = &identities[member_position];
16032            let resolution_sequence = match validated_selection_resolution_sequence(
16033                &state,
16034                &marker,
16035                &member,
16036                expected_winner_identity,
16037            ) {
16038                Ok(sequence) => sequence,
16039                Err(error) => return Poll::Ready(Err(error)),
16040            };
16041            let handles = self
16042                .members
16043                .iter()
16044                .zip(identities)
16045                .map(|(member, identity)| DurableOperationHandle {
16046                    ctx: self.ctx.clone(),
16047                    key: member.key.clone(),
16048                    index: member.index,
16049                    kind: member.kind.clone(),
16050                    identity,
16051                    base_sequence: member.base_sequence,
16052                    size: member.size,
16053                    selection_group_id: marker.selection_group_id.clone(),
16054                    shape: member.shape.clone(),
16055                })
16056                .collect::<Vec<_>>();
16057            if let Err(error) = validate_selection_cancellations_for_handles(&state, &handles) {
16058                return Poll::Ready(Err(error));
16059            }
16060            state.selection_marker_cursor += 1;
16061            (handles, resolution_sequence)
16062        };
16063
16064        let mut winner_failure = None;
16065        let mut flat_results = Vec::with_capacity(member.size);
16066        if marker.outcome == "failed" {
16067            let resolution_offset = match resolution_sequence
16068                .checked_sub(member.base_sequence)
16069                .and_then(|offset| usize::try_from(offset).ok())
16070            {
16071                Some(offset) if offset < member.size => offset,
16072                _ => {
16073                    return Poll::Ready(Err(invalid_recorded_history(
16074                        "selection_resolution_event_mismatch",
16075                        member.base_sequence,
16076                        "failure event within selected member bounds",
16077                        &resolution_sequence.to_string(),
16078                        "selection failure event is outside the authored member",
16079                    )))
16080                }
16081            };
16082            let leaf = &mut self.leaves[member.leaf_start + resolution_offset];
16083            match leaf.outcome.take() {
16084                Some(Err(error)) => winner_failure = Some(error),
16085                _ => {
16086                    return Poll::Ready(Err(invalid_recorded_history(
16087                        "selection_winner_outcome_mismatch",
16088                        member.base_sequence,
16089                        "exact failed terminal history referenced by SelectionResolved",
16090                        "missing or successful resolution event",
16091                        "selection winner marker disagrees with terminal operation history",
16092                    )))
16093                }
16094            }
16095        } else {
16096            for leaf in &mut self.leaves[member.leaf_start..member.leaf_start + member.size] {
16097                match leaf.outcome.take() {
16098                    Some(Ok(result)) => flat_results.push(result),
16099                    Some(Err(_)) => {
16100                        return Poll::Ready(Err(invalid_recorded_history(
16101                            "selection_winner_outcome_mismatch",
16102                            member.base_sequence,
16103                            "fully completed nested selection member",
16104                            "failed durable leaf",
16105                            "completed selection winner contains a failed leaf",
16106                        )))
16107                    }
16108                    None => {
16109                        return Poll::Ready(Err(invalid_recorded_history(
16110                            "selection_winner_unresolved",
16111                            member.base_sequence,
16112                            "terminal history for every completed winner leaf",
16113                            "pending member history",
16114                            "completed SelectionResolved member has an unfinished durable barrier",
16115                        )))
16116                    }
16117                }
16118            }
16119        }
16120        let value = if winner_failure.is_none() {
16121            let mut flat_results = flat_results.into_iter();
16122            let value = parallel_results_for_shape(&member.shape, &mut flat_results);
16123            match value.into_json_result() {
16124                Ok(value) => Some(value),
16125                Err(error) => return Poll::Ready(Err(error)),
16126            }
16127        } else {
16128            None
16129        };
16130        let winner = handles[member_position].clone();
16131        self.ctx
16132            .state
16133            .lock()
16134            .map_err(|_| Error::WorkflowStatePoisoned)?
16135            .consume_replay_selection(&marker.selection_group_id);
16136        Poll::Ready(Ok(SelectionResult {
16137            key: winner.key.clone(),
16138            index: winner.index,
16139            kind: winner.kind.clone(),
16140            identity: winner.identity.clone(),
16141            value,
16142            failure: winner_failure,
16143            winner,
16144            handles,
16145        }))
16146    }
16147}
16148
16149fn selection_operation_identity(
16150    state: &WorkflowState,
16151    kind: &str,
16152    base_sequence: u64,
16153    size: usize,
16154) -> String {
16155    if kind == "group" {
16156        return format!("group:{base_sequence}:{size}");
16157    }
16158    let fields: &[&str] = match kind {
16159        "activity" => &["activity_execution_id"],
16160        "child" => &["child_workflow_run_id"],
16161        "timer" => &["timer_id"],
16162        "signal" => &["signal_wait_id"],
16163        "condition" => &["condition_wait_id"],
16164        _ => &[],
16165    };
16166    for sequence in base_sequence..base_sequence.saturating_add(size as u64) {
16167        for event in state
16168            .history_events
16169            .iter()
16170            .filter(|event| durable_event_sequence(event) == Some(sequence))
16171        {
16172            for field in fields {
16173                if let Some(identity) = event.payload.get(*field).and_then(Value::as_str) {
16174                    if !identity.is_empty() {
16175                        return identity.to_string();
16176                    }
16177                }
16178            }
16179        }
16180    }
16181    String::new()
16182}
16183
16184fn validated_selection_resolution_sequence(
16185    state: &WorkflowState,
16186    marker: &SelectionMarker,
16187    member: &SelectionMemberPlan,
16188    expected_identity: &str,
16189) -> Result<u64> {
16190    if expected_identity.is_empty() {
16191        return Err(invalid_recorded_history(
16192            "selection_operation_identity_missing",
16193            member.base_sequence,
16194            &format!(
16195                "durable {} resource identity from scheduled/open history",
16196                member.kind
16197            ),
16198            "missing operation identity",
16199            "selection member history is missing its canonical durable identity",
16200        ));
16201    }
16202    if marker.operation_identity != expected_identity {
16203        return Err(invalid_recorded_history(
16204            "selection_operation_identity_mismatch",
16205            member.base_sequence,
16206            expected_identity,
16207            &marker.operation_identity,
16208            "selection winner identity does not match durable scheduled/open history",
16209        ));
16210    }
16211
16212    let failure_types = [
16213        "ActivityFailed",
16214        "ActivityCancelled",
16215        "ActivityTimedOut",
16216        "ChildRunFailed",
16217        "ChildRunCancelled",
16218        "ChildRunTerminated",
16219    ];
16220    let success_types = [
16221        "ActivityCompleted",
16222        "ChildRunCompleted",
16223        "TimerFired",
16224        "SignalApplied",
16225        "ConditionWaitSatisfied",
16226        "ConditionWaitTimedOut",
16227    ];
16228    let terminal_types: &[&str] = if marker.outcome == "failed" {
16229        &failure_types
16230    } else {
16231        &success_types
16232    };
16233    let mut candidates = Vec::new();
16234    let member_commands = (member.base_sequence
16235        ..member.base_sequence.saturating_add(member.size as u64))
16236        .filter_map(|sequence| selection_member_recorded_command(state, sequence))
16237        .map(|command| (command.sequence(), command))
16238        .collect::<BTreeMap<_, _>>();
16239    let mut resolved_conditions = BTreeSet::new();
16240    for event in state.history_events.iter() {
16241        let Some(sequence) = durable_event_sequence(event) else {
16242            continue;
16243        };
16244        let Some(command) = member_commands.get(&sequence) else {
16245            continue;
16246        };
16247        if !terminal_types.contains(&event.event_type.as_str()) {
16248            continue;
16249        }
16250        if matches!(command, RecordedCommand::ConditionWait { .. }) {
16251            if !(matches!(
16252                event.event_type.as_str(),
16253                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
16254            ) || (event.event_type == "TimerFired"
16255                && event.payload.get("timer_kind").and_then(Value::as_str)
16256                    == Some("condition_timeout")))
16257            {
16258                continue;
16259            }
16260            if !resolved_conditions.insert(sequence) {
16261                continue;
16262            }
16263        }
16264        let event_id = event
16265            .raw
16266            .get("id")
16267            .or_else(|| event.raw.get("event_id"))
16268            .and_then(Value::as_str)
16269            .filter(|value| !value.is_empty())
16270            .ok_or_else(|| {
16271                invalid_recorded_history(
16272                    "selection_resolution_event_id_missing",
16273                    member.base_sequence,
16274                    "terminal selection history with a durable event id",
16275                    &event.payload.to_string(),
16276                    "selection terminal history cannot be bound to its winner marker",
16277                )
16278            })?;
16279        candidates.push((event_id.to_string(), event.event_type.clone(), sequence));
16280    }
16281    let resolution = if marker.outcome == "failed" {
16282        candidates.first()
16283    } else {
16284        candidates.last()
16285    };
16286    let Some((event_id, event_type, sequence)) = resolution else {
16287        return Err(invalid_recorded_history(
16288            "selection_resolution_event_missing",
16289            member.base_sequence,
16290            "terminal history for the selected member",
16291            &format!("{:?}", marker.member_key),
16292            "selection winner marker has no matching durable terminal event",
16293        ));
16294    };
16295    if event_id != &marker.resolution_event_id || event_type != &marker.resolution_event_type {
16296        return Err(invalid_recorded_history(
16297            "selection_resolution_event_mismatch",
16298            member.base_sequence,
16299            &format!("{event_type}:{event_id}"),
16300            &format!(
16301                "{}:{}",
16302                marker.resolution_event_type, marker.resolution_event_id
16303            ),
16304            "selection winner marker does not reference the event that made its member terminal",
16305        ));
16306    }
16307    Ok(*sequence)
16308}
16309
16310fn selection_member_recorded_command(
16311    state: &WorkflowState,
16312    authored_sequence: u64,
16313) -> Option<&RecordedCommand> {
16314    let original = state
16315        .recorded_commands
16316        .iter()
16317        .find(|command| command.sequence() == authored_sequence)?;
16318    let RecordedCommand::ConditionWait {
16319        occurrence_id,
16320        parallel_group_path: Some(_),
16321        ..
16322    } = original
16323    else {
16324        return Some(original);
16325    };
16326    // Decoding proves each physical reopen has the same authored identity and
16327    // group path after a satisfied predecessor. Only its latest wait can make
16328    // this logical member terminal.
16329    state
16330        .recorded_commands
16331        .iter()
16332        .filter(|command| {
16333            matches!(command, RecordedCommand::ConditionWait {
16334                occurrence_id: candidate, ..
16335            } if candidate == occurrence_id)
16336        })
16337        .max_by_key(|command| command.sequence())
16338}
16339
16340fn recorded_selection_member_outcome(
16341    state: &WorkflowState,
16342    handle: &DurableOperationHandle,
16343) -> Result<Option<ParallelResult>> {
16344    for event in state.history_events.iter() {
16345        let Some(sequence) = durable_event_sequence(event) else {
16346            continue;
16347        };
16348        if sequence < handle.base_sequence
16349            || sequence >= handle.base_sequence.saturating_add(handle.size as u64)
16350            || !matches!(
16351                event.event_type.as_str(),
16352                "ActivityFailed"
16353                    | "ActivityCancelled"
16354                    | "ActivityTimedOut"
16355                    | "ChildRunFailed"
16356                    | "ChildRunCancelled"
16357                    | "ChildRunTerminated"
16358            )
16359        {
16360            continue;
16361        }
16362        let Some(command) = state
16363            .recorded_commands
16364            .iter()
16365            .find(|command| command.sequence() == sequence)
16366        else {
16367            continue;
16368        };
16369        match command {
16370            RecordedCommand::Activity {
16371                outcome: Some(Err(failure)),
16372                ..
16373            } => return Err(Error::ActivityFailed(failure.clone())),
16374            RecordedCommand::ChildWorkflow {
16375                outcome: Some(Err(failure)),
16376                ..
16377            } => return Err(Error::ChildWorkflowFailed(failure.clone())),
16378            _ => {}
16379        }
16380    }
16381
16382    let mut results = Vec::with_capacity(handle.size);
16383    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
16384        let Some(command) = selection_member_recorded_command(state, sequence) else {
16385            return Ok(None);
16386        };
16387        let result = match command {
16388            RecordedCommand::Activity { outcome, .. } => match outcome {
16389                Some(Ok(value)) => ParallelAvroResult::Activity(value.clone()),
16390                Some(Err(failure)) => return Err(Error::ActivityFailed(failure.clone())),
16391                None => return Ok(None),
16392            },
16393            RecordedCommand::Timer { fired, .. } => {
16394                if !fired {
16395                    return Ok(None);
16396                }
16397                ParallelAvroResult::Timer
16398            }
16399            RecordedCommand::ChildWorkflow { outcome, .. } => match outcome {
16400                Some(Ok(value)) => ParallelAvroResult::ChildWorkflow(value.clone()),
16401                Some(Err(failure)) => return Err(Error::ChildWorkflowFailed(failure.clone())),
16402                None => return Ok(None),
16403            },
16404            RecordedCommand::SignalWait { value, .. } => match value {
16405                Some(value) => ParallelAvroResult::Signal(value.clone()),
16406                None => return Ok(None),
16407            },
16408            RecordedCommand::ConditionWait { result, .. } => match result {
16409                Some(result) => ParallelAvroResult::Condition(*result),
16410                None => return Ok(None),
16411            },
16412            other => {
16413                return Err(command_mismatch(
16414                    other,
16415                    format!("selected {} member", handle.kind),
16416                ))
16417            }
16418        };
16419        results.push(result);
16420    }
16421    let mut results = results.into_iter();
16422    parallel_results_for_shape(&handle.shape, &mut results)
16423        .into_json_result()
16424        .map(Some)
16425}
16426
16427fn recorded_selection_member_is_terminal(
16428    state: &WorkflowState,
16429    handle: &DurableOperationHandle,
16430) -> bool {
16431    let mut completed = 0usize;
16432    let mut all_completed = true;
16433    for sequence in handle.base_sequence..handle.base_sequence.saturating_add(handle.size as u64) {
16434        let Some(command) = selection_member_recorded_command(state, sequence) else {
16435            all_completed = false;
16436            continue;
16437        };
16438        let terminal = match command {
16439            RecordedCommand::Activity {
16440                outcome: Some(Err(_)),
16441                ..
16442            }
16443            | RecordedCommand::ChildWorkflow {
16444                outcome: Some(Err(_)),
16445                ..
16446            } => return true,
16447            RecordedCommand::Activity { outcome, .. } => outcome.is_some(),
16448            RecordedCommand::ChildWorkflow { outcome, .. } => outcome.is_some(),
16449            RecordedCommand::Timer { fired, .. } => *fired,
16450            RecordedCommand::SignalWait { value, .. } => value.is_some(),
16451            RecordedCommand::ConditionWait { result, .. } => result.is_some(),
16452            RecordedCommand::SearchAttributes { .. }
16453            | RecordedCommand::CancellationScope { .. }
16454            | RecordedCommand::SideEffect { .. }
16455            | RecordedCommand::VersionMarker { .. }
16456            | RecordedCommand::Memo { .. }
16457            | RecordedCommand::CancellationBoundary { .. }
16458            | RecordedCommand::CancellationGroup { .. } => false,
16459            RecordedCommand::ServiceOperation { .. } | RecordedCommand::ExternalSignal { .. } => {
16460                false
16461            }
16462        };
16463        if !terminal {
16464            all_completed = false;
16465            continue;
16466        }
16467        completed += 1;
16468    }
16469    all_completed && completed == handle.size
16470}
16471
16472fn selection_cancellation_for_handle(
16473    state: &WorkflowState,
16474    handle: &DurableOperationHandle,
16475) -> Result<bool> {
16476    let Some(marker) = state.cancelled_selection_members.iter().find(|recorded| {
16477        recorded.selection_group_id == handle.selection_group_id
16478            && recorded.member_base_sequence == handle.base_sequence
16479    }) else {
16480        return Ok(false);
16481    };
16482    validate_selection_cancellation_marker(marker, handle)?;
16483    Ok(true)
16484}
16485
16486fn validate_selection_cancellations_for_handles(
16487    state: &WorkflowState,
16488    handles: &[DurableOperationHandle],
16489) -> Result<()> {
16490    let Some(group_id) = handles
16491        .first()
16492        .map(|handle| handle.selection_group_id.as_str())
16493    else {
16494        return Ok(());
16495    };
16496    for marker in state
16497        .cancelled_selection_members
16498        .iter()
16499        .filter(|marker| marker.selection_group_id == group_id)
16500    {
16501        let Some(handle) = handles
16502            .iter()
16503            .find(|handle| handle.base_sequence == marker.member_base_sequence)
16504        else {
16505            return Err(invalid_recorded_history(
16506                "selection_cancellation_member_mismatch",
16507                marker.member_base_sequence,
16508                "SelectionOperationCancelled matching an authored selection handle",
16509                &format!("{marker:?}"),
16510                "selection cancellation member base does not name an authored member",
16511            ));
16512        };
16513        validate_selection_cancellation_marker(marker, handle)?;
16514    }
16515    Ok(())
16516}
16517
16518fn validate_selection_cancellation_marker(
16519    marker: &SelectionCancellation,
16520    handle: &DurableOperationHandle,
16521) -> Result<()> {
16522    if marker.selection_group_id != handle.selection_group_id
16523        || marker.member_key != handle.key
16524        || marker.member_index != handle.index
16525        || marker.member_base_sequence != handle.base_sequence
16526        || marker.member_size != handle.size
16527        || marker.operation_kind != handle.kind
16528        || marker.operation_identity != handle.identity
16529    {
16530        return Err(invalid_recorded_history(
16531            "selection_cancellation_member_mismatch",
16532            handle.base_sequence,
16533            "SelectionOperationCancelled matching the authored selection handle",
16534            &format!("{marker:?}"),
16535            "selection cancellation history targets different authored member metadata",
16536        ));
16537    }
16538    Ok(())
16539}
16540
16541/// Future returned by [`DurableOperationHandle::await_result`].
16542pub struct DurableOperationAwaitCall {
16543    handle: DurableOperationHandle,
16544}
16545
16546impl Future for DurableOperationAwaitCall {
16547    type Output = Result<ParallelResult>;
16548
16549    fn poll(self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
16550        let mut state = match self.handle.ctx.state.lock() {
16551            Ok(state) => state,
16552            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16553        };
16554        if let Err(error) = state.replay_selection_handle_cancellation(&self.handle) {
16555            return Poll::Ready(Err(error));
16556        }
16557        match state.prepare_selection_handle_cancellation(&self.handle) {
16558            Ok(true) => return Poll::Pending,
16559            Ok(false) => {}
16560            Err(error) => return Poll::Ready(Err(error)),
16561        }
16562        match selection_cancellation_for_handle(&state, &self.handle) {
16563            Err(error) => return Poll::Ready(Err(error)),
16564            Ok(false) => {}
16565            Ok(true) => {
16566                state.consume_replay_receipt(
16567                    &self.handle.selection_group_id,
16568                    self.handle.base_sequence,
16569                );
16570                return Poll::Ready(Err(Error::DurableOperationCancelled(
16571                    DurableOperationCancelled {
16572                        selection_group_id: self.handle.selection_group_id.clone(),
16573                        member_key: self.handle.key.clone(),
16574                        member_index: self.handle.index,
16575                        operation_kind: self.handle.kind.clone(),
16576                        operation_identity: self.handle.identity.clone(),
16577                    },
16578                )));
16579            }
16580        }
16581        match recorded_selection_member_outcome(&state, &self.handle) {
16582            Ok(Some(result)) => {
16583                state.consume_replay_handle(&self.handle, false);
16584                Poll::Ready(Ok(result))
16585            }
16586            Ok(None) => Poll::Pending,
16587            Err(error) => {
16588                if !workflow_task_integrity_error(&error) {
16589                    state.consume_replay_handle(&self.handle, true);
16590                }
16591                Poll::Ready(Err(error))
16592            }
16593        }
16594    }
16595}
16596
16597fn validate_selection_delivery_handle(
16598    state: &WorkflowState,
16599    handle: &DurableOperationHandle,
16600) -> Result<()> {
16601    let path = state
16602        .recorded_commands
16603        .iter()
16604        .find(|command| command.sequence() == handle.base_sequence)
16605        .and_then(|command| match command {
16606            RecordedCommand::Activity {
16607                parallel_group_path,
16608                ..
16609            }
16610            | RecordedCommand::ChildWorkflow {
16611                parallel_group_path,
16612                ..
16613            }
16614            | RecordedCommand::Timer {
16615                parallel_group_path,
16616                ..
16617            }
16618            | RecordedCommand::SignalWait {
16619                parallel_group_path,
16620                ..
16621            }
16622            | RecordedCommand::ConditionWait {
16623                parallel_group_path,
16624                ..
16625            } => parallel_group_path.as_ref(),
16626            _ => None,
16627        })
16628        .and_then(|path| path.first());
16629    let matches = path.is_some_and(|entry| {
16630        entry.parallel_group_mode.as_deref() == Some("select")
16631            && entry.parallel_group_id == handle.selection_group_id
16632            && entry.selection_member_key.as_ref() == Some(&handle.key)
16633            && entry.selection_member_index == Some(handle.index)
16634            && entry.selection_member_base_sequence == Some(handle.base_sequence)
16635            && entry.selection_member_size == Some(handle.size)
16636            && entry.selection_member_kind.as_deref() == Some(handle.kind.as_str())
16637    });
16638    if !matches
16639        || selection_operation_identity(state, &handle.kind, handle.base_sequence, handle.size)
16640            != handle.identity
16641    {
16642        return Err(invalid_recorded_history(
16643            "cooperative_cancellation_call_mismatch",
16644            handle.base_sequence,
16645            "selection handle matching its authored durable identity",
16646            &format!("{handle:?}"),
16647            "selection handle identity or member metadata changed before cancellation replay",
16648        ));
16649    }
16650    Ok(())
16651}
16652
16653/// Future returned by [`DurableOperationHandle::cancel`].
16654pub struct CancelDurableOperationCall {
16655    handle: DurableOperationHandle,
16656    emitted: bool,
16657}
16658
16659impl Future for CancelDurableOperationCall {
16660    type Output = Result<()>;
16661
16662    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
16663        let ctx = self.handle.ctx.clone();
16664        let mut state = match ctx.state.lock() {
16665            Ok(state) => state,
16666            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16667        };
16668        match selection_cancellation_for_handle(&state, &self.handle) {
16669            Err(error) => return Poll::Ready(Err(error)),
16670            Ok(true) => {
16671                state.consume_replay_receipt(
16672                    &self.handle.selection_group_id,
16673                    self.handle.base_sequence,
16674                );
16675                return Poll::Ready(Ok(()));
16676            }
16677            Ok(false) => {}
16678        }
16679        if recorded_selection_member_is_terminal(&state, &self.handle) {
16680            return Poll::Ready(Ok(()));
16681        }
16682        if !self.emitted {
16683            state.commands.push(json!({
16684                "type": "cancel_selection_operation",
16685                "selection_group_id": self.handle.selection_group_id,
16686                "member_key": self.handle.key,
16687                "member_index": self.handle.index,
16688                "member_base_sequence": self.handle.base_sequence,
16689                "member_size": self.handle.size,
16690                "operation_kind": self.handle.kind,
16691                "operation_identity": self.handle.identity,
16692            }));
16693            self.emitted = true;
16694        }
16695        // Unit completes the request, not the member's outcome. Following
16696        // workflow commands commit atomically with this cancellation request.
16697        // Waiting here would need another workflow task that cancellation
16698        // alone does not create. await_result still requires recorded history.
16699        Poll::Ready(Ok(()))
16700    }
16701}
16702
16703trait PollNestedResultExt<T> {
16704    fn flatten_result(self) -> Poll<Result<T>>;
16705}
16706
16707impl<T> PollNestedResultExt<T> for Poll<Result<Result<T>>> {
16708    fn flatten_result(self) -> Poll<Result<T>> {
16709        match self {
16710            Poll::Ready(Ok(result)) => Poll::Ready(result),
16711            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
16712            Poll::Pending => Poll::Pending,
16713        }
16714    }
16715}
16716
16717struct SagaCompensation {
16718    activity_type: String,
16719    options: ActivityOptions,
16720    arguments: AvroValue,
16721    registration_order: usize,
16722}
16723
16724/// Workflow-local deterministic saga compensation helper.
16725///
16726/// Register each compensation only after its forward step succeeds. Passing
16727/// the forward `Result` to [`Saga::finish`] runs compensations sequentially in
16728/// reverse registration order after any failure, including cooperative
16729/// cancellation. Each compensation is an ordinary durable activity, so replay,
16730/// duplicate delivery, and worker restart use existing history semantics.
16731pub struct Saga {
16732    ctx: WorkflowContext,
16733    compensations: Vec<SagaCompensation>,
16734}
16735
16736impl Saga {
16737    fn new(ctx: WorkflowContext) -> Self {
16738        Self {
16739            ctx,
16740            compensations: Vec::new(),
16741        }
16742    }
16743
16744    pub fn add_compensation<T: Serialize>(
16745        &mut self,
16746        activity_type: impl Into<String>,
16747        args: T,
16748    ) -> Result<&mut Self> {
16749        self.add_compensation_with_options(activity_type, ActivityOptions::new(), args)
16750    }
16751
16752    pub fn add_compensation_with_options<T: Serialize>(
16753        &mut self,
16754        activity_type: impl Into<String>,
16755        options: ActivityOptions,
16756        args: T,
16757    ) -> Result<&mut Self> {
16758        let activity_type = activity_type.into();
16759        if activity_type.trim().is_empty() || activity_type.trim() != activity_type {
16760            return Err(Error::Codec(
16761                "saga compensation activity type must be non-empty without surrounding whitespace"
16762                    .to_string(),
16763            ));
16764        }
16765        options.validate().map_err(Error::InvalidActivityOptions)?;
16766        let arguments = AvroValue::from_serialize(&args)?;
16767        let registration_order = self.compensations.len() + 1;
16768        self.compensations.push(SagaCompensation {
16769            activity_type,
16770            options,
16771            arguments,
16772            registration_order,
16773        });
16774        Ok(self)
16775    }
16776
16777    /// Compensate `initiating_failure` and return the failure that must remain.
16778    pub async fn compensate(mut self, initiating_failure: Error) -> Error {
16779        let _shield = match self.ctx.cancellation_shield() {
16780            Ok(shield) => shield,
16781            Err(error) => return error,
16782        };
16783        while let Some(compensation) = self.compensations.pop() {
16784            if let Err(compensation_failure) = self
16785                .ctx
16786                .activity_with_options_at(
16787                    compensation.activity_type.clone(),
16788                    compensation.options,
16789                    compensation.arguments,
16790                    None,
16791                )
16792                .await
16793            {
16794                if workflow_task_integrity_error(&compensation_failure) {
16795                    return compensation_failure;
16796                }
16797                return Error::SagaCompensationFailed(SagaCompensationFailure {
16798                    initiating_failure: Box::new(initiating_failure),
16799                    compensation_failure: Box::new(compensation_failure),
16800                    compensation_activity_type: compensation.activity_type,
16801                    compensation_registration_order: compensation.registration_order,
16802                });
16803            }
16804        }
16805        initiating_failure
16806    }
16807
16808    /// Return a successful forward value or compensate and preserve its failure.
16809    pub async fn finish<T>(self, outcome: Result<T>) -> Result<T> {
16810        match outcome {
16811            Ok(value) => Ok(value),
16812            Err(error) => Err(self.compensate(error).await),
16813        }
16814    }
16815}
16816
16817pub struct ActivityCall {
16818    source: Option<&'static Location<'static>>,
16819    ctx: WorkflowContext,
16820    activity_type: String,
16821    options: ActivityOptions,
16822    worker_session: Option<WorkerSessionOptions>,
16823    args: Option<Result<AvroValue>>,
16824    scheduled: bool,
16825    local: bool,
16826    local_result: Option<Arc<Mutex<Option<ActivityOutcome>>>>,
16827    parallel_group_path: Vec<ParallelGroupMetadata>,
16828}
16829
16830impl ActivityCall {
16831    fn poll_avro_value(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Result<AvroValue>> {
16832        let source = self.source;
16833        self.poll_history(cx)
16834            .map(|result| result.map_err(|error| replay_error_at(error, source)))
16835    }
16836
16837    fn poll_history(
16838        mut self: Pin<&mut Self>,
16839        _cx: &mut TaskContext<'_>,
16840    ) -> Poll<Result<AvroValue>> {
16841        let ctx = self.ctx.clone();
16842        let mut state = match ctx.state.lock() {
16843            Ok(state) => state,
16844            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16845        };
16846
16847        if let Some(result) = &self.local_result {
16848            return match result.lock() {
16849                Ok(mut result) => result.take().map_or(Poll::Pending, |result| {
16850                    state.replay_clock.unavailable();
16851                    Poll::Ready(result.map_err(Error::ActivityFailed))
16852                }),
16853                Err(_) => Poll::Ready(Err(Error::WorkflowStatePoisoned)),
16854            };
16855        }
16856        if self.scheduled {
16857            return Poll::Pending;
16858        }
16859
16860        let options = match self.options.validate() {
16861            Ok(options) => options,
16862            Err(error) => {
16863                return Poll::Ready(Err(Error::InvalidActivityOptions(error)));
16864            }
16865        };
16866        if self.local {
16867            if self.worker_session.is_some() {
16868                return Poll::Ready(Err(Error::WorkerLoop(
16869                    "local activities cannot use worker-session routing".into(),
16870                )));
16871            }
16872            if let Err(error) = local_activity::validate(&options) {
16873                return Poll::Ready(Err(error));
16874            }
16875        }
16876        let session = match self
16877            .worker_session
16878            .as_ref()
16879            .map(WorkerSessionOptions::to_wire)
16880            .transpose()
16881        {
16882            Ok(value) => value,
16883            Err(error) => return Poll::Ready(Err(error)),
16884        };
16885        let session_queue = session
16886            .as_ref()
16887            .and_then(|session| session["queue"].as_str());
16888        let task_queue = options
16889            .task_queue
16890            .clone()
16891            .or_else(|| session_queue.map(str::to_owned))
16892            .unwrap_or_else(|| state.task_queue.clone());
16893        if session_queue.is_some_and(|queue| queue != task_queue) {
16894            return Poll::Ready(Err(Error::WorkerLoop(
16895                "worker-session queue must match the activity task queue".into(),
16896            )));
16897        }
16898        let current_recorded_options = RecordedActivityOptions {
16899            task_queue: RecordedSnapshotValue::Known(Some(task_queue.clone())),
16900            execution_mode: RecordedSnapshotValue::Known(self.local.then(|| "local".to_string())),
16901            retry_policy: current_activity_retry_snapshot(&options),
16902            worker_session: session,
16903        };
16904
16905        let cursor = state.command_cursor;
16906        let call_kind = if self.local {
16907            CancellationCallKind::LocalActivity
16908        } else {
16909            CancellationCallKind::Activity
16910        };
16911        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
16912            return Poll::Ready(Err(error));
16913        }
16914        let recorded = match state.cancellation_replay_command(cursor, call_kind) {
16915            Ok(recorded) => recorded,
16916            Err(error) => return Poll::Ready(Err(error)),
16917        };
16918        if let Some(recorded) = recorded {
16919            let sequence = recorded.sequence();
16920            match recorded {
16921                RecordedCommand::Activity {
16922                    activity_type,
16923                    cancellation_policy,
16924                    options: recorded_options,
16925                    outcome,
16926                    parallel_group_path,
16927                    ..
16928                } => {
16929                    let current_policy = options
16930                        .cancellation_policy
16931                        .unwrap_or(CancellationPolicy::TryCancel)
16932                        .as_str();
16933                    if cancellation_policy != current_policy {
16934                        return Poll::Ready(Err(Error::NonDeterministicReplay(
16935                            ReplayFailure::new(
16936                                "activity_cancellation_policy_changed",
16937                                Some(sequence),
16938                                Some(cancellation_policy),
16939                                Some(current_policy.to_string()),
16940                                "Activity cancellation policy changed during replay",
16941                            ),
16942                        )));
16943                    }
16944                    if let Err(error) = ensure_parallel_path_matches(
16945                        sequence,
16946                        parallel_group_path.as_deref(),
16947                        &self.parallel_group_path,
16948                    ) {
16949                        return Poll::Ready(Err(error));
16950                    }
16951                    if let Some(recorded_type) = activity_type {
16952                        if recorded_type != self.activity_type {
16953                            return Poll::Ready(Err(Error::NonDeterministicReplay(
16954                                ReplayFailure::new(
16955                                    "recorded_command_detail_mismatch",
16956                                    Some(sequence),
16957                                    Some(format!("activity:{recorded_type}")),
16958                                    Some(format!("activity:{}", self.activity_type)),
16959                                    "recorded activity type differs from the current workflow command",
16960                                ),
16961                            )));
16962                        }
16963                    }
16964                    if let Some(recorded_options) = recorded_options {
16965                        if recorded_options.worker_session
16966                            != current_recorded_options.worker_session
16967                        {
16968                            return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
16969                                "activity_worker_session_mismatch", Some(sequence),
16970                                Some(activity_options_description(&recorded_options)),
16971                                Some(activity_options_description(&current_recorded_options)),
16972                                "recorded worker-session routing differs from the current activity",
16973                            ))));
16974                        }
16975                        if !recorded_options
16976                            .task_queue
16977                            .matches_current(&current_recorded_options.task_queue)
16978                        {
16979                            return Poll::Ready(Err(Error::NonDeterministicReplay(
16980                                ReplayFailure::new(
16981                                    "activity_task_queue_mismatch",
16982                                    Some(sequence),
16983                                    Some(activity_options_description(&recorded_options)),
16984                                    Some(activity_options_description(&current_recorded_options)),
16985                                    "recorded activity task queue differs from the current workflow command",
16986                                ),
16987                            )));
16988                        }
16989                        if (self.local
16990                            && matches!(
16991                                recorded_options.execution_mode,
16992                                RecordedSnapshotValue::Unknown
16993                            ))
16994                            || !recorded_options
16995                                .execution_mode
16996                                .matches_current(&current_recorded_options.execution_mode)
16997                        {
16998                            return Poll::Ready(Err(Error::NonDeterministicReplay(
16999                                ReplayFailure::new(
17000                                    "activity_execution_mode_mismatch",
17001                                    Some(sequence),
17002                                    Some(activity_options_description(&recorded_options)),
17003                                    Some(activity_options_description(&current_recorded_options)),
17004                                    "recorded activity execution mode differs from the current workflow command",
17005                                ),
17006                            )));
17007                        }
17008                        if !recorded_options
17009                            .retry_policy
17010                            .matches_current(&current_recorded_options.retry_policy)
17011                        {
17012                            return Poll::Ready(Err(Error::NonDeterministicReplay(
17013                                ReplayFailure::new(
17014                                    "activity_retry_policy_mismatch",
17015                                    Some(sequence),
17016                                    Some(activity_options_description(&recorded_options)),
17017                                    Some(activity_options_description(&current_recorded_options)),
17018                                    "recorded activity retry policy differs from the current workflow command",
17019                                ),
17020                            )));
17021                        }
17022                    }
17023                    if let Err(error) = state.replay_cancellation_at(cursor, call_kind) {
17024                        return Poll::Ready(Err(error));
17025                    }
17026                    match state.prepare_scalar_cancellation(
17027                        cursor,
17028                        call_kind,
17029                        &self.parallel_group_path,
17030                    ) {
17031                        Ok(true) => {
17032                            self.scheduled = true;
17033                            return Poll::Pending;
17034                        }
17035                        Ok(false) => {}
17036                        Err(error) => return Poll::Ready(Err(error)),
17037                    }
17038                    state.command_cursor += 1;
17039                    if let Some(outcome) = outcome {
17040                        state.consume_replay_sequence(sequence, &self.parallel_group_path);
17041                        if self.local {
17042                            state.replay_clock.unavailable();
17043                        }
17044                        return Poll::Ready(outcome.map_err(Error::ActivityFailed));
17045                    }
17046                    state.matched_recorded_pending = true;
17047                    state.observation_pending = true;
17048                    self.scheduled = true;
17049                    return Poll::Pending;
17050                }
17051                other => {
17052                    return Poll::Ready(Err(command_mismatch(
17053                        &other,
17054                        format!("activity:{}", self.activity_type),
17055                    )));
17056                }
17057            }
17058        }
17059
17060        if !self.scheduled {
17061            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
17062                Ok(args) => args,
17063                Err(error) => return Poll::Ready(Err(error)),
17064            };
17065            let arguments = normalize_avro_arguments(args);
17066            let envelope = match encode_typed_envelope(&arguments, &state.payload_codec) {
17067                Ok(envelope) => envelope,
17068                Err(error) => return Poll::Ready(Err(error)),
17069            };
17070
17071            let mut command = serde_json::Map::from_iter([
17072                (
17073                    "type".to_string(),
17074                    json!(if self.local {
17075                        "record_local_activity"
17076                    } else {
17077                        "schedule_activity"
17078                    }),
17079                ),
17080                (
17081                    "activity_type".to_string(),
17082                    json!(self.activity_type.clone()),
17083                ),
17084                ("queue".to_string(), json!(task_queue)),
17085                ("arguments".to_string(), envelope),
17086            ]);
17087            for (field, value) in [
17088                ("start_to_close_timeout", options.start_to_close_timeout),
17089                (
17090                    "schedule_to_start_timeout",
17091                    options.schedule_to_start_timeout,
17092                ),
17093                (
17094                    "schedule_to_close_timeout",
17095                    options.schedule_to_close_timeout,
17096                ),
17097                ("heartbeat_timeout", options.heartbeat_timeout),
17098            ] {
17099                if let Some(value) = value {
17100                    command.insert(field.to_string(), json!(value));
17101                }
17102            }
17103            if let Some(retry_policy) = &options.retry_policy {
17104                command.insert("retry_policy".to_string(), retry_policy.clone());
17105            }
17106            if let Some(policy) = options.cancellation_policy {
17107                command.insert("cancellation_policy".to_string(), json!(policy.as_str()));
17108            }
17109            if let Some(session) = current_recorded_options.worker_session {
17110                command.insert("worker_session".into(), session);
17111            }
17112            apply_parallel_group_path(&mut command, &self.parallel_group_path);
17113            ctx.apply_scope_membership(&mut command);
17114            match state.prepare_scalar_cancellation(cursor, call_kind, &self.parallel_group_path) {
17115                Ok(true) => {
17116                    self.scheduled = true;
17117                    return Poll::Pending;
17118                }
17119                Ok(false) => {}
17120                Err(error) => return Poll::Ready(Err(error)),
17121            }
17122            if self.local {
17123                command.remove("queue");
17124                command.insert("execution_mode".into(), json!("local"));
17125                let result = Arc::new(Mutex::new(None));
17126                let command_index = state.commands.len();
17127                state.local_activity_requests.push(local_activity::Request {
17128                    command_index,
17129                    options,
17130                    arguments,
17131                    result: result.clone(),
17132                });
17133                self.local_result = Some(result);
17134            }
17135            state.commands.push(Value::Object(command));
17136            self.scheduled = true;
17137        }
17138
17139        Poll::Pending
17140    }
17141}
17142
17143impl Future for ActivityCall {
17144    type Output = Result<Value>;
17145
17146    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
17147        match self.poll_avro_value(cx) {
17148            Poll::Ready(Ok(value)) => Poll::Ready(value.into_json()),
17149            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
17150            Poll::Pending => Poll::Pending,
17151        }
17152    }
17153}
17154
17155/// Future returned by [`WorkflowContext::sleep`].
17156pub struct TimerCall {
17157    source: Option<&'static Location<'static>>,
17158    ctx: WorkflowContext,
17159    delay_seconds: Option<u64>,
17160    scheduled: bool,
17161    matched_pending: bool,
17162    parallel_group_path: Vec<ParallelGroupMetadata>,
17163}
17164
17165impl Future for TimerCall {
17166    type Output = Result<()>;
17167
17168    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
17169        let source = self.source;
17170        self.poll_history(cx)
17171            .map(|result| result.map_err(|error| replay_error_at(error, source)))
17172    }
17173}
17174
17175impl TimerCall {
17176    fn poll_history(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Result<()>> {
17177        if self.matched_pending {
17178            return Poll::Pending;
17179        }
17180
17181        let ctx = self.ctx.clone();
17182        let Some(requested_delay) = self.delay_seconds else {
17183            return Poll::Ready(Err(Error::TimerDurationOverflow));
17184        };
17185        let mut state = match ctx.state.lock() {
17186            Ok(state) => state,
17187            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
17188        };
17189
17190        let cursor = state.command_cursor;
17191        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
17192            return Poll::Ready(Err(error));
17193        }
17194        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Timer)
17195        {
17196            Ok(recorded) => recorded,
17197            Err(error) => return Poll::Ready(Err(error)),
17198        };
17199        if let Some(recorded) = recorded {
17200            match recorded {
17201                RecordedCommand::Timer {
17202                    sequence,
17203                    delay_seconds,
17204                    fired,
17205                    parallel_group_path,
17206                    ..
17207                } => {
17208                    if let Err(error) =
17209                        state.validate_scope_cleanup_timer(&ctx.cancellation_scope_id, sequence)
17210                    {
17211                        return Poll::Ready(Err(error));
17212                    }
17213                    if let Err(error) = ensure_parallel_path_matches(
17214                        sequence,
17215                        parallel_group_path.as_deref(),
17216                        &self.parallel_group_path,
17217                    ) {
17218                        return Poll::Ready(Err(error));
17219                    }
17220                    if delay_seconds != requested_delay {
17221                        return Poll::Ready(Err(Error::NonDeterministicReplay(
17222                            ReplayFailure::new(
17223                                "timer_delay_mismatch",
17224                                Some(sequence),
17225                                Some(format!("timer:{delay_seconds}s")),
17226                                Some(format!("timer:{requested_delay}s")),
17227                                "recorded timer delay differs from the current workflow command",
17228                            ),
17229                        )));
17230                    }
17231                    if let Err(error) =
17232                        state.replay_cancellation_at(cursor, CancellationCallKind::Timer)
17233                    {
17234                        return Poll::Ready(Err(error));
17235                    }
17236                    match state.prepare_scalar_cancellation(
17237                        cursor,
17238                        CancellationCallKind::Timer,
17239                        &self.parallel_group_path,
17240                    ) {
17241                        Ok(true) => {
17242                            self.scheduled = true;
17243                            self.matched_pending = true;
17244                            return Poll::Pending;
17245                        }
17246                        Ok(false) => {}
17247                        Err(error) => return Poll::Ready(Err(error)),
17248                    }
17249                    state.command_cursor += 1;
17250                    if fired {
17251                        state.consume_replay_sequence(sequence, &self.parallel_group_path);
17252                        return Poll::Ready(Ok(()));
17253                    }
17254                    state.matched_recorded_pending = true;
17255                    state.observation_pending = true;
17256                    self.scheduled = true;
17257                    self.matched_pending = true;
17258                    return Poll::Pending;
17259                }
17260                other => return Poll::Ready(Err(command_mismatch(&other, "timer"))),
17261            }
17262        }
17263
17264        if !self.scheduled {
17265            let mut command = serde_json::Map::from_iter([
17266                ("type".to_string(), json!("start_timer")),
17267                ("delay_seconds".to_string(), json!(requested_delay)),
17268            ]);
17269            match state.scope_cleanup_timer_proof(&ctx.cancellation_scope_id) {
17270                Ok(Some(proof)) => {
17271                    command.insert("cancellation_cleanup".into(), proof);
17272                }
17273                Ok(None) => {}
17274                Err(error) => return Poll::Ready(Err(error)),
17275            }
17276            apply_parallel_group_path(&mut command, &self.parallel_group_path);
17277            ctx.apply_scope_membership(&mut command);
17278            match state.prepare_scalar_cancellation(
17279                cursor,
17280                CancellationCallKind::Timer,
17281                &self.parallel_group_path,
17282            ) {
17283                Ok(true) => {
17284                    self.scheduled = true;
17285                    self.matched_pending = true;
17286                    return Poll::Pending;
17287                }
17288                Ok(false) => {}
17289                Err(error) => return Poll::Ready(Err(error)),
17290            }
17291            state.commands.push(Value::Object(command));
17292            self.scheduled = true;
17293        }
17294
17295        Poll::Pending
17296    }
17297}
17298
17299/// Future returned by [`WorkflowContext::wait_condition`].
17300pub struct ConditionWaitCall {
17301    ctx: WorkflowContext,
17302    options: ConditionWaitOptions,
17303    predicate: Box<dyn Fn() -> Result<bool> + Send + 'static>,
17304    occurrence_id: Option<String>,
17305    opened_wait: bool,
17306    parallel_group_path: Vec<ParallelGroupMetadata>,
17307}
17308
17309impl Future for ConditionWaitCall {
17310    type Output = Result<ConditionWaitResult>;
17311
17312    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
17313        if self.opened_wait {
17314            return Poll::Pending;
17315        }
17316
17317        let mut options = match self.options.validate() {
17318            Ok(options) => options,
17319            Err(error) => return Poll::Ready(Err(Error::InvalidConditionWaitOptions(error))),
17320        };
17321        let ctx = self.ctx.clone();
17322        let occurrence_id = match self.occurrence_id.as_ref() {
17323            Some(occurrence_id) => occurrence_id.clone(),
17324            None => {
17325                let mut state = match ctx.state.lock() {
17326                    Ok(state) => state,
17327                    Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
17328                };
17329                let ordinal = state.condition_wait_occurrence_counter;
17330                state.condition_wait_occurrence_counter = match ordinal.checked_add(1) {
17331                    Some(next) => next,
17332                    None => {
17333                        return Poll::Ready(Err(Error::WorkerLoop(
17334                            "condition wait occurrence counter overflowed".to_string(),
17335                        )))
17336                    }
17337                };
17338                let occurrence_id = format!("{CONDITION_WAIT_OCCURRENCE_PREFIX}{ordinal}");
17339                drop(state);
17340                self.occurrence_id = Some(occurrence_id.clone());
17341                occurrence_id
17342            }
17343        };
17344
17345        let recorded_result = {
17346            let mut state = match ctx.state.lock() {
17347                Ok(state) => state,
17348                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
17349            };
17350            let initial_cursor = state.command_cursor;
17351            if let Err(error) = ctx.validate_scope_membership(&mut state, initial_cursor) {
17352                return Poll::Ready(Err(error));
17353            }
17354            let recorded = match state
17355                .cancellation_replay_command(initial_cursor, CancellationCallKind::Condition)
17356            {
17357                Ok(recorded) => recorded,
17358                Err(error) => return Poll::Ready(Err(error)),
17359            };
17360            let Some(recorded) = recorded else {
17361                drop(state);
17362                return self.poll_new_condition(options);
17363            };
17364            if !matches!(recorded, RecordedCommand::ConditionWait { .. }) {
17365                return Poll::Ready(Err(command_mismatch(&recorded, "condition wait")));
17366            }
17367
17368            let mut cursor = state.command_cursor;
17369            let mut result = None;
17370            let mut pending_delivery = false;
17371            let mut first_sequence = None;
17372            let mut latest_timeout_seconds = None;
17373            let mut previous_sequence = None;
17374            loop {
17375                if cursor > initial_cursor
17376                    && matches!(
17377                        state.recorded_commands.get(cursor),
17378                        Some(RecordedCommand::CancellationBoundary { original: None, .. })
17379                    )
17380                {
17381                    break;
17382                }
17383                let recorded = match state
17384                    .cancellation_replay_command(cursor, CancellationCallKind::Condition)
17385                {
17386                    Ok(recorded) => recorded,
17387                    Err(error) => return Poll::Ready(Err(error)),
17388                };
17389                let Some(RecordedCommand::ConditionWait {
17390                    sequence,
17391                    occurrence_id: ref recorded_occurrence_id,
17392                    ref condition_key,
17393                    ref predicate_identity,
17394                    timeout_seconds,
17395                    result: recorded_result,
17396                    ref parallel_group_path,
17397                    ..
17398                }) = recorded
17399                else {
17400                    break;
17401                };
17402
17403                if cursor > initial_cursor && recorded_occurrence_id != &occurrence_id {
17404                    break;
17405                }
17406                if let Err(error) = ensure_parallel_path_matches(
17407                    sequence,
17408                    parallel_group_path.as_deref(),
17409                    &self.parallel_group_path,
17410                ) {
17411                    return Poll::Ready(Err(error));
17412                }
17413                if let Err(error) = validate_recorded_condition_wait(
17414                    RecordedConditionWait {
17415                        sequence,
17416                        occurrence_id: recorded_occurrence_id,
17417                        key: condition_key.as_deref(),
17418                        predicate_identity,
17419                        timeout_seconds,
17420                    },
17421                    &occurrence_id,
17422                    &options,
17423                    cursor > initial_cursor,
17424                ) {
17425                    return Poll::Ready(Err(error));
17426                }
17427                first_sequence.get_or_insert(sequence);
17428                latest_timeout_seconds = timeout_seconds;
17429                if result == Some(ConditionWaitResult::TimedOut)
17430                    && !previous_sequence.is_some_and(|previous| {
17431                        condition_wait_opened_before_timeout(
17432                            &state.history_events,
17433                            &occurrence_id,
17434                            previous,
17435                            sequence,
17436                        )
17437                    })
17438                {
17439                    return Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
17440                        "condition_wait_reopened_after_timeout",
17441                        Some(sequence),
17442                        Some("timed-out condition is terminal".to_string()),
17443                        Some("another physical wait-open".to_string()),
17444                        "condition history reopened one logical wait after its durable timeout",
17445                    ))));
17446                }
17447                if let Err(error) =
17448                    state.replay_cancellation_at(cursor, CancellationCallKind::Condition)
17449                {
17450                    return Poll::Ready(Err(error));
17451                }
17452                match state.prepare_scalar_cancellation(
17453                    cursor,
17454                    CancellationCallKind::Condition,
17455                    &self.parallel_group_path,
17456                ) {
17457                    Ok(pending) => pending_delivery |= pending,
17458                    Err(error) => return Poll::Ready(Err(error)),
17459                }
17460                result = recorded_result;
17461                if result.is_some() {
17462                    state.consume_replay_sequence(sequence, &self.parallel_group_path);
17463                }
17464                previous_sequence = Some(sequence);
17465                cursor += 1;
17466            }
17467            state.command_cursor = cursor;
17468            if pending_delivery {
17469                self.opened_wait = true;
17470                return Poll::Pending;
17471            }
17472            match (result, first_sequence) {
17473                // A grouped (parallel or select) reopen keeps the authored
17474                // timeout while the history does: the PHP Server accepts a
17475                // grouped reopen only when its timeout equals both the original
17476                // and the latest open (#189), so the remaining time would stall
17477                // the run. A history that already recorded a shorter grouped
17478                // reopen came from a Server that accepts them; keep its
17479                // convention.
17480                (None, Some(_))
17481                    if !self.parallel_group_path.is_empty()
17482                        && latest_timeout_seconds == options.timeout_seconds =>
17483                {
17484                    None
17485                }
17486                (None, Some(first_sequence)) => {
17487                    // The logical wait stays open: its deadline is fixed at the
17488                    // first physical open, not reset by a wake that left the
17489                    // predicate false.
17490                    options.timeout_seconds = condition_reopen_timeout(
17491                        &state.history_events,
17492                        first_sequence,
17493                        &occurrence_id,
17494                        options.timeout_seconds,
17495                    );
17496                    None
17497                }
17498                (result, _) => result,
17499            }
17500        };
17501
17502        if let Some(result) = recorded_result {
17503            return Poll::Ready(Ok(result));
17504        }
17505
17506        self.poll_open_condition(options, true)
17507    }
17508}
17509
17510/// Whether the physical wait at `next` was opened while the one at `previous`
17511/// was still open, so that a later timeout of `previous` belongs to an orphaned
17512/// duplicate open rather than ending the logical wait (#192, sdk-php#283). A
17513/// Server can record a second open of a still-open wait (server#1015); the
17514/// first wait's timer then fires after the chain has moved on.
17515fn condition_wait_opened_before_timeout(
17516    history: &[HistoryEvent],
17517    occurrence_id: &str,
17518    previous: u64,
17519    next: u64,
17520) -> bool {
17521    let opened = |sequence: u64| {
17522        history.iter().position(|event| {
17523            event.event_type == "ConditionWaitOpened"
17524                && event.payload.get("sequence").and_then(Value::as_u64) == Some(sequence)
17525                && event
17526                    .payload
17527                    .get("condition_wait_occurrence_id")
17528                    .and_then(Value::as_str)
17529                    == Some(occurrence_id)
17530        })
17531    };
17532    let (Some(previous_open), Some(next_open)) = (opened(previous), opened(next)) else {
17533        return false;
17534    };
17535    let previous_wait_id = history[previous_open]
17536        .payload
17537        .get("condition_wait_id")
17538        .cloned();
17539    let timed_out = history
17540        .iter()
17541        .position(|event| match event.event_type.as_str() {
17542            "ConditionWaitTimedOut" => {
17543                event.payload.get("sequence").and_then(Value::as_u64) == Some(previous)
17544                    && event
17545                        .payload
17546                        .get("condition_wait_occurrence_id")
17547                        .and_then(Value::as_str)
17548                        == Some(occurrence_id)
17549            }
17550            "TimerFired" => {
17551                event.payload.get("timer_kind").and_then(Value::as_str) == Some("condition_timeout")
17552                    && previous_wait_id.is_some()
17553                    && event.payload.get("condition_wait_id") == previous_wait_id.as_ref()
17554            }
17555            _ => false,
17556        });
17557    timed_out.is_some_and(|timed_out| next_open < timed_out)
17558}
17559
17560/// The timeout for reopening a recorded logical condition wait: the authored
17561/// timeout less the time from its first physical open to the latest recorded
17562/// history event, rounded up and clamped to `0..=authored`. Without both
17563/// times, the authored timeout is kept.
17564fn condition_reopen_timeout(
17565    history: &[HistoryEvent],
17566    first_sequence: u64,
17567    occurrence_id: &str,
17568    authored: Option<u64>,
17569) -> Option<u64> {
17570    let authored = authored?;
17571    let wall_time = |event: &HistoryEvent| {
17572        event
17573            .raw
17574            .get("timestamp")
17575            .filter(|value| !value.is_null())
17576            .or_else(|| event.raw.get("recorded_at"))
17577            .and_then(Value::as_str)
17578            .and_then(|time| DateTime::parse_from_rfc3339(time).ok())
17579            .map(|time| time.with_timezone(&chrono::Utc))
17580    };
17581    let opened_at = history
17582        .iter()
17583        .find(|event| {
17584            event.event_type == "ConditionWaitOpened"
17585                && event.payload.get("sequence").and_then(Value::as_u64) == Some(first_sequence)
17586                && event
17587                    .payload
17588                    .get("condition_wait_occurrence_id")
17589                    .and_then(Value::as_str)
17590                    == Some(occurrence_id)
17591        })
17592        .and_then(wall_time);
17593    let latest = history.iter().filter_map(wall_time).max();
17594    let (Some(opened_at), Some(latest)) = (opened_at, latest) else {
17595        return Some(authored);
17596    };
17597    let elapsed_ms = i128::from((latest - opened_at).num_milliseconds().max(0));
17598    let remaining_ms = i128::from(authored) * 1000 - elapsed_ms;
17599    if remaining_ms <= 0 {
17600        return Some(0);
17601    }
17602    let remaining = (remaining_ms + 999) / 1000;
17603    Some(u64::try_from(remaining).map_or(authored, |remaining| remaining.min(authored)))
17604}
17605
17606impl ConditionWaitCall {
17607    fn poll_new_condition(
17608        self: Pin<&mut Self>,
17609        options: ValidatedConditionWaitOptions,
17610    ) -> Poll<Result<ConditionWaitResult>> {
17611        self.poll_open_condition(options, false)
17612    }
17613
17614    fn poll_open_condition(
17615        mut self: Pin<&mut Self>,
17616        options: ValidatedConditionWaitOptions,
17617        recorded_wait: bool,
17618    ) -> Poll<Result<ConditionWaitResult>> {
17619        {
17620            let ctx = self.ctx.clone();
17621            let mut state = match ctx.state.lock() {
17622                Ok(state) => state,
17623                Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
17624            };
17625            let cursor = state.command_cursor;
17626            match state.prepare_scalar_cancellation(
17627                cursor,
17628                CancellationCallKind::Condition,
17629                &self.parallel_group_path,
17630            ) {
17631                Ok(true) => {
17632                    self.opened_wait = true;
17633                    return Poll::Pending;
17634                }
17635                Ok(false) => {}
17636                Err(error) => return Poll::Ready(Err(error)),
17637            }
17638        }
17639        let selection_member = self
17640            .parallel_group_path
17641            .first()
17642            .is_some_and(|entry| entry.parallel_group_mode.as_deref() == Some("select"));
17643        let predicate_result = {
17644            // This predicate inspects the full signal/update view; the current
17645            // executor does not retain its exact triggering event prefix.
17646            let _clock = replay_clock::Guard::unavailable();
17647            (self.predicate)()
17648        };
17649        match predicate_result {
17650            Ok(true) if !selection_member || recorded_wait => {
17651                return Poll::Ready(Ok(ConditionWaitResult::Satisfied))
17652            }
17653            Ok(_) => {}
17654            Err(error) => return Poll::Ready(Err(error)),
17655        }
17656        // A recorded wait reopened after its deadline still opens, with a zero
17657        // timeout, so the Server resolves its wait and timer as timed out.
17658        if options.timeout_seconds == Some(0) && !selection_member && !recorded_wait {
17659            return Poll::Ready(Ok(ConditionWaitResult::TimedOut));
17660        }
17661
17662        let ctx = self.ctx.clone();
17663        let mut state = match ctx.state.lock() {
17664            Ok(state) => state,
17665            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
17666        };
17667        let mut command = serde_json::Map::from_iter([
17668            ("type".to_string(), json!("open_condition_wait")),
17669            (
17670                "condition_wait_occurrence_id".to_string(),
17671                json!(self.occurrence_id.as_deref().unwrap_or_default()),
17672            ),
17673            ("condition_key".to_string(), json!(options.condition_key)),
17674            (
17675                "condition_definition_fingerprint".to_string(),
17676                json!(options.predicate_identity),
17677            ),
17678        ]);
17679        if let Some(timeout_seconds) = options.timeout_seconds {
17680            command.insert("timeout_seconds".to_string(), json!(timeout_seconds));
17681        }
17682        apply_parallel_group_path(&mut command, &self.parallel_group_path);
17683        ctx.apply_scope_membership(&mut command);
17684        state.commands.push(Value::Object(command));
17685        drop(state);
17686        self.opened_wait = true;
17687        Poll::Pending
17688    }
17689}
17690
17691/// The identity recorded for one condition wait.
17692struct RecordedConditionWait<'a> {
17693    sequence: u64,
17694    occurrence_id: &'a str,
17695    key: Option<&'a str>,
17696    predicate_identity: &'a str,
17697    timeout_seconds: Option<u64>,
17698}
17699
17700fn validate_recorded_condition_wait(
17701    recorded: RecordedConditionWait<'_>,
17702    current_occurrence_id: &str,
17703    current: &ValidatedConditionWaitOptions,
17704    physical_reopen: bool,
17705) -> Result<()> {
17706    let RecordedConditionWait {
17707        sequence,
17708        occurrence_id: recorded_occurrence_id,
17709        key: recorded_key,
17710        predicate_identity: recorded_predicate_identity,
17711        timeout_seconds: recorded_timeout_seconds,
17712    } = recorded;
17713    if recorded_occurrence_id != current_occurrence_id {
17714        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
17715            "condition_wait_occurrence_mismatch",
17716            Some(sequence),
17717            Some(recorded_occurrence_id.to_string()),
17718            Some(current_occurrence_id.to_string()),
17719            "recorded condition occurrence differs from the current authored wait position",
17720        )));
17721    }
17722    if recorded_key != Some(current.condition_key.as_str()) {
17723        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
17724            "condition_wait_key_mismatch",
17725            Some(sequence),
17726            recorded_key.map(str::to_string),
17727            Some(current.condition_key.clone()),
17728            "recorded condition identity differs from the current workflow wait",
17729        )));
17730    }
17731    if recorded_predicate_identity != current.predicate_identity {
17732        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
17733            "condition_wait_predicate_mismatch",
17734            Some(sequence),
17735            Some(recorded_predicate_identity.to_string()),
17736            Some(current.predicate_identity.clone()),
17737            "recorded condition predicate behavior differs from current workflow code",
17738        )));
17739    }
17740    // A physical reopen carries the remaining time of the first open, so it may
17741    // record less than the authored timeout, never more.
17742    let timeout_matches = match (recorded_timeout_seconds, current.timeout_seconds) {
17743        (Some(recorded), Some(authored)) if physical_reopen => recorded <= authored,
17744        (recorded, authored) => recorded == authored,
17745    };
17746    if !timeout_matches {
17747        return Err(Error::NonDeterministicReplay(ReplayFailure::new(
17748            "condition_wait_timeout_mismatch",
17749            Some(sequence),
17750            recorded_timeout_seconds.map(|seconds| format!("{seconds}s")),
17751            current.timeout_seconds.map(|seconds| format!("{seconds}s")),
17752            "recorded condition timeout differs from the current workflow wait",
17753        )));
17754    }
17755    Ok(())
17756}
17757
17758/// Future returned by [`WorkflowContext::start_child_workflow`].
17759pub struct ChildWorkflowCall {
17760    ctx: WorkflowContext,
17761    workflow_type: String,
17762    options: ChildWorkflowOptions,
17763    args: Option<Result<AvroValue>>,
17764    scheduled: bool,
17765    matched_pending: bool,
17766    parallel_group_path: Vec<ParallelGroupMetadata>,
17767}
17768
17769impl ChildWorkflowCall {
17770    fn poll_avro_value(
17771        mut self: Pin<&mut Self>,
17772        _cx: &mut TaskContext<'_>,
17773    ) -> Poll<Result<ChildWorkflowAvroResult>> {
17774        if self.matched_pending {
17775            return Poll::Pending;
17776        }
17777
17778        let ctx = self.ctx.clone();
17779        let mut state = match ctx.state.lock() {
17780            Ok(state) => state,
17781            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
17782        };
17783
17784        let cursor = state.command_cursor;
17785        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
17786            return Poll::Ready(Err(error));
17787        }
17788        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Child)
17789        {
17790            Ok(recorded) => recorded,
17791            Err(error) => return Poll::Ready(Err(error)),
17792        };
17793        if let Some(recorded) = recorded {
17794            let sequence = recorded.sequence();
17795            match recorded {
17796                RecordedCommand::ChildWorkflow {
17797                    workflow_type,
17798                    policies,
17799                    outcome,
17800                    parallel_group_path,
17801                    ..
17802                } => {
17803                    if let Err(error) = ensure_parallel_path_matches(
17804                        sequence,
17805                        parallel_group_path.as_deref(),
17806                        &self.parallel_group_path,
17807                    ) {
17808                        return Poll::Ready(Err(error));
17809                    }
17810                    if let Some(recorded_type) = workflow_type {
17811                        if recorded_type != self.workflow_type {
17812                            return Poll::Ready(Err(Error::NonDeterministicReplay(
17813                                ReplayFailure::new(
17814                                    "recorded_command_detail_mismatch",
17815                                    Some(sequence),
17816                                    Some(format!("child workflow:{recorded_type}")),
17817                                    Some(format!("child workflow:{}", self.workflow_type)),
17818                                    "recorded child workflow type differs from the current workflow command",
17819                                ),
17820                            )));
17821                        }
17822                    }
17823                    if let Err(error) =
17824                        ensure_child_policies_match(sequence, &policies, &self.options)
17825                    {
17826                        return Poll::Ready(Err(error));
17827                    }
17828                    if let Err(error) =
17829                        state.replay_cancellation_at(cursor, CancellationCallKind::Child)
17830                    {
17831                        return Poll::Ready(Err(error));
17832                    }
17833                    match state.prepare_scalar_cancellation(
17834                        cursor,
17835                        CancellationCallKind::Child,
17836                        &self.parallel_group_path,
17837                    ) {
17838                        Ok(true) => {
17839                            self.scheduled = true;
17840                            self.matched_pending = true;
17841                            return Poll::Pending;
17842                        }
17843                        Ok(false) => {}
17844                        Err(error) => return Poll::Ready(Err(error)),
17845                    }
17846                    state.command_cursor += 1;
17847                    if let Some(outcome) = outcome {
17848                        state.consume_replay_sequence(sequence, &self.parallel_group_path);
17849                        return Poll::Ready(outcome.map_err(Error::ChildWorkflowFailed));
17850                    }
17851                    state.matched_recorded_pending = true;
17852                    state.observation_pending = true;
17853                    self.scheduled = true;
17854                    self.matched_pending = true;
17855                    return Poll::Pending;
17856                }
17857                other => {
17858                    return Poll::Ready(Err(command_mismatch(
17859                        &other,
17860                        format!("child workflow:{}", self.workflow_type),
17861                    )));
17862                }
17863            }
17864        }
17865
17866        if !self.scheduled {
17867            if self.options.task_queue.trim().is_empty() {
17868                return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
17869                    "task_queue must not be empty".to_string(),
17870                )));
17871            }
17872            for (name, value) in [
17873                (
17874                    "execution_timeout_seconds",
17875                    self.options.execution_timeout_seconds,
17876                ),
17877                ("run_timeout_seconds", self.options.run_timeout_seconds),
17878            ] {
17879                if value == Some(0) {
17880                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(format!(
17881                        "{name} must be at least 1"
17882                    ))));
17883                }
17884            }
17885
17886            let args = match self.args.take().unwrap_or(Ok(AvroValue::Null)) {
17887                Ok(args) => args,
17888                Err(error) => return Poll::Ready(Err(error)),
17889            };
17890            let arguments = match encode_typed_envelope(
17891                &normalize_avro_arguments(args),
17892                &state.payload_codec,
17893            ) {
17894                Ok(arguments) => arguments,
17895                Err(error) => return Poll::Ready(Err(error)),
17896            };
17897            let mut command = json!({
17898                "type": "start_child_workflow",
17899                "workflow_type": self.workflow_type,
17900                "queue": self.options.task_queue,
17901                "parent_close_policy": self.options.parent_close_policy.as_str(),
17902                "arguments": arguments,
17903            });
17904            let object = command
17905                .as_object_mut()
17906                .expect("child workflow command is always an object");
17907            if self.options.cancellation_policy != CancellationPolicy::Abandon {
17908                object.insert(
17909                    "cancellation_policy".to_string(),
17910                    json!(self.options.cancellation_policy.as_str()),
17911                );
17912            }
17913            if let Some(policy) = &self.options.retry_policy {
17914                let mut retry_policy = serde_json::Map::new();
17915                if let Some(max_attempts) = policy.max_attempts {
17916                    if max_attempts == 0 {
17917                        return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
17918                            "retry_policy.max_attempts must be at least 1".to_string(),
17919                        )));
17920                    }
17921                    retry_policy.insert("max_attempts".to_string(), json!(max_attempts));
17922                }
17923                if !policy.backoff_seconds.is_empty() {
17924                    retry_policy
17925                        .insert("backoff_seconds".to_string(), json!(policy.backoff_seconds));
17926                }
17927                if !policy.non_retryable_error_types.is_empty() {
17928                    retry_policy.insert(
17929                        "non_retryable_error_types".to_string(),
17930                        json!(policy.non_retryable_error_types),
17931                    );
17932                }
17933                if retry_policy.is_empty() {
17934                    return Poll::Ready(Err(Error::InvalidChildWorkflowOptions(
17935                        "retry_policy must configure at least one field".to_string(),
17936                    )));
17937                }
17938                object.insert("retry_policy".to_string(), Value::Object(retry_policy));
17939            }
17940            if let Some(seconds) = self.options.execution_timeout_seconds {
17941                object.insert("execution_timeout_seconds".to_string(), json!(seconds));
17942            }
17943            if let Some(seconds) = self.options.run_timeout_seconds {
17944                object.insert("run_timeout_seconds".to_string(), json!(seconds));
17945            }
17946            apply_parallel_group_path(object, &self.parallel_group_path);
17947            ctx.apply_scope_membership(object);
17948            match state.prepare_scalar_cancellation(
17949                cursor,
17950                CancellationCallKind::Child,
17951                &self.parallel_group_path,
17952            ) {
17953                Ok(true) => {
17954                    self.scheduled = true;
17955                    self.matched_pending = true;
17956                    return Poll::Pending;
17957                }
17958                Ok(false) => {}
17959                Err(error) => return Poll::Ready(Err(error)),
17960            }
17961            state.commands.push(command);
17962            self.scheduled = true;
17963        }
17964
17965        Poll::Pending
17966    }
17967}
17968
17969impl Future for ChildWorkflowCall {
17970    type Output = Result<ChildWorkflowResult>;
17971
17972    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
17973        match self.poll_avro_value(cx) {
17974            Poll::Ready(Ok(result)) => match result.result.into_json() {
17975                Ok(projected) => Poll::Ready(Ok(ChildWorkflowResult {
17976                    parent: result.parent,
17977                    child: result.child,
17978                    child_workflow_type: result.child_workflow_type,
17979                    result: projected,
17980                })),
17981                Err(error) => Poll::Ready(Err(error)),
17982            },
17983            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
17984            Poll::Pending => Poll::Pending,
17985        }
17986    }
17987}
17988
17989fn replay_error_at(mut error: Error, source: Option<&'static Location<'static>>) -> Error {
17990    if let (Error::NonDeterministicReplay(failure), Some(source)) = (&mut error, source) {
17991        if let Some(file) = source.file().rsplit(['/', '\\']).next() {
17992            if !file.is_empty() && !file.chars().any(char::is_control) {
17993                failure
17994                    .message
17995                    .push_str(&format!(" Authored at {file}:{}.", source.line()));
17996            }
17997        }
17998    }
17999    error
18000}
18001
18002fn command_mismatch(recorded: &RecordedCommand, actual: impl Into<String>) -> Error {
18003    Error::NonDeterministicReplay(ReplayFailure::new(
18004        "recorded_command_mismatch",
18005        Some(recorded.sequence()),
18006        Some(recorded.shape().to_string()),
18007        Some(actual.into()),
18008        "current workflow command does not match the recorded durable command sequence",
18009    ))
18010}
18011
18012pub struct SignalCall {
18013    ctx: WorkflowContext,
18014    signal_name: String,
18015    runtime_reserved_allowed: bool,
18016    opened_wait: bool,
18017    matched_pending: bool,
18018    parallel_group_path: Vec<ParallelGroupMetadata>,
18019}
18020
18021impl SignalCall {
18022    fn poll_avro_value(
18023        mut self: Pin<&mut Self>,
18024        _cx: &mut TaskContext<'_>,
18025    ) -> Poll<Result<Vec<AvroValue>>> {
18026        if self.matched_pending {
18027            return Poll::Pending;
18028        }
18029        if !self.runtime_reserved_allowed {
18030            if let Err(error) = validate_user_signal_name(&self.signal_name) {
18031                return Poll::Ready(Err(error));
18032            }
18033        }
18034
18035        let ctx = self.ctx.clone();
18036        let mut state = match ctx.state.lock() {
18037            Ok(state) => state,
18038            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
18039        };
18040
18041        let cursor = state.command_cursor;
18042        if let Err(error) = ctx.validate_scope_membership(&mut state, cursor) {
18043            return Poll::Ready(Err(error));
18044        }
18045        let recorded = match state.cancellation_replay_command(cursor, CancellationCallKind::Signal)
18046        {
18047            Ok(recorded) => recorded,
18048            Err(error) => return Poll::Ready(Err(error)),
18049        };
18050        if let Some(recorded) = recorded {
18051            match recorded {
18052                RecordedCommand::SignalWait {
18053                    sequence,
18054                    signal_name,
18055                    value,
18056                    parallel_group_path,
18057                } => {
18058                    if let Err(error) = ensure_parallel_path_matches(
18059                        sequence,
18060                        parallel_group_path.as_deref(),
18061                        &self.parallel_group_path,
18062                    ) {
18063                        return Poll::Ready(Err(error));
18064                    }
18065                    if signal_name != self.signal_name {
18066                        return Poll::Ready(Err(Error::NonDeterministicReplay(
18067                            ReplayFailure::new(
18068                                "recorded_command_detail_mismatch",
18069                                Some(sequence),
18070                                Some(format!("signal wait:{signal_name}")),
18071                                Some(format!("signal wait:{}", self.signal_name)),
18072                                "recorded signal name differs from the current workflow command",
18073                            ),
18074                        )));
18075                    }
18076
18077                    if let Err(error) =
18078                        state.replay_cancellation_at(cursor, CancellationCallKind::Signal)
18079                    {
18080                        return Poll::Ready(Err(error));
18081                    }
18082                    match state.prepare_scalar_cancellation(
18083                        cursor,
18084                        CancellationCallKind::Signal,
18085                        &self.parallel_group_path,
18086                    ) {
18087                        Ok(true) => {
18088                            self.opened_wait = true;
18089                            self.matched_pending = true;
18090                            return Poll::Pending;
18091                        }
18092                        Ok(false) => {}
18093                        Err(error) => return Poll::Ready(Err(error)),
18094                    }
18095                    state.command_cursor += 1;
18096                    if let Some(value) = value {
18097                        state.consume_replay_sequence(sequence, &self.parallel_group_path);
18098                        return Poll::Ready(Ok(value));
18099                    }
18100                    if state
18101                        .resume_signal
18102                        .as_ref()
18103                        .is_some_and(|signal| signal.signal_name == self.signal_name)
18104                    {
18105                        let signal = state
18106                            .resume_signal
18107                            .take()
18108                            .expect("matching resume signal is present");
18109                        state.consume_unproven_boundary(&self.parallel_group_path);
18110                        return Poll::Ready(Ok(signal.arguments));
18111                    }
18112
18113                    state.matched_recorded_pending = true;
18114                    state.observation_pending = true;
18115                    self.opened_wait = true;
18116                    self.matched_pending = true;
18117                    return Poll::Pending;
18118                }
18119                other => {
18120                    return Poll::Ready(Err(command_mismatch(
18121                        &other,
18122                        format!("signal wait:{}", self.signal_name),
18123                    )));
18124                }
18125            }
18126        }
18127
18128        match state.prepare_scalar_cancellation(
18129            cursor,
18130            CancellationCallKind::Signal,
18131            &self.parallel_group_path,
18132        ) {
18133            Ok(true) => {
18134                self.opened_wait = true;
18135                self.matched_pending = true;
18136                return Poll::Pending;
18137            }
18138            Ok(false) => {}
18139            Err(error) => return Poll::Ready(Err(error)),
18140        }
18141
18142        if state
18143            .resume_signal
18144            .as_ref()
18145            .is_some_and(|signal| signal.signal_name == self.signal_name)
18146        {
18147            let signal = state
18148                .resume_signal
18149                .take()
18150                .expect("matching resume signal is present");
18151            state.consume_unproven_boundary(&self.parallel_group_path);
18152            return Poll::Ready(Ok(signal.arguments));
18153        }
18154
18155        if !self.opened_wait {
18156            let mut command = serde_json::Map::from_iter([
18157                ("type".to_string(), json!("open_signal_wait")),
18158                ("signal_name".to_string(), json!(self.signal_name)),
18159            ]);
18160            apply_parallel_group_path(&mut command, &self.parallel_group_path);
18161            ctx.apply_scope_membership(&mut command);
18162            state.commands.push(Value::Object(command));
18163            self.opened_wait = true;
18164        }
18165
18166        Poll::Pending
18167    }
18168}
18169
18170impl Future for SignalCall {
18171    type Output = Result<Vec<Value>>;
18172
18173    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
18174        match self.poll_avro_value(cx) {
18175            Poll::Ready(Ok(values)) => Poll::Ready(
18176                values
18177                    .into_iter()
18178                    .map(AvroValue::into_json)
18179                    .collect::<Result<Vec<_>>>(),
18180            ),
18181            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
18182            Poll::Pending => Poll::Pending,
18183        }
18184    }
18185}
18186
18187#[derive(Clone, Debug)]
18188pub struct ActivityContext {
18189    client: Client,
18190    pub task_id: String,
18191    pub activity_attempt_id: String,
18192    pub lease_owner: String,
18193    pub activity_type: String,
18194    pub attempt_number: u64,
18195    retry_info: ActivityRetryInfo,
18196    heartbeat_resume: activity_checkpoint::HeartbeatResume,
18197    activity_execution_id: Option<String>,
18198    workflow_id: Option<String>,
18199    run_id: Option<String>,
18200    pub task_queue: String,
18201    pub worker_id: String,
18202    claim_guard: Option<cooperative_cancellation::ActivityClaimGuard>,
18203    local_heartbeats: Option<Arc<Mutex<local_activity::Heartbeats>>>,
18204    worker_session: Option<WorkerSession>,
18205}
18206
18207impl ActivityContext {
18208    /// Negotiated resume contract version for this claim; unavailable is `None`.
18209    /// This is not a checkpoint write sequence.
18210    pub fn heartbeat_resume_version(&self) -> Option<u64> {
18211        self.heartbeat_resume.version()
18212    }
18213
18214    /// The read-only acknowledged checkpoint supplied by this claim.
18215    ///
18216    /// `Ok(None)` means the supported claim explicitly has no checkpoint.
18217    /// `Err(ActivityHeartbeatResumeUnavailable)` means the v1 contract was not
18218    /// supplied. Inline local activities and Server-free tests are unavailable.
18219    /// Heartbeat writes never change this received snapshot. Acknowledgement
18220    /// does not atomically commit an external business effect.
18221    pub fn last_heartbeat_checkpoint(
18222        &self,
18223    ) -> std::result::Result<Option<&ActivityHeartbeatCheckpoint>, ActivityHeartbeatResumeUnavailable>
18224    {
18225        self.heartbeat_resume.checkpoint()
18226    }
18227
18228    /// Last acknowledged details, with unavailable distinct from no checkpoint.
18229    pub fn last_heartbeat_details(
18230        &self,
18231    ) -> std::result::Result<Option<&Value>, ActivityHeartbeatResumeUnavailable> {
18232        Ok(self
18233            .last_heartbeat_checkpoint()?
18234            .map(|value| value.details()))
18235    }
18236
18237    /// Producer acknowledgement time, with full fractional precision.
18238    pub fn last_heartbeat_at(
18239        &self,
18240    ) -> std::result::Result<Option<&DateTime<chrono::Utc>>, ActivityHeartbeatResumeUnavailable>
18241    {
18242        Ok(self
18243            .last_heartbeat_checkpoint()?
18244            .map(|value| value.acknowledged_at()))
18245    }
18246
18247    /// Logical Server activity execution ID, stable across that activity's retries.
18248    ///
18249    /// This is the received claim identity, including for worker-session activities.
18250    /// It is unavailable when an older Server omits it, for inline local activities
18251    /// before the Server records their command, and in Server-free tests. It is
18252    /// never derived from a per-attempt task or attempt ID. Use an application
18253    /// business key when this value is unavailable.
18254    pub fn activity_execution_id(&self) -> Option<&str> {
18255        self.activity_execution_id.as_deref()
18256    }
18257
18258    /// Owning workflow instance ID from the claim (or parent local workflow task).
18259    /// Older claims and Server-free activity tests can report `None`.
18260    pub fn workflow_id(&self) -> Option<&str> {
18261        self.workflow_id.as_deref()
18262    }
18263
18264    /// Owning workflow run ID from the claim (or parent local workflow task).
18265    /// Older claims and Server-free activity tests can report `None`.
18266    pub fn run_id(&self) -> Option<&str> {
18267        self.run_id.as_deref()
18268    }
18269
18270    /// Immutable original attempt identity and received retry policy.
18271    pub fn retry_info(&self) -> &ActivityRetryInfo {
18272        &self.retry_info
18273    }
18274
18275    pub async fn heartbeat<T: Serialize>(&self, details: T) -> Result<ActivityHeartbeatResponse> {
18276        if let Some(heartbeats) = &self.local_heartbeats {
18277            return heartbeats
18278                .lock()
18279                .map_err(|_| Error::WorkflowStatePoisoned)?
18280                .record(details);
18281        }
18282        if let Some(guard) = &self.claim_guard {
18283            return guard.heartbeat(self, details).await;
18284        }
18285        if let Some(session) = &self.worker_session {
18286            if !session.active() {
18287                return Err(Error::ActivityExecutionAbandoned(
18288                    "worker-session lease or TTL is no longer active".into(),
18289                ));
18290            }
18291            let result = self
18292                .client
18293                .heartbeat_activity_task_value(
18294                    &self.task_id,
18295                    &self.activity_attempt_id,
18296                    &self.lease_owner,
18297                    details,
18298                )
18299                .await;
18300            return worker_session::settle_activity_heartbeat(
18301                session,
18302                result,
18303                &self.task_id,
18304                &self.activity_attempt_id,
18305                &self.lease_owner,
18306            );
18307        }
18308        self.client
18309            .heartbeat_activity_task(
18310                &self.task_id,
18311                &self.activity_attempt_id,
18312                &self.lease_owner,
18313                details,
18314            )
18315            .await
18316    }
18317}
18318
18319fn decode_task_avro_arguments(value: Option<&Value>, codec: &str) -> Result<AvroValue> {
18320    validate_payload_codec(codec)?;
18321    match value {
18322        Some(value) => Ok(normalize_avro_arguments(decode_wire_avro_value(
18323            value, codec,
18324        )?)),
18325        None => Ok(AvroValue::Array(Vec::new())),
18326    }
18327}
18328
18329fn decode_resume_signal(task: &WorkflowTask) -> Result<Option<ResumeSignal>> {
18330    let Some(signal_name) = task
18331        .signal_name
18332        .as_deref()
18333        .filter(|value| !value.is_empty())
18334    else {
18335        return Ok(None);
18336    };
18337    let decoded = decode_task_avro_arguments(task.signal_arguments.as_ref(), &task.payload_codec)?;
18338    let AvroValue::Array(arguments) = decoded else {
18339        unreachable!("normalize_avro_arguments always returns an array");
18340    };
18341
18342    Ok(Some(ResumeSignal {
18343        signal_name: signal_name.to_string(),
18344        arguments,
18345    }))
18346}
18347
18348fn validate_workflow_task_payloads(task: &WorkflowTask) -> Result<()> {
18349    validate_payload_codec(&task.payload_codec)?;
18350    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)?;
18351    validate_optional_inbound_payload(task.signal_arguments.as_ref(), &task.payload_codec)?;
18352    for event in &task.history_events {
18353        validate_history_event_payloads(event, &task.payload_codec)?;
18354    }
18355    Ok(())
18356}
18357
18358fn validate_activity_task_payloads(task: &ActivityTask) -> Result<()> {
18359    validate_payload_codec(&task.payload_codec)?;
18360    validate_optional_inbound_payload(task.arguments.as_ref(), &task.payload_codec)
18361}
18362
18363fn validate_query_task_payloads(task: &QueryTask) -> Result<()> {
18364    validate_payload_codec(&task.payload_codec)?;
18365    validate_optional_inbound_payload(task.workflow_arguments.as_ref(), &task.payload_codec)?;
18366    validate_optional_inbound_payload(task.query_arguments.as_ref(), &task.payload_codec)?;
18367    for event in &task.history_events {
18368        validate_history_event_payloads(event, &task.payload_codec)?;
18369    }
18370
18371    let Some(export) = task.history_export.as_ref() else {
18372        return Ok(());
18373    };
18374    let export_codec = match export.get("payloads") {
18375        Some(payloads) => declared_payload_codec(payloads, "codec")?,
18376        None => None,
18377    }
18378    .unwrap_or(&task.payload_codec);
18379    validate_payload_codec(export_codec)?;
18380
18381    if let Some(events) = export.get("history_events").and_then(Value::as_array) {
18382        for event in events {
18383            let event_type = event
18384                .get("event_type")
18385                .or_else(|| event.get("type"))
18386                .and_then(Value::as_str)
18387                .unwrap_or_default();
18388            if let Some(payload) = event.get("payload") {
18389                validate_history_payloads(event_type, payload, export_codec)?;
18390            }
18391        }
18392    }
18393    for signal in export
18394        .get("signals")
18395        .and_then(Value::as_array)
18396        .into_iter()
18397        .flatten()
18398    {
18399        let codec = declared_payload_codec(signal, "payload_codec")?.unwrap_or(export_codec);
18400        validate_payload_codec(codec)?;
18401        validate_optional_inbound_payload(signal.get("arguments"), codec)?;
18402    }
18403    for activity in export
18404        .get("activities")
18405        .and_then(Value::as_array)
18406        .into_iter()
18407        .flatten()
18408    {
18409        let codec = declared_payload_codec(activity, "payload_codec")?.unwrap_or(export_codec);
18410        validate_payload_codec(codec)?;
18411        validate_optional_inbound_payload(activity.get("arguments"), codec)?;
18412        validate_optional_inbound_payload(activity.get("result"), codec)?;
18413    }
18414    Ok(())
18415}
18416
18417fn validate_history_event_payloads(event: &HistoryEvent, fallback_codec: &str) -> Result<()> {
18418    validate_history_payloads(&event.event_type, &event.payload, fallback_codec)
18419}
18420
18421fn validate_history_payloads(
18422    event_type: &str,
18423    payload: &Value,
18424    fallback_codec: &str,
18425) -> Result<()> {
18426    let codec = declared_payload_codec(payload, "payload_codec")?.unwrap_or(fallback_codec);
18427    validate_payload_codec(codec)?;
18428    for field in history_payload_fields(event_type) {
18429        validate_optional_inbound_payload(payload.get(*field), codec)?;
18430    }
18431    Ok(())
18432}
18433
18434const SIGNAL_HISTORY_PAYLOAD_FIELDS: &[&str] = &["value", "input", "arguments"];
18435
18436fn history_payload_fields(event_type: &str) -> &'static [&'static str] {
18437    match event_type {
18438        "ActivityCompleted" => &["result"],
18439        "SignalReceived" | "SignalApplied" => SIGNAL_HISTORY_PAYLOAD_FIELDS,
18440        "UpdateAccepted" | "UpdateRejected" | "UpdateApplied" | "ExternalSignalRequested" => {
18441            &["arguments"]
18442        }
18443        "UpdateCompleted" | "SideEffectRecorded" => &["result"],
18444        "ChildRunCompleted" => &["result", "output"],
18445        "WorkflowCompleted" => &["output"],
18446        "ServiceCallStarted"
18447        | "ServiceCallCompleted"
18448        | "ServiceCallFailed"
18449        | "ServiceCallCancelled" => &["request_payload", "response_payload"],
18450        _ => &[],
18451    }
18452}
18453
18454fn signal_history_payload(payload: &Value) -> Option<&Value> {
18455    SIGNAL_HISTORY_PAYLOAD_FIELDS
18456        .iter()
18457        .find_map(|field| payload.get(*field))
18458}
18459
18460fn declared_payload_codec<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>> {
18461    match value.get(field) {
18462        None => Ok(None),
18463        Some(Value::String(codec)) => Ok(Some(codec)),
18464        Some(_) => Err(invalid_payload_envelope()),
18465    }
18466}
18467
18468fn validate_optional_inbound_payload(value: Option<&Value>, codec: &str) -> Result<()> {
18469    validate_payload_codec(codec)?;
18470    if let Some(value) = value.filter(|value| !value.is_null()) {
18471        decode_wire_avro_value(value, codec)?;
18472    }
18473    Ok(())
18474}
18475
18476fn recorded_parallel_group_entry(payload: &Value, sequence: u64) -> Result<ParallelGroupMetadata> {
18477    let group_id = payload_string(payload, "parallel_group_id").ok_or_else(|| {
18478        invalid_recorded_history(
18479            "parallel_group_metadata_invalid",
18480            sequence,
18481            "non-empty parallel_group_id",
18482            &payload.to_string(),
18483            "parallel-group history is missing its stable identity",
18484        )
18485    })?;
18486    let kind = payload_string(payload, "parallel_group_kind").ok_or_else(|| {
18487        invalid_recorded_history(
18488            "parallel_group_metadata_invalid",
18489            sequence,
18490            "activity, child, timer, signal, condition, or mixed group kind",
18491            &payload.to_string(),
18492            "parallel-group history is missing its group kind",
18493        )
18494    })?;
18495    if !matches!(
18496        kind.as_str(),
18497        "activity" | "child" | "timer" | "signal" | "condition" | "mixed"
18498    ) {
18499        return Err(invalid_recorded_history(
18500            "parallel_group_metadata_invalid",
18501            sequence,
18502            "activity, child, timer, signal, condition, or mixed group kind",
18503            &kind,
18504            "parallel-group history contains an unsupported group kind",
18505        ));
18506    }
18507    let base_sequence = payload
18508        .get("parallel_group_base_sequence")
18509        .and_then(value_as_u64)
18510        .filter(|value| *value > 0)
18511        .ok_or_else(|| {
18512            invalid_recorded_history(
18513                "parallel_group_metadata_invalid",
18514                sequence,
18515                "positive parallel_group_base_sequence",
18516                &payload.to_string(),
18517                "parallel-group history contains an invalid base sequence",
18518            )
18519        })?;
18520    let size = payload
18521        .get("parallel_group_size")
18522        .and_then(value_as_u64)
18523        .and_then(|value| usize::try_from(value).ok())
18524        .filter(|value| (1..=MAX_PARALLEL_OPERATIONS).contains(value))
18525        .ok_or_else(|| {
18526            invalid_recorded_history(
18527                "parallel_group_metadata_invalid",
18528                sequence,
18529                "bounded positive parallel_group_size",
18530                &payload.to_string(),
18531                "parallel-group history contains an invalid group size",
18532            )
18533        })?;
18534    let index = payload
18535        .get("parallel_group_index")
18536        .and_then(value_as_u64)
18537        .and_then(|value| usize::try_from(value).ok())
18538        .filter(|value| *value < size)
18539        .ok_or_else(|| {
18540            invalid_recorded_history(
18541                "parallel_group_metadata_invalid",
18542                sequence,
18543                "parallel_group_index within group bounds",
18544                &payload.to_string(),
18545                "parallel-group history contains an invalid member index",
18546            )
18547        })?;
18548    if base_sequence.checked_add(u64::try_from(index).unwrap_or(u64::MAX)) != Some(sequence) {
18549        return Err(invalid_recorded_history(
18550            "parallel_group_metadata_invalid",
18551            sequence,
18552            "base sequence plus member index equals workflow sequence",
18553            &payload.to_string(),
18554            "parallel-group path does not preserve durable workflow position",
18555        ));
18556    }
18557    let mode = payload
18558        .get("parallel_group_mode")
18559        .and_then(Value::as_str)
18560        .unwrap_or("all");
18561    if !matches!(mode, "all" | "select") {
18562        return Err(invalid_recorded_history(
18563            "parallel_group_metadata_invalid",
18564            sequence,
18565            "parallel group mode all or select",
18566            mode,
18567            "parallel-group history contains an unsupported group mode",
18568        ));
18569    }
18570    let expected_id = if mode == "select" {
18571        format!("select-calls:{base_sequence}:{size}")
18572    } else {
18573        format!("{}:{base_sequence}:{size}", parallel_group_prefix(&kind))
18574    };
18575    if group_id != expected_id {
18576        return Err(invalid_recorded_history(
18577            "parallel_group_metadata_invalid",
18578            sequence,
18579            &expected_id,
18580            &group_id,
18581            "parallel-group history contains an incompatible stable group ID",
18582        ));
18583    }
18584    let selection_member_key = if mode == "select" {
18585        Some(selection_key_from_value(
18586            payload.get("selection_member_key"),
18587            sequence,
18588        )?)
18589    } else {
18590        None
18591    };
18592    let selection_member_index = if mode == "select" {
18593        Some(required_parallel_usize(
18594            payload,
18595            "selection_member_index",
18596            sequence,
18597        )?)
18598    } else {
18599        None
18600    };
18601    let selection_member_base_sequence = if mode == "select" {
18602        Some(
18603            payload
18604                .get("selection_member_base_sequence")
18605                .and_then(value_as_u64)
18606                .filter(|value| *value >= base_sequence)
18607                .ok_or_else(|| {
18608                    invalid_recorded_history(
18609                        "parallel_group_metadata_invalid",
18610                        sequence,
18611                        "selection member base within its group",
18612                        &payload.to_string(),
18613                        "selection history contains an invalid member base sequence",
18614                    )
18615                })?,
18616        )
18617    } else {
18618        None
18619    };
18620    let selection_member_size = if mode == "select" {
18621        let member_size = required_parallel_usize(payload, "selection_member_size", sequence)?;
18622        if member_size == 0 {
18623            return Err(invalid_recorded_history(
18624                "parallel_group_metadata_invalid",
18625                sequence,
18626                "positive selection member size",
18627                &payload.to_string(),
18628                "selection history contains an invalid member size",
18629            ));
18630        }
18631        Some(member_size)
18632    } else {
18633        None
18634    };
18635    let selection_member_kind = if mode == "select" {
18636        let kind = payload_string(payload, "selection_member_kind").ok_or_else(|| {
18637            invalid_recorded_history(
18638                "parallel_group_metadata_invalid",
18639                sequence,
18640                "selection member operation kind",
18641                &payload.to_string(),
18642                "selection history is missing its authored member kind",
18643            )
18644        })?;
18645        if !matches!(
18646            kind.as_str(),
18647            "activity" | "child" | "timer" | "signal" | "condition" | "group"
18648        ) {
18649            return Err(invalid_recorded_history(
18650                "parallel_group_metadata_invalid",
18651                sequence,
18652                "activity, child, timer, signal, condition, or group selection member kind",
18653                &kind,
18654                "selection history contains an unsupported member kind",
18655            ));
18656        }
18657        Some(kind)
18658    } else {
18659        None
18660    };
18661    if let (Some(member_base), Some(member_size)) =
18662        (selection_member_base_sequence, selection_member_size)
18663    {
18664        let member_end = member_base
18665            .checked_add(u64::try_from(member_size).unwrap_or(u64::MAX))
18666            .ok_or_else(|| {
18667                invalid_recorded_history(
18668                    "parallel_group_metadata_invalid",
18669                    sequence,
18670                    "bounded selection member range",
18671                    &payload.to_string(),
18672                    "selection member range overflowed",
18673                )
18674            })?;
18675        let group_end = base_sequence.saturating_add(u64::try_from(size).unwrap_or(u64::MAX));
18676        if sequence < member_base || sequence >= member_end || member_end > group_end {
18677            return Err(invalid_recorded_history(
18678                "parallel_group_metadata_invalid",
18679                sequence,
18680                "workflow sequence within one bounded selection member",
18681                &payload.to_string(),
18682                "selection member range does not contain its durable leaf",
18683            ));
18684        }
18685    }
18686    Ok(ParallelGroupMetadata {
18687        parallel_group_id: group_id,
18688        parallel_group_kind: kind,
18689        parallel_group_base_sequence: base_sequence,
18690        parallel_group_size: size,
18691        parallel_group_index: index,
18692        parallel_group_mode: (mode == "select").then(|| "select".to_string()),
18693        selection_member_key,
18694        selection_member_index,
18695        selection_member_base_sequence,
18696        selection_member_size,
18697        selection_member_kind,
18698    })
18699}
18700
18701fn required_parallel_usize(payload: &Value, field: &str, sequence: u64) -> Result<usize> {
18702    payload
18703        .get(field)
18704        .and_then(value_as_u64)
18705        .and_then(|value| usize::try_from(value).ok())
18706        .ok_or_else(|| {
18707            invalid_recorded_history(
18708                "parallel_group_metadata_invalid",
18709                sequence,
18710                &format!("non-negative integer {field}"),
18711                &payload.to_string(),
18712                "selection history contains invalid member metadata",
18713            )
18714        })
18715}
18716
18717fn selection_key_from_value(value: Option<&Value>, sequence: u64) -> Result<SelectionKey> {
18718    match value {
18719        Some(Value::String(value)) if !value.is_empty() => Ok(SelectionKey::Name(value.clone())),
18720        Some(value) => value_as_u64(value)
18721            .and_then(|value| usize::try_from(value).ok())
18722            .map(SelectionKey::Index)
18723            .ok_or_else(|| {
18724                invalid_recorded_history(
18725                    "selection_member_key_invalid",
18726                    sequence,
18727                    "non-empty string or non-negative integer member key",
18728                    &value.to_string(),
18729                    "selection history contains an invalid member key",
18730                )
18731            }),
18732        None => Err(invalid_recorded_history(
18733            "selection_member_key_missing",
18734            sequence,
18735            "selection_member_key",
18736            "<missing>",
18737            "selection history is missing its stable member key",
18738        )),
18739    }
18740}
18741
18742fn recorded_parallel_group_path(
18743    events: &[&HistoryEvent],
18744    sequence: u64,
18745) -> Result<Option<Vec<ParallelGroupMetadata>>> {
18746    let mut recorded: Option<Vec<ParallelGroupMetadata>> = None;
18747    for event in events {
18748        let payload = &event.payload;
18749        let has_metadata = payload.get("parallel_group_path").is_some()
18750            || payload.get("parallel_group_id").is_some()
18751            || payload.get("parallel_group_kind").is_some()
18752            || payload.get("parallel_group_base_sequence").is_some()
18753            || payload.get("parallel_group_size").is_some()
18754            || payload.get("parallel_group_index").is_some()
18755            || payload.get("parallel_group_mode").is_some()
18756            || payload.get("selection_member_key").is_some();
18757        if !has_metadata {
18758            continue;
18759        }
18760
18761        let top_level = recorded_parallel_group_entry(payload, sequence)?;
18762        let path = match payload.get("parallel_group_path") {
18763            None => vec![top_level.clone()],
18764            Some(Value::Array(entries)) if !entries.is_empty() => entries
18765                .iter()
18766                .map(|entry| recorded_parallel_group_entry(entry, sequence))
18767                .collect::<Result<Vec<_>>>()?,
18768            Some(value) => {
18769                return Err(invalid_recorded_history(
18770                    "parallel_group_metadata_invalid",
18771                    sequence,
18772                    "non-empty parallel_group_path list",
18773                    &value.to_string(),
18774                    "parallel-group history contains an invalid group path",
18775                ));
18776            }
18777        };
18778        if path.last() != Some(&top_level) {
18779            return Err(invalid_recorded_history(
18780                "parallel_group_metadata_invalid",
18781                sequence,
18782                &serde_json::to_string(&path.last()).unwrap_or_default(),
18783                &serde_json::to_string(&top_level).unwrap_or_default(),
18784                "parallel-group top-level fields do not match the innermost path entry",
18785            ));
18786        }
18787        if recorded.as_ref().is_some_and(|existing| existing != &path) {
18788            return Err(invalid_recorded_history(
18789                "parallel_group_history_conflict",
18790                sequence,
18791                &serde_json::to_string(&recorded.as_ref()).unwrap_or_default(),
18792                &serde_json::to_string(&path).unwrap_or_default(),
18793                "parallel-group metadata changed between scheduling and resolution history",
18794            ));
18795        }
18796        recorded = Some(path);
18797    }
18798    Ok(recorded)
18799}
18800
18801fn recorded_commands(
18802    events: &[HistoryEvent],
18803    fallback_codec: &str,
18804    parent: WorkflowIdentity,
18805) -> Result<Vec<RecordedCommand>> {
18806    let mut events_by_sequence: BTreeMap<u64, Vec<&HistoryEvent>> = BTreeMap::new();
18807    let mut last_new_sequence = None;
18808
18809    for event in events {
18810        let is_activity = matches!(
18811            event.event_type.as_str(),
18812            "ActivityScheduled"
18813                | "ActivityStarted"
18814                | "ActivityHeartbeatRecorded"
18815                | "ActivityRetryScheduled"
18816                | "ActivityCompleted"
18817                | "ActivityFailed"
18818                | "ActivityCancelled"
18819                | "ActivityTimedOut"
18820        );
18821        let is_workflow_timer = matches!(
18822            event.event_type.as_str(),
18823            "TimerScheduled" | "TimerCancelled" | "TimerFired"
18824        ) && !is_internal_timer_event(event);
18825        let is_child_workflow = matches!(
18826            event.event_type.as_str(),
18827            "ChildWorkflowScheduled"
18828                | "ChildRunStarted"
18829                | "ChildRunCompleted"
18830                | "ChildRunFailed"
18831                | "ChildRunCancelled"
18832                | "ChildRunTerminated"
18833        );
18834        let is_signal_wait = is_recorded_signal_wait_event(event);
18835        let is_condition_wait = is_recorded_condition_wait_event(event);
18836        let is_search_attributes = event.event_type == "SearchAttributesUpserted";
18837        let is_side_effect = event.event_type == "SideEffectRecorded";
18838        let is_version_marker = event.event_type == "VersionMarkerRecorded";
18839        let is_memo = event.event_type == "MemoUpserted";
18840        let is_external_signal = external_signal::is_event(event);
18841        let is_service_operation = nexus::is_service_event(event);
18842        if !is_activity
18843            && !is_workflow_timer
18844            && !is_child_workflow
18845            && !is_signal_wait
18846            && !is_condition_wait
18847            && !is_search_attributes
18848            && !is_side_effect
18849            && !is_version_marker
18850            && !is_memo
18851            && !is_external_signal
18852            && !is_service_operation
18853        {
18854            continue;
18855        }
18856
18857        let sequence = durable_event_sequence(event).ok_or_else(|| {
18858            Error::NonDeterministicReplay(ReplayFailure::new(
18859                "durable_command_sequence_missing",
18860                None,
18861                Some("positive workflow sequence".to_string()),
18862                Some(event.event_type.clone()),
18863                "durable command history event has no workflow sequence",
18864            ))
18865        })?;
18866        if sequence == 0 {
18867            return Err(Error::NonDeterministicReplay(ReplayFailure::new(
18868                "durable_command_sequence_invalid",
18869                Some(sequence),
18870                Some("positive workflow sequence".to_string()),
18871                Some(sequence.to_string()),
18872                "durable command history uses an invalid workflow sequence",
18873            )));
18874        }
18875        if !events_by_sequence.contains_key(&sequence) {
18876            if let Some(previous) = last_new_sequence {
18877                if sequence < previous {
18878                    return Err(invalid_recorded_history(
18879                        "durable_command_sequence_mismatch",
18880                        sequence,
18881                        &format!("workflow sequence greater than {previous}"),
18882                        &sequence.to_string(),
18883                        "durable commands are not strictly ordered by their recorded workflow sequence",
18884                    ));
18885                }
18886            }
18887            last_new_sequence = Some(sequence);
18888        }
18889        events_by_sequence.entry(sequence).or_default().push(event);
18890    }
18891
18892    let commands: Vec<RecordedCommand> = events_by_sequence
18893        .into_iter()
18894        .map(|(sequence, sequence_events)| {
18895            let activity_events: Vec<_> = sequence_events
18896                .iter()
18897                .copied()
18898                .filter(|event| event.event_type.starts_with("Activity"))
18899                .collect();
18900            let timer_events: Vec<_> = sequence_events
18901                .iter()
18902                .copied()
18903                .filter(|event| event.event_type.starts_with("Timer"))
18904                .collect();
18905            let child_events: Vec<_> = sequence_events
18906                .iter()
18907                .copied()
18908                .filter(|event| {
18909                    event.event_type == "ChildWorkflowScheduled"
18910                        || event.event_type.starts_with("ChildRun")
18911                })
18912                .collect();
18913            let signal_wait_events: Vec<_> = sequence_events
18914                .iter()
18915                .copied()
18916                .filter(|event| is_recorded_signal_wait_event(event))
18917                .collect();
18918            let condition_wait_events: Vec<_> = sequence_events
18919                .iter()
18920                .copied()
18921                .filter(|event| is_recorded_condition_wait_event(event))
18922                .collect();
18923            let search_attribute_events: Vec<_> = sequence_events
18924                .iter()
18925                .copied()
18926                .filter(|event| event.event_type == "SearchAttributesUpserted")
18927                .collect();
18928            let side_effect_events: Vec<_> = sequence_events
18929                .iter()
18930                .copied()
18931                .filter(|event| event.event_type == "SideEffectRecorded")
18932                .collect();
18933            let version_marker_events: Vec<_> = sequence_events
18934                .iter()
18935                .copied()
18936                .filter(|event| event.event_type == "VersionMarkerRecorded")
18937                .collect();
18938            let memo_events: Vec<_> = sequence_events
18939                .iter()
18940                .copied()
18941                .filter(|event| event.event_type == "MemoUpserted")
18942                .collect();
18943            let service_events: Vec<_> = sequence_events.iter().copied()
18944                .filter(|event| nexus::is_service_event(event)).collect();
18945            let external_signal_events: Vec<_> = sequence_events
18946                .iter()
18947                .copied()
18948                .filter(|event| external_signal::is_event(event))
18949                .collect();
18950
18951            let command_kind_count = usize::from(!activity_events.is_empty())
18952                + usize::from(!timer_events.is_empty())
18953                + usize::from(!child_events.is_empty())
18954                + usize::from(!signal_wait_events.is_empty())
18955                + usize::from(!condition_wait_events.is_empty())
18956                + usize::from(!search_attribute_events.is_empty())
18957                + usize::from(!side_effect_events.is_empty())
18958                + usize::from(!version_marker_events.is_empty())
18959                + usize::from(!memo_events.is_empty())
18960                + usize::from(!service_events.is_empty())
18961                + usize::from(!external_signal_events.is_empty());
18962            if command_kind_count > 1 {
18963                let actual = [
18964                    (!activity_events.is_empty()).then_some("activity"),
18965                    (!timer_events.is_empty()).then_some("timer"),
18966                    (!child_events.is_empty()).then_some("child workflow"),
18967                    (!signal_wait_events.is_empty()).then_some("signal wait"),
18968                    (!condition_wait_events.is_empty()).then_some("condition wait"),
18969                    (!search_attribute_events.is_empty()).then_some("search-attribute update"),
18970                    (!side_effect_events.is_empty()).then_some("side effect"),
18971                    (!version_marker_events.is_empty()).then_some("version marker"),
18972                    (!memo_events.is_empty()).then_some("memo upsert"),
18973                    (!service_events.is_empty()).then_some("service operation"),
18974                    (!external_signal_events.is_empty()).then_some("external signal"),
18975                ]
18976                .into_iter()
18977                .flatten()
18978                .collect::<Vec<_>>()
18979                .join(" and ");
18980                return Err(invalid_recorded_history(
18981                    "durable_command_sequence_collision",
18982                    sequence,
18983                    "one durable command kind",
18984                    &actual,
18985                    "one workflow sequence records more than one durable command kind",
18986                ));
18987            }
18988
18989            if !external_signal_events.is_empty() {
18990                return external_signal::recorded(&external_signal_events, sequence, fallback_codec);
18991            }
18992
18993            if !service_events.is_empty() {
18994                return Ok(RecordedCommand::ServiceOperation {
18995                    sequence, call: nexus::recorded_call(&service_events, sequence, fallback_codec, &parent)?,
18996                });
18997            }
18998
18999            if !activity_events.is_empty() {
19000                let parallel_group_path =
19001                    recorded_parallel_group_path(&activity_events, sequence)?;
19002                let scheduled_count = activity_events
19003                    .iter()
19004                    .filter(|event| event.event_type == "ActivityScheduled")
19005                    .count();
19006                if scheduled_count > 1 {
19007                    return Err(invalid_recorded_history(
19008                        "duplicate_activity_schedule",
19009                        sequence,
19010                        "at most one ActivityScheduled event",
19011                        "multiple ActivityScheduled events",
19012                        "activity history schedules more than one command at one workflow sequence",
19013                    ));
19014                }
19015                let activity_type = activity_events.iter().find_map(|event| {
19016                    event
19017                        .payload
19018                        .get("activity_type")
19019                        .or_else(|| event.payload.get("activity_name"))
19020                        .and_then(Value::as_str)
19021                        .map(str::to_string)
19022                });
19023                if activity_events.iter().filter_map(|event| {
19024                    event
19025                        .payload
19026                        .get("activity_type")
19027                        .or_else(|| event.payload.get("activity_name"))
19028                        .and_then(Value::as_str)
19029                }).any(|candidate| Some(candidate) != activity_type.as_deref()) {
19030                    return Err(invalid_recorded_history(
19031                        "activity_identity_mismatch",
19032                        sequence,
19033                        activity_type.as_deref().unwrap_or("one activity identity"),
19034                        "conflicting activity identities",
19035                        "activity lifecycle events at one workflow sequence disagree on identity",
19036                    ));
19037                }
19038                let terminal: Vec<_> = activity_events
19039                    .iter()
19040                    .copied()
19041                    .filter(|event| {
19042                        matches!(
19043                            event.event_type.as_str(),
19044                            "ActivityCompleted"
19045                                | "ActivityFailed"
19046                                | "ActivityCancelled"
19047                                | "ActivityTimedOut"
19048                        )
19049                    })
19050                    .collect();
19051                let duplicate_delivery = terminal.first().is_some_and(|first| {
19052                    terminal.iter().all(|event| {
19053                        event.event_type == first.event_type && event.payload == first.payload
19054                    })
19055                });
19056                if terminal.len() > 1 && !duplicate_delivery {
19057                    return Err(invalid_recorded_history(
19058                        "duplicate_activity_terminal_event",
19059                        sequence,
19060                        "at most one terminal activity event",
19061                        "multiple terminal activity events",
19062                        "activity history settles one command more than once",
19063                    ));
19064                }
19065                let outcome = terminal
19066                    .first()
19067                    .map(|event| activity_outcome(event, fallback_codec, activity_type.clone()))
19068                    .transpose()?;
19069                let execution_mode = recorded_activity_execution_mode(&activity_events, sequence)?;
19070                let activity_snapshot = activity_events
19071                    .iter()
19072                    .find(|event| event.event_type == "ActivityScheduled")
19073                    .and_then(|event| event.payload.get("activity"))
19074                    .and_then(Value::as_object);
19075                let options = Some(match activity_snapshot {
19076                    Some(activity) => RecordedActivityOptions {
19077                        task_queue: recorded_optional_string(activity, "queue"),
19078                        execution_mode,
19079                        retry_policy: recorded_activity_retry_snapshot(
19080                            activity.get("retry_policy"),
19081                        ),
19082                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
19083                    },
19084                    None => RecordedActivityOptions {
19085                        task_queue: RecordedSnapshotValue::Unknown,
19086                        execution_mode,
19087                        retry_policy: recorded_activity_retry_snapshot(None),
19088                        worker_session: worker_session::recorded_session(&activity_events, sequence)?,
19089                    },
19090                });
19091                return Ok(RecordedCommand::Activity {
19092                    sequence,
19093                    activity_type,
19094                    cancellation_policy: recorded_activity_cancellation_policy(&activity_events, sequence)?,
19095                    options,
19096                    outcome,
19097                    parallel_group_path,
19098                });
19099            }
19100
19101            if !child_events.is_empty() {
19102                let parallel_group_path = recorded_parallel_group_path(&child_events, sequence)?;
19103                let scheduled: Vec<_> = child_events
19104                    .iter()
19105                    .copied()
19106                    .filter(|event| event.event_type == "ChildWorkflowScheduled")
19107                    .collect();
19108                if scheduled.len() != 1 {
19109                    return Err(invalid_recorded_history(
19110                        "child_workflow_schedule_missing_or_duplicate",
19111                        sequence,
19112                        "one ChildWorkflowScheduled event",
19113                        &format!("{} ChildWorkflowScheduled events", scheduled.len()),
19114                        "child workflow replay requires exactly one recorded schedule event",
19115                    ));
19116                }
19117                let policies = recorded_child_policies(&child_events, scheduled[0], sequence)?;
19118                let workflow_type = child_events.iter().find_map(|event| {
19119                    event
19120                        .payload
19121                        .get("child_workflow_type")
19122                        .or_else(|| event.payload.get("workflow_type"))
19123                        .and_then(Value::as_str)
19124                        .filter(|value| !value.is_empty())
19125                        .map(str::to_string)
19126                });
19127                if child_events
19128                    .iter()
19129                    .filter_map(|event| {
19130                        event
19131                            .payload
19132                            .get("child_workflow_type")
19133                            .or_else(|| event.payload.get("workflow_type"))
19134                            .and_then(Value::as_str)
19135                    })
19136                    .any(|candidate| Some(candidate) != workflow_type.as_deref())
19137                {
19138                    return Err(invalid_recorded_history(
19139                        "child_workflow_identity_mismatch",
19140                        sequence,
19141                        workflow_type
19142                            .as_deref()
19143                            .unwrap_or("one child workflow type"),
19144                        "conflicting child workflow types",
19145                        "child workflow lifecycle events at one sequence disagree on type",
19146                    ));
19147                }
19148                let mut outcomes = child_workflow_outcomes(
19149                    &child_events.iter().map(|event| (*event).clone()).collect::<Vec<_>>(),
19150                    fallback_codec,
19151                    parent.clone(),
19152                )?;
19153                let terminal_events = child_events
19154                    .iter()
19155                    .copied()
19156                    .filter(|event| event.event_type.starts_with("ChildRun"))
19157                    .collect::<Vec<_>>();
19158                let duplicate_delivery = terminal_events.first().is_some_and(|first| {
19159                    terminal_events.iter().all(|event| {
19160                        event.event_type == first.event_type && event.payload == first.payload
19161                    })
19162                });
19163                if outcomes.len() > 1 && !duplicate_delivery {
19164                    return Err(invalid_recorded_history(
19165                        "duplicate_child_workflow_terminal_event",
19166                        sequence,
19167                        "at most one terminal child event",
19168                        "multiple terminal child events",
19169                        "child workflow history settles one command more than once",
19170                    ));
19171                }
19172                return Ok(RecordedCommand::ChildWorkflow {
19173                    sequence,
19174                    workflow_type,
19175                    policies,
19176                    outcome: outcomes.pop(),
19177                    parallel_group_path,
19178                });
19179            }
19180
19181            if !signal_wait_events.is_empty() {
19182                let opened: Vec<_> = signal_wait_events
19183                    .iter()
19184                    .copied()
19185                    .filter(|event| event.event_type == "SignalWaitOpened")
19186                    .collect();
19187                if opened.len() != 1 {
19188                    return Err(invalid_recorded_history(
19189                        "signal_wait_open_missing_or_duplicate",
19190                        sequence,
19191                        "one SignalWaitOpened event",
19192                        &format!("{} SignalWaitOpened events", opened.len()),
19193                        "signal replay requires exactly one canonical wait-open event",
19194                    ));
19195                }
19196
19197                let applied: Vec<_> = signal_wait_events
19198                    .iter()
19199                    .copied()
19200                    .filter(|event| event.event_type == "SignalApplied")
19201                    .collect();
19202                if applied.len() > 1 {
19203                    return Err(invalid_recorded_history(
19204                        "duplicate_signal_wait_apply",
19205                        sequence,
19206                        "at most one SignalApplied event",
19207                        "multiple SignalApplied events",
19208                        "signal history applies one durable wait more than once",
19209                    ));
19210                }
19211
19212                let signal_names = signal_wait_events
19213                    .iter()
19214                    .map(|event| required_signal_wait_name(event, sequence))
19215                    .collect::<Result<Vec<_>>>()?;
19216                let signal_name = signal_names
19217                    .first()
19218                    .expect("signal wait events are not empty")
19219                    .clone();
19220                if signal_names.iter().any(|candidate| candidate != &signal_name) {
19221                    return Err(invalid_recorded_history(
19222                        "signal_wait_identity_mismatch",
19223                        sequence,
19224                        &signal_name,
19225                        "conflicting signal names",
19226                        "signal wait lifecycle events at one workflow sequence disagree on identity",
19227                    ));
19228                }
19229                let value = applied
19230                    .first()
19231                    .map(|event| decode_signal_event_arguments(event, fallback_codec))
19232                    .transpose()?;
19233                return Ok(RecordedCommand::SignalWait {
19234                    sequence,
19235                    signal_name,
19236                    value,
19237                    parallel_group_path: recorded_parallel_group_path(
19238                        &signal_wait_events,
19239                        sequence,
19240                    )?,
19241                });
19242            }
19243
19244            if !condition_wait_events.is_empty() {
19245                return recorded_condition_wait(
19246                    sequence,
19247                    &condition_wait_events,
19248                    events,
19249                );
19250            }
19251
19252            if !search_attribute_events.is_empty() {
19253                if search_attribute_events.len() != 1 {
19254                    return Err(invalid_recorded_history(
19255                        "duplicate_search_attribute_update",
19256                        sequence,
19257                        "one SearchAttributesUpserted event",
19258                        &format!(
19259                            "{} SearchAttributesUpserted events",
19260                            search_attribute_events.len()
19261                        ),
19262                        "search-attribute history records one workflow command more than once",
19263                    ));
19264                }
19265                let payload = &search_attribute_events[0].payload;
19266                let attributes = payload
19267                    .get("attributes")
19268                    .filter(|value| value.as_object().is_some_and(|values| !values.is_empty()))
19269                    .cloned()
19270                    .ok_or_else(|| {
19271                        invalid_recorded_history(
19272                            "search_attribute_update_missing",
19273                            sequence,
19274                            "non-empty attributes object",
19275                            "missing or invalid attributes",
19276                            "search-attribute history is missing its recorded mutation",
19277                        )
19278                    })?;
19279                let attribute_types =
19280                    recorded_search_attribute_types(payload, &attributes, sequence)?;
19281                return Ok(RecordedCommand::SearchAttributes {
19282                    sequence,
19283                    attributes,
19284                    attribute_types,
19285                });
19286            }
19287
19288            if !side_effect_events.is_empty() {
19289                if side_effect_events.len() != 1 {
19290                    return Err(invalid_recorded_history(
19291                        "duplicate_side_effect_record",
19292                        sequence,
19293                        "one SideEffectRecorded event",
19294                        &format!("{} SideEffectRecorded events", side_effect_events.len()),
19295                        "side-effect history records one workflow command more than once",
19296                    ));
19297                }
19298                let event = side_effect_events[0];
19299                let result = event.payload.get("result").ok_or_else(|| {
19300                    invalid_recorded_history(
19301                        "side_effect_result_missing",
19302                        sequence,
19303                        "recorded result payload",
19304                        "missing result",
19305                        "side-effect history is missing its recorded value",
19306                    )
19307                })?;
19308                let has_published_envelope = result.as_str().is_some()
19309                    || result.as_object().is_some_and(|envelope| {
19310                        envelope.get("codec").and_then(Value::as_str).is_some()
19311                            && envelope.get("blob").and_then(Value::as_str).is_some()
19312                    });
19313                if !has_published_envelope {
19314                    return Err(invalid_recorded_history(
19315                        "side_effect_payload_malformed",
19316                        sequence,
19317                        "payload blob or {codec, blob} envelope",
19318                        &result.to_string(),
19319                        "side-effect history result does not use a published payload envelope",
19320                    ));
19321                }
19322                let codec = event
19323                    .payload
19324                    .get("payload_codec")
19325                    .and_then(Value::as_str)
19326                    .unwrap_or(fallback_codec);
19327                let value = decode_wire_avro_value(result, codec).map_err(|error| {
19328                    if error.to_string().contains("unsupported_payload_codec") {
19329                        return error;
19330                    }
19331
19332                    invalid_recorded_history(
19333                        "side_effect_payload_incompatible",
19334                        sequence,
19335                        &format!("valid {codec} payload envelope"),
19336                        &error.to_string(),
19337                        "side-effect history payload cannot be decoded with its recorded codec",
19338                    )
19339                })?;
19340                return Ok(RecordedCommand::SideEffect { sequence, value });
19341            }
19342
19343            if !version_marker_events.is_empty() {
19344                if version_marker_events.len() != 1 {
19345                    return Err(invalid_recorded_history(
19346                        "duplicate_version_marker_record",
19347                        sequence,
19348                        "one VersionMarkerRecorded event",
19349                        &format!("{} VersionMarkerRecorded events", version_marker_events.len()),
19350                        "version-marker history records one workflow command more than once",
19351                    ));
19352                }
19353                let payload = &version_marker_events[0].payload;
19354                let change_id = payload
19355                    .get("change_id")
19356                    .and_then(Value::as_str)
19357                    .filter(|value| !value.is_empty())
19358                    .map(str::to_string)
19359                    .ok_or_else(|| {
19360                        invalid_recorded_history(
19361                            "version_marker_field_missing",
19362                            sequence,
19363                            "non-empty change_id",
19364                            "missing or invalid change_id",
19365                            "version-marker history is missing its stable change ID",
19366                        )
19367                    })?;
19368                let version = required_version_i32(payload, "version", sequence)?;
19369                let min_supported = required_version_i32(payload, "min_supported", sequence)?;
19370                let max_supported = required_version_i32(payload, "max_supported", sequence)?;
19371                if min_supported > max_supported || version < min_supported || version > max_supported {
19372                    return Err(invalid_recorded_history(
19373                        "version_marker_history_range_invalid",
19374                        sequence,
19375                        "min_supported <= version <= max_supported",
19376                        &format!("{min_supported} <= {version} <= {max_supported}"),
19377                        "recorded version marker contains an internally incompatible range",
19378                    ));
19379                }
19380                return Ok(RecordedCommand::VersionMarker {
19381                    sequence,
19382                    change_id,
19383                    version,
19384                });
19385            }
19386
19387            if !memo_events.is_empty() {
19388                if memo_events.len() != 1 {
19389                    return Err(invalid_recorded_history(
19390                        "duplicate_memo_upsert_record",
19391                        sequence,
19392                        "one MemoUpserted event",
19393                        &format!("{} MemoUpserted events", memo_events.len()),
19394                        "memo history records one workflow update more than once",
19395                    ));
19396                }
19397                let payload = &memo_events[0].payload;
19398                let entries = payload.get("entries").cloned().ok_or_else(|| {
19399                    invalid_recorded_history(
19400                        "memo_entries_missing",
19401                        sequence,
19402                        "memo entries object",
19403                        "missing entries",
19404                        "MemoUpserted history is missing replay identity entries",
19405                    )
19406                })?;
19407                let entries = decode_memo_history_map(&entries, true).map_err(|error| {
19408                    invalid_recorded_history(
19409                        "memo_entries_invalid",
19410                        sequence,
19411                        "valid canonical memo entries",
19412                        &error.to_string(),
19413                        "MemoUpserted history contains invalid replay identity entries",
19414                    )
19415                })?;
19416                let merged = payload.get("merged").cloned().ok_or_else(|| {
19417                    invalid_recorded_history(
19418                        "memo_merged_projection_missing",
19419                        sequence,
19420                        "merged memo projection",
19421                        "missing merged",
19422                        "MemoUpserted history is missing its merged projection",
19423                    )
19424                })?;
19425                decode_memo_history_map(&merged, false).map_err(|error| {
19426                    invalid_recorded_history(
19427                        "memo_merged_projection_invalid",
19428                        sequence,
19429                        "valid merged memo projection",
19430                        &error.to_string(),
19431                        "MemoUpserted history contains an invalid merged projection",
19432                    )
19433                })?;
19434
19435                return Ok(RecordedCommand::Memo { sequence, entries });
19436            }
19437            let scheduled: Vec<_> = timer_events
19438                .iter()
19439                .copied()
19440                .filter(|event| event.event_type == "TimerScheduled")
19441                .collect();
19442            let fired: Vec<_> = timer_events
19443                .iter()
19444                .copied()
19445                .filter(|event| event.event_type == "TimerFired")
19446                .collect();
19447            if scheduled.len() != 1 {
19448                return Err(invalid_recorded_history(
19449                    "timer_schedule_missing_or_duplicate",
19450                    sequence,
19451                    "one TimerScheduled event",
19452                    &format!("{} TimerScheduled events", scheduled.len()),
19453                    "timer replay requires exactly one recorded schedule event",
19454                ));
19455            }
19456            if fired.len() > 1 {
19457                return Err(invalid_recorded_history(
19458                    "duplicate_timer_fire",
19459                    sequence,
19460                    "at most one TimerFired event",
19461                    "multiple TimerFired events",
19462                    "timer history contains more than one fire event for a workflow sequence",
19463                ));
19464            }
19465
19466            let scheduled = scheduled[0];
19467            let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
19468            let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
19469            if let Some(fired) = fired.first() {
19470                let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
19471                if fired_timer_id != timer_id {
19472                    return Err(invalid_recorded_history(
19473                        "timer_identity_mismatch",
19474                        sequence,
19475                        &timer_id,
19476                        &fired_timer_id,
19477                        "TimerFired does not correspond to the recorded TimerScheduled event",
19478                    ));
19479                }
19480                let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
19481                if fired_delay != delay_seconds {
19482                    return Err(invalid_recorded_history(
19483                        "timer_history_delay_mismatch",
19484                        sequence,
19485                        &delay_seconds.to_string(),
19486                        &fired_delay.to_string(),
19487                        "TimerScheduled and TimerFired record different delays",
19488                    ));
19489                }
19490            }
19491
19492            Ok(RecordedCommand::Timer {
19493                sequence,
19494                delay_seconds,
19495                fired: !fired.is_empty(),
19496                parallel_group_path: recorded_parallel_group_path(&timer_events, sequence)?,
19497            })
19498        })
19499        .collect::<Result<_>>()?;
19500
19501    let mut marker_decisions = HashMap::new();
19502    for command in &commands {
19503        if let RecordedCommand::VersionMarker {
19504            sequence,
19505            change_id,
19506            version,
19507        } = command
19508        {
19509            if let Some((first_version, first_sequence)) = marker_decisions.get(change_id) {
19510                if version != first_version {
19511                    return Err(invalid_recorded_history(
19512                        "version_marker_conflict",
19513                        *sequence,
19514                        &format!("version {first_version} for change ID {change_id:?} at sequence {first_sequence}"),
19515                        &format!("version {version} at sequence {sequence}"),
19516                        "workflow history contains conflicting decisions for one stable change ID",
19517                    ));
19518                }
19519            } else {
19520                marker_decisions.insert(change_id.clone(), (*version, *sequence));
19521            }
19522        }
19523    }
19524
19525    Ok(commands)
19526}
19527
19528/// Within a run of commands from one parallel group, move each physical
19529/// condition reopen directly after the earlier waits of the same member; other
19530/// leaves keep their place.
19531///
19532/// Members replay in order from one shared cursor, and a member's chain reads
19533/// only adjacent commands. When several members are woken in one task, the
19534/// Server records their reopens after all originals (a1, b1, a2, b2), so each
19535/// chain would stop at its sibling and leave reopens unconsumed (#191).
19536/// Outcomes are looked up by sequence and occurrence, so only consumption order
19537/// changes.
19538fn group_condition_reopens_by_member(commands: Vec<RecordedCommand>) -> Vec<RecordedCommand> {
19539    // Every leaf of a group belongs to the run; a condition member is keyed by
19540    // its occurrence so its reopens join it, any other leaf by its sequence so
19541    // it keeps its place (#194: a timer between condition members).
19542    fn grouped_member(command: &RecordedCommand) -> Option<(String, String)> {
19543        let (path, member) = match command {
19544            RecordedCommand::ConditionWait {
19545                occurrence_id,
19546                parallel_group_path: Some(path),
19547                ..
19548            } => (path, format!("condition:{occurrence_id}")),
19549            RecordedCommand::Activity {
19550                parallel_group_path: Some(path),
19551                ..
19552            }
19553            | RecordedCommand::Timer {
19554                parallel_group_path: Some(path),
19555                ..
19556            }
19557            | RecordedCommand::ChildWorkflow {
19558                parallel_group_path: Some(path),
19559                ..
19560            }
19561            | RecordedCommand::SignalWait {
19562                parallel_group_path: Some(path),
19563                ..
19564            } => (path, format!("leaf:{}", command.sequence())),
19565            _ => return None,
19566        };
19567        path.first()
19568            .map(|entry| (entry.parallel_group_id.clone(), member))
19569    }
19570    let mut ordered = Vec::with_capacity(commands.len());
19571    let mut run: Vec<RecordedCommand> = Vec::new();
19572    let mut run_group: Option<String> = None;
19573    let flush = |run: &mut Vec<RecordedCommand>, ordered: &mut Vec<RecordedCommand>| {
19574        let mut members: Vec<(String, Vec<RecordedCommand>)> = Vec::new();
19575        for command in run.drain(..) {
19576            let occurrence = grouped_member(&command)
19577                .map(|(_, occurrence)| occurrence)
19578                .unwrap_or_default();
19579            match members.iter_mut().find(|(member, _)| *member == occurrence) {
19580                Some((_, chain)) => chain.push(command),
19581                None => members.push((occurrence, vec![command])),
19582            }
19583        }
19584        ordered.extend(members.into_iter().flat_map(|(_, chain)| chain));
19585    };
19586    for command in commands {
19587        match grouped_member(&command) {
19588            Some((group, _)) if run_group.as_deref() == Some(group.as_str()) => run.push(command),
19589            Some((group, _)) => {
19590                flush(&mut run, &mut ordered);
19591                run_group = Some(group);
19592                run.push(command);
19593            }
19594            None => {
19595                flush(&mut run, &mut ordered);
19596                run_group = None;
19597                ordered.push(command);
19598            }
19599        }
19600    }
19601    flush(&mut run, &mut ordered);
19602    ordered
19603}
19604
19605/// A two-member condition group where only member `a` was reopened:
19606/// a1 (seq 1), b1 (seq 2), a1 satisfied, a2 (seq 3). Replay consumes it as
19607/// a1, a2, b1, so the last recorded command is not the highest sequence.
19608#[cfg(test)]
19609fn one_sided_grouped_reopen_history(extra: Vec<HistoryEvent>) -> Vec<HistoryEvent> {
19610    let member = |event_type: &str, sequence: u64, index: u64, key: &str| HistoryEvent {
19611        event_type: event_type.to_string(),
19612        payload: json!({
19613            "sequence": sequence,
19614            "condition_wait_id": format!("condition:{sequence}"),
19615            "condition_wait_occurrence_id": format!("rust:condition-wait:{index}"),
19616            "condition_key": key,
19617            "condition_definition_fingerprint": format!("sha256:{key}-v1"),
19618            "timeout_seconds": 300,
19619            "parallel_group_id": "parallel-calls:1:2",
19620            "parallel_group_kind": "condition",
19621            "parallel_group_base_sequence": 1,
19622            "parallel_group_size": 2,
19623            "parallel_group_index": index,
19624        }),
19625        raw: HashMap::new(),
19626    };
19627    let mut history = vec![
19628        member("ConditionWaitOpened", 1, 0, "votes"),
19629        member("ConditionWaitOpened", 2, 1, "approvals"),
19630        member("ConditionWaitSatisfied", 1, 0, "votes"),
19631        member("ConditionWaitOpened", 3, 0, "votes"),
19632    ];
19633    history.extend(extra);
19634    history
19635}
19636
19637impl WorkflowState {
19638    /// The highest recorded durable sequence. Recorded commands are consumed in
19639    /// replay order, which is not always sequence order (grouped condition
19640    /// reopens are ordered by member, #191), so the next authored sequence must
19641    /// not be read from the last command.
19642    fn max_recorded_sequence(&self) -> u64 {
19643        self.recorded_commands
19644            .iter()
19645            .map(RecordedCommand::sequence)
19646            .max()
19647            .unwrap_or(0)
19648    }
19649}
19650
19651fn required_version_i32(payload: &Value, field: &str, sequence: u64) -> Result<i32> {
19652    payload
19653        .get(field)
19654        .and_then(Value::as_i64)
19655        .and_then(|value| i32::try_from(value).ok())
19656        .ok_or_else(|| {
19657            invalid_recorded_history(
19658                "version_marker_field_missing",
19659                sequence,
19660                &format!("integer {field}"),
19661                "missing or out-of-range integer",
19662                "version-marker history is missing a required integer field",
19663            )
19664        })
19665}
19666
19667fn durable_event_sequence(event: &HistoryEvent) -> Option<u64> {
19668    event
19669        .payload
19670        .get("sequence")
19671        .or_else(|| event.payload.get("workflow_sequence"))
19672        .or_else(|| event.raw.get("sequence"))
19673        .or_else(|| event.raw.get("workflow_sequence"))
19674        .and_then(value_as_u64)
19675}
19676
19677fn is_internal_timer_event(event: &HistoryEvent) -> bool {
19678    matches!(
19679        event
19680            .payload
19681            .get("timer_kind")
19682            .or_else(|| event.raw.get("timer_kind"))
19683            .and_then(Value::as_str),
19684        Some("condition_timeout" | "signal_timeout")
19685    )
19686}
19687
19688fn is_recorded_condition_wait_event(event: &HistoryEvent) -> bool {
19689    matches!(
19690        event.event_type.as_str(),
19691        "ConditionWaitOpened" | "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
19692    )
19693}
19694
19695fn recorded_condition_wait(
19696    sequence: u64,
19697    condition_events: &[&HistoryEvent],
19698    all_events: &[HistoryEvent],
19699) -> Result<RecordedCommand> {
19700    let opened = condition_events
19701        .iter()
19702        .copied()
19703        .filter(|event| event.event_type == "ConditionWaitOpened")
19704        .collect::<Vec<_>>();
19705    if opened.len() != 1 {
19706        return Err(invalid_recorded_history(
19707            "condition_wait_open_missing_or_duplicate",
19708            sequence,
19709            "one ConditionWaitOpened event",
19710            &format!("{} ConditionWaitOpened events", opened.len()),
19711            "condition replay requires exactly one canonical wait-open event",
19712        ));
19713    }
19714    let terminal = condition_events
19715        .iter()
19716        .copied()
19717        .filter(|event| {
19718            matches!(
19719                event.event_type.as_str(),
19720                "ConditionWaitSatisfied" | "ConditionWaitTimedOut"
19721            )
19722        })
19723        .collect::<Vec<_>>();
19724    if terminal.len() > 1 {
19725        return Err(invalid_recorded_history(
19726            "duplicate_condition_wait_terminal_event",
19727            sequence,
19728            "at most one condition terminal event",
19729            "multiple condition terminal events",
19730            "condition history settles one durable wait more than once",
19731        ));
19732    }
19733
19734    let opened = opened[0];
19735    let condition_wait_id = required_condition_wait_id(opened, sequence)?;
19736    let occurrence_id = required_condition_wait_occurrence_id(opened, sequence)?;
19737    for event in condition_events
19738        .iter()
19739        .copied()
19740        .filter(|event| !std::ptr::eq(*event, opened))
19741    {
19742        let event_wait_id = required_condition_wait_id(event, sequence)?;
19743        if event_wait_id != condition_wait_id {
19744            return Err(invalid_recorded_history(
19745                "condition_wait_id_mismatch",
19746                sequence,
19747                &condition_wait_id,
19748                &event_wait_id,
19749                "condition lifecycle events at one sequence disagree on wait identity",
19750            ));
19751        }
19752        let event_occurrence_id = required_condition_wait_occurrence_id(event, sequence)?;
19753        if event_occurrence_id != occurrence_id {
19754            return Err(invalid_recorded_history(
19755                "condition_wait_occurrence_history_mismatch",
19756                sequence,
19757                &occurrence_id,
19758                &event_occurrence_id,
19759                "condition lifecycle events at one sequence disagree on authored occurrence identity",
19760            ));
19761        }
19762    }
19763
19764    let condition_key = optional_non_empty_history_string(opened, "condition_key");
19765    let predicate_identity = opened
19766        .payload
19767        .get("condition_definition_fingerprint")
19768        .and_then(Value::as_str)
19769        .filter(|value| !value.is_empty())
19770        .map(str::to_string)
19771        .ok_or_else(|| {
19772            invalid_recorded_history(
19773                "condition_wait_predicate_fingerprint_missing",
19774                sequence,
19775                "non-empty condition_definition_fingerprint",
19776                &opened.event_type,
19777                "canonical condition history is missing its predicate identity",
19778            )
19779        })?;
19780    let timeout_seconds = optional_history_u64(opened, "timeout_seconds", sequence)?;
19781    for event in condition_events
19782        .iter()
19783        .copied()
19784        .filter(|event| !std::ptr::eq(*event, opened))
19785    {
19786        for (field, opened_value) in [
19787            ("condition_key", condition_key.as_deref()),
19788            (
19789                "condition_definition_fingerprint",
19790                Some(predicate_identity.as_str()),
19791            ),
19792        ] {
19793            if let Some(value) = optional_non_empty_history_string(event, field) {
19794                if opened_value.is_some_and(|opened_value| opened_value != value) {
19795                    return Err(invalid_recorded_history(
19796                        "condition_wait_definition_history_mismatch",
19797                        sequence,
19798                        opened_value.unwrap_or_default(),
19799                        &value,
19800                        "condition lifecycle events disagree on the recorded definition",
19801                    ));
19802                }
19803            }
19804        }
19805        if let Some(event_timeout) = optional_history_u64(event, "timeout_seconds", sequence)? {
19806            if timeout_seconds.is_some_and(|opened_timeout| opened_timeout != event_timeout) {
19807                return Err(invalid_recorded_history(
19808                    "condition_wait_definition_history_mismatch",
19809                    sequence,
19810                    &format!("{}s", timeout_seconds.unwrap_or_default()),
19811                    &format!("{event_timeout}s"),
19812                    "condition lifecycle events disagree on the recorded timeout",
19813                ));
19814            }
19815        }
19816    }
19817
19818    let timeout_timer_events = all_events
19819        .iter()
19820        .filter(|event| {
19821            matches!(
19822                event.event_type.as_str(),
19823                "TimerScheduled" | "TimerCancelled" | "TimerFired"
19824            ) && event.payload.get("timer_kind").and_then(Value::as_str)
19825                == Some("condition_timeout")
19826                && event
19827                    .payload
19828                    .get("condition_wait_id")
19829                    .and_then(Value::as_str)
19830                    == Some(condition_wait_id.as_str())
19831        })
19832        .collect::<Vec<_>>();
19833    let scheduled = timeout_timer_events
19834        .iter()
19835        .copied()
19836        .filter(|event| event.event_type == "TimerScheduled")
19837        .collect::<Vec<_>>();
19838    let fired = timeout_timer_events
19839        .iter()
19840        .copied()
19841        .filter(|event| event.event_type == "TimerFired")
19842        .collect::<Vec<_>>();
19843    if scheduled.len() > 1 || fired.len() > 1 || (!fired.is_empty() && scheduled.len() != 1) {
19844        return Err(invalid_recorded_history(
19845            "condition_wait_timeout_history_invalid",
19846            sequence,
19847            "one timeout schedule and at most one fire",
19848            &format!("{} schedules and {} fires", scheduled.len(), fired.len()),
19849            "condition timeout history has a missing or duplicate lifecycle event",
19850        ));
19851    }
19852    if let Some(scheduled) = scheduled.first() {
19853        let timer_id = required_history_string(scheduled, "timer_id", sequence)?;
19854        let delay_seconds = required_history_u64(scheduled, "delay_seconds", sequence)?;
19855        if timeout_seconds.is_some_and(|timeout| timeout != delay_seconds) {
19856            return Err(invalid_recorded_history(
19857                "condition_wait_timeout_delay_mismatch",
19858                sequence,
19859                &format!("{}s", timeout_seconds.unwrap_or_default()),
19860                &format!("{delay_seconds}s"),
19861                "condition timeout timer differs from the wait definition",
19862            ));
19863        }
19864        if let Some(fired) = fired.first() {
19865            let fired_timer_id = required_history_string(fired, "timer_id", sequence)?;
19866            let fired_delay = required_history_u64(fired, "delay_seconds", sequence)?;
19867            if fired_timer_id != timer_id || fired_delay != delay_seconds {
19868                return Err(invalid_recorded_history(
19869                    "condition_wait_timeout_identity_mismatch",
19870                    sequence,
19871                    &format!("{timer_id}:{delay_seconds}s"),
19872                    &format!("{fired_timer_id}:{fired_delay}s"),
19873                    "condition timeout fire does not match its durable schedule",
19874                ));
19875            }
19876        }
19877    }
19878
19879    let result = terminal.first().map(|event| {
19880        if event.event_type == "ConditionWaitTimedOut" {
19881            ConditionWaitResult::TimedOut
19882        } else {
19883            ConditionWaitResult::Satisfied
19884        }
19885    });
19886    let result = if !fired.is_empty() {
19887        if result == Some(ConditionWaitResult::Satisfied) {
19888            return Err(invalid_recorded_history(
19889                "condition_wait_terminal_conflict",
19890                sequence,
19891                "one satisfied or timed-out outcome",
19892                "satisfied event and fired timeout",
19893                "condition history records conflicting terminal outcomes",
19894            ));
19895        }
19896        Some(ConditionWaitResult::TimedOut)
19897    } else {
19898        result
19899    };
19900
19901    Ok(RecordedCommand::ConditionWait {
19902        sequence,
19903        occurrence_id,
19904        condition_key,
19905        predicate_identity,
19906        timeout_seconds,
19907        result,
19908        parallel_group_path: recorded_condition_group_path(condition_events, all_events, sequence)?,
19909    })
19910}
19911
19912fn recorded_condition_group_path(
19913    condition_events: &[&HistoryEvent],
19914    all_events: &[HistoryEvent],
19915    sequence: u64,
19916) -> Result<Option<Vec<ParallelGroupMetadata>>> {
19917    let opened = condition_events
19918        .iter()
19919        .copied()
19920        .find(|event| event.event_type == "ConditionWaitOpened")
19921        .expect("canonical condition opener is validated first");
19922    let occurrence = required_condition_wait_occurrence_id(opened, sequence)?;
19923    let previous_events = all_events
19924        .iter()
19925        .take_while(|event| !std::ptr::eq(*event, opened))
19926        .collect::<Vec<_>>();
19927    let originals = previous_events
19928        .iter()
19929        .copied()
19930        .filter(|event| event.event_type == "ConditionWaitOpened")
19931        .filter(|event| {
19932            event
19933                .payload
19934                .get("condition_wait_occurrence_id")
19935                .and_then(Value::as_str)
19936                == Some(occurrence.as_str())
19937        })
19938        .collect::<Vec<_>>();
19939    let Some(original) = originals.first().copied() else {
19940        return recorded_parallel_group_path(condition_events, sequence);
19941    };
19942    let authored_sequence = required_history_u64(original, "sequence", sequence)?;
19943    if authored_sequence == sequence {
19944        return recorded_parallel_group_path(condition_events, sequence);
19945    }
19946    let original_path = recorded_parallel_group_path(&[original], authored_sequence)?;
19947    if original_path.is_none() {
19948        return recorded_parallel_group_path(condition_events, sequence);
19949    }
19950    let reopened_path = recorded_parallel_group_path(condition_events, authored_sequence)?;
19951    // A reopen carries the time remaining since the original open (#187), so
19952    // its timeout may be smaller than the original's, never larger.
19953    let timeout_matches = match (
19954        opened
19955            .payload
19956            .get("timeout_seconds")
19957            .filter(|value| !value.is_null()),
19958        original
19959            .payload
19960            .get("timeout_seconds")
19961            .filter(|value| !value.is_null()),
19962    ) {
19963        (None, None) => true,
19964        (Some(reopened), Some(original)) => reopened
19965            .as_u64()
19966            .zip(original.as_u64())
19967            .is_some_and(|(reopened, original)| reopened <= original),
19968        _ => false,
19969    };
19970    let identity_matches = timeout_matches
19971        && ["condition_key", "condition_definition_fingerprint"]
19972            .iter()
19973            .all(|field| opened.payload.get(*field) == original.payload.get(*field));
19974    let previous = originals
19975        .iter()
19976        .copied()
19977        .filter(|event| durable_event_sequence(event).is_some_and(|physical| physical < sequence))
19978        .max_by_key(|event| durable_event_sequence(event));
19979    let previously_satisfied = previous.is_some_and(|previous| {
19980        previous_events.iter().any(|event| {
19981            event.event_type == "ConditionWaitSatisfied"
19982                && event.payload.get("condition_wait_id")
19983                    == previous.payload.get("condition_wait_id")
19984                && event.payload.get("condition_wait_occurrence_id")
19985                    == previous.payload.get("condition_wait_occurrence_id")
19986                && durable_event_sequence(event) == durable_event_sequence(previous)
19987        })
19988    });
19989    // The PHP Server also accepts a grouped re-send of a member whose latest
19990    // wait is still open, and records it as a new physical open without
19991    // resolving the earlier one (#191). That predecessor was unresolved when
19992    // this wait opened: it is a repeated open of the same logical member.
19993    let previously_unresolved = previous.is_some_and(|previous| {
19994        !previous_events
19995            .iter()
19996            .any(|event| match event.event_type.as_str() {
19997                "ConditionWaitSatisfied" | "ConditionWaitTimedOut" => {
19998                    event.payload.get("condition_wait_id")
19999                        == previous.payload.get("condition_wait_id")
20000                        && durable_event_sequence(event) == durable_event_sequence(previous)
20001                }
20002                "TimerFired" => {
20003                    event.payload.get("timer_kind").and_then(Value::as_str)
20004                        == Some("condition_timeout")
20005                        && event.payload.get("condition_wait_id")
20006                            == previous.payload.get("condition_wait_id")
20007                }
20008                _ => false,
20009            })
20010    });
20011    if !identity_matches
20012        || reopened_path != original_path
20013        || !(previously_satisfied || previously_unresolved)
20014    {
20015        return Err(invalid_recorded_history(
20016            "condition_wait_group_reopen_mismatch",
20017            sequence,
20018            "same authored condition and group path after a satisfied physical wait",
20019            &opened.payload.to_string(),
20020            "grouped condition reopen has no matching recorded predecessor",
20021        ));
20022    }
20023    Ok(reopened_path)
20024}
20025
20026fn required_condition_wait_occurrence_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
20027    event
20028        .payload
20029        .get("condition_wait_occurrence_id")
20030        .and_then(Value::as_str)
20031        .filter(|value| !value.is_empty())
20032        .map(str::to_string)
20033        .ok_or_else(|| {
20034            invalid_recorded_history(
20035                "condition_wait_occurrence_id_missing",
20036                sequence,
20037                "non-empty condition_wait_occurrence_id",
20038                &event.event_type,
20039                "condition history is missing authored occurrence identity",
20040            )
20041        })
20042}
20043
20044fn required_condition_wait_id(event: &HistoryEvent, sequence: u64) -> Result<String> {
20045    event
20046        .payload
20047        .get("condition_wait_id")
20048        .and_then(Value::as_str)
20049        .filter(|value| !value.is_empty())
20050        .map(str::to_string)
20051        .ok_or_else(|| {
20052            invalid_recorded_history(
20053                "condition_wait_id_missing",
20054                sequence,
20055                "non-empty condition_wait_id",
20056                &event.event_type,
20057                "canonical condition history is missing its durable wait identity",
20058            )
20059        })
20060}
20061
20062fn optional_non_empty_history_string(event: &HistoryEvent, field: &str) -> Option<String> {
20063    event
20064        .payload
20065        .get(field)
20066        .and_then(Value::as_str)
20067        .filter(|value| !value.is_empty())
20068        .map(str::to_string)
20069}
20070
20071fn optional_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<Option<u64>> {
20072    match event.payload.get(field) {
20073        None | Some(Value::Null) => Ok(None),
20074        Some(value) => value_as_u64(value).map(Some).ok_or_else(|| {
20075            invalid_recorded_history(
20076                "condition_wait_definition_invalid",
20077                sequence,
20078                &format!("non-negative integer {field}"),
20079                &value.to_string(),
20080                "condition history contains an invalid numeric definition field",
20081            )
20082        }),
20083    }
20084}
20085
20086fn required_signal_wait_name(event: &HistoryEvent, sequence: u64) -> Result<String> {
20087    event
20088        .payload
20089        .get("signal_name")
20090        .or_else(|| event.raw.get("signal_name"))
20091        .and_then(Value::as_str)
20092        .filter(|value| !value.is_empty())
20093        .map(str::to_string)
20094        .ok_or_else(|| {
20095            invalid_recorded_history(
20096                "signal_wait_name_missing",
20097                sequence,
20098                "non-empty signal_name",
20099                &event.event_type,
20100                "canonical signal-wait history is missing its signal identity",
20101            )
20102        })
20103}
20104
20105fn is_recorded_signal_wait_event(event: &HistoryEvent) -> bool {
20106    // Applying a buffered control-plane signal has no authored call sequence.
20107    // Its outer sequence orders history events and must not become a wait.
20108    if event.event_type == "SignalApplied"
20109        && event
20110            .payload
20111            .get("signal_wait_id")
20112            .and_then(Value::as_str)
20113            .is_some_and(|id| id.starts_with("signal-command:"))
20114        && event.payload.get("sequence").is_none()
20115        && event.payload.get("workflow_sequence").is_none()
20116    {
20117        return false;
20118    }
20119    matches!(
20120        event.event_type.as_str(),
20121        "SignalWaitOpened" | "SignalApplied"
20122    )
20123}
20124
20125fn required_history_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
20126    event
20127        .payload
20128        .get(field)
20129        .and_then(Value::as_str)
20130        .filter(|value| !value.is_empty())
20131        .map(str::to_string)
20132        .ok_or_else(|| {
20133            invalid_recorded_history(
20134                "timer_history_field_missing",
20135                sequence,
20136                field,
20137                &event.event_type,
20138                "timer history is missing a required identity field",
20139            )
20140        })
20141}
20142
20143fn required_history_u64(event: &HistoryEvent, field: &str, sequence: u64) -> Result<u64> {
20144    event
20145        .payload
20146        .get(field)
20147        .and_then(value_as_u64)
20148        .ok_or_else(|| {
20149            invalid_recorded_history(
20150                "timer_history_field_missing",
20151                sequence,
20152                field,
20153                &event.event_type,
20154                "timer history is missing a required numeric field",
20155            )
20156        })
20157}
20158
20159fn recorded_search_attribute_types(
20160    payload: &Value,
20161    attributes: &Value,
20162    sequence: u64,
20163) -> Result<RecordedSnapshotValue<BTreeMap<String, String>>> {
20164    let Some(raw_types) = payload.get("attribute_types") else {
20165        // This is the explicit compatibility rule for histories recorded
20166        // before typed identity was persisted. Values still constrain replay;
20167        // the unknown type snapshot does not assert a typed match.
20168        return Ok(RecordedSnapshotValue::Unknown);
20169    };
20170    let Some(raw_types) = raw_types.as_object() else {
20171        return Err(invalid_recorded_history(
20172            "search_attribute_types_malformed",
20173            sequence,
20174            "canonical attribute type map",
20175            &raw_types.to_string(),
20176            "search-attribute history contains malformed type identity",
20177        ));
20178    };
20179    let attribute_keys = attributes
20180        .as_object()
20181        .expect("recorded search attributes were validated as an object");
20182    let mut types = BTreeMap::new();
20183    for (key, value) in raw_types {
20184        let Some(attribute_type) = value.as_str() else {
20185            return Err(invalid_recorded_history(
20186                "search_attribute_types_malformed",
20187                sequence,
20188                "canonical string type name",
20189                &value.to_string(),
20190                "search-attribute history contains a non-string type identity",
20191            ));
20192        };
20193        if !attribute_keys.contains_key(key)
20194            || !matches!(
20195                attribute_type,
20196                "string" | "keyword" | "keyword_list" | "int" | "float" | "bool" | "datetime"
20197            )
20198        {
20199            return Err(invalid_recorded_history(
20200                "search_attribute_types_malformed",
20201                sequence,
20202                "canonical types for keys present in attributes",
20203                &format!("{key}:{attribute_type}"),
20204                "search-attribute history contains unsupported or orphaned type identity",
20205            ));
20206        }
20207        types.insert(key.clone(), attribute_type.to_string());
20208    }
20209    Ok(RecordedSnapshotValue::Known(types))
20210}
20211
20212fn invalid_recorded_history(
20213    reason: &str,
20214    sequence: u64,
20215    expected: &str,
20216    actual: &str,
20217    message: &str,
20218) -> Error {
20219    Error::NonDeterministicReplay(ReplayFailure::new(
20220        reason,
20221        Some(sequence),
20222        Some(expected.to_string()),
20223        Some(actual.to_string()),
20224        message,
20225    ))
20226}
20227
20228type ActivityOutcome = std::result::Result<AvroValue, ActivityFailure>;
20229
20230fn activity_outcome(
20231    event: &HistoryEvent,
20232    fallback_codec: &str,
20233    recorded_activity_type: Option<String>,
20234) -> Result<ActivityOutcome> {
20235    if event.event_type == "ActivityCompleted" {
20236        let codec = event
20237            .payload
20238            .get("payload_codec")
20239            .and_then(Value::as_str)
20240            .unwrap_or(fallback_codec);
20241        return Ok(Ok(decode_wire_avro_value(
20242            event.payload.get("result").unwrap_or(&Value::Null),
20243            codec,
20244        )?));
20245    }
20246
20247    let payload = &event.payload;
20248    let (kind, fallback_reason, fallback_message) = match event.event_type.as_str() {
20249        "ActivityFailed" => (ActivityFailureKind::Failed, "activity", "activity failed"),
20250        "ActivityCancelled" => (
20251            ActivityFailureKind::Cancelled,
20252            "cancelled",
20253            "activity was cancelled",
20254        ),
20255        "ActivityTimedOut" => (
20256            ActivityFailureKind::TimedOut,
20257            "timeout",
20258            "activity timed out",
20259        ),
20260        _ => unreachable!("activity_outcome is called only for terminal activity events"),
20261    };
20262    let mut exception = payload
20263        .get("exception")
20264        .filter(|value| !value.is_null())
20265        .cloned();
20266    // A Server-settled lease loss records `failure_reason` beside the
20267    // exception. Carry it in the exception descriptor so that
20268    // `ActivityFailure::lease_loss_reason` can read it without a new field.
20269    if payload_string(payload, "exception_class").as_deref() == Some(ACTIVITY_LEASE_EXPIRED_CLASS) {
20270        if let Some(reason) = payload_string(payload, "failure_reason") {
20271            match &mut exception {
20272                Some(Value::Object(fields)) => {
20273                    fields
20274                        .entry("failure_reason")
20275                        .or_insert_with(|| json!(reason));
20276                }
20277                None => {
20278                    exception = Some(json!({
20279                        "class": ACTIVITY_LEASE_EXPIRED_CLASS,
20280                        "failure_reason": reason,
20281                    }));
20282                }
20283                Some(_) => {}
20284            }
20285        }
20286    }
20287    let failure_category = payload_string(payload, "failure_category");
20288    let timeout_kind = payload_string(payload, "timeout_kind");
20289    let reason = payload_string(payload, "reason").unwrap_or_else(|| match kind {
20290        ActivityFailureKind::Failed => failure_category
20291            .clone()
20292            .unwrap_or_else(|| fallback_reason.to_string()),
20293        ActivityFailureKind::Cancelled => fallback_reason.to_string(),
20294        ActivityFailureKind::TimedOut => timeout_kind
20295            .clone()
20296            .unwrap_or_else(|| fallback_reason.to_string()),
20297    });
20298    let message = payload_string(payload, "message")
20299        .or_else(|| {
20300            exception
20301                .as_ref()
20302                .and_then(|value| payload_string(value, "message"))
20303        })
20304        .unwrap_or_else(|| fallback_message.to_string());
20305
20306    Ok(Err(ActivityFailure {
20307        kind,
20308        reason,
20309        message,
20310        activity_execution_id: payload_string(payload, "activity_execution_id"),
20311        activity_attempt_id: payload_string(payload, "activity_attempt_id"),
20312        activity_type: payload_string(payload, "activity_type")
20313            .or_else(|| payload_string(payload, "activity_name"))
20314            .or(recorded_activity_type),
20315        activity_class: payload_string(payload, "activity_class"),
20316        attempt_number: payload.get("attempt_number").and_then(value_as_u64),
20317        failure_id: payload_string(payload, "failure_id"),
20318        failure_category,
20319        timeout_kind,
20320        non_retryable: payload
20321            .get("non_retryable")
20322            .and_then(Value::as_bool)
20323            .unwrap_or(false),
20324        exception_type: payload_string(payload, "exception_type").or_else(|| {
20325            exception
20326                .as_ref()
20327                .and_then(|value| payload_string(value, "type"))
20328        }),
20329        exception_class: payload_string(payload, "exception_class").or_else(|| {
20330            exception
20331                .as_ref()
20332                .and_then(|value| payload_string(value, "class"))
20333        }),
20334        code: payload
20335            .get("code")
20336            .filter(|value| !value.is_null())
20337            .cloned(),
20338        exception,
20339    }))
20340}
20341
20342type ChildWorkflowOutcome = std::result::Result<ChildWorkflowAvroResult, ChildWorkflowFailure>;
20343
20344fn child_workflow_outcomes(
20345    events: &[HistoryEvent],
20346    fallback_codec: &str,
20347    parent: WorkflowIdentity,
20348) -> Result<Vec<ChildWorkflowOutcome>> {
20349    let mut outcomes = Vec::new();
20350
20351    for event in events {
20352        let kind = match event.event_type.as_str() {
20353            "ChildRunCompleted" => None,
20354            "ChildRunFailed" => Some((
20355                ChildWorkflowFailureKind::Failed,
20356                "child_workflow",
20357                "child workflow failed",
20358            )),
20359            "ChildRunCancelled" => Some((
20360                ChildWorkflowFailureKind::Cancelled,
20361                "cancelled",
20362                "child workflow was cancelled",
20363            )),
20364            "ChildRunTerminated" => Some((
20365                ChildWorkflowFailureKind::Terminated,
20366                "terminated",
20367                "child workflow was terminated",
20368            )),
20369            _ => continue,
20370        };
20371        let payload = &event.payload;
20372        let child_workflow_id = payload_string(payload, "child_workflow_instance_id");
20373        let child_workflow_run_id = payload_string(payload, "child_workflow_run_id");
20374        let child_workflow_type = payload_string(payload, "child_workflow_type");
20375
20376        if let Some((kind, reason, fallback_message)) = kind {
20377            let exception = payload
20378                .get("exception")
20379                .filter(|value| !value.is_null())
20380                .cloned();
20381            let message = payload_string(payload, "message")
20382                .or_else(|| {
20383                    exception
20384                        .as_ref()
20385                        .and_then(|value| payload_string(value, "message"))
20386                })
20387                .unwrap_or_else(|| fallback_message.to_string());
20388            let exception_type = payload_string(payload, "exception_type").or_else(|| {
20389                exception
20390                    .as_ref()
20391                    .and_then(|value| payload_string(value, "type"))
20392            });
20393            let exception_class = payload_string(payload, "exception_class").or_else(|| {
20394                exception
20395                    .as_ref()
20396                    .and_then(|value| payload_string(value, "class"))
20397            });
20398            outcomes.push(Err(ChildWorkflowFailure {
20399                kind,
20400                reason: reason.to_string(),
20401                message,
20402                parent_workflow_id: parent.workflow_id.clone(),
20403                parent_workflow_run_id: parent.run_id.clone(),
20404                child_workflow_id,
20405                child_workflow_run_id,
20406                child_workflow_type,
20407                failure_id: payload_string(payload, "failure_id"),
20408                failure_category: payload_string(payload, "failure_category"),
20409                exception_type,
20410                exception_class,
20411                non_retryable: payload
20412                    .get("non_retryable")
20413                    .and_then(Value::as_bool)
20414                    .unwrap_or(false),
20415                code: payload
20416                    .get("code")
20417                    .filter(|value| !value.is_null())
20418                    .cloned(),
20419                exception,
20420            }));
20421            continue;
20422        }
20423
20424        let codec = payload
20425            .get("payload_codec")
20426            .and_then(Value::as_str)
20427            .unwrap_or(fallback_codec);
20428        let result = payload
20429            .get("result")
20430            .or_else(|| payload.get("output"))
20431            .unwrap_or(&Value::Null);
20432        outcomes.push(Ok(ChildWorkflowAvroResult {
20433            parent: parent.clone(),
20434            child: WorkflowIdentity {
20435                workflow_id: child_workflow_id,
20436                run_id: child_workflow_run_id,
20437            },
20438            child_workflow_type,
20439            result: decode_wire_avro_value(result, codec)?,
20440        }));
20441    }
20442
20443    Ok(outcomes)
20444}
20445
20446fn payload_string(payload: &Value, key: &str) -> Option<String> {
20447    payload
20448        .get(key)
20449        .and_then(Value::as_str)
20450        .filter(|value| !value.is_empty())
20451        .map(str::to_string)
20452}
20453
20454fn recorded_activity_failure_boundary(
20455    ctx: &WorkflowContext,
20456    error: &Error,
20457) -> Option<(u64, String)> {
20458    let Error::ActivityFailed(failure) = error else {
20459        return None;
20460    };
20461    if failure.kind != ActivityFailureKind::Failed {
20462        return None;
20463    }
20464    let activity_execution_id = failure
20465        .activity_execution_id
20466        .as_deref()
20467        .filter(|value| !value.is_empty())?;
20468    let state = ctx.state.lock().ok()?;
20469    let mut matches = state.recorded_commands.iter().filter_map(|command| {
20470        let RecordedCommand::Activity {
20471            sequence,
20472            outcome: Some(Err(recorded_failure)),
20473            ..
20474        } = command
20475        else {
20476            return None;
20477        };
20478        (*sequence > 0 && recorded_failure == failure)
20479            .then_some((*sequence, activity_execution_id.to_string()))
20480    });
20481    let boundary = matches.next()?;
20482    matches.next().is_none().then_some(boundary)
20483}
20484
20485fn workflow_failure_command(
20486    error: &Error,
20487    failed_activity_boundary: Option<(u64, String)>,
20488) -> Value {
20489    let (exception_type, exception_class, properties) = match error {
20490        Error::NexusOperationFailed(failure) => (
20491            "NexusOperationFailed",
20492            "durable_workflow::NexusOperationFailure",
20493            json!({"service_call_id":failure.service_call_id, "status":failure.status,
20494                "caller_observed_error_type":failure.exception_type, "service_exception":failure.exception}),
20495        ),
20496        Error::ActivityFailed(failure) => (
20497            match failure.kind {
20498                ActivityFailureKind::Failed => "ActivityFailed",
20499                ActivityFailureKind::Cancelled => "ActivityCancelled",
20500                ActivityFailureKind::TimedOut => "ActivityTimedOut",
20501            },
20502            "durable_workflow::ActivityFailure",
20503            json!({
20504                "reason": failure.reason,
20505                "activity_execution_id": failure.activity_execution_id,
20506                "activity_attempt_id": failure.activity_attempt_id,
20507                "activity_type": failure.activity_type,
20508                "activity_class": failure.activity_class,
20509                "attempt_number": failure.attempt_number,
20510                "failure_id": failure.failure_id,
20511                "failure_category": failure.failure_category,
20512                "timeout_kind": failure.timeout_kind,
20513                "activity_non_retryable": failure.non_retryable,
20514                "activity_exception_type": failure.exception_type,
20515                "activity_exception_class": failure.exception_class,
20516                "activity_code": failure.code,
20517                "activity_exception": failure.exception,
20518            }),
20519        ),
20520        Error::ChildWorkflowFailed(failure) => (
20521            match failure.kind {
20522                ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
20523                ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
20524                ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
20525            },
20526            "durable_workflow::ChildWorkflowFailure",
20527            json!({
20528                "reason": failure.reason,
20529                "parent_workflow_id": failure.parent_workflow_id,
20530                "parent_workflow_run_id": failure.parent_workflow_run_id,
20531                "child_workflow_id": failure.child_workflow_id,
20532                "child_workflow_run_id": failure.child_workflow_run_id,
20533                "child_workflow_type": failure.child_workflow_type,
20534                "failure_id": failure.failure_id,
20535                "failure_category": failure.failure_category,
20536                "child_exception_type": failure.exception_type,
20537                "child_exception_class": failure.exception_class,
20538                "child_non_retryable": failure.non_retryable,
20539                "child_code": failure.code,
20540                "child_exception": failure.exception,
20541            }),
20542        ),
20543        Error::ParallelFailed(failure) => (
20544            "ParallelFailed",
20545            "durable_workflow::ParallelFailure",
20546            json!({
20547                "parallel_group_id": failure.group_id,
20548                "parallel_member_path": failure.member_path,
20549                "parallel_group_path": failure.group_path,
20550                "completed_members": failure.completed.iter().map(|completion| &completion.member_path).collect::<Vec<_>>(),
20551                "cause_type": workflow_error_type(&failure.cause),
20552                "cause_message": failure.cause.to_string(),
20553            }),
20554        ),
20555        Error::SagaCompensationFailed(failure) => (
20556            "SagaCompensationFailed",
20557            "durable_workflow::SagaCompensationFailure",
20558            json!({
20559                "initiating_failure_type": workflow_error_type(&failure.initiating_failure),
20560                "initiating_failure_message": failure.initiating_failure.to_string(),
20561                "compensation_activity_type": failure.compensation_activity_type,
20562                "compensation_registration_order": failure.compensation_registration_order,
20563                "compensation_failure_type": workflow_error_type(&failure.compensation_failure),
20564                "compensation_failure_message": failure.compensation_failure.to_string(),
20565            }),
20566        ),
20567        Error::WorkflowCancellationRequested(_) => (
20568            "WorkflowCancellationRequested",
20569            "durable_workflow::WorkflowCancellationRequested",
20570            json!({"reason": "cancelled"}),
20571        ),
20572        Error::CooperativeCancellationRequested(cancellation) => (
20573            "WorkflowCancellationRequested",
20574            "durable_workflow::CooperativeCancellationRequested",
20575            json!({"reason": "cancelled", "request_id": cancellation.request.request_id,
20576                "cleanup_deadline_at": cancellation.request.cleanup_deadline_at}),
20577        ),
20578        Error::CancellationScopeRequested(cancellation) => (
20579            "WorkflowCancellationRequested",
20580            "durable_workflow::CancellationScopeRequested",
20581            json!({"reason":"scope_cancelled", "request_id":cancellation.context.request_id(),
20582                "cleanup_deadline_at":cancellation.context.deadline().to_rfc3339(),
20583                "cancellation":cancellation.context.to_value()}),
20584        ),
20585        Error::NonDeterministicReplay(_) => (
20586            "NonDeterministicReplay",
20587            "durable_workflow::Error",
20588            Value::Null,
20589        ),
20590        Error::WorkflowTaskCompletionTooLarge(refusal) => (
20591            "StructuralLimitExceeded",
20592            "durable_workflow::WorkflowTaskCompletionTooLarge",
20593            json!({
20594                "structural_limit_kind": refusal.limit_kind,
20595                "structural_limit_value": refusal.size,
20596                "structural_limit_configured": refusal.limit,
20597            }),
20598        ),
20599        Error::WorkflowTaskHistoryLimitExceeded(refusal) => (
20600            "StructuralLimitExceeded",
20601            "durable_workflow::WorkflowTaskHistoryLimitExceeded",
20602            json!({
20603                "structural_limit_kind": refusal.limit_kind,
20604                "structural_limit_value": refusal.current_value,
20605                "structural_limit_configured": refusal.configured_limit,
20606            }),
20607        ),
20608        _ => ("RustWorkflowError", "durable_workflow::Error", Value::Null),
20609    };
20610    let non_retryable = match error {
20611        Error::ActivityFailed(failure) => failure.non_retryable,
20612        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
20613        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
20614        Error::SagaCompensationFailed(failure) => {
20615            workflow_error_non_retryable(&failure.compensation_failure)
20616        }
20617        Error::WorkflowCancellationRequested(_)
20618        | Error::CooperativeCancellationRequested(_)
20619        | Error::CancellationScopeRequested(_) => true,
20620        Error::NonDeterministicReplay(_) => true,
20621        Error::WorkflowTaskCompletionTooLarge(_) | Error::WorkflowTaskHistoryLimitExceeded(_) => {
20622            true
20623        }
20624        _ => false,
20625    };
20626
20627    let mut command = json!({
20628        "type": "fail_workflow",
20629        "message": error.to_string(),
20630        "exception_type": exception_type,
20631        "exception_class": exception_class,
20632        "non_retryable": non_retryable,
20633        "exception": {
20634            "type": exception_type,
20635            "class": exception_class,
20636            "message": error.to_string(),
20637            "properties": properties,
20638        }
20639    });
20640
20641    if let Some((sequence, activity_execution_id)) = failed_activity_boundary {
20642        command["failed_step_sequence"] = json!(sequence);
20643        command["failed_activity_execution_id"] = json!(activity_execution_id);
20644    }
20645
20646    command
20647}
20648
20649fn workflow_error_type(error: &Error) -> &'static str {
20650    match error {
20651        Error::NexusOperationFailed(_) => "NexusOperationFailed",
20652        Error::ActivityFailed(failure) => match failure.kind {
20653            ActivityFailureKind::Failed => "ActivityFailed",
20654            ActivityFailureKind::Cancelled => "ActivityCancelled",
20655            ActivityFailureKind::TimedOut => "ActivityTimedOut",
20656        },
20657        Error::ChildWorkflowFailed(failure) => match failure.kind {
20658            ChildWorkflowFailureKind::Failed => "ChildWorkflowFailed",
20659            ChildWorkflowFailureKind::Cancelled => "ChildWorkflowCancelled",
20660            ChildWorkflowFailureKind::Terminated => "ChildWorkflowTerminated",
20661        },
20662        Error::ParallelFailed(_) => "ParallelFailed",
20663        Error::SagaCompensationFailed(_) => "SagaCompensationFailed",
20664        Error::WorkflowCancellationRequested(_)
20665        | Error::CooperativeCancellationRequested(_)
20666        | Error::CancellationScopeRequested(_) => "WorkflowCancellationRequested",
20667        Error::NonDeterministicReplay(_) => "NonDeterministicReplay",
20668        _ => "RustWorkflowError",
20669    }
20670}
20671
20672fn workflow_error_non_retryable(error: &Error) -> bool {
20673    match error {
20674        Error::ActivityFailed(failure) => failure.non_retryable,
20675        Error::ChildWorkflowFailed(failure) => failure.non_retryable,
20676        Error::ParallelFailed(failure) => workflow_error_non_retryable(&failure.cause),
20677        Error::SagaCompensationFailed(failure) => {
20678            workflow_error_non_retryable(&failure.compensation_failure)
20679        }
20680        Error::WorkflowCancellationRequested(_)
20681        | Error::CooperativeCancellationRequested(_)
20682        | Error::CancellationScopeRequested(_)
20683        | Error::NonDeterministicReplay(_) => true,
20684        _ => false,
20685    }
20686}
20687
20688fn workflow_task_integrity_error(error: &Error) -> bool {
20689    matches!(
20690        error,
20691        Error::NonDeterministicReplay(_)
20692            | Error::Protocol(_)
20693            | Error::CancellationScopeExecutionUnavailable
20694            | Error::SignalExternalWorkflowUnavailable
20695            | Error::MissingWorkflowCommandIdentity
20696            | Error::WorkflowStatePoisoned
20697    )
20698}
20699
20700fn decode_signal_event_arguments(
20701    event: &HistoryEvent,
20702    fallback_codec: &str,
20703) -> Result<Vec<AvroValue>> {
20704    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
20705    validate_payload_codec(codec)?;
20706    let raw = signal_history_payload(&event.payload);
20707    let decoded = match raw.filter(|value| !value.is_null()) {
20708        Some(value) => decode_wire_avro_value(value, codec)?,
20709        None => AvroValue::Array(Vec::new()),
20710    };
20711    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
20712        unreachable!("normalize_avro_arguments always returns an array");
20713    };
20714    Ok(arguments)
20715}
20716
20717fn decode_update_event_arguments(
20718    event: &HistoryEvent,
20719    fallback_codec: &str,
20720) -> Result<Vec<AvroValue>> {
20721    let codec = declared_payload_codec(&event.payload, "payload_codec")?.unwrap_or(fallback_codec);
20722    validate_payload_codec(codec)?;
20723    let decoded = match event
20724        .payload
20725        .get("arguments")
20726        .filter(|value| !value.is_null())
20727    {
20728        Some(value) => decode_wire_avro_value(value, codec)?,
20729        None => AvroValue::Array(Vec::new()),
20730    };
20731    let AvroValue::Array(arguments) = normalize_avro_arguments(decoded) else {
20732        unreachable!("normalize_avro_arguments always returns an array");
20733    };
20734    Ok(arguments)
20735}
20736
20737fn hydrate_query_history_from_export(task: &mut QueryTask) -> Result<()> {
20738    let Some(export_events) = task
20739        .history_export
20740        .as_ref()
20741        .and_then(|export| export.get("history_events"))
20742        .and_then(Value::as_array)
20743    else {
20744        return Ok(());
20745    };
20746
20747    if export_events.len() > task.history_events.len() {
20748        task.history_events = serde_json::from_value(Value::Array(export_events.clone()))?;
20749    }
20750
20751    Ok(())
20752}
20753
20754fn enrich_query_history_from_export(task: &mut QueryTask) -> Result<()> {
20755    let Some(export) = task.history_export.as_ref() else {
20756        return Ok(());
20757    };
20758    let signals = export
20759        .get("signals")
20760        .and_then(Value::as_array)
20761        .cloned()
20762        .unwrap_or_default();
20763    let activities = export
20764        .get("activities")
20765        .and_then(Value::as_array)
20766        .cloned()
20767        .unwrap_or_default();
20768    let export_codec = export
20769        .get("payloads")
20770        .and_then(|payloads| payloads.get("codec"))
20771        .and_then(Value::as_str)
20772        .unwrap_or(&task.payload_codec)
20773        .to_string();
20774    let mut signal_name_offsets: HashMap<String, usize> = HashMap::new();
20775
20776    for event in &mut task.history_events {
20777        if event.event_type == "ActivityCompleted" {
20778            let sequence = event
20779                .payload
20780                .get("sequence")
20781                .or_else(|| event.payload.get("workflow_sequence"))
20782                .and_then(value_as_u64);
20783            let Some(activity) = sequence.and_then(|sequence| {
20784                activities.iter().find(|activity| {
20785                    activity.get("sequence").and_then(value_as_u64) == Some(sequence)
20786                })
20787            }) else {
20788                continue;
20789            };
20790            let Some(payload) = event.payload.as_object_mut() else {
20791                continue;
20792            };
20793            if missing_payload(payload.get("result")) {
20794                if let Some(result) = activity
20795                    .get("result")
20796                    .filter(|value| !missing_payload(Some(value)))
20797                {
20798                    payload.insert("result".to_string(), result.clone());
20799                }
20800            }
20801            for field in ["payload_codec", "activity_type"] {
20802                if payload
20803                    .get(field)
20804                    .and_then(Value::as_str)
20805                    .unwrap_or_default()
20806                    .is_empty()
20807                {
20808                    if let Some(value) = activity.get(field) {
20809                        payload.insert(field.to_string(), value.clone());
20810                    }
20811                }
20812            }
20813            continue;
20814        }
20815
20816        if event.event_type != "SignalReceived" && event.event_type != "SignalApplied" {
20817            continue;
20818        }
20819        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
20820        let command_id = event
20821            .payload
20822            .get("workflow_command_id")
20823            .or_else(|| event.raw.get("workflow_command_id"))
20824            .and_then(Value::as_str);
20825        let signal_name = event
20826            .payload
20827            .get("signal_name")
20828            .and_then(Value::as_str)
20829            .unwrap_or_default()
20830            .to_string();
20831        let matched = signals
20832            .iter()
20833            .find(|signal| {
20834                signal_id.is_some() && signal.get("id").and_then(Value::as_str) == signal_id
20835            })
20836            .or_else(|| {
20837                signals.iter().find(|signal| {
20838                    command_id.is_some()
20839                        && signal.get("command_id").and_then(Value::as_str) == command_id
20840                })
20841            })
20842            .or_else(|| {
20843                let offset = signal_name_offsets.entry(signal_name.clone()).or_default();
20844                let signal = signals
20845                    .iter()
20846                    .filter(|signal| {
20847                        signal.get("name").and_then(Value::as_str) == Some(signal_name.as_str())
20848                    })
20849                    .nth(*offset);
20850                if signal.is_some() {
20851                    *offset += 1;
20852                }
20853                signal
20854            });
20855        let Some(signal) = matched else {
20856            continue;
20857        };
20858        let signal_codec = signal
20859            .get("payload_codec")
20860            .and_then(Value::as_str)
20861            .unwrap_or(&export_codec);
20862        let Some(payload) = event.payload.as_object_mut() else {
20863            continue;
20864        };
20865        if missing_payload(payload.get("arguments")) {
20866            if let Some(arguments) = signal
20867                .get("arguments")
20868                .filter(|value| !missing_payload(Some(value)))
20869            {
20870                let envelope = match arguments {
20871                    Value::String(blob) => json!({"codec": signal_codec, "blob": blob}),
20872                    other => other.clone(),
20873                };
20874                payload.insert("arguments".to_string(), envelope);
20875            }
20876        }
20877        if payload
20878            .get("payload_codec")
20879            .and_then(Value::as_str)
20880            .unwrap_or_default()
20881            .is_empty()
20882        {
20883            payload.insert("payload_codec".to_string(), json!(signal_codec));
20884        }
20885    }
20886
20887    Ok(())
20888}
20889
20890fn missing_payload(value: Option<&Value>) -> bool {
20891    match value {
20892        None | Some(Value::Null) => true,
20893        Some(Value::String(value)) => value.is_empty(),
20894        Some(_) => false,
20895    }
20896}
20897
20898fn query_signal_events(task: &QueryTask) -> Result<Vec<QuerySignal>> {
20899    history_signal_events(
20900        &task.history_events,
20901        task.history_export.as_ref(),
20902        &task.payload_codec,
20903    )
20904}
20905
20906fn history_signal_events(
20907    history_events: &[HistoryEvent],
20908    history_export: Option<&Value>,
20909    payload_codec: &str,
20910) -> Result<Vec<QuerySignal>> {
20911    let export_signals = history_export
20912        .and_then(|export| export.get("signals"))
20913        .and_then(Value::as_array)
20914        .cloned()
20915        .unwrap_or_default();
20916    let export_codec = history_export
20917        .and_then(|export| export.get("payloads"))
20918        .and_then(|payloads| payloads.get("codec"))
20919        .and_then(Value::as_str)
20920        .unwrap_or(payload_codec);
20921    let mut name_offsets: HashMap<String, usize> = HashMap::new();
20922    let mut signals: Vec<QuerySignal> = Vec::new();
20923    let mut signal_indices = HashMap::new();
20924    let mut command_indices = HashMap::new();
20925
20926    for event in history_events {
20927        if event.event_type != "SignalApplied" && event.event_type != "SignalReceived" {
20928            continue;
20929        }
20930
20931        let name = event
20932            .payload
20933            .get("signal_name")
20934            .and_then(Value::as_str)
20935            .unwrap_or_default();
20936        if name.is_empty() {
20937            continue;
20938        }
20939        let signal_id = event.payload.get("signal_id").and_then(Value::as_str);
20940        let command_id = event
20941            .payload
20942            .get("workflow_command_id")
20943            .or_else(|| event.raw.get("workflow_command_id"))
20944            .and_then(Value::as_str);
20945        let matched_export = export_signals
20946            .iter()
20947            .find(|candidate| {
20948                signal_id.is_some() && candidate.get("id").and_then(Value::as_str) == signal_id
20949            })
20950            .or_else(|| {
20951                export_signals.iter().find(|candidate| {
20952                    command_id.is_some()
20953                        && candidate.get("command_id").and_then(Value::as_str) == command_id
20954                })
20955            })
20956            .or_else(|| {
20957                let offset = name_offsets.entry(name.to_string()).or_default();
20958                let candidate = export_signals
20959                    .iter()
20960                    .filter(|candidate| candidate.get("name").and_then(Value::as_str) == Some(name))
20961                    .nth(*offset);
20962                if candidate.is_some() {
20963                    *offset += 1;
20964                }
20965                candidate
20966            });
20967        let codec = event
20968            .payload
20969            .get("payload_codec")
20970            .and_then(Value::as_str)
20971            .or_else(|| {
20972                matched_export
20973                    .and_then(|signal| signal.get("payload_codec"))
20974                    .and_then(Value::as_str)
20975            })
20976            .unwrap_or(export_codec);
20977        let raw_arguments = signal_history_payload(&event.payload)
20978            .filter(|value| !value.is_null())
20979            .or_else(|| matched_export.and_then(|signal| signal.get("arguments")));
20980        let (arguments, avro_arguments) = decode_query_signal_arguments(raw_arguments, codec)?;
20981        let workflow_sequence = event
20982            .payload
20983            .get("workflow_sequence")
20984            .and_then(value_as_u64)
20985            .or_else(|| {
20986                matched_export
20987                    .and_then(|signal| signal.get("workflow_sequence"))
20988                    .and_then(value_as_u64)
20989            });
20990
20991        let id = signal_id.or_else(|| {
20992            matched_export
20993                .and_then(|signal| signal.get("id"))
20994                .and_then(Value::as_str)
20995        });
20996        let command_id = command_id.or_else(|| {
20997            matched_export
20998                .and_then(|signal| signal.get("command_id"))
20999                .and_then(Value::as_str)
21000        });
21001        let duplicate = id
21002            .and_then(|id| signal_indices.get(id))
21003            .or_else(|| command_id.and_then(|id| command_indices.get(id)))
21004            .copied();
21005        let index = duplicate.unwrap_or(signals.len());
21006        if let Some(index) = duplicate {
21007            let original = &mut signals[index];
21008            let same_arguments = if event.event_type == "SignalApplied" {
21009                if let Some(value) = event.payload.get("value") {
21010                    let expected = match original.avro_arguments.as_slice() {
21011                        [] => AvroValue::Boolean(true),
21012                        [value] => value.clone(),
21013                        values => AvroValue::Array(values.to_vec()),
21014                    };
21015                    let applied = decode_wire_avro_value(value, codec)?;
21016                    applied == expected
21017                        || applied == AvroValue::Array(original.avro_arguments.clone())
21018                } else {
21019                    original.avro_arguments == avro_arguments
21020                }
21021            } else {
21022                original.avro_arguments == avro_arguments
21023            };
21024            if original.name != name
21025                || !same_arguments
21026                || matches!((original.id.as_deref(), id), (Some(first), Some(next)) if first != next)
21027            {
21028                return Err(Error::Codec("conflicting committed signal identity".into()));
21029            }
21030            if original.id.is_none() {
21031                original.id = id.map(str::to_string);
21032            }
21033            original.workflow_sequence = original.workflow_sequence.or(workflow_sequence);
21034        } else {
21035            signals.push(QuerySignal {
21036                id: id.map(str::to_string),
21037                name: name.to_string(),
21038                arguments,
21039                avro_arguments,
21040                workflow_sequence,
21041            });
21042        }
21043        if let Some(id) = id {
21044            signal_indices.insert(id.to_string(), index);
21045        }
21046        if let Some(id) = command_id {
21047            command_indices.insert(id.to_string(), index);
21048        }
21049    }
21050
21051    if signals.is_empty() {
21052        for signal in export_signals {
21053            if signal.get("status").and_then(Value::as_str) == Some("rejected") {
21054                continue;
21055            }
21056            let Some(name) = signal.get("name").and_then(Value::as_str) else {
21057                continue;
21058            };
21059            let codec = signal
21060                .get("payload_codec")
21061                .and_then(Value::as_str)
21062                .unwrap_or(export_codec);
21063            let (arguments, avro_arguments) =
21064                decode_query_signal_arguments(signal.get("arguments"), codec)?;
21065            signals.push(QuerySignal {
21066                id: signal.get("id").and_then(Value::as_str).map(str::to_string),
21067                name: name.to_string(),
21068                arguments,
21069                avro_arguments,
21070                workflow_sequence: signal.get("workflow_sequence").and_then(value_as_u64),
21071            });
21072        }
21073        signals.sort_by_key(|signal| signal.workflow_sequence.unwrap_or(u64::MAX));
21074    }
21075
21076    Ok(signals)
21077}
21078
21079fn decode_query_signal_arguments(
21080    raw: Option<&Value>,
21081    codec: &str,
21082) -> Result<(Vec<Value>, Vec<AvroValue>)> {
21083    validate_payload_codec(codec)?;
21084    let decoded = match raw.filter(|value| !value.is_null()) {
21085        Some(value) => decode_wire_avro_value(value, codec)?,
21086        None => AvroValue::Array(Vec::new()),
21087    };
21088    let AvroValue::Array(avro_arguments) = normalize_avro_arguments(decoded) else {
21089        unreachable!("normalize_avro_arguments always returns an array");
21090    };
21091    let arguments = avro_arguments
21092        .iter()
21093        .cloned()
21094        .map(AvroValue::into_json)
21095        .collect::<Result<Vec<_>>>()?;
21096    Ok((arguments, avro_arguments))
21097}
21098
21099fn value_as_u64(value: &Value) -> Option<u64> {
21100    value
21101        .as_u64()
21102        .or_else(|| value.as_str().and_then(|value| value.parse().ok()))
21103}
21104
21105#[cfg(test)]
21106mod tests {
21107    use super::*;
21108    #[cfg(feature = "telemetry")]
21109    static OBSERVABILITY_PROPAGATOR_TEST_LOCK: tokio::sync::Mutex<()> =
21110        tokio::sync::Mutex::const_new(());
21111    mod activity_cancellation_policies;
21112    mod activity_lease_worker;
21113    mod cancellation_scope_admission;
21114    mod cancellation_scope_authoring;
21115    mod cancellation_scope_history;
21116    mod cancellation_scope_opening;
21117    mod cancellation_scope_replay;
21118    mod child_workflow_policies;
21119    mod completion_limits;
21120    mod condition_fingerprint;
21121    mod cooperative_cancellation;
21122    mod external_signal;
21123    mod history_transaction_limit;
21124    mod local_activity;
21125    mod nexus;
21126    mod path_segments;
21127    mod run_closed_settlement;
21128    mod runtime_payloads;
21129    mod runtime_uploads;
21130    mod static_credentials;
21131    mod version_marker_contract;
21132    mod worker_capacity;
21133    mod worker_session;
21134    mod worker_transient_outage;
21135    use std::{
21136        fs,
21137        io::{Read, Write},
21138        net::{SocketAddr, TcpListener, TcpStream},
21139        process::Command as ProcessCommand,
21140        sync::atomic::AtomicUsize,
21141        thread,
21142    };
21143
21144    #[derive(Clone, Copy, Debug)]
21145    enum InvalidTaskPayloadCodec {
21146        Missing,
21147        Null,
21148        NonString,
21149    }
21150
21151    impl InvalidTaskPayloadCodec {
21152        fn label(self) -> &'static str {
21153            match self {
21154                Self::Missing => "missing",
21155                Self::Null => "null",
21156                Self::NonString => "non-string",
21157            }
21158        }
21159
21160        fn apply(self, task: &mut Value) {
21161            let task = task.as_object_mut().expect("task fixture object");
21162            match self {
21163                Self::Missing => {
21164                    task.remove("payload_codec");
21165                }
21166                Self::Null => {
21167                    task.insert("payload_codec".to_string(), Value::Null);
21168                }
21169                Self::NonString => {
21170                    task.insert("payload_codec".to_string(), json!(42));
21171                }
21172            }
21173        }
21174    }
21175
21176    fn fixture_envelope(value: Value) -> Value {
21177        encode_value_envelope(&value, DEFAULT_CODEC).expect("encode Avro test fixture")
21178    }
21179
21180    fn fixture_blob(value: Value) -> String {
21181        encode_payload(&value, DEFAULT_CODEC)
21182            .expect("encode Avro test fixture")
21183            .blob
21184    }
21185
21186    #[test]
21187    fn client_builder_rejects_the_sdk_owned_api_suffix() {
21188        for base_url in [
21189            "http://127.0.0.1:8080/api",
21190            "http://localhost:8080/api/",
21191            "https://runtime.example.test/namespaces/orders/api",
21192        ] {
21193            let error = Client::builder(base_url)
21194                .build()
21195                .expect_err("SDK-owned /api suffix must be rejected during build");
21196
21197            assert!(matches!(error, Error::InvalidBaseUrl), "{base_url}");
21198            assert!(
21199                error.to_string().contains("SDK appends /api automatically"),
21200                "the validation error must explain how to fix the endpoint"
21201            );
21202        }
21203    }
21204
21205    #[test]
21206    fn client_builder_preserves_self_hosted_and_managed_runtime_prefixes() {
21207        for (base_url, expected) in [
21208            ("http://127.0.0.1:8080", "http://127.0.0.1:8080"),
21209            (
21210                "http://localhost:8080/durable-workflow/",
21211                "http://localhost:8080/durable-workflow",
21212            ),
21213            (
21214                "https://runtime.example.test/namespaces/orders",
21215                "https://runtime.example.test/namespaces/orders",
21216            ),
21217            (
21218                "https://runtime.example.test/gateway/api/namespaces/orders",
21219                "https://runtime.example.test/gateway/api/namespaces/orders",
21220            ),
21221            (
21222                "https://api.example.test/runtime/orders/",
21223                "https://api.example.test/runtime/orders",
21224            ),
21225        ] {
21226            let client = Client::builder(base_url)
21227                .build()
21228                .expect("Server and Cloud runtime base URL must remain valid");
21229
21230            assert_eq!(client.base_url, expected);
21231        }
21232    }
21233
21234    #[test]
21235    fn workflow_completion_uses_the_additive_command_protocol_floor() {
21236        assert_eq!(
21237            workflow_completion_protocol_version(&[json!({"type": "complete_workflow"})]),
21238            MINIMUM_WORKER_PROTOCOL_VERSION
21239        );
21240        assert_eq!(
21241            workflow_completion_protocol_version(&[json!({
21242                "type": "upsert_search_attributes",
21243                "attributes": {"OrderStatus": "waiting"},
21244            })]),
21245            SEARCH_ATTRIBUTE_UPDATE_MINIMUM_WORKER_PROTOCOL_VERSION
21246        );
21247        assert_eq!(
21248            workflow_completion_protocol_version(&[json!({
21249                "type": "upsert_search_attributes",
21250                "attributes": {"OrderStatus": "waiting"},
21251                "attribute_types": {"OrderStatus": "keyword"},
21252            })]),
21253            TYPED_SEARCH_ATTRIBUTES_MINIMUM_WORKER_PROTOCOL_VERSION
21254        );
21255        assert_eq!(
21256            workflow_completion_protocol_version(&[
21257                json!({"type": "upsert_memo", "entries": {"status": "waiting"}}),
21258                json!({"type": "open_condition_wait", "condition_key": "ready"}),
21259            ]),
21260            MEMO_UPSERT_MINIMUM_WORKER_PROTOCOL_VERSION
21261        );
21262        assert_eq!(
21263            workflow_completion_protocol_version(&[
21264                json!({"type": "upsert_search_attributes", "attributes": {"State": "waiting"}}),
21265                json!({"type": "open_condition_wait", "condition_key": "ready"}),
21266            ]),
21267            CONDITION_WAIT_MINIMUM_WORKER_PROTOCOL_VERSION
21268        );
21269        assert_eq!(
21270            workflow_completion_protocol_version(&[json!({
21271                "type": "open_condition_wait",
21272                "condition_wait_occurrence_id": "rust:condition-wait:0",
21273                "condition_key": "ready",
21274            })]),
21275            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
21276        );
21277        assert_eq!(
21278            workflow_completion_protocol_version_with_message_streams(
21279                &[json!({"type": "upsert_memo", "entries": {"status": "waiting"}})],
21280                true,
21281            ),
21282            MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION
21283        );
21284        assert_eq!(
21285            workflow_completion_protocol_version_with_message_streams(
21286                &[json!({
21287                    "type": "open_condition_wait",
21288                    "condition_wait_occurrence_id": "rust:condition-wait:0",
21289                    "condition_key": "ready",
21290                })],
21291                true,
21292            ),
21293            CONDITION_WAIT_OCCURRENCE_IDENTITY_MINIMUM_WORKER_PROTOCOL_VERSION
21294        );
21295    }
21296
21297    #[test]
21298    fn portable_worker_affinity_manifest_explicitly_refuses_unimplemented_features() {
21299        let manifest = portable_worker_affinity_capability_manifest();
21300
21301        for capability in ["local_activities", "worker_sessions", "sticky_execution"] {
21302            assert_eq!(manifest[capability]["supported"], json!(false));
21303            assert_eq!(
21304                manifest[capability]["minimum_protocol_version"],
21305                json!(PORTABLE_WORKER_AFFINITY_MINIMUM_PROTOCOL_VERSION)
21306            );
21307            assert!(manifest[capability]["reason"]
21308                .as_str()
21309                .is_some_and(|reason| !reason.is_empty()));
21310        }
21311    }
21312
21313    fn typed_fidelity_probe() -> AvroValue {
21314        AvroValue::Map(BTreeMap::from([
21315            ("bytes".to_string(), AvroValue::Bytes(vec![0, 0xff])),
21316            ("empty".to_string(), AvroValue::Map(BTreeMap::new())),
21317            (
21318                "numeric".to_string(),
21319                AvroValue::Map(BTreeMap::from([
21320                    ("0".to_string(), AvroValue::String("zero".to_string())),
21321                    ("1".to_string(), AvroValue::String("one".to_string())),
21322                ])),
21323            ),
21324            (
21325                "nested".to_string(),
21326                AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([(
21327                    "enabled".to_string(),
21328                    AvroValue::Boolean(true),
21329                )]))]),
21330            ),
21331            (
21332                "projection_collisions".to_string(),
21333                AvroValue::Array(projection_collision_probe()),
21334            ),
21335        ]))
21336    }
21337
21338    fn projection_collision_probe() -> Vec<AvroValue> {
21339        vec![
21340            AvroValue::Map(BTreeMap::from([
21341                ("$type".to_string(), AvroValue::String("bytes".to_string())),
21342                (
21343                    "base64".to_string(),
21344                    AvroValue::String("ordinary user text".to_string()),
21345                ),
21346            ])),
21347            AvroValue::Map(BTreeMap::from([
21348                ("$type".to_string(), AvroValue::String("map".to_string())),
21349                (
21350                    "entries".to_string(),
21351                    AvroValue::Array(vec![AvroValue::Map(BTreeMap::from([
21352                        ("key".to_string(), AvroValue::String("ordinary".to_string())),
21353                        (
21354                            "value".to_string(),
21355                            AvroValue::String("user map".to_string()),
21356                        ),
21357                    ]))]),
21358                ),
21359            ])),
21360        ]
21361    }
21362
21363    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
21364    struct TypedContract {
21365        nested: TypedNested,
21366        mode: TypedMode,
21367        optional: Option<String>,
21368        absent: Option<String>,
21369        items: Vec<i64>,
21370        labels: BTreeMap<String, String>,
21371        bytes: serde_bytes::ByteBuf,
21372        signed: i64,
21373        finite: f64,
21374    }
21375
21376    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
21377    struct TypedNested {
21378        enabled: bool,
21379    }
21380
21381    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
21382    enum TypedMode {
21383        Detailed { label: String },
21384    }
21385
21386    fn typed_contract() -> TypedContract {
21387        TypedContract {
21388            nested: TypedNested { enabled: true },
21389            mode: TypedMode::Detailed {
21390                label: "compiler-checked".to_string(),
21391            },
21392            optional: Some("present".to_string()),
21393            absent: None,
21394            items: vec![i64::MIN, 0, i64::MAX],
21395            labels: BTreeMap::from([
21396                ("language".to_string(), "rust".to_string()),
21397                ("wire".to_string(), "avro".to_string()),
21398            ]),
21399            bytes: serde_bytes::ByteBuf::from(vec![0, 0xff, 7]),
21400            signed: -9_223_372_036_854_775_000,
21401            finite: 12.5,
21402        }
21403    }
21404
21405    #[derive(Clone, Debug, Default, PartialEq)]
21406    struct ReplayCounterState {
21407        loaded: Option<String>,
21408        count: i64,
21409        finished: bool,
21410    }
21411
21412    fn replay_counter_worker() -> Worker {
21413        let client = Client::new("http://127.0.0.1:8080").expect("client");
21414        let mut worker = Worker::new(client, "rust-workers");
21415        worker.register_replayed_workflow(
21416            "replay-counter",
21417            ReplayCounterState::default,
21418            |ctx, _input, state| async move {
21419                let loaded = ctx.activity("load-counter", json!([])).await?;
21420                state.update(|current| {
21421                    current.loaded = loaded.as_str().map(str::to_string);
21422                })?;
21423                for _ in 0..2 {
21424                    let signal = ctx.wait_signal("increment").await?;
21425                    let amount = signal.first().and_then(Value::as_i64).unwrap_or_default();
21426                    state.update(|current| current.count += amount)?;
21427                }
21428                state.update(|current| current.finished = true)?;
21429                state.read(|current| Ok(json!(current.count)))?
21430            },
21431        );
21432        worker.register_replayed_query::<ReplayCounterState, _, _>(
21433            "replay-counter",
21434            "current",
21435            |_ctx, state, _args| async move {
21436                Ok(json!({
21437                    "loaded": state.loaded,
21438                    "count": state.count,
21439                    "finished": state.finished,
21440                }))
21441            },
21442        );
21443        worker.register_replayed_query::<ReplayCounterState, _, _>(
21444            "replay-counter",
21445            "detached-mutation",
21446            |_ctx, state, _args| async move {
21447                let mut detached = (*state).clone();
21448                detached.count = 999;
21449                Ok(json!(detached.count))
21450            },
21451        );
21452        worker.register_replayed_query::<ReplayCounterState, _, _>(
21453            "replay-counter",
21454            "failed-mutation",
21455            |_ctx, state, _args| async move {
21456                let mut detached = (*state).clone();
21457                detached.count = 999;
21458                Err(Error::WorkerLoop("query refused".to_string()))
21459            },
21460        );
21461        worker
21462    }
21463
21464    fn replay_counter_query(
21465        query_name: &str,
21466        history_events: Value,
21467        run_status: &str,
21468    ) -> QueryTask {
21469        let arguments = fixture_envelope(json!([]));
21470        serde_json::from_value(json!({
21471            "query_task_id": format!("query-{query_name}"),
21472            "workflow_type": "replay-counter",
21473            "query_name": query_name,
21474            "payload_codec": DEFAULT_CODEC,
21475            "workflow_arguments": arguments.clone(),
21476            "query_arguments": arguments,
21477            "history_events": history_events,
21478            "run_status": run_status,
21479        }))
21480        .expect("query task")
21481    }
21482
21483    fn workflow_context(history: Vec<HistoryEvent>) -> WorkflowContext {
21484        workflow_context_with_codec(history, DEFAULT_CODEC)
21485    }
21486
21487    fn workflow_context_with_codec(
21488        history: Vec<HistoryEvent>,
21489        payload_codec: &str,
21490    ) -> WorkflowContext {
21491        WorkflowContext {
21492            cancellation_scope_id: "root".into(),
21493            state: Arc::new(Mutex::new(
21494                WorkflowState::new_with_identity(
21495                    history,
21496                    None,
21497                    None,
21498                    "rust-workers".to_string(),
21499                    payload_codec.to_string(),
21500                    None,
21501                )
21502                .expect("valid workflow history"),
21503            )),
21504        }
21505    }
21506
21507    fn history_event(event_type: &str, payload: Value) -> HistoryEvent {
21508        HistoryEvent {
21509            event_type: event_type.to_string(),
21510            payload,
21511            raw: HashMap::new(),
21512        }
21513    }
21514
21515    fn parallel_path_entry(
21516        kind: &str,
21517        base: u64,
21518        size: usize,
21519        index: usize,
21520    ) -> ParallelGroupMetadata {
21521        parallel_group_entry(base, size, index, kind)
21522    }
21523
21524    fn parallel_history_event(
21525        event_type: &str,
21526        sequence: u64,
21527        identity_field: &str,
21528        identity: &str,
21529        path: Vec<ParallelGroupMetadata>,
21530        result: Option<Value>,
21531    ) -> HistoryEvent {
21532        let mut payload = serde_json::Map::from_iter([
21533            ("sequence".to_string(), json!(sequence)),
21534            (identity_field.to_string(), json!(identity)),
21535        ]);
21536        let inner = path.last().expect("parallel history path");
21537        apply_parallel_group_path(&mut payload, std::slice::from_ref(inner));
21538        payload.insert("parallel_group_path".to_string(), json!(path));
21539        if let Some(result) = result {
21540            payload.insert("result".to_string(), fixture_envelope(result));
21541            payload.insert("payload_codec".to_string(), json!(DEFAULT_CODEC));
21542        }
21543        history_event(event_type, Value::Object(payload))
21544    }
21545
21546    fn nested_parallel_operations() -> Vec<ParallelOperation> {
21547        vec![
21548            ParallelOperation::activity("first", json!([])),
21549            ParallelOperation::group(vec![
21550                ParallelOperation::child_workflow(
21551                    "second",
21552                    ChildWorkflowOptions::new("child-workers"),
21553                    json!([]),
21554                ),
21555                ParallelOperation::activity("third", json!([])),
21556            ]),
21557        ]
21558    }
21559
21560    fn nested_parallel_paths() -> [Vec<ParallelGroupMetadata>; 3] {
21561        let outer = [
21562            parallel_path_entry("mixed", 1, 3, 0),
21563            parallel_path_entry("mixed", 1, 3, 1),
21564            parallel_path_entry("mixed", 1, 3, 2),
21565        ];
21566        [
21567            vec![outer[0].clone()],
21568            vec![outer[1].clone(), parallel_path_entry("mixed", 2, 2, 0)],
21569            vec![outer[2].clone(), parallel_path_entry("mixed", 2, 2, 1)],
21570        ]
21571    }
21572
21573    #[test]
21574    fn parallel_schedules_every_nested_mixed_leaf_with_stable_metadata() {
21575        let ctx = workflow_context(Vec::new());
21576        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
21577        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21578
21579        assert!(matches!(
21580            call.as_mut().poll(&mut task_context),
21581            Poll::Pending
21582        ));
21583        let commands = ctx.take_commands().expect("parallel commands");
21584        assert_eq!(
21585            commands
21586                .iter()
21587                .map(|command| command["type"].as_str().unwrap_or_default())
21588                .collect::<Vec<_>>(),
21589            [
21590                "schedule_activity",
21591                "start_child_workflow",
21592                "schedule_activity"
21593            ]
21594        );
21595        let paths = nested_parallel_paths();
21596        for (command, path) in commands.iter().zip(paths) {
21597            assert_eq!(command["parallel_group_path"], json!(path));
21598            assert_eq!(
21599                command["parallel_group_id"],
21600                json!(path.last().expect("inner group").parallel_group_id)
21601            );
21602        }
21603    }
21604
21605    fn completed_nested_parallel_history() -> Vec<HistoryEvent> {
21606        let paths = nested_parallel_paths();
21607        let third = parallel_history_event(
21608            "ActivityCompleted",
21609            3,
21610            "activity_type",
21611            "third",
21612            paths[2].clone(),
21613            Some(json!("three")),
21614        );
21615        vec![
21616            parallel_history_event(
21617                "ActivityCompleted",
21618                1,
21619                "activity_type",
21620                "first",
21621                paths[0].clone(),
21622                Some(json!("one")),
21623            ),
21624            parallel_history_event(
21625                "ChildWorkflowScheduled",
21626                2,
21627                "child_workflow_type",
21628                "second",
21629                paths[1].clone(),
21630                None,
21631            ),
21632            parallel_history_event(
21633                "ChildRunCompleted",
21634                2,
21635                "child_workflow_type",
21636                "second",
21637                paths[1].clone(),
21638                Some(json!("two")),
21639            ),
21640            third.clone(),
21641            third,
21642        ]
21643    }
21644
21645    #[test]
21646    fn parallel_replay_rebuilds_input_order_and_tolerates_duplicate_delivery() {
21647        for _restart_or_completed_replay in 0..2 {
21648            let ctx = workflow_context(completed_nested_parallel_history());
21649            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
21650            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21651            let Poll::Ready(Ok(results)) = call.as_mut().poll(&mut task_context) else {
21652                panic!("completed nested parallel history must replay");
21653            };
21654            assert_eq!(
21655                results,
21656                vec![
21657                    ParallelResult::Activity(json!("one")),
21658                    ParallelResult::Group(vec![
21659                        ParallelResult::ChildWorkflow(ChildWorkflowResult {
21660                            parent: WorkflowIdentity {
21661                                workflow_id: None,
21662                                run_id: None,
21663                            },
21664                            child: WorkflowIdentity {
21665                                workflow_id: None,
21666                                run_id: None,
21667                            },
21668                            child_workflow_type: Some("second".to_string()),
21669                            result: json!("two"),
21670                        }),
21671                        ParallelResult::Activity(json!("three")),
21672                    ]),
21673                ]
21674            );
21675            assert!(ctx.take_commands().expect("commands").is_empty());
21676            ctx.ensure_history_consumed().expect("history consumed");
21677        }
21678    }
21679
21680    #[test]
21681    fn parallel_failure_keeps_typed_cause_path_and_late_completions() {
21682        let paths = nested_parallel_paths();
21683        let history = vec![
21684            parallel_history_event(
21685                "ActivityCompleted",
21686                1,
21687                "activity_type",
21688                "first",
21689                paths[0].clone(),
21690                Some(json!("one")),
21691            ),
21692            parallel_history_event(
21693                "ChildWorkflowScheduled",
21694                2,
21695                "child_workflow_type",
21696                "second",
21697                paths[1].clone(),
21698                None,
21699            ),
21700            parallel_history_event(
21701                "ChildRunFailed",
21702                2,
21703                "child_workflow_type",
21704                "second",
21705                paths[1].clone(),
21706                None,
21707            ),
21708            parallel_history_event(
21709                "ActivityCompleted",
21710                3,
21711                "activity_type",
21712                "third",
21713                paths[2].clone(),
21714                Some(json!("late")),
21715            ),
21716        ];
21717        let ctx = workflow_context(history);
21718        let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
21719        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21720        let outcome = call.as_mut().poll(&mut task_context);
21721        let Poll::Ready(Err(Error::ParallelFailed(failure))) = outcome else {
21722            panic!("one failed child must return a typed partial failure: {outcome:?}");
21723        };
21724        assert_eq!(failure.member_path, [1, 0]);
21725        assert_eq!(failure.group_id, "parallel-calls:1:3");
21726        assert!(matches!(*failure.cause, Error::ChildWorkflowFailed(_)));
21727        assert_eq!(
21728            failure
21729                .completed
21730                .iter()
21731                .map(|completion| completion.member_path.clone())
21732                .collect::<Vec<_>>(),
21733            [vec![0], vec![1, 1]]
21734        );
21735    }
21736
21737    #[test]
21738    fn pending_parallel_history_restarts_without_rescheduling_any_leaf() {
21739        let paths = nested_parallel_paths();
21740        let history = vec![
21741            parallel_history_event(
21742                "ActivityScheduled",
21743                1,
21744                "activity_type",
21745                "first",
21746                paths[0].clone(),
21747                None,
21748            ),
21749            parallel_history_event(
21750                "ChildWorkflowScheduled",
21751                2,
21752                "child_workflow_type",
21753                "second",
21754                paths[1].clone(),
21755                None,
21756            ),
21757            parallel_history_event(
21758                "ActivityScheduled",
21759                3,
21760                "activity_type",
21761                "third",
21762                paths[2].clone(),
21763                None,
21764            ),
21765        ];
21766        for _restart in 0..2 {
21767            let ctx = workflow_context(history.clone());
21768            let mut call = Box::pin(ctx.parallel(nested_parallel_operations()));
21769            let mut task_context = TaskContext::from_waker(noop_waker_ref());
21770            let outcome = call.as_mut().poll(&mut task_context);
21771            assert!(matches!(outcome, Poll::Pending), "{outcome:?}");
21772            assert!(ctx.take_commands().expect("commands").is_empty());
21773        }
21774    }
21775
21776    fn selection_path(index: usize, key: &str) -> Vec<ParallelGroupMetadata> {
21777        vec![selection_group_entry(
21778            1,
21779            2,
21780            index,
21781            "activity",
21782            &SelectionMemberMetadata {
21783                key: SelectionKey::Name(key.to_string()),
21784                index,
21785                base_sequence: index as u64 + 1,
21786                size: 1,
21787                kind: "activity".to_string(),
21788            },
21789        )]
21790    }
21791
21792    fn selection_activity_event(
21793        event_type: &str,
21794        index: usize,
21795        key: &str,
21796        result: Option<Value>,
21797    ) -> HistoryEvent {
21798        let sequence = index as u64 + 1;
21799        let mut event = parallel_history_event(
21800            event_type,
21801            sequence,
21802            "activity_type",
21803            &format!("{key}-activity"),
21804            selection_path(index, key),
21805            result,
21806        );
21807        event.payload["activity_execution_id"] = json!(format!("activity-{key}"));
21808        event.raw.insert(
21809            "id".to_string(),
21810            json!(if event_type == "ActivityCompleted" {
21811                format!("event-{key}")
21812            } else {
21813                format!("{event_type}-{key}")
21814            }),
21815        );
21816        event
21817    }
21818
21819    fn selection_winner_marker() -> HistoryEvent {
21820        history_event(
21821            "SelectionResolved",
21822            json!({
21823                "selection_group_id": "select-calls:1:2",
21824                "selection_group_base_sequence": 1,
21825                "selection_group_size": 2,
21826                "member_key": "fast",
21827                "member_index": 1,
21828                "member_base_sequence": 2,
21829                "member_size": 1,
21830                "operation_kind": "activity",
21831                "operation_identity": "activity-fast",
21832                "outcome": "completed",
21833                "resolution_event_id": "event-fast",
21834                "resolution_event_type": "ActivityCompleted",
21835            }),
21836        )
21837    }
21838
21839    fn keyed_activity_selection(ctx: &WorkflowContext) -> SelectCall {
21840        ctx.select_keyed(vec![
21841            (
21842                "slow",
21843                ParallelOperation::activity_with_options(
21844                    "slow-activity",
21845                    ActivityOptions::new().task_queue("default"),
21846                    json!([]),
21847                ),
21848            ),
21849            (
21850                "fast",
21851                ParallelOperation::activity_with_options(
21852                    "fast-activity",
21853                    ActivityOptions::new().task_queue("default"),
21854                    json!([]),
21855                ),
21856            ),
21857        ])
21858    }
21859
21860    fn assert_persisted_selection_replay(history: Vec<HistoryEvent>) {
21861        let ctx = workflow_context(history);
21862        let mut call = Box::pin(keyed_activity_selection(&ctx));
21863        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21864        let selected = match call.as_mut().poll(&mut task_context) {
21865            Poll::Ready(Ok(selected)) => selected,
21866            Poll::Ready(Err(error)) => panic!("persisted selection winner must replay: {error:?}"),
21867            Poll::Pending => panic!("persisted selection winner must replay without pending"),
21868        };
21869        assert_eq!(selected.key, SelectionKey::Name("fast".to_string()));
21870        assert_eq!(
21871            selected.value,
21872            Some(ParallelResult::Activity(json!("winner-value")))
21873        );
21874        let slow = selected
21875            .handle(&SelectionKey::Name("slow".to_string()))
21876            .expect("slow handle")
21877            .clone();
21878        let mut await_slow = Box::pin(slow.await_result());
21879        assert!(matches!(
21880            await_slow.as_mut().poll(&mut task_context),
21881            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("loser-value")
21882        ));
21883        assert!(ctx.take_commands().expect("commands").is_empty());
21884    }
21885
21886    const SELECTION_COLD_REPLAY_HISTORY: &str = "DURABLE_WORKFLOW_SELECTION_COLD_REPLAY_HISTORY";
21887
21888    fn canonical_selection_history() -> Vec<HistoryEvent> {
21889        const FIXTURE: &[u8] =
21890            include_bytes!("../tests/fixtures/durable_selection_runtime_history.json");
21891        assert_eq!(
21892            format!("{:x}", Sha256::digest(FIXTURE)),
21893            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
21894        );
21895        let fixture: Value = serde_json::from_slice(FIXTURE).expect("canonical selection fixture");
21896
21897        serde_json::from_value(fixture["history"].clone()).expect("canonical selection history")
21898    }
21899
21900    #[test]
21901    fn selection_fresh_process_entrypoint() {
21902        let Ok(path) = std::env::var(SELECTION_COLD_REPLAY_HISTORY) else {
21903            return;
21904        };
21905        let persisted = fs::read(path).expect("persisted selection history");
21906        assert_eq!(
21907            format!("{:x}", Sha256::digest(&persisted)),
21908            "51fd8b9c16e978dcef536a5c727b9fdc0ae724d9afc17d9a7837d219f41ee3ba",
21909        );
21910        let fixture: Value =
21911            serde_json::from_slice(&persisted).expect("valid persisted selection fixture");
21912        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
21913            .expect("valid persisted selection history");
21914
21915        assert_persisted_selection_replay(history);
21916    }
21917
21918    #[test]
21919    fn selection_starts_every_member_with_stable_keys_and_group_identity() {
21920        let ctx = workflow_context(Vec::new());
21921        let mut call = Box::pin(keyed_activity_selection(&ctx));
21922        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21923
21924        assert!(matches!(
21925            call.as_mut().poll(&mut task_context),
21926            Poll::Pending
21927        ));
21928        let commands = ctx.take_commands().expect("selection commands");
21929        assert_eq!(commands.len(), 2);
21930        assert_eq!(commands[0]["selection_member_key"], json!("slow"));
21931        assert_eq!(commands[1]["selection_member_key"], json!("fast"));
21932        assert!(commands.iter().all(|command| {
21933            command["parallel_group_id"] == json!("select-calls:1:2")
21934                && command["parallel_group_mode"] == json!("select")
21935        }));
21936    }
21937
21938    #[test]
21939    fn selection_key_domain_rejects_empty_authoring_and_malformed_history() {
21940        let ctx = workflow_context(Vec::new());
21941        let mut invalid = Box::pin(ctx.select_keyed(vec![(
21942            "",
21943            ParallelOperation::activity("invalid", json!([])),
21944        )]));
21945        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21946        assert!(matches!(
21947            invalid.as_mut().poll(&mut task_context),
21948            Poll::Ready(Err(Error::InvalidParallelGroup(ParallelGroupError {
21949                reason: "selection_key_invalid",
21950                ..
21951            })))
21952        ));
21953
21954        for invalid_key in [json!(""), json!(-1)] {
21955            let mut event = selection_activity_event("ActivityScheduled", 0, "slow", None);
21956            event.payload["selection_member_key"] = invalid_key.clone();
21957            event.payload["parallel_group_path"][0]["selection_member_key"] = invalid_key;
21958            assert!(matches!(
21959                WorkflowState::new_with_identity(
21960                    vec![event],
21961                    None,
21962                    None,
21963                    "rust-workers".to_string(),
21964                    DEFAULT_CODEC.to_string(),
21965                    None,
21966                ),
21967                Err(Error::NonDeterministicReplay(_))
21968            ));
21969        }
21970    }
21971
21972    #[test]
21973    fn selection_preserves_valid_named_and_numeric_keys() {
21974        let ctx = workflow_context(Vec::new());
21975        let mut selection = Box::pin(ctx.select_keyed(vec![
21976            (
21977                SelectionKey::Index(0),
21978                ParallelOperation::activity("numeric", json!([])),
21979            ),
21980            (
21981                SelectionKey::Name("named".to_string()),
21982                ParallelOperation::timer(Duration::from_secs(1)),
21983            ),
21984        ]));
21985        let mut task_context = TaskContext::from_waker(noop_waker_ref());
21986
21987        assert!(matches!(
21988            selection.as_mut().poll(&mut task_context),
21989            Poll::Pending
21990        ));
21991        let commands = ctx.take_commands().expect("selection commands");
21992        assert_eq!(commands[0]["selection_member_key"], json!(0));
21993        assert_eq!(commands[1]["selection_member_key"], json!("named"));
21994    }
21995
21996    #[test]
21997    fn selection_replays_persisted_winner_and_loser_can_be_awaited_later() {
21998        let history = canonical_selection_history();
21999        assert_persisted_selection_replay(history.clone());
22000
22001        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
22002            .join("tests/fixtures/durable_selection_runtime_history.json");
22003        let output =
22004            ProcessCommand::new(std::env::current_exe().expect("current Rust test binary"))
22005                .args([
22006                    "--exact",
22007                    "tests::selection_fresh_process_entrypoint",
22008                    "--nocapture",
22009                ])
22010                .env(SELECTION_COLD_REPLAY_HISTORY, &path)
22011                .output()
22012                .expect("run fresh selection replay process");
22013
22014        assert!(
22015            output.status.success(),
22016            "fresh selection replay failed:\nstdout:\n{}\nstderr:\n{}",
22017            String::from_utf8_lossy(&output.stdout),
22018            String::from_utf8_lossy(&output.stderr),
22019        );
22020    }
22021
22022    #[test]
22023    fn selection_waits_durably_when_terminal_members_precede_the_winner_marker() {
22024        let mut history = canonical_selection_history();
22025        history.retain(|event| event.event_type != "SelectionResolved");
22026        let ctx = workflow_context(history);
22027        let mut selection = Box::pin(keyed_activity_selection(&ctx));
22028        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22029
22030        assert!(matches!(
22031            selection.as_mut().poll(&mut task_context),
22032            Poll::Pending
22033        ));
22034        assert!(ctx.take_commands().expect("commands").is_empty());
22035        assert!(
22036            ctx.matched_recorded_pending()
22037                .expect("selection pending state"),
22038            "terminal member history must keep the workflow durably pending until SelectionResolved commits"
22039        );
22040    }
22041
22042    #[test]
22043    fn selection_terminal_condition_history_waits_durably_for_its_winner_marker() {
22044        for (terminal_event, predicate_satisfied, timeout_seconds) in [
22045            ("ConditionWaitSatisfied", true, None),
22046            ("ConditionWaitTimedOut", false, Some(0)),
22047        ] {
22048            let member = SelectionMemberMetadata {
22049                key: SelectionKey::Name("condition".to_string()),
22050                index: 0,
22051                base_sequence: 1,
22052                size: 1,
22053                kind: "condition".to_string(),
22054            };
22055            let path = vec![selection_group_entry(1, 1, 0, "condition", &member)];
22056            let mut payload = json!({
22057                "sequence": 1,
22058                "condition_wait_id": "condition-1",
22059                "condition_wait_occurrence_id": "rust:condition-wait:0",
22060                "condition_key": "ready",
22061                "condition_definition_fingerprint": "sha256:ready-v1",
22062                "parallel_group_path": path,
22063            });
22064            payload
22065                .as_object_mut()
22066                .expect("condition history payload")
22067                .extend(
22068                    serde_json::to_value(&path[0])
22069                        .expect("condition selection metadata")
22070                        .as_object()
22071                        .expect("condition selection metadata object")
22072                        .clone(),
22073                );
22074            if let Some(timeout_seconds) = timeout_seconds {
22075                payload["timeout_seconds"] = json!(timeout_seconds);
22076            }
22077            let history = vec![
22078                history_event("ConditionWaitOpened", payload.clone()),
22079                history_event(terminal_event, payload),
22080            ];
22081            let ctx = workflow_context(history);
22082            let mut options = ConditionWaitOptions::new("ready", "sha256:ready-v1");
22083            if timeout_seconds.is_some() {
22084                options = options.timeout(Duration::ZERO);
22085            }
22086            let mut selection = Box::pin(ctx.select_keyed(vec![(
22087                "condition",
22088                ParallelOperation::condition(options, move || Ok(predicate_satisfied)),
22089            )]));
22090            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22091
22092            assert!(matches!(
22093                selection.as_mut().poll(&mut task_context),
22094                Poll::Pending
22095            ));
22096            assert!(ctx.take_commands().expect("commands").is_empty());
22097            assert!(
22098                ctx.matched_recorded_pending()
22099                    .expect("condition selection pending state"),
22100                "{terminal_event} must keep the workflow durably pending until SelectionResolved commits"
22101            );
22102        }
22103    }
22104
22105    #[test]
22106    fn selection_immediate_condition_members_open_a_durable_wait() {
22107        for predicate_satisfied in [true, false] {
22108            let ctx = workflow_context(Vec::new());
22109            let mut selection = Box::pin(ctx.select_keyed(vec![(
22110                "condition",
22111                ParallelOperation::condition(
22112                    ConditionWaitOptions::new("ready", "sha256:ready-v1").timeout(Duration::ZERO),
22113                    move || Ok(predicate_satisfied),
22114                ),
22115            )]));
22116            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22117
22118            assert!(matches!(
22119                selection.as_mut().poll(&mut task_context),
22120                Poll::Pending
22121            ));
22122            let commands = ctx.take_commands().expect("condition selection command");
22123            assert_eq!(commands.len(), 1);
22124            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
22125            assert_eq!(commands[0]["timeout_seconds"], json!(0));
22126            assert_eq!(
22127                commands[0]["parallel_group_path"][0]["parallel_group_mode"],
22128                json!("select")
22129            );
22130        }
22131    }
22132
22133    #[test]
22134    fn selection_loser_cancellation_is_explicit_and_idempotent() {
22135        let history = vec![
22136            selection_activity_event("ActivityScheduled", 0, "slow", None),
22137            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
22138            selection_winner_marker(),
22139        ];
22140        let ctx = workflow_context(history.clone());
22141        let mut call = Box::pin(keyed_activity_selection(&ctx));
22142        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22143        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
22144            panic!("winner must replay");
22145        };
22146        let slow = selected
22147            .handle(&SelectionKey::Name("slow".to_string()))
22148            .expect("slow handle")
22149            .clone();
22150        let mut cancel = Box::pin(slow.cancel());
22151        assert!(matches!(
22152            cancel.as_mut().poll(&mut task_context),
22153            Poll::Ready(Ok(()))
22154        ));
22155        assert!(matches!(
22156            cancel.as_mut().poll(&mut task_context),
22157            Poll::Ready(Ok(()))
22158        ));
22159        let mut outcome = Box::pin(slow.await_result());
22160        assert!(matches!(
22161            outcome.as_mut().poll(&mut task_context),
22162            Poll::Pending
22163        ));
22164        let commands = ctx.take_commands().expect("cancel command");
22165        assert_eq!(commands.len(), 1);
22166        assert_eq!(commands[0]["type"], json!("cancel_selection_operation"));
22167        assert_eq!(commands[0]["member_key"], json!("slow"));
22168
22169        let mut cancelled_history = history;
22170        cancelled_history.push(history_event(
22171            "SelectionOperationCancelled",
22172            json!({
22173                "selection_group_id": "select-calls:1:2",
22174                "member_key": "slow",
22175                "member_index": 0,
22176                "member_base_sequence": 1,
22177                "member_size": 1,
22178                "operation_kind": "activity",
22179                "operation_identity": "activity-slow",
22180                "cancelled_at": "2026-08-27T00:00:00Z",
22181            }),
22182        ));
22183        let replayed = workflow_context(cancelled_history);
22184        let mut call = Box::pin(keyed_activity_selection(&replayed));
22185        let Poll::Ready(Ok(selected)) = call.as_mut().poll(&mut task_context) else {
22186            panic!("winner must replay after cancellation");
22187        };
22188        let slow = selected
22189            .handle(&SelectionKey::Name("slow".to_string()))
22190            .expect("slow handle")
22191            .clone();
22192        let mut cancel = Box::pin(slow.cancel());
22193        assert!(matches!(
22194            cancel.as_mut().poll(&mut task_context),
22195            Poll::Ready(Ok(()))
22196        ));
22197        assert!(replayed.take_commands().expect("commands").is_empty());
22198    }
22199
22200    #[test]
22201    fn selection_cancellation_marker_is_bound_to_every_authored_handle_field() {
22202        let base_history = vec![
22203            selection_activity_event("ActivityScheduled", 0, "slow", None),
22204            selection_activity_event("ActivityScheduled", 1, "fast", None),
22205            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
22206            selection_winner_marker(),
22207        ];
22208        for (field, corrupt) in [
22209            ("member_key", json!("fast")),
22210            ("member_index", json!(1)),
22211            ("member_base_sequence", json!(3)),
22212            ("member_size", json!(2)),
22213            ("operation_kind", json!("timer")),
22214            ("operation_identity", json!("forged")),
22215        ] {
22216            let mut cancellation = json!({
22217                "selection_group_id": "select-calls:1:2",
22218                "member_key": "slow",
22219                "member_index": 0,
22220                "member_base_sequence": 1,
22221                "member_size": 1,
22222                "operation_kind": "activity",
22223                "operation_identity": "activity-slow",
22224            });
22225            cancellation[field] = corrupt;
22226            let mut history = base_history.clone();
22227            history.push(history_event("SelectionOperationCancelled", cancellation));
22228            let ctx = workflow_context(history);
22229            let mut selection = Box::pin(keyed_activity_selection(&ctx));
22230            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22231
22232            assert!(matches!(
22233                selection.as_mut().poll(&mut task_context),
22234                Poll::Ready(Err(Error::NonDeterministicReplay(_)))
22235            ));
22236        }
22237    }
22238
22239    #[test]
22240    fn selection_child_identity_prefers_the_durable_run_id() {
22241        let ctx = workflow_context(vec![history_event(
22242            "ChildWorkflowScheduled",
22243            json!({
22244                "sequence": 1,
22245                "child_workflow_type": "child",
22246                "child_workflow_instance_id": "child-instance",
22247                "child_workflow_run_id": "child-run",
22248            }),
22249        )]);
22250        let state = ctx.state.lock().expect("workflow state");
22251
22252        assert_eq!(
22253            selection_operation_identity(&state, "child", 1, 1),
22254            "child-run"
22255        );
22256    }
22257
22258    #[test]
22259    fn selection_activity_identity_requires_canonical_execution_id() {
22260        let slow = selection_activity_event("ActivityScheduled", 0, "slow", None);
22261        let mut fast_open = selection_activity_event("ActivityScheduled", 1, "fast", None);
22262        let mut fast_completed =
22263            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner")));
22264        for event in [&mut fast_open, &mut fast_completed] {
22265            event
22266                .payload
22267                .as_object_mut()
22268                .expect("activity payload")
22269                .remove("activity_execution_id");
22270            event.payload["activity_id"] = json!("forged-activity-id");
22271        }
22272        let mut marker = selection_winner_marker();
22273        marker.payload["operation_identity"] = json!("forged-activity-id");
22274        let ctx = workflow_context(vec![slow, fast_open, fast_completed, marker]);
22275        let mut selection = Box::pin(keyed_activity_selection(&ctx));
22276        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22277
22278        assert!(matches!(
22279            selection.as_mut().poll(&mut task_context),
22280            Poll::Ready(Err(Error::NonDeterministicReplay(_)))
22281        ));
22282    }
22283
22284    #[test]
22285    fn selection_completion_before_cancellation_remains_awaitable() {
22286        let history = vec![
22287            selection_activity_event("ActivityScheduled", 0, "slow", None),
22288            selection_activity_event("ActivityCompleted", 1, "fast", Some(json!("winner"))),
22289            selection_winner_marker(),
22290            selection_activity_event(
22291                "ActivityCompleted",
22292                0,
22293                "slow",
22294                Some(json!("completed-first")),
22295            ),
22296        ];
22297        let ctx = workflow_context(history);
22298        let mut selection = Box::pin(keyed_activity_selection(&ctx));
22299        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22300        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
22301            panic!("winner must replay");
22302        };
22303        let slow = selected
22304            .handle(&SelectionKey::Name("slow".to_string()))
22305            .expect("slow handle")
22306            .clone();
22307        let mut cancel = Box::pin(slow.cancel());
22308        assert!(matches!(
22309            cancel.as_mut().poll(&mut task_context),
22310            Poll::Ready(Ok(()))
22311        ));
22312        let mut await_slow = Box::pin(slow.await_result());
22313        assert!(matches!(
22314            await_slow.as_mut().poll(&mut task_context),
22315            Poll::Ready(Ok(ParallelResult::Activity(value))) if value == json!("completed-first")
22316        ));
22317        let commands = ctx.take_commands().expect("commands");
22318        assert!(commands.is_empty());
22319    }
22320
22321    #[test]
22322    fn selection_nested_later_failure_before_cancel_remains_the_awaited_failure() {
22323        let nested_member = SelectionMemberMetadata {
22324            key: SelectionKey::Name("nested".to_string()),
22325            index: 0,
22326            base_sequence: 1,
22327            size: 2,
22328            kind: "group".to_string(),
22329        };
22330        let deadline_member = SelectionMemberMetadata {
22331            key: SelectionKey::Name("deadline".to_string()),
22332            index: 1,
22333            base_sequence: 3,
22334            size: 1,
22335            kind: "timer".to_string(),
22336        };
22337        let nested_paths = [
22338            vec![
22339                selection_group_entry(1, 3, 0, "mixed", &nested_member),
22340                parallel_group_entry(1, 2, 0, "activity"),
22341            ],
22342            vec![
22343                selection_group_entry(1, 3, 1, "mixed", &nested_member),
22344                parallel_group_entry(1, 2, 1, "activity"),
22345            ],
22346        ];
22347        let deadline_path = vec![selection_group_entry(1, 3, 2, "mixed", &deadline_member)];
22348        let mut timer_fired = parallel_history_event(
22349            "TimerFired",
22350            3,
22351            "timer_id",
22352            "timer-3",
22353            deadline_path.clone(),
22354            None,
22355        );
22356        timer_fired.payload["delay_seconds"] = json!(0);
22357        timer_fired
22358            .raw
22359            .insert("id".to_string(), json!("timer-fired"));
22360        let mut timer_scheduled = parallel_history_event(
22361            "TimerScheduled",
22362            3,
22363            "timer_id",
22364            "timer-3",
22365            deadline_path,
22366            None,
22367        );
22368        timer_scheduled.payload["delay_seconds"] = json!(0);
22369        let history = vec![
22370            parallel_history_event(
22371                "ActivityScheduled",
22372                1,
22373                "activity_type",
22374                "nested-first",
22375                nested_paths[0].clone(),
22376                None,
22377            ),
22378            parallel_history_event(
22379                "ActivityScheduled",
22380                2,
22381                "activity_type",
22382                "nested-second",
22383                nested_paths[1].clone(),
22384                None,
22385            ),
22386            timer_scheduled,
22387            timer_fired,
22388            history_event(
22389                "SelectionResolved",
22390                json!({
22391                    "selection_group_id": "select-calls:1:3",
22392                    "selection_group_base_sequence": 1,
22393                    "selection_group_size": 3,
22394                    "member_key": "deadline",
22395                    "member_index": 1,
22396                    "member_base_sequence": 3,
22397                    "member_size": 1,
22398                    "operation_kind": "timer",
22399                    "operation_identity": "timer-3",
22400                    "outcome": "completed",
22401                    "resolution_event_id": "timer-fired",
22402                    "resolution_event_type": "TimerFired",
22403                }),
22404            ),
22405            parallel_history_event(
22406                "ActivityFailed",
22407                2,
22408                "activity_type",
22409                "nested-second",
22410                nested_paths[1].clone(),
22411                None,
22412            ),
22413        ];
22414        let ctx = workflow_context(history);
22415        let mut selection = Box::pin(ctx.select_keyed(vec![
22416            (
22417                "nested",
22418                ParallelOperation::group(vec![
22419                    ParallelOperation::activity("nested-first", json!([])),
22420                    ParallelOperation::activity("nested-second", json!([])),
22421                ]),
22422            ),
22423            ("deadline", ParallelOperation::timer(Duration::ZERO)),
22424        ]));
22425        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22426        let Poll::Ready(Ok(selected)) = selection.as_mut().poll(&mut task_context) else {
22427            panic!("deadline winner must replay");
22428        };
22429        let nested = selected
22430            .handle(&SelectionKey::Name("nested".to_string()))
22431            .expect("nested handle")
22432            .clone();
22433        let mut cancel = Box::pin(nested.cancel());
22434        assert!(matches!(
22435            cancel.as_mut().poll(&mut task_context),
22436            Poll::Ready(Ok(()))
22437        ));
22438        let mut await_nested = Box::pin(nested.await_result());
22439
22440        assert!(matches!(
22441            await_nested.as_mut().poll(&mut task_context),
22442            Poll::Ready(Err(Error::ActivityFailed(_)))
22443        ));
22444        assert!(ctx.take_commands().expect("commands").is_empty());
22445    }
22446
22447    #[test]
22448    fn selection_supports_child_timer_signal_condition_and_nested_groups() {
22449        let ctx = workflow_context(Vec::new());
22450        let mut call = Box::pin(ctx.select(vec![
22451            ParallelOperation::child_workflow(
22452                "child",
22453                ChildWorkflowOptions::new("children"),
22454                json!([]),
22455            ),
22456            ParallelOperation::timer(Duration::from_secs(30)),
22457            ParallelOperation::signal("approval"),
22458            ParallelOperation::condition(
22459                ConditionWaitOptions::new("ready", "sha256:ready"),
22460                || Ok(false),
22461            ),
22462            ParallelOperation::group(vec![
22463                ParallelOperation::activity("nested-one", json!([])),
22464                ParallelOperation::activity("nested-two", json!([])),
22465            ]),
22466        ]));
22467        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22468        assert!(matches!(
22469            call.as_mut().poll(&mut task_context),
22470            Poll::Pending
22471        ));
22472        let commands = ctx.take_commands().expect("selection commands");
22473        assert_eq!(
22474            commands
22475                .iter()
22476                .map(|command| command["type"].as_str().unwrap_or_default())
22477                .collect::<Vec<_>>(),
22478            [
22479                "start_child_workflow",
22480                "start_timer",
22481                "open_signal_wait",
22482                "open_condition_wait",
22483                "schedule_activity",
22484                "schedule_activity",
22485            ]
22486        );
22487        assert!(commands.iter().all(|command| {
22488            command["parallel_group_path"][0]["parallel_group_mode"] == json!("select")
22489        }));
22490        assert_eq!(
22491            commands[4]["parallel_group_path"].as_array().map(Vec::len),
22492            Some(2)
22493        );
22494        assert_eq!(
22495            commands[4]["parallel_group_path"][0]["selection_member_kind"],
22496            json!("group")
22497        );
22498        assert_eq!(
22499            commands[5]["parallel_group_path"][0]["selection_member_kind"],
22500            json!("group")
22501        );
22502
22503        let one_leaf_ctx = workflow_context(Vec::new());
22504        let mut one_leaf = Box::pin(one_leaf_ctx.select(vec![ParallelOperation::group(vec![
22505            ParallelOperation::activity("nested-only", json!([])),
22506        ])]));
22507        assert!(matches!(
22508            one_leaf.as_mut().poll(&mut task_context),
22509            Poll::Pending
22510        ));
22511        let one_leaf_commands = one_leaf_ctx.take_commands().expect("one-leaf commands");
22512        assert_eq!(one_leaf_commands.len(), 1);
22513        assert_eq!(
22514            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_kind"],
22515            json!("group")
22516        );
22517        assert_eq!(
22518            one_leaf_commands[0]["parallel_group_path"][0]["selection_member_size"],
22519            json!(1)
22520        );
22521    }
22522
22523    async fn trip_saga(ctx: WorkflowContext) -> Result<Value> {
22524        let mut saga = ctx.saga();
22525        let outcome = async {
22526            let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
22527            saga.add_compensation("trip.cancel-flight", json!([flight]))?;
22528            let hotel = ctx.activity("trip.reserve-hotel", json!([])).await?;
22529            saga.add_compensation("trip.cancel-hotel", json!([hotel]))?;
22530            ctx.activity("trip.charge", json!([])).await?;
22531            Ok(json!({"status": "booked"}))
22532        }
22533        .await;
22534        saga.finish(outcome).await
22535    }
22536
22537    fn saga_activity(
22538        event_type: &str,
22539        sequence: u64,
22540        activity_type: &str,
22541        result: Option<Value>,
22542    ) -> HistoryEvent {
22543        let mut payload = json!({
22544            "sequence": sequence,
22545            "activity_type": activity_type,
22546            "message": format!("{activity_type} failed"),
22547            "exception_type": "PlannedFailure",
22548            "non_retryable": true,
22549        });
22550        if let Some(result) = result {
22551            payload["result"] = fixture_envelope(result);
22552        }
22553        history_event(event_type, payload)
22554    }
22555
22556    #[test]
22557    fn saga_replays_reverse_compensation_across_restart_and_duplicate_delivery() {
22558        let completed_hotel_compensation = saga_activity(
22559            "ActivityCompleted",
22560            4,
22561            "trip.cancel-hotel",
22562            Some(Value::Null),
22563        );
22564        let history = vec![
22565            saga_activity(
22566                "ActivityCompleted",
22567                1,
22568                "trip.reserve-flight",
22569                Some(json!("flight-1")),
22570            ),
22571            saga_activity(
22572                "ActivityCompleted",
22573                2,
22574                "trip.reserve-hotel",
22575                Some(json!("hotel-1")),
22576            ),
22577            saga_activity("ActivityFailed", 3, "trip.charge", None),
22578            completed_hotel_compensation.clone(),
22579            completed_hotel_compensation,
22580        ];
22581
22582        for _restart in 0..2 {
22583            let ctx = workflow_context(history.clone());
22584            let mut future = Box::pin(trip_saga(ctx.clone()));
22585            let mut task_context = TaskContext::from_waker(noop_waker_ref());
22586            assert!(matches!(
22587                future.as_mut().poll(&mut task_context),
22588                Poll::Pending
22589            ));
22590            let commands = ctx.take_commands().expect("compensation command");
22591            assert_eq!(commands.len(), 1);
22592            assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
22593        }
22594    }
22595
22596    #[test]
22597    fn saga_compensation_failure_preserves_both_typed_failures() {
22598        let history = vec![
22599            saga_activity(
22600                "ActivityCompleted",
22601                1,
22602                "trip.reserve-flight",
22603                Some(json!("flight-1")),
22604            ),
22605            saga_activity(
22606                "ActivityCompleted",
22607                2,
22608                "trip.reserve-hotel",
22609                Some(json!("hotel-1")),
22610            ),
22611            saga_activity("ActivityFailed", 3, "trip.charge", None),
22612            saga_activity("ActivityFailed", 4, "trip.cancel-hotel", None),
22613        ];
22614        let ctx = workflow_context(history);
22615        let mut future = Box::pin(trip_saga(ctx));
22616        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22617        let Poll::Ready(Err(Error::SagaCompensationFailed(failure))) =
22618            future.as_mut().poll(&mut task_context)
22619        else {
22620            panic!("compensation failure must remain structured");
22621        };
22622        assert!(matches!(
22623            *failure.initiating_failure,
22624            Error::ActivityFailed(_)
22625        ));
22626        assert!(matches!(
22627            *failure.compensation_failure,
22628            Error::ActivityFailed(_)
22629        ));
22630        assert_eq!(failure.compensation_activity_type, "trip.cancel-hotel");
22631        assert_eq!(failure.compensation_registration_order, 2);
22632    }
22633
22634    #[test]
22635    fn saga_compensates_cooperative_cancellation() {
22636        let ctx = workflow_context(vec![saga_activity(
22637            "ActivityCompleted",
22638            1,
22639            "trip.reserve-flight",
22640            Some(json!("flight-1")),
22641        )]);
22642        ctx.state.lock().expect("state").cancel_requested = true;
22643        let run = {
22644            let ctx = ctx.clone();
22645            async move {
22646                let mut saga = ctx.saga();
22647                let outcome = async {
22648                    let flight = ctx.activity("trip.reserve-flight", json!([])).await?;
22649                    saga.add_compensation("trip.cancel-flight", json!([flight]))?;
22650                    ctx.throw_if_cancellation_requested()?;
22651                    Ok(json!("unexpected"))
22652                }
22653                .await;
22654                saga.finish(outcome).await
22655            }
22656        };
22657        let mut future = Box::pin(run);
22658        let mut task_context = TaskContext::from_waker(noop_waker_ref());
22659        assert!(matches!(
22660            future.as_mut().poll(&mut task_context),
22661            Poll::Pending
22662        ));
22663        let commands = ctx.take_commands().expect("cancellation compensation");
22664        assert_eq!(commands[0]["activity_type"], "trip.cancel-flight");
22665    }
22666
22667    #[test]
22668    fn optional_task_observability_fields_round_trip_without_interpretation() {
22669        let context = json!({"schema": "unknown", "carrier": {"traceparent": "untrusted"}});
22670        let dispatch = json!({"task_id": "other-task"});
22671        let links = json!({"links": []});
22672        let mut value = json!({
22673            "task_id": "task", "query_task_id": "query", "workflow_type": "workflow",
22674            "activity_type": "activity", "query_name": "query", "payload_codec": "avro"
22675        });
22676        let workflow: WorkflowTask =
22677            serde_json::from_value(value.clone()).expect("legacy workflow task");
22678        let activity: ActivityTask =
22679            serde_json::from_value(value.clone()).expect("legacy activity task");
22680        let query: QueryTask = serde_json::from_value(value.clone()).expect("legacy query task");
22681        assert!(workflow.observability_context.is_none());
22682        assert!(activity.observability_context.is_none());
22683        assert!(query.observability_context.is_none());
22684        assert!(activity.workflow_id.is_none());
22685        assert!(activity.run_id.is_none());
22686        assert!(activity.activity_execution_id.is_none());
22687
22688        value["observability_context"] = context.clone();
22689        value["dispatch_observability_context"] = dispatch.clone();
22690        value["observability_links"] = links.clone();
22691        value["workflow_id"] = json!("workflow-id");
22692        value["run_id"] = json!("run-id");
22693        value["activity_execution_id"] = json!("activity-id");
22694        let workflow: WorkflowTask =
22695            serde_json::from_value(value.clone()).expect("workflow metadata");
22696        let activity: ActivityTask =
22697            serde_json::from_value(value.clone()).expect("activity metadata");
22698        let query: QueryTask = serde_json::from_value(value).expect("query metadata");
22699        for fields in [
22700            (
22701                workflow.observability_context,
22702                workflow.dispatch_observability_context,
22703                workflow.observability_links,
22704            ),
22705            (
22706                activity.observability_context,
22707                activity.dispatch_observability_context,
22708                activity.observability_links,
22709            ),
22710            (
22711                query.observability_context,
22712                query.dispatch_observability_context,
22713                query.observability_links,
22714            ),
22715        ] {
22716            assert_eq!(
22717                fields,
22718                (
22719                    Some(context.clone()),
22720                    Some(dispatch.clone()),
22721                    Some(links.clone())
22722                )
22723            );
22724        }
22725        assert_eq!(activity.workflow_id.as_deref(), Some("workflow-id"));
22726        assert_eq!(activity.run_id.as_deref(), Some("run-id"));
22727        assert_eq!(
22728            activity.activity_execution_id.as_deref(),
22729            Some("activity-id")
22730        );
22731    }
22732
22733    fn workflow_task(
22734        workflow_type: &str,
22735        history_events: Vec<HistoryEvent>,
22736        payload_codec: &str,
22737    ) -> WorkflowTask {
22738        WorkflowTask {
22739            task_id: format!("wft-{workflow_type}"),
22740            observability_context: None,
22741            dispatch_observability_context: None,
22742            observability_links: None,
22743            workflow_command_id: None,
22744            workflow_id: Some(format!("wf-{workflow_type}")),
22745            run_id: Some(format!("run-{workflow_type}")),
22746            workflow_type: workflow_type.to_string(),
22747            cancel_requested: false,
22748            payload_codec: payload_codec.to_string(),
22749            arguments: Some(
22750                encode_value_envelope(&json!([]), payload_codec).expect("workflow arguments"),
22751            ),
22752            total_history_events: Some(history_events.len() as u64),
22753            history_size_bytes: None,
22754            continue_as_new_recommended: None,
22755            history_budget_pressure: None,
22756            history_events,
22757            next_history_page_token: None,
22758            workflow_task_attempt: 1,
22759            workflow_signal_id: None,
22760            signal_name: None,
22761            signal_arguments: None,
22762            workflow_update_id: None,
22763            update_name: None,
22764            lease_owner: Some("rust-worker".to_string()),
22765        }
22766    }
22767
22768    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
22769    struct SideEffectProbe {
22770        request_id: String,
22771        attempt: u32,
22772    }
22773
22774    #[test]
22775    fn typed_side_effect_runs_callback_once_and_replay_skips_it() {
22776        let calls = AtomicUsize::new(0);
22777        let ctx = workflow_context(Vec::new());
22778        let value = ctx
22779            .side_effect(|| {
22780                calls.fetch_add(1, Ordering::SeqCst);
22781                SideEffectProbe {
22782                    request_id: "request-42".to_string(),
22783                    attempt: 3,
22784                }
22785            })
22786            .expect("first side effect");
22787        assert_eq!(value.attempt, 3);
22788        assert_eq!(calls.load(Ordering::SeqCst), 1);
22789        let commands = ctx.take_commands().expect("commands");
22790        assert_eq!(commands.len(), 1);
22791        assert_eq!(commands[0]["type"], "record_side_effect");
22792        assert_eq!(
22793            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
22794            serde_json::to_value(&value).expect("value")
22795        );
22796
22797        let replay = workflow_context(vec![history_event(
22798            "SideEffectRecorded",
22799            json!({"sequence": 1, "result": commands[0]["result"].clone()}),
22800        )]);
22801        let replayed: SideEffectProbe = replay
22802            .side_effect(|| {
22803                calls.fetch_add(1, Ordering::SeqCst);
22804                panic!("committed side-effect callbacks must not run during replay")
22805            })
22806            .expect("replayed side effect");
22807        assert_eq!(replayed, value);
22808        assert_eq!(calls.load(Ordering::SeqCst), 1);
22809        assert!(replay.take_commands().expect("commands").is_empty());
22810        replay.ensure_history_consumed().expect("history consumed");
22811    }
22812
22813    #[test]
22814    fn side_effect_uses_avro_envelope_and_uuid_is_replay_stable() {
22815        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
22816        let value = ctx
22817            .side_effect(|| SideEffectProbe {
22818                request_id: "avro-request".to_string(),
22819                attempt: 1,
22820            })
22821            .expect("Avro side effect");
22822        let uuid = ctx.uuid_v4().expect("deterministic UUID");
22823        let commands = ctx.take_commands().expect("commands");
22824        assert_eq!(commands.len(), 2);
22825        assert_eq!(commands[0]["result"]["codec"], DEFAULT_CODEC);
22826        assert_eq!(commands[1]["result"]["codec"], DEFAULT_CODEC);
22827        assert_eq!(
22828            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("Avro result"),
22829            serde_json::to_value(&value).expect("value")
22830        );
22831
22832        let replay = workflow_context_with_codec(
22833            vec![
22834                history_event(
22835                    "SideEffectRecorded",
22836                    json!({"sequence": 1, "result": commands[0]["result"].clone()}),
22837                ),
22838                history_event(
22839                    "SideEffectRecorded",
22840                    json!({"sequence": 2, "result": commands[1]["result"].clone()}),
22841                ),
22842            ],
22843            DEFAULT_CODEC,
22844        );
22845        let replayed: SideEffectProbe = replay
22846            .side_effect(|| panic!("Avro callback must not run"))
22847            .expect("replayed Avro value");
22848        let replayed_uuid = replay.uuid_v4().expect("replayed UUID");
22849        assert_eq!(replayed, value);
22850        assert_eq!(replayed_uuid, uuid);
22851        assert!(replay.take_commands().expect("commands").is_empty());
22852    }
22853
22854    #[test]
22855    fn typed_side_effect_replay_preserves_bytes_and_maps() {
22856        let ctx = workflow_context_with_codec(Vec::new(), DEFAULT_CODEC);
22857        let value = ctx
22858            .side_effect_avro_value(typed_fidelity_probe)
22859            .expect("typed side effect");
22860        let commands = ctx.take_commands().expect("side-effect command");
22861        assert_eq!(
22862            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
22863                .expect("recorded side effect"),
22864            value
22865        );
22866
22867        let replay = workflow_context_with_codec(
22868            vec![history_event(
22869                "SideEffectRecorded",
22870                json!({"sequence": 1, "result": commands[0]["result"].clone()}),
22871            )],
22872            DEFAULT_CODEC,
22873        );
22874        assert_eq!(
22875            replay
22876                .side_effect_avro_value(|| panic!("replay must not invoke callback"))
22877                .expect("replayed typed side effect"),
22878            value
22879        );
22880    }
22881
22882    #[test]
22883    fn ordered_side_effects_share_the_durable_command_stream() {
22884        let first = encode_value_envelope(&json!("first"), DEFAULT_CODEC).expect("first");
22885        let second = encode_value_envelope(&json!(29), DEFAULT_CODEC).expect("second");
22886        let ctx = workflow_context(vec![
22887            history_event(
22888                "SideEffectRecorded",
22889                json!({"sequence": 1, "result": first}),
22890            ),
22891            history_event(
22892                "SideEffectRecorded",
22893                json!({"sequence": 2, "result": second}),
22894            ),
22895        ]);
22896        let first: String = ctx
22897            .side_effect(|| panic!("first callback must not run"))
22898            .expect("first replay");
22899        let second: i32 = ctx
22900            .side_effect(|| panic!("second callback must not run"))
22901            .expect("second replay");
22902        assert_eq!(first, "first");
22903        assert_eq!(second, 29);
22904        ctx.ensure_history_consumed().expect("ordered history");
22905
22906        let reordered = workflow_context(vec![history_event(
22907            "VersionMarkerRecorded",
22908            json!({
22909                "sequence": 1,
22910                "change_id": "before-side-effect",
22911                "version": 1,
22912                "min_supported": 1,
22913                "max_supported": 1,
22914            }),
22915        )]);
22916        let error = reordered
22917            .side_effect(|| "new".to_string())
22918            .expect_err("command reordering must fail");
22919        assert!(matches!(
22920            error,
22921            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22922                if reason == "recorded_command_mismatch"
22923        ));
22924    }
22925
22926    #[test]
22927    fn legacy_patch_preserves_pending_and_completed_activity_history() {
22928        for completed in [false, true] {
22929            let mut history = vec![history_event(
22930                "ActivityScheduled",
22931                json!({"sequence": 1, "activity_type": "old"}),
22932            )];
22933            if completed {
22934                history.push(history_event(
22935                    "ActivityCompleted",
22936                    json!({
22937                        "sequence": 1,
22938                        "activity_type": "old",
22939                        "result": encode_value_envelope(&json!(41), DEFAULT_CODEC).unwrap(),
22940                    }),
22941                ));
22942            }
22943            for _cold_replay in 0..2 {
22944                let ctx = workflow_context(history.clone());
22945                assert!(!ctx.patched("added-step").expect("legacy patch decision"));
22946                assert!(!ctx.patched("added-step").expect("same frozen decision"));
22947                ctx.deprecate_patch("added-step")
22948                    .expect("retained boundary");
22949                let mut activity = Box::pin(ctx.activity("old", json!([])));
22950                let mut context = TaskContext::from_waker(noop_waker_ref());
22951                match activity.as_mut().poll(&mut context) {
22952                    Poll::Ready(result) => {
22953                        assert!(completed);
22954                        assert_eq!(result.expect("recorded result"), json!(41));
22955                        ctx.ensure_history_consumed().expect("old command retained");
22956                    }
22957                    Poll::Pending => assert!(!completed),
22958                }
22959                assert!(ctx.take_commands().expect("commands").is_empty());
22960            }
22961        }
22962    }
22963
22964    #[test]
22965    fn legacy_patch_preserves_an_unmarked_completed_workflow() {
22966        let ctx = workflow_context(vec![history_event("WorkflowCompleted", json!({}))]);
22967        assert!(!ctx.patched("added-step").expect("legacy completed run"));
22968        ctx.deprecate_patch("added-step")
22969            .expect("same legacy decision");
22970        assert!(ctx.take_commands().expect("commands").is_empty());
22971        ctx.ensure_history_consumed().expect("completed history");
22972    }
22973
22974    #[test]
22975    fn legacy_patch_rejects_a_range_without_the_original_branch() {
22976        let ctx = workflow_context(vec![history_event(
22977            "ActivityScheduled",
22978            json!({"sequence": 1, "activity_type": "old"}),
22979        )]);
22980        let error = ctx
22981            .get_version("added-step", 0, 1)
22982            .expect_err("legacy is unsupported");
22983        assert!(matches!(
22984            error,
22985            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
22986                if reason == "version_marker_incompatible_range"
22987        ));
22988        assert!(!ctx
22989            .patched("supported-step")
22990            .expect("failed check did not consume history"));
22991        assert!(ctx.take_commands().expect("commands").is_empty());
22992    }
22993
22994    fn retained_patch_marker(sequence: u64, version: i32, time: &str) -> HistoryEvent {
22995        let mut event = history_event(
22996            "VersionMarkerRecorded",
22997            json!({
22998                "sequence": sequence,
22999                "change_id": "retained-patch",
23000                "version": version,
23001                "min_supported": -1,
23002                "max_supported": 1,
23003            }),
23004        );
23005        event.raw.insert("timestamp".into(), json!(time));
23006        event
23007    }
23008
23009    #[test]
23010    fn retained_patch_markers_preserve_each_original_boundary() {
23011        for completed in [false, true] {
23012            let mut history = vec![
23013                retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
23014                retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
23015                history_event(
23016                    "ActivityScheduled",
23017                    json!({"sequence": 3, "activity_type": "old"}),
23018                ),
23019            ];
23020            if completed {
23021                history.push(history_event(
23022                    "ActivityCompleted",
23023                    json!({
23024                        "sequence": 3,
23025                        "activity_type": "old",
23026                        "result": fixture_envelope(json!(41)),
23027                    }),
23028                ));
23029            }
23030            for _cold_replay in 0..2 {
23031                let ctx = workflow_context(history.clone());
23032                assert!(ctx.patched("retained-patch").unwrap());
23033                assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
23034                assert!(ctx.patched("retained-patch").unwrap());
23035                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
23036                ctx.deprecate_patch("retained-patch").unwrap();
23037                assert_eq!(ctx.state.lock().unwrap().command_cursor, 2);
23038                let mut activity = Box::pin(ctx.activity("old", json!([])));
23039                let mut context = TaskContext::from_waker(noop_waker_ref());
23040                match activity.as_mut().poll(&mut context) {
23041                    Poll::Ready(result) => {
23042                        assert!(completed);
23043                        assert_eq!(result.unwrap(), json!(41));
23044                        ctx.ensure_history_consumed().unwrap();
23045                    }
23046                    Poll::Pending => assert!(!completed),
23047                }
23048                assert!(ctx.take_commands().unwrap().is_empty());
23049                let state = ctx.state.lock().unwrap();
23050                for (actual, original) in state.history_events.iter().zip(&history) {
23051                    assert_eq!(actual.payload, original.payload);
23052                    assert_eq!(actual.raw, original.raw);
23053                }
23054            }
23055        }
23056    }
23057
23058    #[test]
23059    fn retained_patch_aliases_do_not_skip_intervening_operations() {
23060        let ctx = workflow_context(vec![
23061            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
23062            history_event(
23063                "SideEffectRecorded",
23064                json!({
23065                    "sequence": 2, "result": fixture_envelope(json!("between")),
23066                }),
23067            ),
23068            retained_patch_marker(3, 1, "2026-10-10T21:47:29.123604Z"),
23069            history_event(
23070                "VersionMarkerRecorded",
23071                json!({
23072                    "sequence": 4, "change_id": "other-patch", "version": 1,
23073                    "min_supported": -1, "max_supported": 1,
23074                }),
23075            ),
23076        ]);
23077        assert!(ctx.patched("retained-patch").unwrap());
23078        assert!(ctx.patched("retained-patch").unwrap());
23079        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
23080        assert_eq!(
23081            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
23082            "between"
23083        );
23084        ctx.deprecate_patch("retained-patch").unwrap();
23085        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
23086        ctx.deprecate_patch("retained-patch").unwrap();
23087        assert_eq!(ctx.state.lock().unwrap().command_cursor, 3);
23088        assert!(ctx.patched("other-patch").unwrap());
23089        ctx.ensure_history_consumed().unwrap();
23090        assert!(ctx.take_commands().unwrap().is_empty());
23091    }
23092
23093    #[test]
23094    fn retained_patch_alias_range_validation_leaves_the_cursor_unchanged() {
23095        let mut alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
23096        alias.payload["max_supported"] = json!(3);
23097        let ctx = workflow_context(vec![
23098            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
23099            alias,
23100        ]);
23101        assert_eq!(ctx.get_version("retained-patch", -1, 2).unwrap(), 1);
23102        let error = ctx.get_version("retained-patch", 2, 3).unwrap_err();
23103        assert!(matches!(error,
23104            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23105                if reason == "version_marker_incompatible_range"));
23106        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
23107        assert_eq!(ctx.get_version("retained-patch", -1, 3).unwrap(), 1);
23108        ctx.ensure_history_consumed().unwrap();
23109        assert!(ctx.take_commands().unwrap().is_empty());
23110    }
23111
23112    #[test]
23113    fn version_markers_replay_across_upgrades_and_do_not_duplicate() {
23114        let ctx = workflow_context(Vec::new());
23115        assert_eq!(ctx.get_version("checkout-v2", 1, 2).expect("version"), 2);
23116        assert_eq!(ctx.get_version("checkout-v2", 1, 3).expect("cached"), 2);
23117        assert!(ctx.patched("new-search").expect("patch"));
23118        ctx.deprecate_patch("new-search").expect("deprecate patch");
23119        let commands = ctx.take_commands().expect("commands");
23120        assert_eq!(commands.len(), 2);
23121        assert_eq!(commands[0]["type"], "record_version_marker");
23122        assert_eq!(commands[0]["version"], 2);
23123        assert_eq!(commands[1]["change_id"], "new-search");
23124
23125        let replay = workflow_context(vec![history_event(
23126            "VersionMarkerRecorded",
23127            json!({
23128                "sequence": 1,
23129                "change_id": "checkout-v2",
23130                "version": 2,
23131                "min_supported": 1,
23132                "max_supported": 2,
23133            }),
23134        )]);
23135        assert_eq!(replay.get_version("checkout-v2", 1, 4).expect("upgrade"), 2);
23136        assert_eq!(replay.get_version("checkout-v2", 2, 5).expect("repeat"), 2);
23137        assert!(replay.take_commands().expect("commands").is_empty());
23138        replay.ensure_history_consumed().expect("history consumed");
23139    }
23140
23141    #[test]
23142    fn version_markers_reject_incompatible_or_malformed_history() {
23143        let incompatible = workflow_context(vec![history_event(
23144            "VersionMarkerRecorded",
23145            json!({
23146                "sequence": 1,
23147                "change_id": "checkout-v2",
23148                "version": 1,
23149                "min_supported": 1,
23150                "max_supported": 2,
23151            }),
23152        )]);
23153        let error = incompatible
23154            .get_version("checkout-v2", 2, 3)
23155            .expect_err("old version is unsupported");
23156        assert!(matches!(
23157            error,
23158            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23159                if reason == "version_marker_incompatible_range"
23160        ));
23161
23162        for (history, reason) in [
23163            (
23164                vec![history_event("SideEffectRecorded", json!({"sequence": 1}))],
23165                "side_effect_result_missing",
23166            ),
23167            (
23168                vec![history_event(
23169                    "SideEffectRecorded",
23170                    json!({
23171                        "sequence": 1,
23172                        "result": {"codec": "avro", "blob": "not-base64"},
23173                    }),
23174                )],
23175                "side_effect_payload_incompatible",
23176            ),
23177            (
23178                vec![history_event(
23179                    "SideEffectRecorded",
23180                    json!({"sequence": 1, "result": {"unwrapped": true}}),
23181                )],
23182                "side_effect_payload_malformed",
23183            ),
23184            (
23185                vec![history_event(
23186                    "VersionMarkerRecorded",
23187                    json!({
23188                        "sequence": 1,
23189                        "change_id": "change",
23190                        "version": 1,
23191                        "min_supported": 2,
23192                        "max_supported": 1,
23193                    }),
23194                )],
23195                "version_marker_history_range_invalid",
23196            ),
23197        ] {
23198            let error = WorkflowState::new(
23199                history,
23200                "rust-workers".to_string(),
23201                DEFAULT_CODEC.to_string(),
23202                None,
23203            )
23204            .expect_err("malformed history must fail");
23205            assert!(matches!(
23206                error,
23207                Error::NonDeterministicReplay(ReplayFailure { reason: actual, .. })
23208                    if actual == reason
23209            ));
23210        }
23211    }
23212
23213    #[test]
23214    fn typed_search_attributes_replay_value_and_type_identity_after_restart() {
23215        let history = vec![history_event(
23216            "SearchAttributesUpserted",
23217            json!({
23218                "sequence": 1,
23219                "attributes": {"customer_tier": "gold"},
23220                "attribute_types": {"customer_tier": "keyword"},
23221                "merged": {"customer_tier": "gold"}
23222            }),
23223        )];
23224
23225        let matching = workflow_context(history.clone());
23226        matching
23227            .upsert_search_attributes(
23228                SearchAttributeUpdate::new()
23229                    .keyword("customer_tier", "gold")
23230                    .expect("keyword update"),
23231            )
23232            .expect("matching typed update must replay");
23233        matching
23234            .ensure_history_consumed()
23235            .expect("history consumed");
23236
23237        let changed_type = workflow_context(history.clone());
23238        let error = changed_type
23239            .upsert_search_attributes(
23240                SearchAttributeUpdate::new()
23241                    .string("customer_tier", "gold")
23242                    .expect("string update"),
23243            )
23244            .expect_err("same JSON value with a different declaration must be nondeterministic");
23245        let Error::NonDeterministicReplay(failure) = error else {
23246            panic!("typed identity drift must be a replay failure");
23247        };
23248        assert_eq!(failure.reason, "search_attribute_type_mismatch");
23249        assert_eq!(failure.sequence, Some(1));
23250
23251        let changed_value = workflow_context(history);
23252        let error = changed_value
23253            .upsert_search_attributes(
23254                SearchAttributeUpdate::new()
23255                    .keyword("customer_tier", "platinum")
23256                    .expect("keyword update"),
23257            )
23258            .expect_err("changed values must be nondeterministic");
23259        let Error::NonDeterministicReplay(failure) = error else {
23260            panic!("value drift must be a replay failure");
23261        };
23262        assert_eq!(failure.reason, "search_attribute_value_mismatch");
23263    }
23264
23265    #[test]
23266    fn legacy_search_attribute_history_keeps_type_identity_unknown() {
23267        let history = vec![history_event(
23268            "SearchAttributesUpserted",
23269            json!({
23270                "sequence": 1,
23271                "attributes": {"customer_tier": "gold"},
23272                "merged": {"customer_tier": "gold"}
23273            }),
23274        )];
23275
23276        for update in [
23277            SearchAttributeUpdate::new()
23278                .keyword("customer_tier", "gold")
23279                .expect("keyword update"),
23280            SearchAttributeUpdate::new()
23281                .string("customer_tier", "gold")
23282                .expect("string update"),
23283        ] {
23284            let restarted = workflow_context(history.clone());
23285            restarted
23286                .upsert_search_attributes(update)
23287                .expect("legacy history constrains values but has unknown type identity");
23288            restarted
23289                .ensure_history_consumed()
23290                .expect("history consumed");
23291        }
23292    }
23293
23294    #[test]
23295    fn search_attribute_command_emits_canonical_types() {
23296        let ctx = workflow_context(Vec::new());
23297        ctx.upsert_search_attributes(
23298            SearchAttributeUpdate::new()
23299                .keyword("customer_tier", "gold")
23300                .expect("keyword update")
23301                .int("attempts", 3)
23302                .expect("int update")
23303                .delete("obsolete")
23304                .expect("delete update"),
23305        )
23306        .expect("valid search attributes");
23307
23308        assert_eq!(
23309            ctx.take_commands().expect("commands"),
23310            vec![json!({
23311                "type": "upsert_search_attributes",
23312                "attributes": {
23313                    "attempts": 3,
23314                    "customer_tier": "gold",
23315                    "obsolete": null
23316                },
23317                "attribute_types": {
23318                    "attempts": "int",
23319                    "customer_tier": "keyword"
23320                }
23321            })]
23322        );
23323    }
23324
23325    #[test]
23326    fn duplicate_side_effects_and_conflicting_version_markers_are_rejected() {
23327        let duplicate_side_effect = WorkflowState::new(
23328            vec![
23329                history_event(
23330                    "SideEffectRecorded",
23331                    json!({"sequence": 1, "result": fixture_envelope(json!(1))}),
23332                ),
23333                history_event(
23334                    "SideEffectRecorded",
23335                    json!({"sequence": 1, "result": fixture_envelope(json!(2))}),
23336                ),
23337            ],
23338            "rust-workers".to_string(),
23339            DEFAULT_CODEC.to_string(),
23340            None,
23341        )
23342        .expect_err("duplicate side effect");
23343        assert!(matches!(
23344            duplicate_side_effect,
23345            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23346                if reason == "duplicate_side_effect_record"
23347        ));
23348
23349        let marker = |sequence, version| {
23350            history_event(
23351                "VersionMarkerRecorded",
23352                json!({
23353                    "sequence": sequence,
23354                    "change_id": "same-change",
23355                    "version": version,
23356                    "min_supported": -1,
23357                    "max_supported": 1,
23358                }),
23359            )
23360        };
23361        let duplicate_marker = WorkflowState::new(
23362            vec![marker(1, 1), marker(3, -1)],
23363            "rust-workers".to_string(),
23364            DEFAULT_CODEC.to_string(),
23365            None,
23366        )
23367        .expect_err("conflicting marker");
23368        assert!(matches!(
23369            duplicate_marker,
23370            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23371                if reason == "version_marker_conflict"
23372        ));
23373    }
23374
23375    #[test]
23376    fn retained_patch_aliases_reject_duplicate_physical_records_and_invalid_ranges() {
23377        let marker = retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z");
23378        let mut invalid_alias = retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z");
23379        invalid_alias.payload["max_supported"] = json!(0);
23380        for (history, expected_reason) in [
23381            (
23382                vec![marker.clone(), marker.clone()],
23383                "duplicate_version_marker_record",
23384            ),
23385            (
23386                vec![marker, invalid_alias],
23387                "version_marker_history_range_invalid",
23388            ),
23389        ] {
23390            let error =
23391                WorkflowState::new(history, "rust-workers".into(), DEFAULT_CODEC.into(), None)
23392                    .expect_err("invalid historical alias");
23393            assert!(matches!(error,
23394                Error::NonDeterministicReplay(ReplayFailure { reason, .. })
23395                    if reason == expected_reason));
23396        }
23397    }
23398
23399    #[test]
23400    fn retained_patch_aliases_require_the_original_call_boundary() {
23401        let ctx = workflow_context(vec![
23402            retained_patch_marker(1, 1, "2026-10-10T21:47:29.120756Z"),
23403            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
23404        ]);
23405        assert!(ctx.patched("retained-patch").unwrap());
23406        assert!(ctx.ensure_history_consumed().is_err());
23407        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
23408        ctx.deprecate_patch("retained-patch").unwrap();
23409        ctx.ensure_history_consumed().unwrap();
23410        assert!(ctx.take_commands().unwrap().is_empty());
23411    }
23412
23413    #[test]
23414    fn retained_patch_aliases_do_not_replace_an_earlier_legacy_decision() {
23415        let ctx = workflow_context(vec![
23416            history_event(
23417                "SideEffectRecorded",
23418                json!({
23419                    "sequence": 1, "result": fixture_envelope(json!("old-operation")),
23420                }),
23421            ),
23422            retained_patch_marker(2, 1, "2026-10-10T21:47:29.123604Z"),
23423        ]);
23424        assert!(!ctx.patched("retained-patch").unwrap());
23425        assert_eq!(
23426            ctx.side_effect(|| "must not execute".to_string()).unwrap(),
23427            "old-operation"
23428        );
23429        let error = ctx.patched("retained-patch").unwrap_err();
23430        assert!(matches!(error,
23431            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23432                if reason == "version_marker_conflict"));
23433        assert_eq!(ctx.state.lock().unwrap().command_cursor, 1);
23434        assert!(ctx.take_commands().unwrap().is_empty());
23435    }
23436
23437    #[test]
23438    fn workflow_stream_authoring_derives_identity_and_replay_skips_duplicate_append() {
23439        let mut state = WorkflowState::new(
23440            Vec::new(),
23441            "rust-workers".to_string(),
23442            DEFAULT_CODEC.to_string(),
23443            None,
23444        )
23445        .expect("workflow state");
23446        state.workflow_command_identity = "command-7".to_string();
23447        let context = WorkflowContext {
23448            state: Arc::new(Mutex::new(state)),
23449            cancellation_scope_id: "root".into(),
23450        };
23451        let item =
23452            WorkflowStreamAppendItem::from_reference("s3://bucket/item.avro").item_type("receipt");
23453
23454        context
23455            .append_workflow_stream("output", &[item], Some(10))
23456            .expect("append command");
23457        context
23458            .error_workflow_stream("output", "producer failed", None)
23459            .expect("error command");
23460        let commands = context.take_commands().expect("commands");
23461
23462        assert_eq!(commands[0]["type"], "record_side_effect");
23463        assert_eq!(
23464            commands[0]["workflow_stream"]["command_identity"],
23465            "command-7"
23466        );
23467        assert_eq!(commands[0]["workflow_stream"]["command_ordinal"], 0);
23468        assert_eq!(
23469            commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
23470            "dw-stream:command-7:0:0"
23471        );
23472        assert_eq!(commands[1]["workflow_stream"]["operation"], "error");
23473
23474        let recorded = history_event(
23475            "SideEffectRecorded",
23476            json!({"sequence": 1, "result": fixture_envelope(Value::Null)}),
23477        );
23478        let mut replay_state = WorkflowState::new(
23479            vec![recorded],
23480            "rust-workers".to_string(),
23481            DEFAULT_CODEC.to_string(),
23482            None,
23483        )
23484        .expect("replay state");
23485        replay_state.workflow_command_identity = "command-7".to_string();
23486        let replay_context = WorkflowContext {
23487            state: Arc::new(Mutex::new(replay_state)),
23488            cancellation_scope_id: "root".into(),
23489        };
23490        replay_context
23491            .append_workflow_stream(
23492                "output",
23493                &[WorkflowStreamAppendItem::from_reference(
23494                    "s3://bucket/item.avro",
23495                )],
23496                Some(10),
23497            )
23498            .expect("replayed append");
23499        assert!(replay_context
23500            .take_commands()
23501            .expect("replayed commands")
23502            .is_empty());
23503    }
23504
23505    #[test]
23506    fn workflow_stream_authoring_requires_server_durable_command_identity() {
23507        let context = workflow_context(Vec::new());
23508        let error = context
23509            .append_workflow_stream(
23510                "output",
23511                &[WorkflowStreamAppendItem::from_reference(
23512                    "s3://bucket/item.avro",
23513                )],
23514                None,
23515            )
23516            .expect_err("stream append without durable command identity must fail closed");
23517
23518        assert!(matches!(error, Error::MissingWorkflowCommandIdentity));
23519        assert!(context.take_commands().expect("commands").is_empty());
23520    }
23521
23522    #[test]
23523    fn worker_stream_authoring_uses_task_identity_and_replays_without_output() {
23524        let client = Client::builder("http://localhost:8080").build().unwrap();
23525        let mut worker = Worker::new(client, "rust-workers");
23526        worker.register_workflow("streams.worker", |ctx, _| async move {
23527            ctx.append_workflow_stream(
23528                "output",
23529                &[WorkflowStreamAppendItem::new(json!("hello"))?],
23530                None,
23531            )?;
23532            ctx.close_workflow_stream("output", None)?;
23533            Ok(json!("done"))
23534        });
23535        for command_id in [None, Some(String::new()), Some("command-42".to_string())] {
23536            let mut task = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
23537            task.workflow_command_id = command_id.clone();
23538            let expected_identity = command_id
23539                .as_deref()
23540                .filter(|id| !id.is_empty())
23541                .unwrap_or(&task.task_id)
23542                .to_string();
23543            let commands = worker
23544                .execute_workflow_task(task)
23545                .expect("ordinary worker stream output");
23546            assert_eq!(commands.len(), 3);
23547            assert_eq!(
23548                commands[0]["workflow_stream"]["command_identity"],
23549                expected_identity
23550            );
23551            assert_eq!(
23552                commands[0]["workflow_stream"]["items"][0]["idempotency_key"],
23553                format!("dw-stream:{expected_identity}:0:0")
23554            );
23555            assert_eq!(
23556                commands[1]["workflow_stream"]["command_identity"],
23557                expected_identity
23558            );
23559            assert_eq!(commands[1]["workflow_stream"]["operation"], "close");
23560            let history = commands[..2]
23561                .iter()
23562                .enumerate()
23563                .map(|(index, command)| {
23564                    history_event(
23565                        "SideEffectRecorded",
23566                        json!({"sequence":index + 1,"result":command["result"]}),
23567                    )
23568                })
23569                .collect();
23570            let mut replay = workflow_task("streams.worker", history, DEFAULT_CODEC);
23571            replay.task_id = "replacement-task".to_string();
23572            let replayed = worker
23573                .execute_workflow_task(replay)
23574                .expect("replacement worker consumes recorded stream effects");
23575            assert_eq!(replayed.len(), 1);
23576            assert_eq!(replayed[0]["type"], "complete_workflow");
23577        }
23578        let mut missing = workflow_task("streams.worker", Vec::new(), DEFAULT_CODEC);
23579        missing.task_id.clear();
23580        assert!(matches!(
23581            worker.execute_workflow_task(missing),
23582            Err(Error::MissingWorkflowCommandIdentity)
23583        ));
23584    }
23585
23586    #[test]
23587    fn cold_worker_replay_does_not_repeat_committed_side_effects_or_markers() {
23588        fn worker(calls: Arc<AtomicUsize>) -> Worker {
23589            let client = Client::new("http://127.0.0.1:8080").expect("client");
23590            let mut worker = Worker::new(client, "rust-workers");
23591            worker.register_workflow("rust.side-effect-version", move |ctx, _input| {
23592                let calls = Arc::clone(&calls);
23593                async move {
23594                    let captured = ctx.side_effect(|| {
23595                        calls.fetch_add(1, Ordering::SeqCst);
23596                        "captured-once".to_string()
23597                    })?;
23598                    let version = ctx.get_version("cold-restart", 1, 2)?;
23599                    Ok(json!({"captured": captured, "version": version}))
23600                }
23601            });
23602            worker
23603        }
23604
23605        fn task(history_events: Vec<HistoryEvent>) -> WorkflowTask {
23606            WorkflowTask {
23607                task_id: "wft-side-effect-version".to_string(),
23608                observability_context: None,
23609                dispatch_observability_context: None,
23610                observability_links: None,
23611                workflow_command_id: None,
23612                workflow_id: Some("wf-side-effect-version".to_string()),
23613                run_id: Some("run-side-effect-version".to_string()),
23614                workflow_type: "rust.side-effect-version".to_string(),
23615                cancel_requested: false,
23616                payload_codec: DEFAULT_CODEC.to_string(),
23617                arguments: Some(
23618                    encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("arguments"),
23619                ),
23620                history_events,
23621                total_history_events: None,
23622                history_size_bytes: None,
23623                continue_as_new_recommended: None,
23624                history_budget_pressure: None,
23625                next_history_page_token: None,
23626                workflow_task_attempt: 1,
23627                workflow_signal_id: None,
23628                signal_name: None,
23629                signal_arguments: None,
23630                workflow_update_id: None,
23631                update_name: None,
23632                lease_owner: Some("rust-worker".to_string()),
23633            }
23634        }
23635
23636        let calls = Arc::new(AtomicUsize::new(0));
23637        let initial = worker(Arc::clone(&calls))
23638            .execute_workflow_task(task(Vec::new()))
23639            .expect("initial execution");
23640        assert_eq!(
23641            initial
23642                .iter()
23643                .map(|command| &command["type"])
23644                .collect::<Vec<_>>(),
23645            vec![
23646                "record_side_effect",
23647                "record_version_marker",
23648                "complete_workflow"
23649            ]
23650        );
23651        assert_eq!(calls.load(Ordering::SeqCst), 1);
23652
23653        let restarted = worker(Arc::clone(&calls));
23654        let replayed = restarted
23655            .execute_workflow_task(task(vec![
23656                history_event(
23657                    "SideEffectRecorded",
23658                    json!({"sequence": 1, "result": initial[0]["result"].clone()}),
23659                ),
23660                history_event(
23661                    "VersionMarkerRecorded",
23662                    json!({
23663                        "sequence": 2,
23664                        "change_id": "cold-restart",
23665                        "version": 2,
23666                        "min_supported": 1,
23667                        "max_supported": 2,
23668                    }),
23669                ),
23670            ]))
23671            .expect("cold replay");
23672        assert_eq!(replayed.len(), 1);
23673        assert_eq!(replayed[0]["type"], "complete_workflow");
23674        assert_eq!(calls.load(Ordering::SeqCst), 1);
23675    }
23676
23677    #[test]
23678    fn side_effect_replay_rejects_changed_rust_value_type() {
23679        let result = encode_value_envelope(&json!({"value": 42}), DEFAULT_CODEC).expect("result");
23680        let ctx = workflow_context(vec![history_event(
23681            "SideEffectRecorded",
23682            json!({"sequence": 1, "result": result}),
23683        )]);
23684        let error = ctx
23685            .side_effect::<Vec<String>, _>(|| panic!("callback must not run"))
23686            .expect_err("changed type must fail replay");
23687        assert!(matches!(
23688            error,
23689            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
23690                if reason == "side_effect_type_mismatch"
23691        ));
23692    }
23693
23694    fn completed_retry_activity_history() -> Vec<HistoryEvent> {
23695        vec![
23696            history_event(
23697                "ActivityScheduled",
23698                json!({
23699                    "sequence": 1,
23700                    "activity_type": "flaky",
23701                    "activity_execution_id": "act-1",
23702                    "activity": {
23703                        "id": "act-1",
23704                        "sequence": 1,
23705                        "type": "flaky",
23706                        "queue": "critical-activities",
23707                        "execution_mode": null,
23708                        "retry_policy": {
23709                            "snapshot_version": 1,
23710                            "max_attempts": 3,
23711                            "backoff_seconds": [2, 4],
23712                            "start_to_close_timeout": 30,
23713                            "schedule_to_start_timeout": 5,
23714                            "schedule_to_close_timeout": 90,
23715                            "heartbeat_timeout": 10,
23716                            "non_retryable_error_types": ["PermanentError"]
23717                        }
23718                    }
23719                }),
23720            ),
23721            history_event(
23722                "ActivityStarted",
23723                json!({
23724                    "sequence": 1,
23725                    "activity_type": "flaky",
23726                    "activity_execution_id": "act-1",
23727                    "activity_attempt_id": "attempt-1",
23728                    "attempt_number": 1
23729                }),
23730            ),
23731            history_event(
23732                "ActivityRetryScheduled",
23733                json!({
23734                    "sequence": 1,
23735                    "activity_type": "flaky",
23736                    "activity_execution_id": "act-1",
23737                    "activity_attempt_id": "attempt-1",
23738                    "attempt_number": 1,
23739                    "retry_after_attempt": 1,
23740                    "retry_backoff_seconds": 2,
23741                    "failure_category": "activity",
23742                    "exception_type": "TransientError"
23743                }),
23744            ),
23745            history_event(
23746                "ActivityStarted",
23747                json!({
23748                    "sequence": 1,
23749                    "activity_type": "flaky",
23750                    "activity_execution_id": "act-1",
23751                    "activity_attempt_id": "attempt-2",
23752                    "attempt_number": 2
23753                }),
23754            ),
23755            history_event(
23756                "ActivityCompleted",
23757                json!({
23758                    "sequence": 1,
23759                    "activity_type": "flaky",
23760                    "activity_execution_id": "act-1",
23761                    "activity_attempt_id": "attempt-2",
23762                    "attempt_number": 2,
23763                    "payload_codec": DEFAULT_CODEC,
23764                    "result": fixture_envelope(json!({"status":"recovered"}))
23765                }),
23766            ),
23767        ]
23768    }
23769
23770    fn retry_activity_options() -> ActivityOptions {
23771        ActivityOptions::new()
23772            .task_queue("critical-activities")
23773            .retry_policy(
23774                ActivityRetryPolicy::new(3)
23775                    .backoff_intervals([Duration::from_secs(2), Duration::from_secs(4)])
23776                    .non_retryable_error_type("PermanentError"),
23777            )
23778            .start_to_close_timeout(Duration::from_secs(30))
23779            .schedule_to_start_timeout(Duration::from_secs(5))
23780            .schedule_to_close_timeout(Duration::from_secs(90))
23781            .heartbeat_timeout(Duration::from_secs(10))
23782    }
23783
23784    #[test]
23785    fn fixed_avro_value_round_trips_json_values() {
23786        let value = json!({"greeting": "hello", "count": 3, "ok": true});
23787        let envelope = PayloadEnvelope::avro(&value).expect("encode");
23788        assert_eq!(envelope.codec, DEFAULT_CODEC);
23789        assert_eq!(decode_payload::<Value>(&envelope).expect("decode"), value);
23790    }
23791
23792    #[tokio::test]
23793    async fn typed_handler_adapters_round_trip_serde_contracts_on_the_fixed_wire() {
23794        let client = Client::new("http://127.0.0.1:8080").expect("client");
23795        let mut worker = Worker::new(client, "rust-workers");
23796        worker.register_typed_workflow(
23797            "typed.contract.workflow",
23798            |_ctx, input: TypedContract| async move { Ok(input) },
23799        );
23800        worker.register_typed_activity(
23801            "typed.contract.activity",
23802            |_ctx, input: TypedContract| async move { Ok(input) },
23803        );
23804
23805        let expected = typed_contract();
23806        let arguments = AvroValue::Array(vec![
23807            AvroValue::from_serialize(&expected).expect("typed request")
23808        ]);
23809        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("arguments");
23810        let mut workflow = workflow_task("typed.contract.workflow", Vec::new(), DEFAULT_CODEC);
23811        workflow.arguments = Some(envelope.clone());
23812        let commands = worker
23813            .execute_workflow_task(workflow)
23814            .expect("typed workflow task");
23815        let workflow_result: TypedContract =
23816            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
23817                .expect("workflow result envelope")
23818                .deserialize()
23819                .expect("workflow result type");
23820        assert_eq!(workflow_result, expected);
23821
23822        let activity = ActivityTask {
23823            task_id: "typed-contract-activity".to_string(),
23824            workflow_id: None,
23825            run_id: None,
23826            activity_execution_id: None,
23827            observability_context: None,
23828            dispatch_observability_context: None,
23829            observability_links: None,
23830            activity_attempt_id: Some("typed-contract-attempt".to_string()),
23831            attempt_id: None,
23832            activity_type: "typed.contract.activity".to_string(),
23833            payload_codec: DEFAULT_CODEC.to_string(),
23834            arguments: Some(envelope),
23835            attempt_number: 1,
23836            lease_owner: Some("rust-worker".to_string()),
23837        };
23838        let activity_result: TypedContract = worker
23839            .execute_activity_task(activity)
23840            .await
23841            .expect("typed activity task")
23842            .deserialize()
23843            .expect("activity result type");
23844        assert_eq!(activity_result, expected);
23845    }
23846
23847    #[test]
23848    fn typed_entry_mismatch_refuses_before_body_and_preserves_original_input() {
23849        let calls = Arc::new(AtomicUsize::new(0));
23850        let observed = Arc::clone(&calls);
23851        let client = Client::new("http://127.0.0.1:8080").expect("client");
23852        let mut worker = Worker::new(client.clone(), "rust-workers");
23853        worker.register_typed_workflow("entry.safe", move |_ctx, input: i64| {
23854            observed.fetch_add(1, Ordering::SeqCst);
23855            async move { Ok(input) }
23856        });
23857        let mut task = workflow_task("entry.safe", Vec::new(), DEFAULT_CODEC);
23858        task.arguments = Some(fixture_envelope(json!(["private-original-value"])));
23859        let original = task.clone();
23860        let error = worker
23861            .execute_workflow_task(task)
23862            .expect_err("incompatible entry must refuse the task, not fail the run");
23863        assert_eq!(calls.load(Ordering::SeqCst), 0);
23864        assert!(error
23865            .to_string()
23866            .contains("workflow_entry_arguments_mismatch:"));
23867        assert!(!error.to_string().contains("private-original-value"));
23868
23869        let mut compatible = Worker::new(client, "rust-workers");
23870        compatible
23871            .register_typed_workflow("entry.safe", |_ctx, input: String| async move { Ok(input) });
23872        let commands = compatible
23873            .execute_workflow_task(original)
23874            .expect("same recorded input");
23875        assert_eq!(commands[0]["type"], "complete_workflow");
23876        assert_eq!(
23877            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).unwrap(),
23878            json!("private-original-value")
23879        );
23880    }
23881
23882    #[test]
23883    fn typed_entry_replayed_mismatch_refuses_before_state_factory_and_body() {
23884        let factories = Arc::new(AtomicUsize::new(0));
23885        let observed = Arc::clone(&factories);
23886        let client = Client::new("http://127.0.0.1:8080").expect("client");
23887        let mut worker = Worker::new(client, "rust-workers");
23888        worker.register_typed_replayed_workflow(
23889            "entry.replayed",
23890            move || {
23891                observed.fetch_add(1, Ordering::SeqCst);
23892            },
23893            |_ctx, _input: i64, _state| async move {
23894                panic!("body must not start");
23895                #[allow(unreachable_code)]
23896                Ok(0_i64)
23897            },
23898        );
23899        let mut task = workflow_task("entry.replayed", Vec::new(), DEFAULT_CODEC);
23900        task.arguments = Some(fixture_envelope(json!(["private-replayed-value"])));
23901        let error = worker
23902            .execute_workflow_task(task)
23903            .expect_err("entry refusal");
23904        assert_eq!(factories.load(Ordering::SeqCst), 0);
23905        assert!(error
23906            .to_string()
23907            .contains("workflow_entry_arguments_mismatch:"));
23908        assert!(!error.to_string().contains("private-replayed-value"));
23909
23910        let replay = worker.workflows["entry.replayed"].replay.as_ref().unwrap();
23911        let Err(error) = replay(
23912            workflow_context(Vec::new()),
23913            AvroValue::Array(vec![AvroValue::String("private-replayed-value".into())]),
23914        ) else {
23915            panic!("query replay must refuse before creating application state");
23916        };
23917        assert_eq!(factories.load(Ordering::SeqCst), 0);
23918        assert!(!error.to_string().contains("private-replayed-value"));
23919    }
23920
23921    #[test]
23922    fn typed_entry_deserializes_once_before_entering_application_code() {
23923        static DECODES: AtomicUsize = AtomicUsize::new(0);
23924        struct Counted(i64);
23925        impl<'de> Deserialize<'de> for Counted {
23926            fn deserialize<D: Deserializer<'de>>(
23927                deserializer: D,
23928            ) -> std::result::Result<Self, D::Error> {
23929                DECODES.fetch_add(1, Ordering::SeqCst);
23930                i64::deserialize(deserializer).map(Self)
23931            }
23932        }
23933        DECODES.store(0, Ordering::SeqCst);
23934        let client = Client::new("http://127.0.0.1:8080").expect("client");
23935        let mut worker = Worker::new(client, "rust-workers");
23936        worker.register_typed_workflow(
23937            "entry.once",
23938            |_ctx, input: Counted| async move { Ok(input.0) },
23939        );
23940        let mut task = workflow_task("entry.once", Vec::new(), DEFAULT_CODEC);
23941        task.arguments = Some(fixture_envelope(json!([7])));
23942        let commands = worker.execute_workflow_task(task).expect("typed result");
23943        assert_eq!(commands[0]["type"], "complete_workflow");
23944        assert_eq!(DECODES.load(Ordering::SeqCst), 1);
23945    }
23946
23947    #[test]
23948    fn typed_entry_body_input_error_remains_a_business_failure() {
23949        let client = Client::new("http://127.0.0.1:8080").expect("client");
23950        let mut worker = Worker::new(client, "rust-workers");
23951        worker.register_typed_workflow("entry.body", |_ctx, _input: i64| async move {
23952            Err::<i64, _>(handler_type_error::<i64>(
23953                HandlerKind::Workflow,
23954                "entry.body",
23955                HandlerValueKind::Input,
23956                "deliberate body error",
23957            ))
23958        });
23959        let mut task = workflow_task("entry.body", Vec::new(), DEFAULT_CODEC);
23960        task.arguments = Some(fixture_envelope(json!([7])));
23961        let commands = worker
23962            .execute_workflow_task(task)
23963            .expect("business failure command");
23964        assert_eq!(commands[0]["type"], "fail_workflow");
23965        assert!(commands[0]["message"]
23966            .as_str()
23967            .unwrap()
23968            .contains("deliberate body error"));
23969    }
23970
23971    #[test]
23972    fn typed_entry_body_cannot_claim_the_adapter_refusal() {
23973        let client = Client::new("http://127.0.0.1:8080").expect("client");
23974        let mut worker = Worker::new(client, "rust-workers");
23975        worker.register_typed_workflow("entry.body.refusal", |_ctx, _input: i64| async move {
23976            Err::<i64, _>(handler_type_error::<i64>(
23977                HandlerKind::Workflow,
23978                "entry.body.refusal",
23979                HandlerValueKind::Input,
23980                "workflow_entry_arguments_mismatch: deliberate body error",
23981            ))
23982        });
23983        let mut task = workflow_task("entry.body.refusal", Vec::new(), DEFAULT_CODEC);
23984        task.arguments = Some(fixture_envelope(json!([7])));
23985        let commands = worker
23986            .execute_workflow_task(task)
23987            .expect("business failure");
23988        assert_eq!(commands[0]["type"], "fail_workflow");
23989    }
23990
23991    #[tokio::test]
23992    async fn typed_handler_errors_include_handler_name_direction_and_rust_type() {
23993        let client = Client::new("http://127.0.0.1:8080").expect("client");
23994        let mut worker = Worker::new(client, "rust-workers");
23995        worker.register_typed_workflow(
23996            "typed.shape.workflow",
23997            |_ctx, input: TypedContract| async move { Ok(input) },
23998        );
23999        worker.register_typed_activity("typed.unsupported.activity", |_ctx, (): ()| async move {
24000            Ok(f64::NAN)
24001        });
24002
24003        let mut workflow = workflow_task("typed.shape.workflow", Vec::new(), DEFAULT_CODEC);
24004        workflow.arguments = Some(
24005            encode_typed_envelope(
24006                &AvroValue::Array(vec![
24007                    AvroValue::String("first".to_string()),
24008                    AvroValue::String("second".to_string()),
24009                ]),
24010                DEFAULT_CODEC,
24011            )
24012            .expect("malformed typed arguments"),
24013        );
24014        let error = worker
24015            .execute_workflow_task(workflow)
24016            .expect_err("entry shape mismatch refuses the task");
24017        let message = error.to_string();
24018        assert!(message.contains("workflow_entry_arguments_mismatch:"));
24019        assert!(message.contains("typed.shape.workflow"));
24020        assert!(message.contains(type_name::<TypedContract>()));
24021
24022        let activity = ActivityTask {
24023            task_id: "typed-unsupported-activity".to_string(),
24024            workflow_id: None,
24025            run_id: None,
24026            activity_execution_id: None,
24027            observability_context: None,
24028            dispatch_observability_context: None,
24029            observability_links: None,
24030            activity_attempt_id: Some("typed-unsupported-attempt".to_string()),
24031            attempt_id: None,
24032            activity_type: "typed.unsupported.activity".to_string(),
24033            payload_codec: DEFAULT_CODEC.to_string(),
24034            arguments: Some(
24035                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
24036                    .expect("unit arguments"),
24037            ),
24038            attempt_number: 1,
24039            lease_owner: Some("rust-worker".to_string()),
24040        };
24041        let Error::HandlerType {
24042            handler_kind,
24043            handler_name,
24044            value_kind,
24045            rust_type,
24046            message,
24047        } = worker
24048            .execute_activity_task(activity)
24049            .await
24050            .expect_err("non-finite handler output must fail")
24051        else {
24052            panic!("expected contextual handler type failure");
24053        };
24054        assert_eq!(handler_kind, HandlerKind::Activity);
24055        assert_eq!(handler_name, "typed.unsupported.activity");
24056        assert_eq!(value_kind, HandlerValueKind::Result);
24057        assert_eq!(rust_type, type_name::<f64>());
24058        assert!(message.contains("non_finite_float"));
24059    }
24060
24061    #[tokio::test]
24062    async fn typed_replayed_workflow_decodes_input_and_activity_result_losslessly() {
24063        #[derive(Clone, Default)]
24064        struct State {
24065            observed: Option<TypedContract>,
24066        }
24067
24068        let client = Client::new("http://127.0.0.1:8080").expect("client");
24069        let mut worker = Worker::new(client, "rust-workers");
24070        worker.register_typed_replayed_workflow(
24071            "typed.contract.replayed",
24072            State::default,
24073            |ctx, input: TypedContract, state| async move {
24074                let result: TypedContract =
24075                    ctx.activity_typed("typed.contract.activity", input).await?;
24076                state.update(|current| current.observed = Some(result.clone()))?;
24077                Ok(result)
24078            },
24079        );
24080        worker.register_replayed_query::<State, _, _>(
24081            "typed.contract.replayed",
24082            "observed",
24083            |_ctx, state, _args| async move {
24084                Ok(json!(state.observed.as_ref().map(|value| value.signed)))
24085            },
24086        );
24087
24088        let expected = typed_contract();
24089        let typed_value = AvroValue::from_serialize(&expected).expect("typed value");
24090        let workflow_arguments =
24091            encode_typed_envelope(&AvroValue::Array(vec![typed_value.clone()]), DEFAULT_CODEC)
24092                .expect("workflow arguments");
24093        let result = encode_typed_envelope(&typed_value, DEFAULT_CODEC).expect("activity result");
24094        let task = QueryTask {
24095            query_task_id: "typed-replay-query".to_string(),
24096            observability_context: None,
24097            dispatch_observability_context: None,
24098            observability_links: None,
24099            query_task_attempt: 1,
24100            lease_owner: Some("rust-worker".to_string()),
24101            workflow_id: Some("typed-replay".to_string()),
24102            run_id: Some("typed-replay-run".to_string()),
24103            workflow_type: "typed.contract.replayed".to_string(),
24104            query_name: "observed".to_string(),
24105            payload_codec: DEFAULT_CODEC.to_string(),
24106            workflow_arguments: Some(workflow_arguments),
24107            query_arguments: Some(
24108                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
24109                    .expect("query arguments"),
24110            ),
24111            history_events: vec![
24112                history_event(
24113                    "ActivityScheduled",
24114                    json!({
24115                        "sequence": 1,
24116                        "activity_type": "typed.contract.activity"
24117                    }),
24118                ),
24119                history_event(
24120                    "ActivityCompleted",
24121                    json!({
24122                        "sequence": 1,
24123                        "activity_type": "typed.contract.activity",
24124                        "payload_codec": DEFAULT_CODEC,
24125                        "result": result
24126                    }),
24127                ),
24128            ],
24129            history_export: None,
24130            run_status: Some("completed".to_string()),
24131        };
24132
24133        assert_eq!(
24134            worker
24135                .execute_query_task(task)
24136                .await
24137                .expect("typed replay query")
24138                .deserialize::<i64>()
24139                .expect("query result"),
24140            expected.signed
24141        );
24142    }
24143
24144    #[tokio::test]
24145    async fn update_context_preserves_workflow_input_and_committed_signals() {
24146        let client = Client::new("http://127.0.0.1:8080").expect("client");
24147        let mut worker = Worker::new(client, "rust-workers");
24148        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
24149        let workflow_input = AvroValue::Array(vec![typed_fidelity_probe()]);
24150        let signal_arguments = vec![AvroValue::Bytes(vec![0, 255]), AvroValue::Long(7)];
24151        let expected_input = workflow_input.clone();
24152        let expected_signals = signal_arguments.clone();
24153        let handler = move |context: QueryContext, arguments: AvroValue| {
24154            let expected_input = expected_input.clone();
24155            let expected_signals = expected_signals.clone();
24156            async move {
24157                assert_eq!(context.workflow_id.as_deref(), Some("wf-snapshot"));
24158                assert_eq!(context.run_id.as_deref(), Some("run-snapshot"));
24159                assert_eq!(context.workflow_input_avro_value(), &expected_input);
24160                assert_eq!(context.workflow_input(), &expected_input.into_json()?);
24161                assert_eq!(
24162                    context.signals_avro_value("changed"),
24163                    vec![expected_signals.clone()]
24164                );
24165                assert_eq!(
24166                    context.signals("changed"),
24167                    vec![expected_signals
24168                        .into_iter()
24169                        .map(AvroValue::into_json)
24170                        .collect::<Result<Vec<_>>>()?]
24171                );
24172                assert_eq!(
24173                    context.signal_events()[0].id.as_deref(),
24174                    Some("signal-original")
24175                );
24176                assert_eq!(context.signal_events()[0].workflow_sequence, Some(1));
24177                Ok(arguments)
24178            }
24179        };
24180        worker.register_query_avro_value("snapshot", "inspect", handler.clone());
24181        worker.register_update_avro_value("snapshot", "inspect", handler);
24182        let update_arguments = AvroValue::Array(vec![AvroValue::String("update-only".into())]);
24183        let update_envelope =
24184            encode_typed_envelope(&update_arguments, DEFAULT_CODEC).expect("update input");
24185        let mut task = workflow_task(
24186            "snapshot",
24187            vec![
24188                history_event(
24189                    "SignalReceived",
24190                    json!({
24191                        "signal_id": "signal-original", "signal_name": "changed", "workflow_sequence": 1,
24192                        "arguments": encode_typed_envelope(&AvroValue::Array(signal_arguments), DEFAULT_CODEC).expect("signal input"),
24193                    }),
24194                ),
24195                history_event(
24196                    "UpdateAccepted",
24197                    json!({
24198                        "update_id": "update-original", "update_name": "inspect", "arguments": update_envelope.clone(),
24199                    }),
24200                ),
24201            ],
24202            DEFAULT_CODEC,
24203        );
24204        task.arguments =
24205            Some(encode_typed_envelope(&workflow_input, DEFAULT_CODEC).expect("workflow input"));
24206        task.workflow_update_id = Some("update-original".into());
24207        task.update_name = Some("inspect".into());
24208        let query = QueryTask {
24209            query_task_id: "query-snapshot".into(),
24210            observability_context: None,
24211            dispatch_observability_context: None,
24212            observability_links: None,
24213            query_task_attempt: 1,
24214            lease_owner: None,
24215            workflow_id: task.workflow_id.clone(),
24216            run_id: task.run_id.clone(),
24217            workflow_type: task.workflow_type.clone(),
24218            query_name: "inspect".into(),
24219            payload_codec: DEFAULT_CODEC.into(),
24220            workflow_arguments: task.arguments.clone(),
24221            query_arguments: Some(update_envelope),
24222            history_events: task.history_events.clone(),
24223            history_export: None,
24224            run_status: Some("running".into()),
24225        };
24226        assert_eq!(
24227            worker
24228                .execute_query_task(query)
24229                .await
24230                .expect("query snapshot"),
24231            update_arguments
24232        );
24233        for _ in 0..2 {
24234            let commands = worker
24235                .execute_workflow_task(task.clone())
24236                .expect("cold update snapshot");
24237            assert_eq!(commands[0]["type"], "complete_update");
24238            assert_eq!(commands[0]["update_id"], "update-original");
24239            assert_eq!(
24240                decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
24241                    .expect("update result"),
24242                update_arguments
24243            );
24244        }
24245    }
24246
24247    #[test]
24248    fn committed_signal_snapshot_counts_identities_once() {
24249        let arguments = encode_value_envelope(&json!([7]), DEFAULT_CODEC).expect("signal input");
24250        let received = history_event(
24251            "SignalReceived",
24252            json!({
24253                "signal_id": "signal-first", "workflow_command_id": "command-first",
24254                "signal_name": "changed", "arguments": arguments.clone(),
24255            }),
24256        );
24257        let applied = history_event(
24258            "SignalApplied",
24259            json!({
24260                "signal_id": "signal-first", "workflow_command_id": "command-first",
24261                "signal_name": "changed", "value": encode_value_envelope(&json!(7), DEFAULT_CODEC).expect("applied value"), "workflow_sequence": 1,
24262            }),
24263        );
24264        let distinct = history_event(
24265            "SignalReceived",
24266            json!({
24267                "signal_id": "signal-second", "workflow_command_id": "command-second",
24268                "signal_name": "changed", "arguments": arguments,
24269            }),
24270        );
24271        let history = vec![received.clone(), applied.clone(), distinct];
24272        let signals =
24273            history_signal_events(&history, None, DEFAULT_CODEC).expect("signal snapshot");
24274        assert_eq!(signals.len(), 2);
24275        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
24276        assert_eq!(signals[1].id.as_deref(), Some("signal-second"));
24277        assert_eq!(signals[0].workflow_sequence, Some(1));
24278        assert_eq!(signals[0].arguments, signals[1].arguments);
24279        let mut command_only = received.clone();
24280        command_only
24281            .payload
24282            .as_object_mut()
24283            .expect("payload")
24284            .remove("signal_id");
24285        let signals = history_signal_events(&[command_only, applied.clone()], None, DEFAULT_CODEC)
24286            .expect("command identity");
24287        assert_eq!(signals.len(), 1);
24288        assert_eq!(signals[0].id.as_deref(), Some("signal-first"));
24289        let mut conflicting = applied;
24290        conflicting.payload["value"] =
24291            encode_value_envelope(&json!(8), DEFAULT_CODEC).expect("different input");
24292        assert!(history_signal_events(&[received, conflicting], None, DEFAULT_CODEC).is_err());
24293    }
24294
24295    #[test]
24296    fn committed_signal_snapshot_preserves_argument_vectors_after_application() {
24297        for arguments in [
24298            vec![],
24299            vec![AvroValue::Array(vec![
24300                AvroValue::Long(1),
24301                AvroValue::Long(2),
24302            ])],
24303            vec![AvroValue::Bytes(vec![0, 255])],
24304            vec![AvroValue::Null],
24305            vec![AvroValue::Boolean(false)],
24306            vec![
24307                AvroValue::Long(1),
24308                AvroValue::Array(vec![AvroValue::Long(2)]),
24309            ],
24310        ] {
24311            let applied = match arguments.as_slice() {
24312                [] => AvroValue::Boolean(true),
24313                [value] => value.clone(),
24314                values => AvroValue::Array(values.to_vec()),
24315            };
24316            for applied in [applied, AvroValue::Array(arguments.clone())] {
24317                let events = vec![
24318                    history_event(
24319                        "SignalReceived",
24320                        json!({
24321                            "signal_id": "original", "signal_name": "changed",
24322                            "arguments": encode_typed_envelope(&AvroValue::Array(arguments.clone()), DEFAULT_CODEC).expect("signal arguments"),
24323                        }),
24324                    ),
24325                    history_event(
24326                        "SignalApplied",
24327                        json!({
24328                            "signal_id": "original", "signal_name": "changed",
24329                            "value": encode_typed_envelope(&applied, DEFAULT_CODEC).expect("application value"),
24330                        }),
24331                    ),
24332                ];
24333                let signals = history_signal_events(&events, None, DEFAULT_CODEC)
24334                    .expect("canonical signal snapshot");
24335                assert_eq!(signals.len(), 1);
24336                assert_eq!(signals[0].avro_arguments, arguments);
24337            }
24338        }
24339    }
24340
24341    #[tokio::test]
24342    async fn update_context_rejects_malformed_snapshot_before_handler() {
24343        let client = Client::new("http://127.0.0.1:8080").expect("client");
24344        let mut worker = Worker::new(client, "rust-workers");
24345        worker.register_workflow("snapshot", |_ctx, _input| async move { Ok(Value::Null) });
24346        let calls = Arc::new(AtomicUsize::new(0));
24347        let observed = Arc::clone(&calls);
24348        worker.register_update("snapshot", "inspect", move |_ctx, _arguments| {
24349            observed.fetch_add(1, Ordering::SeqCst);
24350            async { Ok(Value::Null) }
24351        });
24352        let mut task = workflow_task(
24353            "snapshot",
24354            vec![history_event(
24355                "UpdateAccepted",
24356                json!({
24357                    "update_id": "update-original", "update_name": "inspect",
24358                    "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("update input"),
24359                }),
24360            )],
24361            DEFAULT_CODEC,
24362        );
24363        task.workflow_update_id = Some("update-original".into());
24364        task.update_name = Some("inspect".into());
24365        let mut bad_input = task.clone();
24366        bad_input.arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "invalid"}));
24367        assert!(worker.execute_workflow_task(bad_input).is_err());
24368        task.history_events.insert(0, history_event("SignalReceived", json!({
24369            "signal_name": "changed", "arguments": {"codec": DEFAULT_CODEC, "blob": "invalid"},
24370        })));
24371        assert!(worker.execute_workflow_task(task).is_err());
24372        assert_eq!(calls.load(Ordering::SeqCst), 0);
24373    }
24374
24375    #[tokio::test]
24376    async fn typed_worker_surfaces_preserve_bytes_and_map_list_identity() {
24377        let client = Client::new("http://127.0.0.1:8080").expect("client");
24378        let mut worker = Worker::new(client, "rust-workers");
24379        worker.register_workflow_avro_value("typed.echo", |_ctx, input| async move { Ok(input) });
24380        worker
24381            .register_activity_avro_value("typed.activity", |_ctx, input| async move { Ok(input) });
24382        worker.register_query_avro_value("typed.echo", "inspect", |_ctx, input| async move {
24383            Ok(input)
24384        });
24385        worker.register_update_avro_value("typed.echo", "replace", |_ctx, input| async move {
24386            Ok(input)
24387        });
24388        worker.register_workflow_avro_value("typed.signal", |ctx, _input| async move {
24389            Ok(AvroValue::Array(
24390                ctx.wait_signal_avro_value("changed").await?,
24391            ))
24392        });
24393
24394        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
24395        let envelope = encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed envelope");
24396
24397        let mut workflow = workflow_task("typed.echo", Vec::new(), DEFAULT_CODEC);
24398        workflow.arguments = Some(envelope.clone());
24399        let commands = worker
24400            .execute_workflow_task(workflow)
24401            .expect("typed workflow task");
24402        assert_eq!(commands[0]["type"], "complete_workflow");
24403        assert_eq!(
24404            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
24405                .expect("typed workflow result"),
24406            arguments
24407        );
24408
24409        let activity = ActivityTask {
24410            task_id: "activity-typed".to_string(),
24411            workflow_id: None,
24412            run_id: None,
24413            activity_execution_id: None,
24414            observability_context: None,
24415            dispatch_observability_context: None,
24416            observability_links: None,
24417            activity_attempt_id: Some("attempt-typed".to_string()),
24418            attempt_id: None,
24419            activity_type: "typed.activity".to_string(),
24420            payload_codec: DEFAULT_CODEC.to_string(),
24421            arguments: Some(envelope.clone()),
24422            attempt_number: 1,
24423            lease_owner: Some("rust-worker".to_string()),
24424        };
24425        assert_eq!(
24426            worker
24427                .execute_activity_task(activity)
24428                .await
24429                .expect("typed activity result"),
24430            arguments
24431        );
24432
24433        let query = QueryTask {
24434            query_task_id: "query-typed".to_string(),
24435            observability_context: None,
24436            dispatch_observability_context: None,
24437            observability_links: None,
24438            query_task_attempt: 1,
24439            lease_owner: Some("rust-worker".to_string()),
24440            workflow_id: Some("typed-1".to_string()),
24441            run_id: Some("run-typed".to_string()),
24442            workflow_type: "typed.echo".to_string(),
24443            query_name: "inspect".to_string(),
24444            payload_codec: DEFAULT_CODEC.to_string(),
24445            workflow_arguments: Some(
24446                encode_typed_envelope(&AvroValue::Array(Vec::new()), DEFAULT_CODEC)
24447                    .expect("workflow input"),
24448            ),
24449            query_arguments: Some(envelope.clone()),
24450            history_events: Vec::new(),
24451            history_export: None,
24452            run_status: Some("running".to_string()),
24453        };
24454        assert_eq!(
24455            worker
24456                .execute_query_task(query)
24457                .await
24458                .expect("typed query result"),
24459            arguments
24460        );
24461
24462        let mut update = workflow_task(
24463            "typed.echo",
24464            vec![history_event(
24465                "UpdateAccepted",
24466                json!({
24467                    "update_id": "update-typed",
24468                    "update_name": "replace",
24469                    "arguments": envelope.clone(),
24470                }),
24471            )],
24472            DEFAULT_CODEC,
24473        );
24474        update.workflow_update_id = Some("update-typed".to_string());
24475        update.update_name = Some("replace".to_string());
24476        let commands = worker
24477            .execute_workflow_task(update)
24478            .expect("typed update task");
24479        assert_eq!(commands[0]["type"], "complete_update");
24480        assert_eq!(
24481            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
24482                .expect("typed update result"),
24483            arguments
24484        );
24485
24486        let mut signal = workflow_task(
24487            "typed.signal",
24488            vec![history_event(
24489                "SignalReceived",
24490                json!({
24491                    "signal_id": "signal-typed",
24492                    "signal_name": "changed",
24493                    "arguments": envelope.clone(),
24494                }),
24495            )],
24496            DEFAULT_CODEC,
24497        );
24498        signal.workflow_signal_id = Some("signal-typed".to_string());
24499        signal.signal_name = Some("changed".to_string());
24500        signal.signal_arguments = Some(envelope);
24501        let commands = worker
24502            .execute_workflow_task(signal)
24503            .expect("typed signal resume");
24504        assert_eq!(
24505            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
24506                .expect("typed signal result"),
24507            arguments
24508        );
24509    }
24510
24511    #[tokio::test]
24512    async fn typed_helpers_never_parse_json_inspection_projection() {
24513        let collision_values = projection_collision_probe();
24514        let expected = AvroValue::Array(collision_values.clone());
24515        let envelope = encode_typed_envelope(&expected, DEFAULT_CODEC).expect("collision envelope");
24516
24517        let activity_context = workflow_context_with_codec(
24518            vec![history_event(
24519                "ActivityCompleted",
24520                json!({
24521                    "sequence": 1,
24522                    "activity_type": "collision.activity",
24523                    "payload_codec": DEFAULT_CODEC,
24524                    "result": envelope.clone(),
24525                }),
24526            )],
24527            DEFAULT_CODEC,
24528        );
24529        assert_eq!(
24530            activity_context
24531                .activity_avro_value("collision.activity", AvroValue::Array(Vec::new()))
24532                .await
24533                .expect("typed activity collision result"),
24534            expected
24535        );
24536
24537        let signal_context = workflow_context_with_codec(
24538            vec![
24539                history_event(
24540                    "SignalWaitOpened",
24541                    json!({"sequence": 1, "signal_name": "collision"}),
24542                ),
24543                history_event(
24544                    "SignalApplied",
24545                    json!({
24546                        "sequence": 1,
24547                        "signal_name": "collision",
24548                        "payload_codec": DEFAULT_CODEC,
24549                        "value": envelope.clone(),
24550                    }),
24551                ),
24552            ],
24553            DEFAULT_CODEC,
24554        );
24555        assert_eq!(
24556            signal_context
24557                .wait_signal_avro_value("collision")
24558                .await
24559                .expect("typed signal collision arguments"),
24560            collision_values
24561        );
24562
24563        let child_context = workflow_context_with_codec(
24564            vec![
24565                history_event(
24566                    "ChildWorkflowScheduled",
24567                    json!({
24568                        "sequence": 1,
24569                        "child_workflow_instance_id": "collision-child",
24570                        "child_workflow_run_id": "collision-run",
24571                        "child_workflow_type": "collision.child",
24572                    }),
24573                ),
24574                history_event(
24575                    "ChildRunCompleted",
24576                    json!({
24577                        "sequence": 1,
24578                        "child_workflow_instance_id": "collision-child",
24579                        "child_workflow_run_id": "collision-run",
24580                        "child_workflow_type": "collision.child",
24581                        "payload_codec": DEFAULT_CODEC,
24582                        "result": envelope,
24583                    }),
24584                ),
24585            ],
24586            DEFAULT_CODEC,
24587        );
24588        let child = child_context
24589            .start_child_workflow_avro_value(
24590                "collision.child",
24591                ChildWorkflowOptions::new("collision-workers"),
24592                AvroValue::Array(Vec::new()),
24593            )
24594            .await
24595            .expect("typed child collision result");
24596        assert_eq!(child.result, expected);
24597    }
24598
24599    #[tokio::test]
24600    async fn replayed_typed_query_keeps_lossless_workflow_and_query_inputs() {
24601        let client = Client::new("http://127.0.0.1:8080").expect("client");
24602        let mut worker = Worker::new(client, "rust-workers");
24603        worker.register_replayed_workflow_avro_value(
24604            "typed.replayed",
24605            || (),
24606            |_ctx, input, _state| async move { Ok(input) },
24607        );
24608        worker.register_replayed_query_avro_value::<(), _, _>(
24609            "typed.replayed",
24610            "inspect",
24611            |ctx, _state, args| async move {
24612                let mut signals = ctx.signals_avro_value("collision");
24613                let signal = signals
24614                    .pop()
24615                    .map(AvroValue::Array)
24616                    .unwrap_or_else(|| AvroValue::Array(Vec::new()));
24617                Ok(AvroValue::Array(vec![
24618                    ctx.workflow_input_avro_value().clone(),
24619                    signal,
24620                    args,
24621                ]))
24622            },
24623        );
24624        let arguments = AvroValue::Array(projection_collision_probe());
24625        let signal_arguments =
24626            encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("typed query signal arguments");
24627        let task = QueryTask {
24628            query_task_id: "query-typed-replay".to_string(),
24629            observability_context: None,
24630            dispatch_observability_context: None,
24631            observability_links: None,
24632            query_task_attempt: 1,
24633            lease_owner: Some("rust-worker".to_string()),
24634            workflow_id: Some("typed-replay".to_string()),
24635            run_id: Some("run-typed-replay".to_string()),
24636            workflow_type: "typed.replayed".to_string(),
24637            query_name: "inspect".to_string(),
24638            payload_codec: DEFAULT_CODEC.to_string(),
24639            workflow_arguments: Some(
24640                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("workflow arguments"),
24641            ),
24642            query_arguments: Some(
24643                encode_typed_envelope(&arguments, DEFAULT_CODEC).expect("query arguments"),
24644            ),
24645            history_events: vec![history_event(
24646                "SignalReceived",
24647                json!({
24648                    "signal_id": "collision-signal",
24649                    "signal_name": "collision",
24650                    "workflow_sequence": 1,
24651                    "payload_codec": DEFAULT_CODEC,
24652                    "arguments": signal_arguments,
24653                }),
24654            )],
24655            history_export: None,
24656            run_status: Some("completed".to_string()),
24657        };
24658
24659        assert_eq!(
24660            worker
24661                .execute_query_task(task)
24662                .await
24663                .expect("typed replay query"),
24664            AvroValue::Array(vec![arguments.clone(), arguments.clone(), arguments])
24665        );
24666    }
24667
24668    #[test]
24669    fn public_avro_adapter_rejects_non_string_map_keys_before_json_conversion() {
24670        let value = BTreeMap::from([(1_i32, "integer key")]);
24671        let error = PayloadEnvelope::avro(&value)
24672            .expect_err("integer map keys must fail")
24673            .to_string();
24674
24675        assert!(error.contains("invalid_map_key"));
24676    }
24677
24678    #[test]
24679    fn json_tagged_payload_fails_closed_with_actionable_diagnostic() {
24680        let envelope = PayloadEnvelope {
24681            codec: "json".to_string(),
24682            blob: r#"{"greeting":"hello"}"#.to_string(),
24683        };
24684
24685        let error = decode_payload::<Value>(&envelope).expect_err("JSON payload must fail");
24686        let diagnostic = error.to_string();
24687        assert!(diagnostic.contains("unsupported_payload_codec"));
24688        assert!(diagnostic.contains("codec=\"avro\""));
24689        assert!(diagnostic.contains("HTTP document transport"));
24690    }
24691
24692    #[test]
24693    fn untagged_json_payload_value_fails_closed() {
24694        let error = decode_wire_value(&json!({"stale": true}), DEFAULT_CODEC)
24695            .expect_err("untagged JSON payload values must fail");
24696        let diagnostic = error.to_string();
24697        assert!(diagnostic.contains("unsupported_payload_codec"));
24698        assert!(diagnostic.contains("untagged durable payload"));
24699        assert!(diagnostic.contains("HTTP document transport"));
24700    }
24701
24702    #[test]
24703    fn prerelease_avro_payload_without_single_object_frame_is_rejected() {
24704        let envelope = PayloadEnvelope {
24705            codec: DEFAULT_CODEC.to_string(),
24706            blob: BASE64.encode([0x01]),
24707        };
24708
24709        let error = decode_payload::<Value>(&envelope).expect_err("prerelease payload must fail");
24710        assert!(error.to_string().contains("invalid_payload_framing"));
24711    }
24712
24713    #[tokio::test]
24714    async fn workflow_completion_rejects_invalid_payload_slots_without_transport() {
24715        let server = MockWorkerServer::start();
24716        let client = Client::builder(server.base_url())
24717            .timeout(Duration::from_secs(2))
24718            .build()
24719            .expect("client");
24720        let invalid_commands = [
24721            json!({
24722                "type": "complete_workflow",
24723                "result": {"codec": "json", "blob": null}
24724            }),
24725            json!({
24726                "type": "schedule_activity",
24727                "arguments": {"codec": "yaml", "blob": "ignored"}
24728            }),
24729            json!({
24730                "type": "start_child_workflow",
24731                "arguments": {"codec": DEFAULT_CODEC, "blob": null}
24732            }),
24733            json!({"type": "continue_as_new", "arguments": []}),
24734            json!({"type": "complete_update"}),
24735            json!({"type": "record_side_effect", "result": null}),
24736            json!({
24737                "type": "start_service_operation",
24738                "payload_codec": DEFAULT_CODEC,
24739                "request_payload": "raw-avro-bytes"
24740            }),
24741        ];
24742
24743        for command in invalid_commands {
24744            let error = client
24745                .complete_workflow_task("invalid-codec", "rust-worker", 1, vec![command])
24746                .await
24747                .expect_err("invalid durable payload must fail locally");
24748            let diagnostic = error.to_string();
24749            assert!(
24750                diagnostic.contains("unsupported_payload_codec")
24751                    || diagnostic.contains("invalid_payload_envelope")
24752                    || diagnostic.contains("untagged durable payload"),
24753                "unexpected validation diagnostic: {diagnostic}"
24754            );
24755        }
24756
24757        assert_eq!(
24758            server.request_count("/api/worker/workflow-tasks/invalid-codec/complete"),
24759            0,
24760            "invalid command payloads must not reach HTTP transport"
24761        );
24762    }
24763
24764    #[test]
24765    fn workflow_completion_validates_only_protocol_owned_payload_slots() {
24766        let envelope = fixture_envelope(json!({"codec": "customer-value"}));
24767        let commands = [
24768            json!({"type": "complete_workflow", "result": envelope.clone()}),
24769            json!({"type": "schedule_activity", "arguments": envelope.clone()}),
24770            json!({"type": "start_child_workflow", "arguments": envelope.clone()}),
24771            json!({"type": "continue_as_new", "arguments": envelope.clone()}),
24772            json!({"type": "complete_update", "result": envelope.clone()}),
24773            json!({"type": "record_side_effect", "result": envelope.clone()}),
24774            json!({
24775                "type": "start_service_operation",
24776                "payload_codec": DEFAULT_CODEC,
24777                "request_payload": envelope.clone()
24778            }),
24779            json!({
24780                "type": "complete_workflow",
24781                "result": envelope,
24782                "metadata": {
24783                    "codec": "json",
24784                    "payload_codec": "customer-codec",
24785                    "result": {"codec": "yaml", "blob": null}
24786                }
24787            }),
24788        ];
24789
24790        validate_workflow_task_commands(&commands)
24791            .expect("customer metadata must not become a protocol codec declaration");
24792    }
24793
24794    #[test]
24795    fn valid_avro_tasks_normalize_absent_and_null_arguments_to_empty_lists() {
24796        assert_eq!(
24797            decode_task_avro_arguments(None, DEFAULT_CODEC).expect("absent arguments"),
24798            AvroValue::Array(Vec::new())
24799        );
24800        assert_eq!(
24801            decode_task_avro_arguments(Some(&Value::Null), DEFAULT_CODEC).expect("null arguments"),
24802            AvroValue::Array(Vec::new())
24803        );
24804
24805        let mut signal = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
24806        signal.signal_name = Some("empty-signal".to_string());
24807        signal.signal_arguments = None;
24808        let decoded = decode_resume_signal(&signal)
24809            .expect("valid Avro signal")
24810            .expect("named signal resumes the workflow");
24811        assert!(decoded.arguments.is_empty());
24812    }
24813
24814    #[tokio::test]
24815    async fn malformed_task_level_codecs_become_pre_handler_failures() {
24816        let client = Client::new("http://127.0.0.1:8080").expect("client");
24817        let mut worker = Worker::new(client, "rust-workers");
24818        let handler_calls = Arc::new(AtomicUsize::new(0));
24819
24820        let calls = Arc::clone(&handler_calls);
24821        worker.register_workflow("codec.workflow", move |_ctx, _args| {
24822            calls.fetch_add(1, Ordering::SeqCst);
24823            async move { Ok(Value::Null) }
24824        });
24825        let calls = Arc::clone(&handler_calls);
24826        worker.register_activity("codec.activity", move |_ctx, _args| {
24827            calls.fetch_add(1, Ordering::SeqCst);
24828            async move { Ok(Value::Null) }
24829        });
24830        let calls = Arc::clone(&handler_calls);
24831        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
24832            calls.fetch_add(1, Ordering::SeqCst);
24833            async move { Ok(Value::Null) }
24834        });
24835
24836        let mut failures = Vec::new();
24837        for codec_case in [
24838            InvalidTaskPayloadCodec::Missing,
24839            InvalidTaskPayloadCodec::Null,
24840            InvalidTaskPayloadCodec::NonString,
24841        ] {
24842            let mut workflow = json!({
24843                "task_id": format!("workflow-{}", codec_case.label()),
24844                "workflow_type": "codec.workflow"
24845            });
24846            codec_case.apply(&mut workflow);
24847            match serde_json::from_value::<WorkflowTask>(workflow) {
24848                Ok(task) => match worker.execute_workflow_task(task) {
24849                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
24850                    outcome => failures.push(format!(
24851                        "workflow {} codec returned {outcome:?}",
24852                        codec_case.label()
24853                    )),
24854                },
24855                Err(error) => failures.push(format!(
24856                    "workflow {} codec failed transport deserialization: {error}",
24857                    codec_case.label()
24858                )),
24859            }
24860
24861            let mut activity = json!({
24862                "task_id": format!("activity-{}", codec_case.label()),
24863                "activity_attempt_id": format!("attempt-{}", codec_case.label()),
24864                "activity_type": "codec.activity",
24865                "attempt_number": 1
24866            });
24867            codec_case.apply(&mut activity);
24868            match serde_json::from_value::<ActivityTask>(activity) {
24869                Ok(task) => match worker.execute_activity_task(task).await {
24870                    Err(error) if error.to_string().contains("unsupported_payload_codec") => {}
24871                    outcome => failures.push(format!(
24872                        "activity {} codec returned {outcome:?}",
24873                        codec_case.label()
24874                    )),
24875                },
24876                Err(error) => failures.push(format!(
24877                    "activity {} codec failed transport deserialization: {error}",
24878                    codec_case.label()
24879                )),
24880            }
24881
24882            let mut query = json!({
24883                "query_task_id": format!("query-{}", codec_case.label()),
24884                "workflow_type": "codec.workflow",
24885                "query_name": "known"
24886            });
24887            codec_case.apply(&mut query);
24888            match serde_json::from_value::<QueryTask>(query) {
24889                Ok(task) => match worker.execute_query_task(task).await {
24890                    Err(failure) if failure.message.contains("unsupported_payload_codec") => {}
24891                    outcome => failures.push(format!(
24892                        "query {} codec returned {outcome:?}",
24893                        codec_case.label()
24894                    )),
24895                },
24896                Err(error) => failures.push(format!(
24897                    "query {} codec failed transport deserialization: {error}",
24898                    codec_case.label()
24899                )),
24900            }
24901        }
24902
24903        assert!(failures.is_empty(), "{}", failures.join("\n"));
24904        assert_eq!(
24905            handler_calls.load(Ordering::SeqCst),
24906            0,
24907            "invalid task codecs must not invoke a handler"
24908        );
24909    }
24910
24911    #[tokio::test]
24912    async fn polled_malformed_task_codecs_are_settled_without_handler_execution() {
24913        for codec_case in [
24914            InvalidTaskPayloadCodec::Missing,
24915            InvalidTaskPayloadCodec::Null,
24916            InvalidTaskPayloadCodec::NonString,
24917        ] {
24918            let server = MockWorkerServer::invalid_task_payload_codec(codec_case);
24919            let client = Client::builder(server.base_url())
24920                .timeout(Duration::from_secs(2))
24921                .build()
24922                .expect("client");
24923            let mut worker = Worker::new(client, "rust-workers")
24924                .worker_id("codec-worker")
24925                .poll_timeout(Duration::from_millis(10));
24926            let handler_calls = Arc::new(AtomicUsize::new(0));
24927
24928            let calls = Arc::clone(&handler_calls);
24929            worker.register_workflow("codec.workflow", move |_ctx, _args| {
24930                calls.fetch_add(1, Ordering::SeqCst);
24931                async move { Ok(Value::Null) }
24932            });
24933            let calls = Arc::clone(&handler_calls);
24934            worker.register_activity("codec.activity", move |_ctx, _args| {
24935                calls.fetch_add(1, Ordering::SeqCst);
24936                async move { Ok(Value::Null) }
24937            });
24938            let calls = Arc::clone(&handler_calls);
24939            worker.register_query("codec.workflow", "known", move |_ctx, _args| {
24940                calls.fetch_add(1, Ordering::SeqCst);
24941                async move { Ok(Value::Null) }
24942            });
24943
24944            assert_eq!(
24945                worker.run_once().await.expect("invalid tasks are settled"),
24946                3,
24947                "all {} codec tasks must be handled",
24948                codec_case.label()
24949            );
24950            assert_eq!(
24951                handler_calls.load(Ordering::SeqCst),
24952                0,
24953                "{} task codecs must fail before every handler",
24954                codec_case.label()
24955            );
24956
24957            for path in [
24958                "/api/worker/workflow-tasks/codec-workflow/fail",
24959                "/api/worker/activity-tasks/codec-activity/fail",
24960                "/api/worker/query-tasks/codec-query/fail",
24961            ] {
24962                let body = server.request_body(path);
24963                assert!(
24964                    body["failure"]["message"]
24965                        .as_str()
24966                        .is_some_and(|message| message.contains("unsupported_payload_codec")),
24967                    "{path} must receive the stable codec diagnostic for the {} case: {body}",
24968                    codec_case.label()
24969                );
24970            }
24971            assert_eq!(
24972                server.request_body("/api/worker/query-tasks/codec-query/fail")["failure"]
24973                    ["reason"],
24974                "query_payload_decode_failed"
24975            );
24976            for path in [
24977                "/api/worker/workflow-tasks/codec-workflow/complete",
24978                "/api/worker/activity-tasks/codec-activity/complete",
24979                "/api/worker/query-tasks/codec-query/complete",
24980            ] {
24981                assert_eq!(
24982                    server.request_count(path),
24983                    0,
24984                    "invalid {} codec task reached {path}",
24985                    codec_case.label()
24986                );
24987            }
24988        }
24989    }
24990
24991    #[tokio::test]
24992    async fn invalid_inbound_codecs_precede_handlers_and_unrelated_outcomes() {
24993        let client = Client::new("http://127.0.0.1:8080").expect("client");
24994        let mut worker = Worker::new(client, "rust-workers");
24995        let handler_calls = Arc::new(AtomicUsize::new(0));
24996
24997        let calls = Arc::clone(&handler_calls);
24998        worker.register_workflow("codec.workflow", move |_ctx, _args| {
24999            calls.fetch_add(1, Ordering::SeqCst);
25000            async move { Ok(Value::Null) }
25001        });
25002        let calls = Arc::clone(&handler_calls);
25003        worker.register_activity("codec.activity", move |_ctx, _args| {
25004            calls.fetch_add(1, Ordering::SeqCst);
25005            async move { Ok(Value::Null) }
25006        });
25007        let calls = Arc::clone(&handler_calls);
25008        worker.register_update("codec.workflow", "known", move |_ctx, _args| {
25009            calls.fetch_add(1, Ordering::SeqCst);
25010            async move { Ok(Value::Null) }
25011        });
25012        let calls = Arc::clone(&handler_calls);
25013        worker.register_query("codec.workflow", "known", move |_ctx, _args| {
25014            calls.fetch_add(1, Ordering::SeqCst);
25015            async move { Ok(Value::Null) }
25016        });
25017
25018        let mut workflow = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
25019        workflow.payload_codec = "json".to_string();
25020        workflow.arguments = None;
25021        let error = worker
25022            .execute_workflow_task(workflow)
25023            .expect_err("task codec must be checked before workflow invocation");
25024        assert!(error.to_string().contains("unsupported_payload_codec"));
25025
25026        let activity = ActivityTask {
25027            task_id: "activity-invalid-codec".to_string(),
25028            workflow_id: None,
25029            run_id: None,
25030            activity_execution_id: None,
25031            observability_context: None,
25032            dispatch_observability_context: None,
25033            observability_links: None,
25034            activity_attempt_id: None,
25035            attempt_id: None,
25036            activity_type: "codec.activity".to_string(),
25037            payload_codec: "unknown".to_string(),
25038            arguments: None,
25039            attempt_number: 1,
25040            lease_owner: None,
25041        };
25042        let error = worker
25043            .execute_activity_task(activity)
25044            .await
25045            .expect_err("task codec must be checked before activity invocation");
25046        assert!(error.to_string().contains("unsupported_payload_codec"));
25047
25048        let mut update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
25049        update.workflow_update_id = Some("update-invalid-codec".to_string());
25050        update.update_name = Some("known".to_string());
25051        update.history_events.push(history_event(
25052            "UpdateAccepted",
25053            json!({
25054                "update_id": "update-invalid-codec",
25055                "update_name": "known",
25056                "arguments": {"codec": "json", "blob": null}
25057            }),
25058        ));
25059        let error = worker
25060            .execute_workflow_task(update)
25061            .expect_err("nested update codec must be checked before handler lookup");
25062        assert!(error.to_string().contains("unsupported_payload_codec"));
25063
25064        let query: QueryTask = serde_json::from_value(json!({
25065            "query_task_id": "query-invalid-codec",
25066            "workflow_type": "codec.workflow",
25067            "query_name": "known",
25068            "payload_codec": DEFAULT_CODEC,
25069            "workflow_arguments": null,
25070            "query_arguments": null,
25071            "history_export": {
25072                "payloads": {"codec": DEFAULT_CODEC},
25073                "signals": [{
25074                    "name": "empty",
25075                    "payload_codec": "json",
25076                    "arguments": null
25077                }]
25078            }
25079        }))
25080        .expect("query task");
25081        let failure = worker
25082            .execute_query_task(query)
25083            .await
25084            .expect_err("exported signal codec must be checked before query invocation");
25085        assert_eq!(failure.reason, "query_payload_decode_failed");
25086        assert!(failure.message.contains("unsupported_payload_codec"));
25087
25088        let exported_history: QueryTask = serde_json::from_value(json!({
25089            "query_task_id": "query-invalid-history-codec",
25090            "workflow_type": "codec.workflow",
25091            "query_name": "known",
25092            "payload_codec": DEFAULT_CODEC,
25093            "history_export": {
25094                "payloads": {"codec": DEFAULT_CODEC},
25095                "history_events": [{
25096                    "type": "ActivityCompleted",
25097                    "payload": {"payload_codec": "unknown", "result": null}
25098                }]
25099            }
25100        }))
25101        .expect("query task");
25102        let failure = worker
25103            .execute_query_task(exported_history)
25104            .await
25105            .expect_err("exported history codec must be checked before query invocation");
25106        assert_eq!(failure.reason, "query_payload_decode_failed");
25107        assert!(failure.message.contains("unsupported_payload_codec"));
25108        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
25109
25110        let mut unknown_workflow = workflow_task("missing", Vec::new(), DEFAULT_CODEC);
25111        unknown_workflow.arguments = None;
25112        unknown_workflow.history_events.push(history_event(
25113            "SignalReceived",
25114            json!({
25115                "signal_name": "empty",
25116                "payload_codec": "json",
25117                "arguments": null
25118            }),
25119        ));
25120        let error = worker
25121            .execute_workflow_task(unknown_workflow)
25122            .expect_err("history codec must precede unknown workflow outcome");
25123        assert!(error.to_string().contains("unsupported_payload_codec"));
25124
25125        let unknown_activity = ActivityTask {
25126            task_id: "activity-unknown".to_string(),
25127            workflow_id: None,
25128            run_id: None,
25129            activity_execution_id: None,
25130            observability_context: None,
25131            dispatch_observability_context: None,
25132            observability_links: None,
25133            activity_attempt_id: None,
25134            attempt_id: None,
25135            activity_type: "missing".to_string(),
25136            payload_codec: "json".to_string(),
25137            arguments: None,
25138            attempt_number: 1,
25139            lease_owner: None,
25140        };
25141        let error = worker
25142            .execute_activity_task(unknown_activity)
25143            .await
25144            .expect_err("codec must precede unknown activity outcome");
25145        assert!(error.to_string().contains("unsupported_payload_codec"));
25146
25147        let mut unknown_update = workflow_task("codec.workflow", Vec::new(), DEFAULT_CODEC);
25148        unknown_update.payload_codec = "json".to_string();
25149        unknown_update.arguments = None;
25150        unknown_update.workflow_update_id = Some("update-unknown".to_string());
25151        unknown_update.update_name = Some("missing".to_string());
25152        let error = worker
25153            .execute_workflow_task(unknown_update)
25154            .expect_err("codec must precede fail_update shortcut");
25155        assert!(error.to_string().contains("unsupported_payload_codec"));
25156
25157        let unknown_query: QueryTask = serde_json::from_value(json!({
25158            "query_task_id": "query-unknown",
25159            "workflow_type": "missing",
25160            "query_name": "missing",
25161            "payload_codec": "json",
25162            "workflow_arguments": null,
25163            "query_arguments": null
25164        }))
25165        .expect("query task");
25166        let failure = worker
25167            .execute_query_task(unknown_query)
25168            .await
25169            .expect_err("codec must precede unknown query outcome");
25170        assert_eq!(failure.reason, "query_payload_decode_failed");
25171        assert!(failure.message.contains("unsupported_payload_codec"));
25172    }
25173
25174    #[tokio::test]
25175    async fn invalid_signal_history_payload_aliases_precede_shortcuts() {
25176        let client = Client::new("http://127.0.0.1:8080").expect("client");
25177        let worker = Worker::new(client, "rust-workers");
25178
25179        for event_type in ["SignalReceived", "SignalApplied"] {
25180            for (payload_field, codec) in [
25181                ("value", "json"),
25182                ("input", "unknown"),
25183                ("arguments", "json"),
25184            ] {
25185                let payload = json!({
25186                    "signal_name": "empty",
25187                    payload_field: {"codec": codec, "blob": null}
25188                });
25189                let workflow = workflow_task(
25190                    "missing",
25191                    vec![history_event(event_type, payload.clone())],
25192                    DEFAULT_CODEC,
25193                );
25194                let error = worker
25195                    .execute_workflow_task(workflow)
25196                    .expect_err("signal payload codec must precede unknown workflow outcome");
25197                assert!(
25198                    error.to_string().contains("unsupported_payload_codec"),
25199                    "{event_type}.{payload_field} returned an unrelated workflow error: {error}"
25200                );
25201
25202                let query: QueryTask = serde_json::from_value(json!({
25203                    "query_task_id": format!("query-{event_type}-{payload_field}"),
25204                    "workflow_type": "missing",
25205                    "query_name": "missing",
25206                    "payload_codec": DEFAULT_CODEC,
25207                    "workflow_arguments": null,
25208                    "query_arguments": null,
25209                    "history_events": [{
25210                        "event_type": event_type,
25211                        "payload": payload
25212                    }]
25213                }))
25214                .expect("query task");
25215                let failure = worker
25216                    .execute_query_task(query)
25217                    .await
25218                    .expect_err("signal payload codec must precede unknown query outcome");
25219                assert_eq!(
25220                    failure.reason, "query_payload_decode_failed",
25221                    "{event_type}.{payload_field} returned an unrelated query outcome"
25222                );
25223                assert!(
25224                    failure.message.contains("unsupported_payload_codec"),
25225                    "{event_type}.{payload_field} returned an unrelated query error: {}",
25226                    failure.message
25227                );
25228            }
25229        }
25230    }
25231
25232    #[test]
25233    fn workflow_context_schedules_activity_until_completion_is_in_history() {
25234        let ctx = WorkflowContext {
25235            cancellation_scope_id: "root".into(),
25236            state: Arc::new(Mutex::new(
25237                WorkflowState::new_with_identity(
25238                    Vec::new(),
25239                    Some("wf-parent".to_string()),
25240                    Some("run-parent".to_string()),
25241                    "rust-workers".to_string(),
25242                    DEFAULT_CODEC.to_string(),
25243                    None,
25244                )
25245                .expect("workflow state"),
25246            )),
25247        };
25248
25249        let mut call = Box::pin(ctx.activity("hello.activity", json!(["Ada"])));
25250        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25251        assert!(matches!(
25252            call.as_mut().poll(&mut task_context),
25253            Poll::Pending
25254        ));
25255
25256        let commands = ctx.take_commands().expect("commands");
25257        assert_eq!(commands[0]["type"], "schedule_activity");
25258        assert_eq!(commands[0]["activity_type"], "hello.activity");
25259    }
25260
25261    #[test]
25262    fn activity_options_encode_retry_policy_queue_and_every_timeout() {
25263        let ctx = workflow_context(Vec::new());
25264        let options = ActivityOptions::new()
25265            .task_queue("payments")
25266            .retry_policy(
25267                ActivityRetryPolicy::new(4)
25268                    .exponential_backoff(Duration::from_secs(1), 3, Some(Duration::from_secs(10)))
25269                    .non_retryable_error_type("ValidationError"),
25270            )
25271            .start_to_close_timeout(Duration::from_secs(120))
25272            .schedule_to_start_timeout(Duration::from_secs(10))
25273            .schedule_to_close_timeout(Duration::from_secs(300))
25274            .heartbeat_timeout(Duration::from_secs(15));
25275        let mut call = Box::pin(ctx.activity_with_options(
25276            "charge-card",
25277            options,
25278            json!([{"order_id": "o-1"}]),
25279        ));
25280        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25281
25282        assert!(matches!(
25283            call.as_mut().poll(&mut task_context),
25284            Poll::Pending
25285        ));
25286        assert!(matches!(
25287            call.as_mut().poll(&mut task_context),
25288            Poll::Pending
25289        ));
25290
25291        let commands = ctx.take_commands().expect("activity command");
25292        assert_eq!(commands.len(), 1, "one future emits one logical schedule");
25293        assert_eq!(commands[0]["queue"], "payments");
25294        assert_eq!(
25295            commands[0]["retry_policy"],
25296            json!({
25297                "max_attempts": 4,
25298                "backoff_seconds": [1, 3, 9],
25299                "non_retryable_error_types": ["ValidationError"],
25300            })
25301        );
25302        assert_eq!(commands[0]["start_to_close_timeout"], 120);
25303        assert_eq!(commands[0]["schedule_to_start_timeout"], 10);
25304        assert_eq!(commands[0]["schedule_to_close_timeout"], 300);
25305        assert_eq!(commands[0]["heartbeat_timeout"], 15);
25306    }
25307
25308    #[test]
25309    fn exponential_backoff_without_maximum_keeps_growing_and_replays() {
25310        let mut options = retry_activity_options();
25311        options.retry_policy = Some(
25312            ActivityRetryPolicy::new(9)
25313                .exponential_backoff(Duration::from_secs(1), 2, None)
25314                .non_retryable_error_type("PermanentError"),
25315        );
25316        let expected = json!([1, 2, 4, 8, 16, 32, 64, 128]);
25317        let ctx = workflow_context(Vec::new());
25318        let mut call = Box::pin(ctx.activity_with_options("flaky", options.clone(), json!([])));
25319        let mut cx = TaskContext::from_waker(noop_waker_ref());
25320        assert!(call.as_mut().poll(&mut cx).is_pending());
25321        let commands = ctx.take_commands().expect("one new schedule");
25322        assert_eq!(commands.len(), 1);
25323        assert_eq!(commands[0]["retry_policy"]["max_attempts"], 9);
25324        assert_eq!(commands[0]["retry_policy"]["backoff_seconds"], expected);
25325
25326        let mut history = completed_retry_activity_history();
25327        history[0].payload["activity"]["retry_policy"]["max_attempts"] = json!(9);
25328        history[0].payload["activity"]["retry_policy"]["backoff_seconds"] = expected;
25329        history[2].payload["retry_backoff_seconds"] = json!(1);
25330        let replay = workflow_context(history.clone());
25331        let mut replay_call =
25332            Box::pin(replay.activity_with_options("flaky", options.clone(), json!([])));
25333        assert!(matches!(
25334            replay_call.as_mut().poll(&mut cx),
25335            Poll::Ready(Ok(value)) if value == json!({"status":"recovered"})
25336        ));
25337        assert!(replay.take_commands().unwrap().is_empty());
25338        replay
25339            .ensure_history_consumed()
25340            .expect("recorded history consumed");
25341
25342        options.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Exponential {
25343            initial_interval: Duration::from_secs(1),
25344            coefficient: 2,
25345            maximum_interval: Some(Duration::from_secs(60)),
25346        });
25347        let changed = workflow_context(history);
25348        let mut changed_call = Box::pin(changed.activity_with_options("flaky", options, json!([])));
25349        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25350            changed_call.as_mut().poll(&mut cx)
25351        else {
25352            panic!("adding a cap must not reinterpret a recorded uncapped policy");
25353        };
25354        assert_eq!(failure.reason, "activity_retry_policy_mismatch");
25355        assert!(changed.take_commands().unwrap().is_empty());
25356    }
25357
25358    fn completed_worker_session_history(session: &WorkerSessionOptions) -> Vec<HistoryEvent> {
25359        vec![
25360            history_event(
25361                "ActivityScheduled",
25362                json!({"sequence":1,"activity_type":"render",
25363                "activity":{"queue":"gpu-workers","worker_session":session.to_wire().unwrap()}}),
25364            ),
25365            history_event(
25366                "ActivityCompleted",
25367                json!({"sequence":1,"activity_type":"render",
25368                "payload_codec":DEFAULT_CODEC,
25369                "result":encode_typed_envelope(&AvroValue::Long(42),DEFAULT_CODEC).unwrap()}),
25370            ),
25371        ]
25372    }
25373
25374    #[test]
25375    fn worker_session_activity_routes_to_session_queue_once() {
25376        let ctx = workflow_context(Vec::new());
25377        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
25378        let mut call = Box::pin(
25379            ctx.activity("render", json!([]))
25380                .in_worker_session(session.clone()),
25381        );
25382        let mut cx = TaskContext::from_waker(noop_waker_ref());
25383        assert!(call.as_mut().poll(&mut cx).is_pending());
25384        assert!(call.as_mut().poll(&mut cx).is_pending());
25385        let commands = ctx.take_commands().unwrap();
25386        assert_eq!(commands.len(), 1);
25387        assert_eq!(commands[0]["queue"], "gpu-workers");
25388        assert_eq!(commands[0]["worker_session"], session.to_wire().unwrap());
25389    }
25390
25391    #[tokio::test]
25392    async fn worker_session_cold_replay_uses_recorded_avro_result() {
25393        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
25394        for _replacement in 0..2 {
25395            let ctx = workflow_context(completed_worker_session_history(&session));
25396            let result: i64 = ctx
25397                .activity("render", json!([]))
25398                .in_worker_session(session.clone())
25399                .typed()
25400                .await
25401                .unwrap();
25402            assert_eq!(result, 42);
25403            assert!(ctx.take_commands().unwrap().is_empty());
25404        }
25405    }
25406
25407    #[test]
25408    fn worker_session_cold_replay_rejects_changed_identity_and_lifetime() {
25409        let original = WorkerSessionOptions::new("render-1").queue("gpu-workers");
25410        for changed in [
25411            Some(WorkerSessionOptions::new("render-2").queue("gpu-workers")),
25412            Some(original.clone().ttl_seconds(60)),
25413            Some(original.clone().requirements(["gpu:l4"])),
25414            None,
25415        ] {
25416            let ctx = workflow_context(completed_worker_session_history(&original));
25417            let mut call = ctx.activity_with_options(
25418                "render",
25419                ActivityOptions::new().task_queue("gpu-workers"),
25420                json!([]),
25421            );
25422            if let Some(changed) = changed {
25423                call = call.in_worker_session(changed);
25424            }
25425            let mut call = Box::pin(call);
25426            let mut cx = TaskContext::from_waker(noop_waker_ref());
25427            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25428                call.as_mut().poll(&mut cx)
25429            else {
25430                panic!("changed session must fail replay");
25431            };
25432            assert_eq!(failure.reason, "activity_worker_session_mismatch");
25433            assert!(ctx.take_commands().unwrap().is_empty());
25434        }
25435    }
25436
25437    #[test]
25438    fn worker_session_local_and_contradictory_queue_routing_emit_no_commands() {
25439        let session = WorkerSessionOptions::new("render-1").queue("gpu-workers");
25440        let ctx = workflow_context(Vec::new());
25441        let mut local = Box::pin(
25442            ctx.local_activity("render", json!([]))
25443                .in_worker_session(session.clone()),
25444        );
25445        let mut cx = TaskContext::from_waker(noop_waker_ref());
25446        assert!(matches!(
25447            local.as_mut().poll(&mut cx),
25448            Poll::Ready(Err(Error::WorkerLoop(_)))
25449        ));
25450        assert!(ctx.take_commands().unwrap().is_empty());
25451        let mut remote = Box::pin(
25452            ctx.activity_with_options(
25453                "render",
25454                ActivityOptions::new().task_queue("other"),
25455                json!([]),
25456            )
25457            .in_worker_session(session),
25458        );
25459        assert!(matches!(
25460            remote.as_mut().poll(&mut cx),
25461            Poll::Ready(Err(Error::WorkerLoop(_)))
25462        ));
25463        assert!(ctx.take_commands().unwrap().is_empty());
25464    }
25465
25466    #[test]
25467    fn activity_options_encode_explicit_and_rounded_backoff_intervals() {
25468        let ctx = workflow_context(Vec::new());
25469        let options = ActivityOptions::new().retry_policy(
25470            ActivityRetryPolicy::new(3)
25471                .backoff_intervals([Duration::from_millis(1), Duration::from_millis(1_001)]),
25472        );
25473        let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
25474        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25475
25476        assert!(matches!(
25477            call.as_mut().poll(&mut task_context),
25478            Poll::Pending
25479        ));
25480        assert_eq!(
25481            ctx.take_commands().expect("command")[0]["retry_policy"]["backoff_seconds"],
25482            json!([1, 2])
25483        );
25484    }
25485
25486    #[test]
25487    fn activity_options_preserve_unused_explicit_backoff_entries() {
25488        for max_attempts in [1, 2, 10] {
25489            let ctx = workflow_context(Vec::new());
25490            let options =
25491                ActivityOptions::new()
25492                    .retry_policy(ActivityRetryPolicy::new(max_attempts).backoff_intervals(
25493                        [1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs),
25494                    ));
25495            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
25496            let mut task_context = TaskContext::from_waker(noop_waker_ref());
25497            assert!(matches!(
25498                call.as_mut().poll(&mut task_context),
25499                Poll::Pending
25500            ));
25501            let commands = ctx.take_commands().expect("command");
25502            assert_eq!(commands.len(), 1);
25503            assert_eq!(commands[0]["retry_policy"]["max_attempts"], max_attempts);
25504            assert_eq!(
25505                commands[0]["retry_policy"]["backoff_seconds"],
25506                json!([1, 2, 5, 10, 15, 30, 60, 120])
25507            );
25508        }
25509        let default_options = ActivityOptions::new().validate().expect("default options");
25510        let default_policy = current_activity_retry_snapshot(&default_options);
25511        assert_eq!(
25512            default_policy.max_attempts,
25513            RecordedSnapshotValue::Known(Some(1))
25514        );
25515        assert_eq!(
25516            default_policy.backoff_seconds,
25517            RecordedSnapshotValue::Known(Vec::new())
25518        );
25519    }
25520
25521    #[test]
25522    fn published_php_snapshot_rejects_changed_unused_backoff_and_known_fields() {
25523        let fixture: Value = serde_json::from_str(include_str!(
25524            "../tests/fixtures/replay-regressions/published-php-complete-explicit-backoff.json"
25525        ))
25526        .expect("published PHP fixture");
25527        let history: Vec<HistoryEvent> = serde_json::from_value(fixture["history"].clone())
25528            .expect("unchanged published history");
25529        let matching = ActivityOptions::new().task_queue("default").retry_policy(
25530            ActivityRetryPolicy::new(1)
25531                .backoff_intervals([1, 2, 5, 10, 15, 30, 60, 120].map(Duration::from_secs)),
25532        );
25533        let mut changed_tail = matching.clone();
25534        changed_tail.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
25535            [1, 2, 5, 10, 15, 30, 60, 121]
25536                .map(Duration::from_secs)
25537                .to_vec(),
25538        ));
25539        let mut changed_first = matching.clone();
25540        changed_first.retry_policy.as_mut().unwrap().backoff = Some(ActivityBackoff::Explicit(
25541            [2, 2, 5, 10, 15, 30, 60, 120]
25542                .map(Duration::from_secs)
25543                .to_vec(),
25544        ));
25545        let mut changed_attempts = matching.clone();
25546        changed_attempts.retry_policy.as_mut().unwrap().max_attempts = Some(2);
25547        let mut changed_types = matching.clone();
25548        changed_types
25549            .retry_policy
25550            .as_mut()
25551            .unwrap()
25552            .non_retryable_error_types = vec!["ChangedError".into()];
25553        let mut changed_start = matching.clone();
25554        changed_start.start_to_close_timeout = Some(Duration::from_secs(30));
25555        let mut changed_schedule_start = matching.clone();
25556        changed_schedule_start.schedule_to_start_timeout = Some(Duration::from_secs(30));
25557        let mut changed_schedule_close = matching.clone();
25558        changed_schedule_close.schedule_to_close_timeout = Some(Duration::from_secs(30));
25559        let mut changed_heartbeat = matching;
25560        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(30));
25561        let unchanged_defaults = ActivityOptions::new().task_queue("default");
25562        for options in [
25563            changed_tail,
25564            changed_first,
25565            changed_attempts,
25566            changed_types,
25567            changed_start,
25568            changed_schedule_start,
25569            changed_schedule_close,
25570            changed_heartbeat,
25571            unchanged_defaults,
25572        ] {
25573            let ctx = workflow_context(history.clone());
25574            assert_eq!(ctx.get_version("frozen-zero", -7, 0).unwrap(), 0);
25575            assert!(!ctx.patched("frozen-zero").unwrap());
25576            ctx.deprecate_patch("frozen-zero").unwrap();
25577            let mut call =
25578                Box::pin(ctx.activity_with_options("MatrixActivity", options, json!([])));
25579            let mut task_context = TaskContext::from_waker(noop_waker_ref());
25580            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25581                call.as_mut().poll(&mut task_context)
25582            else {
25583                panic!("changed explicit policy must fail replay")
25584            };
25585            assert_eq!(failure.reason, "activity_retry_policy_mismatch");
25586            assert_eq!(failure.sequence, Some(2));
25587            assert!(ctx.take_commands().unwrap().is_empty());
25588        }
25589    }
25590
25591    #[test]
25592    fn invalid_activity_options_return_typed_errors_before_emitting_commands() {
25593        let cases = [
25594            (
25595                ActivityOptions::new().task_queue("  "),
25596                ActivityOptionsErrorKind::EmptyTaskQueue,
25597            ),
25598            (
25599                ActivityOptions::new().retry_policy(ActivityRetryPolicy::default()),
25600                ActivityOptionsErrorKind::EmptyRetryPolicy,
25601            ),
25602            (
25603                ActivityOptions::new().retry_policy(ActivityRetryPolicy::new(0)),
25604                ActivityOptionsErrorKind::InvalidMaxAttempts,
25605            ),
25606            (
25607                ActivityOptions::new().retry_policy(ActivityRetryPolicy {
25608                    max_attempts: None,
25609                    backoff: Some(ActivityBackoff::Explicit(vec![Duration::from_secs(1)])),
25610                    non_retryable_error_types: Vec::new(),
25611                }),
25612                ActivityOptionsErrorKind::BackoffWithoutRetryBudget,
25613            ),
25614            (
25615                ActivityOptions::new().retry_policy(
25616                    ActivityRetryPolicy::new(2).exponential_backoff(
25617                        Duration::from_secs(1),
25618                        0,
25619                        None,
25620                    ),
25621                ),
25622                ActivityOptionsErrorKind::InvalidBackoffCoefficient,
25623            ),
25624            (
25625                ActivityOptions::new()
25626                    .retry_policy(ActivityRetryPolicy::new(2).non_retryable_error_type("  ")),
25627                ActivityOptionsErrorKind::EmptyNonRetryableErrorType,
25628            ),
25629            (
25630                ActivityOptions::new().retry_policy(
25631                    ActivityRetryPolicy::new(10_002).exponential_backoff(
25632                        Duration::from_secs(1),
25633                        1,
25634                        None,
25635                    ),
25636                ),
25637                ActivityOptionsErrorKind::BackoffGenerationTooLarge,
25638            ),
25639            (
25640                ActivityOptions::new().retry_policy(
25641                    ActivityRetryPolicy::new(2)
25642                        .backoff_intervals([Duration::from_secs(i64::MAX as u64 + 1)]),
25643                ),
25644                ActivityOptionsErrorKind::BackoffOverflow,
25645            ),
25646        ];
25647
25648        for (options, expected_kind) in cases {
25649            let ctx = workflow_context(Vec::new());
25650            let mut call = Box::pin(ctx.activity_with_options("work", options, json!([])));
25651            let mut task_context = TaskContext::from_waker(noop_waker_ref());
25652            let Poll::Ready(Err(Error::InvalidActivityOptions(error))) =
25653                call.as_mut().poll(&mut task_context)
25654            else {
25655                panic!("expected typed activity validation error");
25656            };
25657            assert_eq!(error.kind, expected_kind);
25658            assert!(ctx.take_commands().expect("commands").is_empty());
25659        }
25660    }
25661
25662    #[test]
25663    fn activity_options_validate_positive_and_ordered_timeouts() {
25664        let zero_timeout_cases = [
25665            ActivityOptions::new().start_to_close_timeout(Duration::ZERO),
25666            ActivityOptions::new().schedule_to_start_timeout(Duration::ZERO),
25667            ActivityOptions::new().schedule_to_close_timeout(Duration::ZERO),
25668            ActivityOptions::new().heartbeat_timeout(Duration::ZERO),
25669        ];
25670        for options in zero_timeout_cases {
25671            assert_eq!(
25672                options.validate().expect_err("zero timeout").kind,
25673                ActivityOptionsErrorKind::TimeoutNotPositive
25674            );
25675        }
25676
25677        let ordering_cases = [
25678            ActivityOptions::new()
25679                .heartbeat_timeout(Duration::from_secs(11))
25680                .start_to_close_timeout(Duration::from_secs(10)),
25681            ActivityOptions::new()
25682                .start_to_close_timeout(Duration::from_secs(31))
25683                .schedule_to_close_timeout(Duration::from_secs(30)),
25684            ActivityOptions::new()
25685                .schedule_to_start_timeout(Duration::from_secs(31))
25686                .schedule_to_close_timeout(Duration::from_secs(30)),
25687        ];
25688        for options in ordering_cases {
25689            assert_eq!(
25690                options.validate().expect_err("timeout order").kind,
25691                ActivityOptionsErrorKind::TimeoutOrder
25692            );
25693        }
25694
25695        assert_eq!(
25696            ActivityOptions::new()
25697                .start_to_close_timeout(Duration::from_secs(i64::MAX as u64 + 1))
25698                .validate()
25699                .expect_err("protocol integer overflow")
25700                .kind,
25701            ActivityOptionsErrorKind::TimeoutOverflow
25702        );
25703    }
25704
25705    #[test]
25706    fn replayed_activity_retry_history_completes_without_duplicate_schedule() {
25707        let ctx = workflow_context(completed_retry_activity_history());
25708        let mut call =
25709            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
25710        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25711
25712        assert!(matches!(
25713            call.as_mut().poll(&mut task_context),
25714            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
25715        ));
25716        assert!(ctx.take_commands().expect("commands").is_empty());
25717        ctx.ensure_history_consumed().expect("history consumed");
25718    }
25719
25720    #[test]
25721    fn duplicate_non_retryable_types_use_one_command_and_replay_representation() {
25722        let mut options = retry_activity_options();
25723        options
25724            .retry_policy
25725            .as_mut()
25726            .expect("retry policy")
25727            .non_retryable_error_types
25728            .extend([" PermanentError ".to_string(), "PermanentError".to_string()]);
25729
25730        let new_ctx = workflow_context(Vec::new());
25731        let mut new_call =
25732            Box::pin(new_ctx.activity_with_options("flaky", options.clone(), json!([])));
25733        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25734        assert!(matches!(
25735            new_call.as_mut().poll(&mut task_context),
25736            Poll::Pending
25737        ));
25738        let commands = new_ctx.take_commands().expect("commands");
25739        assert_eq!(commands.len(), 1);
25740        assert_eq!(
25741            commands[0]["retry_policy"]["non_retryable_error_types"],
25742            json!(["PermanentError"])
25743        );
25744
25745        let replay_ctx = workflow_context(completed_retry_activity_history());
25746        let mut replay_call =
25747            Box::pin(replay_ctx.activity_with_options("flaky", options, json!([])));
25748        assert!(matches!(
25749            replay_call.as_mut().poll(&mut task_context),
25750            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
25751        ));
25752        assert!(replay_ctx.take_commands().expect("commands").is_empty());
25753        replay_ctx
25754            .ensure_history_consumed()
25755            .expect("history consumed");
25756    }
25757
25758    #[test]
25759    fn replayed_intermediate_retry_remains_pending_across_restarts() {
25760        let history = completed_retry_activity_history()
25761            .into_iter()
25762            .take(3)
25763            .collect::<Vec<_>>();
25764
25765        for _restart in 0..2 {
25766            let ctx = workflow_context(history.clone());
25767            let mut call =
25768                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
25769            let mut task_context = TaskContext::from_waker(noop_waker_ref());
25770            assert!(matches!(
25771                call.as_mut().poll(&mut task_context),
25772                Poll::Pending
25773            ));
25774            assert!(ctx.take_commands().expect("commands").is_empty());
25775        }
25776    }
25777
25778    #[test]
25779    fn replayed_activity_rejects_changed_queue_retry_and_every_timeout_field() {
25780        let mut changed_queue = retry_activity_options();
25781        changed_queue.task_queue = Some("different-queue".to_string());
25782
25783        let mut changed_max_attempts = retry_activity_options();
25784        let retry_policy = changed_max_attempts
25785            .retry_policy
25786            .as_mut()
25787            .expect("retry policy");
25788        retry_policy.max_attempts = Some(4);
25789
25790        let mut changed_backoff = retry_activity_options();
25791        let retry_policy = changed_backoff.retry_policy.as_mut().expect("retry policy");
25792        retry_policy.backoff = Some(ActivityBackoff::Explicit(vec![
25793            Duration::from_secs(3),
25794            Duration::from_secs(4),
25795        ]));
25796
25797        let mut changed_non_retryable_types = retry_activity_options();
25798        let retry_policy = changed_non_retryable_types
25799            .retry_policy
25800            .as_mut()
25801            .expect("retry policy");
25802        retry_policy.non_retryable_error_types = vec!["AnotherPermanentError".to_string()];
25803
25804        let mut changed_start_to_close = retry_activity_options();
25805        changed_start_to_close.start_to_close_timeout = Some(Duration::from_secs(31));
25806        let mut changed_schedule_to_start = retry_activity_options();
25807        changed_schedule_to_start.schedule_to_start_timeout = Some(Duration::from_secs(6));
25808        let mut changed_schedule_to_close = retry_activity_options();
25809        changed_schedule_to_close.schedule_to_close_timeout = Some(Duration::from_secs(91));
25810        let mut changed_heartbeat = retry_activity_options();
25811        changed_heartbeat.heartbeat_timeout = Some(Duration::from_secs(11));
25812
25813        let cases = [
25814            (changed_queue, "activity_task_queue_mismatch"),
25815            (changed_max_attempts, "activity_retry_policy_mismatch"),
25816            (changed_backoff, "activity_retry_policy_mismatch"),
25817            (
25818                changed_non_retryable_types,
25819                "activity_retry_policy_mismatch",
25820            ),
25821            (changed_start_to_close, "activity_retry_policy_mismatch"),
25822            (changed_schedule_to_start, "activity_retry_policy_mismatch"),
25823            (changed_schedule_to_close, "activity_retry_policy_mismatch"),
25824            (changed_heartbeat, "activity_retry_policy_mismatch"),
25825        ];
25826
25827        for (options, expected_reason) in cases {
25828            let ctx = workflow_context(completed_retry_activity_history());
25829            let mut call = Box::pin(ctx.activity_with_options("flaky", options, json!([])));
25830            let mut task_context = TaskContext::from_waker(noop_waker_ref());
25831            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25832                call.as_mut().poll(&mut task_context)
25833            else {
25834                panic!("changed activity options must fail replay");
25835            };
25836            assert_eq!(failure.reason, expected_reason);
25837            assert_eq!(failure.sequence, Some(1));
25838            assert!(ctx.take_commands().expect("commands").is_empty());
25839        }
25840    }
25841
25842    #[test]
25843    fn replayed_activity_rejects_changed_execution_mode_and_snapshot_version() {
25844        let cases = [
25845            (
25846                "execution_mode",
25847                json!("local"),
25848                "activity_execution_mode_mismatch",
25849            ),
25850            (
25851                "snapshot_version",
25852                json!(2),
25853                "activity_retry_policy_mismatch",
25854            ),
25855        ];
25856
25857        for (field, value, expected_reason) in cases {
25858            let mut history = completed_retry_activity_history();
25859            let activity = history[0].payload["activity"]
25860                .as_object_mut()
25861                .expect("activity snapshot");
25862            if field == "execution_mode" {
25863                activity.insert(field.to_string(), value);
25864            } else {
25865                activity["retry_policy"]
25866                    .as_object_mut()
25867                    .expect("retry snapshot")
25868                    .insert(field.to_string(), value);
25869            }
25870
25871            let ctx = workflow_context(history);
25872            let mut call =
25873                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
25874            let mut task_context = TaskContext::from_waker(noop_waker_ref());
25875            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25876                call.as_mut().poll(&mut task_context)
25877            else {
25878                panic!("changed {field} must fail replay");
25879            };
25880            assert_eq!(failure.reason, expected_reason);
25881            assert_eq!(failure.sequence, Some(1));
25882            assert!(ctx.take_commands().expect("commands").is_empty());
25883        }
25884    }
25885
25886    #[test]
25887    fn remote_activity_rejects_local_history_markers_without_option_snapshot() {
25888        for (nested, field, value, terminal_only) in [
25889            (false, "execution_mode", json!("local"), false),
25890            (false, "local_activity", json!(true), false),
25891            (true, "local_activity", json!(true), false),
25892            (false, "local_activity", json!(true), true),
25893        ] {
25894            let mut history = completed_retry_activity_history();
25895            history[0]
25896                .payload
25897                .as_object_mut()
25898                .unwrap()
25899                .remove("activity");
25900            let event = if terminal_only {
25901                history.last_mut().unwrap()
25902            } else {
25903                &mut history[0]
25904            };
25905            if nested {
25906                event.payload["activity"] = json!({(field): value});
25907            } else {
25908                event.payload[field] = value;
25909            }
25910            let ctx = workflow_context(history);
25911            let mut call =
25912                Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
25913            let mut task_context = TaskContext::from_waker(noop_waker_ref());
25914            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
25915                call.as_mut().poll(&mut task_context)
25916            else {
25917                panic!("local history must not replay as a remote activity: {nested}/{field}/{terminal_only}");
25918            };
25919            assert_eq!(failure.reason, "activity_execution_mode_mismatch");
25920            assert_eq!(failure.sequence, Some(1));
25921            assert!(ctx.take_commands().expect("commands").is_empty());
25922        }
25923    }
25924
25925    #[test]
25926    fn activity_history_rejects_conflicting_local_execution_markers() {
25927        let mut history = completed_retry_activity_history();
25928        history.last_mut().unwrap().payload["local_activity"] = json!(true);
25929        let error = WorkflowState::new(history, "queue".into(), DEFAULT_CODEC.into(), None)
25930            .expect_err("remote schedule cannot become a local completion");
25931        assert!(
25932            matches!(error, Error::NonDeterministicReplay(ReplayFailure { reason, sequence: Some(1), .. })
25933            if reason == "activity_execution_mode_conflict")
25934        );
25935    }
25936
25937    #[test]
25938    fn replayed_legacy_activity_treats_missing_option_snapshot_as_unknown() {
25939        let mut history = completed_retry_activity_history();
25940        let activity = history[0].payload["activity"]
25941            .as_object_mut()
25942            .expect("activity snapshot");
25943        activity.remove("execution_mode");
25944        activity.remove("retry_policy");
25945
25946        let mut current = retry_activity_options();
25947        current.start_to_close_timeout = Some(Duration::from_secs(45));
25948        current.schedule_to_start_timeout = Some(Duration::from_secs(8));
25949        current.schedule_to_close_timeout = Some(Duration::from_secs(120));
25950        current.heartbeat_timeout = Some(Duration::from_secs(12));
25951
25952        let ctx = workflow_context(history);
25953        let mut call = Box::pin(ctx.activity_with_options("flaky", current, json!([])));
25954        let mut task_context = TaskContext::from_waker(noop_waker_ref());
25955        assert!(matches!(
25956            call.as_mut().poll(&mut task_context),
25957            Poll::Ready(Ok(result)) if result == json!({"status": "recovered"})
25958        ));
25959        assert!(ctx.take_commands().expect("commands").is_empty());
25960        ctx.ensure_history_consumed().expect("history consumed");
25961    }
25962
25963    #[test]
25964    fn terminal_activity_failed_after_start_returns_typed_failure() {
25965        let history = vec![
25966            history_event(
25967                "ActivityScheduled",
25968                json!({
25969                    "sequence": 1,
25970                    "activity_type": "flaky",
25971                    "activity_execution_id": "act-terminal",
25972                    "activity": {
25973                        "id": "act-terminal",
25974                        "sequence": 1,
25975                        "type": "flaky",
25976                        "queue": "critical-activities",
25977                        "retry_policy": {
25978                            "snapshot_version": 1,
25979                            "max_attempts": 3,
25980                            "backoff_seconds": [2, 4],
25981                            "non_retryable_error_types": ["PermanentError"]
25982                        }
25983                    }
25984                }),
25985            ),
25986            history_event(
25987                "ActivityStarted",
25988                json!({
25989                    "sequence": 1,
25990                    "activity_type": "flaky",
25991                    "activity_execution_id": "act-terminal",
25992                    "activity_attempt_id": "attempt-1",
25993                    "attempt_number": 1
25994                }),
25995            ),
25996            history_event(
25997                "ActivityFailed",
25998                json!({
25999                    "sequence": 1,
26000                    "activity_type": "flaky",
26001                    "activity_execution_id": "act-terminal",
26002                    "activity_attempt_id": "attempt-1",
26003                    "attempt_number": 1,
26004                    "failure_id": "failure-terminal",
26005                    "failure_category": "activity",
26006                    "exception_type": "PermanentError",
26007                    "message": "cannot retry",
26008                    "non_retryable": true
26009                }),
26010            ),
26011        ];
26012        let ctx = workflow_context(history);
26013        let mut call =
26014            Box::pin(ctx.activity_with_options("flaky", retry_activity_options(), json!([])));
26015        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26016
26017        let Poll::Ready(Err(Error::ActivityFailed(failure))) =
26018            call.as_mut().poll(&mut task_context)
26019        else {
26020            panic!("terminal ActivityFailed must settle the activity future");
26021        };
26022        assert_eq!(failure.kind, ActivityFailureKind::Failed);
26023        assert_eq!(
26024            failure.activity_execution_id.as_deref(),
26025            Some("act-terminal")
26026        );
26027        assert_eq!(failure.exception_type.as_deref(), Some("PermanentError"));
26028        assert!(failure.non_retryable);
26029        assert!(ctx.take_commands().expect("commands").is_empty());
26030        ctx.ensure_history_consumed().expect("history consumed");
26031    }
26032
26033    #[test]
26034    fn activity_terminal_events_return_machine_readable_failures() {
26035        let cases = [
26036            (
26037                "ActivityFailed",
26038                json!({
26039                    "sequence": 1,
26040                    "activity_type": "charge-card",
26041                    "activity_execution_id": "act-1",
26042                    "activity_attempt_id": "attempt-2",
26043                    "attempt_number": 2,
26044                    "failure_id": "failure-1",
26045                    "failure_category": "activity",
26046                    "exception_type": "PaymentDeclined",
26047                    "exception_class": "payments.PaymentDeclined",
26048                    "message": "card declined",
26049                    "non_retryable": true
26050                }),
26051                ActivityFailureKind::Failed,
26052                "activity",
26053            ),
26054            (
26055                "ActivityCancelled",
26056                json!({
26057                    "sequence": 1,
26058                    "activity_type": "charge-card",
26059                    "activity_execution_id": "act-1",
26060                    "activity_attempt_id": "attempt-1"
26061                }),
26062                ActivityFailureKind::Cancelled,
26063                "cancelled",
26064            ),
26065        ];
26066
26067        for (event_type, payload, expected_kind, expected_reason) in cases {
26068            let ctx = workflow_context(vec![history_event(event_type, payload)]);
26069            let mut call = Box::pin(ctx.activity("charge-card", json!([])));
26070            let mut task_context = TaskContext::from_waker(noop_waker_ref());
26071            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
26072                call.as_mut().poll(&mut task_context)
26073            else {
26074                panic!("expected terminal activity failure");
26075            };
26076            assert_eq!(failure.kind, expected_kind);
26077            assert_eq!(failure.reason, expected_reason);
26078            assert_eq!(failure.activity_execution_id.as_deref(), Some("act-1"));
26079            assert_eq!(failure.activity_type.as_deref(), Some("charge-card"));
26080        }
26081    }
26082
26083    #[test]
26084    fn every_activity_timeout_class_is_typed() {
26085        for timeout_kind in [
26086            "start_to_close",
26087            "schedule_to_start",
26088            "schedule_to_close",
26089            "heartbeat",
26090        ] {
26091            let ctx = workflow_context(vec![history_event(
26092                "ActivityTimedOut",
26093                json!({
26094                    "sequence": 1,
26095                    "activity_type": "slow",
26096                    "activity_execution_id": "act-timeout",
26097                    "activity_attempt_id": "attempt-timeout",
26098                    "failure_category": "timeout",
26099                    "timeout_kind": timeout_kind,
26100                    "message": "deadline expired"
26101                }),
26102            )]);
26103            let mut call = Box::pin(ctx.activity("slow", json!([])));
26104            let mut task_context = TaskContext::from_waker(noop_waker_ref());
26105            let Poll::Ready(Err(Error::ActivityFailed(failure))) =
26106                call.as_mut().poll(&mut task_context)
26107            else {
26108                panic!("expected timeout failure");
26109            };
26110            assert_eq!(failure.kind, ActivityFailureKind::TimedOut);
26111            assert_eq!(failure.reason, timeout_kind);
26112            assert_eq!(failure.timeout_kind.as_deref(), Some(timeout_kind));
26113            assert_eq!(failure.failure_category.as_deref(), Some("timeout"));
26114        }
26115    }
26116
26117    #[test]
26118    fn workflow_sleep_emits_one_durable_timer_and_rounds_up() {
26119        let ctx = workflow_context(Vec::new());
26120        let mut sleep = Box::pin(ctx.sleep(Duration::from_millis(1_001)));
26121        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26122
26123        assert!(matches!(
26124            sleep.as_mut().poll(&mut task_context),
26125            Poll::Pending
26126        ));
26127        assert!(matches!(
26128            sleep.as_mut().poll(&mut task_context),
26129            Poll::Pending
26130        ));
26131
26132        let commands = ctx.take_commands().expect("timer command");
26133        assert_eq!(
26134            commands,
26135            vec![json!({
26136                "type": "start_timer",
26137                "delay_seconds": 2,
26138            })]
26139        );
26140    }
26141
26142    #[test]
26143    fn workflow_sleep_replays_matching_schedule_and_fire_without_a_command() {
26144        let history = vec![
26145            history_event(
26146                "TimerScheduled",
26147                json!({
26148                    "sequence": 1,
26149                    "timer_id": "timer-1",
26150                    "delay_seconds": 5,
26151                    "fire_at": "2026-07-11T12:00:05Z",
26152                }),
26153            ),
26154            history_event(
26155                "TimerFired",
26156                json!({
26157                    "sequence": 1,
26158                    "timer_id": "timer-1",
26159                    "delay_seconds": 5,
26160                    "fire_at": "2026-07-11T12:00:05Z",
26161                    "fired_at": "2026-07-11T12:00:05Z",
26162                }),
26163            ),
26164        ];
26165
26166        for _restart in 0..2 {
26167            let ctx = workflow_context(history.clone());
26168            let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(5)));
26169            let mut task_context = TaskContext::from_waker(noop_waker_ref());
26170            assert!(matches!(
26171                sleep.as_mut().poll(&mut task_context),
26172                Poll::Ready(Ok(()))
26173            ));
26174            assert!(ctx.take_commands().expect("commands").is_empty());
26175            ctx.ensure_history_consumed().expect("history consumed");
26176        }
26177    }
26178
26179    #[test]
26180    fn workflow_sleep_rejects_changed_delay_during_replay() {
26181        let ctx = workflow_context(vec![
26182            history_event(
26183                "TimerScheduled",
26184                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26185            ),
26186            history_event(
26187                "TimerFired",
26188                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
26189            ),
26190        ]);
26191        let mut sleep = Box::pin(ctx.sleep(Duration::from_secs(500)));
26192        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26193
26194        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
26195            sleep.as_mut().poll(&mut task_context)
26196        else {
26197            panic!("changed timer delay must be rejected");
26198        };
26199        assert_eq!(failure.reason, "timer_delay_mismatch");
26200        assert_eq!(failure.sequence, Some(1));
26201    }
26202
26203    #[test]
26204    fn workflow_condition_wait_emits_published_identity_and_timeout_contract() {
26205        let ctx = workflow_context(Vec::new());
26206        let mut wait = Box::pin(
26207            ctx.wait_condition(
26208                ConditionWaitOptions::new("approval.ready", "sha256:approval-v1")
26209                    .timeout(Duration::from_millis(60_001)),
26210                || Ok(false),
26211            ),
26212        );
26213        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26214
26215        assert!(matches!(
26216            wait.as_mut().poll(&mut task_context),
26217            Poll::Pending
26218        ));
26219        assert!(matches!(
26220            wait.as_mut().poll(&mut task_context),
26221            Poll::Pending
26222        ));
26223        assert_eq!(
26224            ctx.take_commands().expect("condition command"),
26225            vec![json!({
26226                "type": "open_condition_wait",
26227                "condition_wait_occurrence_id": "rust:condition-wait:0",
26228                "condition_key": "approval.ready",
26229                "condition_definition_fingerprint": "sha256:approval-v1",
26230                "timeout_seconds": 61,
26231            })]
26232        );
26233    }
26234
26235    #[test]
26236    fn workflow_condition_wait_returns_explicit_immediate_results_without_commands() {
26237        let ctx = workflow_context(Vec::new());
26238        let mut satisfied = Box::pin(wait_condition!(ctx, "already-ready", || Ok(true)));
26239        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26240        assert!(matches!(
26241            satisfied.as_mut().poll(&mut task_context),
26242            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
26243        ));
26244
26245        let mut timed_out = Box::pin(wait_condition!(
26246            ctx,
26247            "no-wait",
26248            timeout: Duration::ZERO,
26249            || Ok(false),
26250        ));
26251        assert!(matches!(
26252            timed_out.as_mut().poll(&mut task_context),
26253            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
26254        ));
26255        assert!(ctx.take_commands().expect("commands").is_empty());
26256    }
26257
26258    #[test]
26259    fn signal_and_update_history_reevaluate_open_conditions_after_restart() {
26260        let signal_history = vec![
26261            history_event(
26262                "ConditionWaitOpened",
26263                json!({
26264                    "sequence": 4,
26265                    "condition_wait_id": "condition:4",
26266                    "condition_wait_occurrence_id": "rust:condition-wait:0",
26267                    "condition_key": "approval",
26268                    "condition_definition_fingerprint": "sha256:approval-v1",
26269                    "timeout_seconds": 30,
26270                }),
26271            ),
26272            history_event(
26273                "SignalReceived",
26274                json!({
26275                    "workflow_sequence": 4,
26276                    "signal_name": "approve",
26277                    "arguments": fixture_envelope(json!(["Ada"])),
26278                }),
26279            ),
26280        ];
26281        for _worker_before_or_after_restart in 0..2 {
26282            let ctx = workflow_context(signal_history.clone());
26283            let predicate_ctx = ctx.clone();
26284            let mut wait = Box::pin(
26285                ctx.wait_condition(
26286                    ConditionWaitOptions::new("approval", "sha256:approval-v1")
26287                        .timeout(Duration::from_secs(30)),
26288                    move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
26289                ),
26290            );
26291            let mut task_context = TaskContext::from_waker(noop_waker_ref());
26292            assert!(matches!(
26293                wait.as_mut().poll(&mut task_context),
26294                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
26295            ));
26296            assert!(ctx.take_commands().expect("commands").is_empty());
26297            ctx.ensure_history_consumed().expect("condition consumed");
26298        }
26299
26300        let update_history = vec![
26301            history_event(
26302                "ConditionWaitOpened",
26303                json!({
26304                    "sequence": 7,
26305                    "condition_wait_id": "condition:7",
26306                    "condition_wait_occurrence_id": "rust:condition-wait:0",
26307                    "condition_key": "update-approval",
26308                    "condition_definition_fingerprint": "sha256:update-approval-v1",
26309                }),
26310            ),
26311            history_event(
26312                "UpdateApplied",
26313                json!({
26314                    "sequence": 7,
26315                    "update_id": "update-1",
26316                    "update_name": "approve",
26317                    "arguments": fixture_envelope(json!([true])),
26318                }),
26319            ),
26320        ];
26321        let ctx = workflow_context(update_history);
26322        let predicate_ctx = ctx.clone();
26323        let mut wait = Box::pin(ctx.wait_condition(
26324            ConditionWaitOptions::new("update-approval", "sha256:update-approval-v1"),
26325            move || {
26326                Ok(predicate_ctx
26327                    .updates("approve")?
26328                    .first()
26329                    .and_then(|arguments| arguments.first())
26330                    .and_then(Value::as_bool)
26331                    == Some(true))
26332            },
26333        ));
26334        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26335        assert!(matches!(
26336            wait.as_mut().poll(&mut task_context),
26337            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
26338        ));
26339        assert!(ctx.take_commands().expect("commands").is_empty());
26340        ctx.ensure_history_consumed().expect("condition consumed");
26341    }
26342
26343    #[test]
26344    fn condition_wait_preserves_open_satisfied_and_timed_out_replay_states() {
26345        let open_history = vec![
26346            history_event(
26347                "ConditionWaitOpened",
26348                json!({
26349                    "sequence": 3,
26350                    "condition_wait_id": "condition:3",
26351                    "condition_wait_occurrence_id": "rust:condition-wait:0",
26352                    "condition_key": "two-votes",
26353                    "condition_definition_fingerprint": "sha256:two-votes-v1",
26354                    "timeout_seconds": 120,
26355                }),
26356            ),
26357            history_event(
26358                "SignalReceived",
26359                json!({
26360                    "workflow_sequence": 3,
26361                    "signal_name": "vote",
26362                    "arguments": fixture_envelope(json!(["first"])),
26363                }),
26364            ),
26365        ];
26366        for _worker_before_or_after_restart in 0..2 {
26367            let ctx = workflow_context(open_history.clone());
26368            let predicate_ctx = ctx.clone();
26369            let mut wait = Box::pin(
26370                ctx.wait_condition(
26371                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
26372                        .timeout(Duration::from_secs(120)),
26373                    move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
26374                ),
26375            );
26376            let mut task_context = TaskContext::from_waker(noop_waker_ref());
26377            assert!(matches!(
26378                wait.as_mut().poll(&mut task_context),
26379                Poll::Pending
26380            ));
26381            assert_eq!(
26382                ctx.take_commands().expect("reopened condition"),
26383                vec![json!({
26384                    "type": "open_condition_wait",
26385                    "condition_wait_occurrence_id": "rust:condition-wait:0",
26386                    "condition_key": "two-votes",
26387                    "condition_definition_fingerprint": "sha256:two-votes-v1",
26388                    "timeout_seconds": 120,
26389                })]
26390            );
26391        }
26392
26393        let satisfied_ctx = workflow_context(vec![
26394            history_event(
26395                "ConditionWaitOpened",
26396                json!({
26397                    "sequence": 5,
26398                    "condition_wait_id": "condition:5",
26399                    "condition_wait_occurrence_id": "rust:condition-wait:0",
26400                    "condition_key": "approval",
26401                    "condition_definition_fingerprint": "sha256:approval-v1",
26402                }),
26403            ),
26404            history_event(
26405                "ConditionWaitSatisfied",
26406                json!({
26407                    "sequence": 5,
26408                    "condition_wait_id": "condition:5",
26409                    "condition_wait_occurrence_id": "rust:condition-wait:0",
26410                    "condition_key": "approval",
26411                    "condition_definition_fingerprint": "sha256:approval-v1",
26412                }),
26413            ),
26414        ]);
26415        let mut satisfied = Box::pin(satisfied_ctx.wait_condition(
26416            ConditionWaitOptions::new("approval", "sha256:approval-v1"),
26417            || Ok(false),
26418        ));
26419        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26420        assert!(matches!(
26421            satisfied.as_mut().poll(&mut task_context),
26422            Poll::Ready(Ok(ConditionWaitResult::Satisfied))
26423        ));
26424
26425        let timed_out_ctx = workflow_context(vec![
26426            history_event(
26427                "ConditionWaitOpened",
26428                json!({
26429                    "sequence": 8,
26430                    "condition_wait_id": "condition:8",
26431                    "condition_wait_occurrence_id": "rust:condition-wait:0",
26432                    "condition_key": "approval-timeout",
26433                    "condition_definition_fingerprint": "sha256:approval-timeout-v1",
26434                    "timeout_seconds": 5,
26435                }),
26436            ),
26437            history_event(
26438                "TimerScheduled",
26439                json!({
26440                    "sequence": 9,
26441                    "timer_id": "condition-timer:9",
26442                    "timer_kind": "condition_timeout",
26443                    "condition_wait_id": "condition:8",
26444                    "delay_seconds": 5,
26445                }),
26446            ),
26447            history_event(
26448                "TimerFired",
26449                json!({
26450                    "sequence": 9,
26451                    "timer_id": "condition-timer:9",
26452                    "timer_kind": "condition_timeout",
26453                    "condition_wait_id": "condition:8",
26454                    "delay_seconds": 5,
26455                }),
26456            ),
26457        ]);
26458        let mut timed_out = Box::pin(
26459            timed_out_ctx.wait_condition(
26460                ConditionWaitOptions::new("approval-timeout", "sha256:approval-timeout-v1")
26461                    .timeout(Duration::from_secs(5)),
26462                || Ok(true),
26463            ),
26464        );
26465        assert!(matches!(
26466            timed_out.as_mut().poll(&mut task_context),
26467            Poll::Ready(Ok(ConditionWaitResult::TimedOut))
26468        ));
26469    }
26470
26471    #[test]
26472    fn satisfied_reopened_selection_condition_waits_for_its_canonical_winner() {
26473        let ctx = workflow_context(reopened_selection_condition_history());
26474        {
26475            let state = ctx.state.lock().unwrap();
26476            assert!(matches!(
26477                selection_member_recorded_command(&state, 2),
26478                Some(RecordedCommand::ConditionWait {
26479                    sequence: 3,
26480                    result: None,
26481                    ..
26482                })
26483            ));
26484        }
26485        let mut selected = Box::pin(ctx.select_keyed(vec![
26486            ("timer", ParallelOperation::timer(Duration::from_secs(300))),
26487            (
26488                "votes",
26489                ParallelOperation::condition(
26490                    ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
26491                    || Ok(true),
26492                ),
26493            ),
26494        ]));
26495        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26496        assert!(selected.as_mut().poll(&mut task_context).is_pending());
26497        assert!(
26498            ctx.take_commands().unwrap().is_empty(),
26499            "true predicate must not reopen the recorded wait"
26500        );
26501        ctx.ensure_history_consumed()
26502            .expect("physical reopens are consumed while canonical selection is pending");
26503    }
26504
26505    #[test]
26506    fn reopened_selection_condition_replays_its_latest_physical_winner() {
26507        for (terminal_type, acknowledge_timeout) in [
26508            ("ConditionWaitSatisfied", false),
26509            ("ConditionWaitTimedOut", false),
26510            ("TimerFired", false),
26511            ("TimerFired", true),
26512        ] {
26513            let mut history = reopened_selection_condition_history();
26514            let original_identity = history[1].payload["condition_wait_id"].clone();
26515            let uses_timer = terminal_type == "TimerFired";
26516            let mut resolution_payload = history[3].payload.clone();
26517            if uses_timer {
26518                for event in &mut history[1..] {
26519                    event.payload["timeout_seconds"] = json!(3);
26520                }
26521                resolution_payload = history[3].payload.clone();
26522                resolution_payload["timer_kind"] = json!("condition_timeout");
26523                resolution_payload["timer_id"] = json!("condition-timeout-3");
26524                resolution_payload["delay_seconds"] = json!(3);
26525                history.push(history_event("TimerScheduled", resolution_payload.clone()));
26526            }
26527            let mut resolution = history_event(terminal_type, resolution_payload.clone());
26528            resolution
26529                .raw
26530                .insert("id".into(), json!("latest-condition-resolution"));
26531            history.push(resolution);
26532            history.push(history_event(
26533                "SelectionResolved",
26534                json!({
26535                    "selection_group_id": "select-calls:1:2",
26536                    "selection_group_base_sequence": 1,
26537                    "selection_group_size": 2,
26538                    "member_key": "votes",
26539                    "member_index": 1,
26540                    "member_base_sequence": 2,
26541                    "member_size": 1,
26542                    "operation_kind": "condition",
26543                    "operation_identity": original_identity,
26544                    "outcome": "completed",
26545                    "resolution_event_id": "latest-condition-resolution",
26546                    "resolution_event_type": terminal_type,
26547                }),
26548            ));
26549            if acknowledge_timeout {
26550                history.push(history_event("ConditionWaitTimedOut", resolution_payload));
26551            }
26552            let ctx = workflow_context(history);
26553            let mut selected = Box::pin(ctx.select_keyed(vec![
26554                ("timer", ParallelOperation::timer(Duration::from_secs(300))),
26555                (
26556                    "votes",
26557                    ParallelOperation::condition(
26558                        if uses_timer {
26559                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
26560                                .timeout(Duration::from_secs(3))
26561                        } else {
26562                            ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
26563                        },
26564                        || Ok(true),
26565                    ),
26566                ),
26567            ]));
26568            let mut task_context = TaskContext::from_waker(noop_waker_ref());
26569            match selected.as_mut().poll(&mut task_context) {
26570                Poll::Ready(Ok(result)) => {
26571                    assert_eq!(result.key, SelectionKey::Name("votes".into()));
26572                    let expected = if terminal_type == "ConditionWaitSatisfied" {
26573                        ConditionWaitResult::Satisfied
26574                    } else {
26575                        ConditionWaitResult::TimedOut
26576                    };
26577                    assert_eq!(result.value, Some(ParallelResult::Condition(expected)));
26578                }
26579                other => panic!("latest physical winner must replay: {other:?}"),
26580            }
26581            assert!(ctx.take_commands().unwrap().is_empty());
26582            ctx.ensure_history_consumed()
26583                .expect("winner history consumed");
26584        }
26585    }
26586
26587    fn reopened_selection_condition_history() -> Vec<HistoryEvent> {
26588        let fixture: Value = serde_json::from_str(include_str!(
26589            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
26590        ))
26591        .expect("grouped condition fixture");
26592        fixture["history"]
26593            .as_array()
26594            .unwrap()
26595            .iter()
26596            .map(|event| {
26597                let mut payload = event["payload"].clone();
26598                let index = payload["parallel_group_index"].as_u64().unwrap();
26599                payload["parallel_group_id"] = json!("select-calls:1:2");
26600                payload["parallel_group_mode"] = json!("select");
26601                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
26602                payload["selection_member_index"] = json!(index);
26603                payload["selection_member_base_sequence"] = json!(index + 1);
26604                payload["selection_member_size"] = json!(1);
26605                payload["selection_member_kind"] =
26606                    json!(if index == 0 { "timer" } else { "condition" });
26607                history_event(event["event_type"].as_str().unwrap(), payload)
26608            })
26609            .collect()
26610    }
26611
26612    fn grouped_wait(sequence: u64, base: u64, size: usize, index: usize) -> RecordedCommand {
26613        RecordedCommand::ConditionWait {
26614            sequence,
26615            occurrence_id: format!("rust:condition-wait:{base}-{index}"),
26616            condition_key: Some(format!("member-{index}")),
26617            predicate_identity: format!("sha256:member-{index}"),
26618            timeout_seconds: Some(300),
26619            result: None,
26620            parallel_group_path: Some(vec![parallel_group_entry(base, size, index, "condition")]),
26621        }
26622    }
26623
26624    fn order(commands: Vec<RecordedCommand>) -> Vec<u64> {
26625        group_condition_reopens_by_member(commands)
26626            .iter()
26627            .map(RecordedCommand::sequence)
26628            .collect()
26629    }
26630
26631    // #191: reorder only within a contiguous run of one group's condition
26632    // waits, member by member, keeping each member's own order.
26633    #[test]
26634    fn grouped_reopens_are_ordered_by_member_only_within_one_contiguous_group_run() {
26635        // Three members with unequal reopen counts: a1 b1 c1 a2 c2 a3.
26636        assert_eq!(
26637            order(vec![
26638                grouped_wait(1, 1, 3, 0),
26639                grouped_wait(2, 1, 3, 1),
26640                grouped_wait(3, 1, 3, 2),
26641                grouped_wait(4, 1, 3, 0),
26642                grouped_wait(5, 1, 3, 2),
26643                grouped_wait(6, 1, 3, 0),
26644            ]),
26645            vec![1, 4, 6, 2, 3, 5]
26646        );
26647
26648        // Another command between members ends the run: nothing moves across it.
26649        assert_eq!(
26650            order(vec![
26651                grouped_wait(1, 1, 2, 0),
26652                RecordedCommand::Timer {
26653                    sequence: 2,
26654                    delay_seconds: 5,
26655                    fired: false,
26656                    parallel_group_path: None,
26657                },
26658                grouped_wait(3, 1, 2, 1),
26659                grouped_wait(4, 1, 2, 0),
26660            ]),
26661            vec![1, 2, 3, 4]
26662        );
26663
26664        // A timer of the same group between condition members keeps its place
26665        // while each condition member's reopens join it (#194):
26666        // a1 t b1 a2 b2 -> a1 a2 t b1 b2.
26667        assert_eq!(
26668            order(vec![
26669                grouped_wait(1, 1, 3, 0),
26670                RecordedCommand::Timer {
26671                    sequence: 2,
26672                    delay_seconds: 5,
26673                    fired: false,
26674                    parallel_group_path: Some(vec![parallel_group_entry(1, 3, 1, "condition")]),
26675                },
26676                grouped_wait(3, 1, 3, 2),
26677                grouped_wait(4, 1, 3, 0),
26678                grouped_wait(5, 1, 3, 2),
26679            ]),
26680            vec![1, 4, 2, 3, 5]
26681        );
26682
26683        // Two different groups interleaved never merge into one run.
26684        assert_eq!(
26685            order(vec![
26686                grouped_wait(1, 1, 2, 0),
26687                grouped_wait(10, 10, 2, 0),
26688                grouped_wait(2, 1, 2, 1),
26689                grouped_wait(11, 10, 2, 1),
26690            ]),
26691            vec![1, 10, 2, 11]
26692        );
26693
26694        // Ungrouped waits and an already member-ordered run are unchanged.
26695        let ungrouped = |sequence| RecordedCommand::ConditionWait {
26696            sequence,
26697            occurrence_id: "rust:condition-wait:0".into(),
26698            condition_key: Some("approval".into()),
26699            predicate_identity: "sha256:approval".into(),
26700            timeout_seconds: Some(30),
26701            result: None,
26702            parallel_group_path: None,
26703        };
26704        assert_eq!(order(vec![ungrouped(1), ungrouped(2)]), vec![1, 2]);
26705        assert_eq!(
26706            order(vec![
26707                grouped_wait(1, 1, 2, 0),
26708                grouped_wait(3, 1, 2, 0),
26709                grouped_wait(2, 1, 2, 1),
26710            ]),
26711            vec![1, 3, 2]
26712        );
26713    }
26714
26715    // General's #193 review: after a one-sided grouped reopen, recorded commands
26716    // are consumed out of sequence order, so a new group must start after the
26717    // highest recorded sequence, not after the last consumed command.
26718    #[test]
26719    fn a_group_after_a_one_sided_grouped_reopen_starts_after_the_highest_sequence() {
26720        let signals = vec![
26721            approval_signal("vote", "v1", "2026-11-04T03:55:13.000000+00:00"),
26722            approval_signal("vote", "v2", "2026-11-04T03:55:30.000000+00:00"),
26723            approval_signal("approve", "a1", "2026-11-04T03:55:30.100000+00:00"),
26724        ];
26725        for select in [false, true] {
26726            let ctx = workflow_context(one_sided_grouped_reopen_history(signals.clone()));
26727            let workflow = {
26728                let ctx = ctx.clone();
26729                async move {
26730                    let votes = ctx.clone();
26731                    let approvals = ctx.clone();
26732                    ctx.parallel(vec![
26733                        ParallelOperation::condition(
26734                            ConditionWaitOptions::new("votes", "sha256:votes-v1")
26735                                .timeout(Duration::from_secs(300)),
26736                            move || Ok(votes.signals("vote")?.len() >= 2),
26737                        ),
26738                        ParallelOperation::condition(
26739                            ConditionWaitOptions::new("approvals", "sha256:approvals-v1")
26740                                .timeout(Duration::from_secs(300)),
26741                            move || Ok(!approvals.signals("approve")?.is_empty()),
26742                        ),
26743                    ])
26744                    .await?;
26745                    if select {
26746                        ctx.select_keyed(vec![
26747                            ("a", ParallelOperation::timer(Duration::from_secs(5))),
26748                            ("b", ParallelOperation::timer(Duration::from_secs(6))),
26749                        ])
26750                        .await
26751                        .map(|_| ())
26752                    } else {
26753                        ctx.parallel(vec![
26754                            ParallelOperation::timer(Duration::from_secs(5)),
26755                            ParallelOperation::timer(Duration::from_secs(6)),
26756                        ])
26757                        .await
26758                        .map(|_| ())
26759                    }
26760                }
26761            };
26762            let mut workflow = Box::pin(workflow);
26763            let mut task_context = TaskContext::from_waker(noop_waker_ref());
26764            assert!(matches!(
26765                workflow.as_mut().poll(&mut task_context),
26766                Poll::Pending
26767            ));
26768            let commands = ctx.take_commands().expect("commands");
26769            assert_eq!(commands.len(), 2, "select {select}: {commands:?}");
26770            for command in &commands {
26771                assert_eq!(command["type"], json!("start_timer"));
26772                assert_eq!(
26773                    command["parallel_group_base_sequence"],
26774                    json!(4),
26775                    "select {select}: {command}"
26776                );
26777            }
26778        }
26779    }
26780
26781    // #194: a timer member between two condition members. The Server reopens
26782    // both condition members (votes 1, timer 2, approvals 3, votes 4,
26783    // approvals 5); each member must still consume its own reopen.
26784    #[test]
26785    fn a_timer_between_grouped_condition_members_does_not_strand_their_reopens() {
26786        let group = |index: u64| {
26787            json!({
26788                "parallel_group_id": "parallel-calls:1:3",
26789                "parallel_group_kind": "mixed",
26790                "parallel_group_base_sequence": 1,
26791                "parallel_group_size": 3,
26792                "parallel_group_index": index,
26793            })
26794        };
26795        let member = |event_type: &str, sequence: u64, index: u64, key: &str, at: &str| {
26796            let mut payload = group(index);
26797            payload["sequence"] = json!(sequence);
26798            payload["condition_wait_id"] = json!(format!("condition:{sequence}"));
26799            payload["condition_wait_occurrence_id"] = json!(format!(
26800                "rust:condition-wait:{}",
26801                if index == 0 { 0 } else { 1 }
26802            ));
26803            payload["condition_key"] = json!(key);
26804            payload["condition_definition_fingerprint"] = json!(format!("sha256:{key}-v1"));
26805            payload["timeout_seconds"] = json!(300);
26806            timed_event(event_type, at, payload)
26807        };
26808        let timer = |event_type: &str, at: &str| {
26809            let mut payload = group(1);
26810            payload["sequence"] = json!(2);
26811            payload["timer_id"] = json!("timer-2");
26812            payload["delay_seconds"] = json!(5);
26813            timed_event(event_type, at, payload)
26814        };
26815        let history = vec![
26816            member(
26817                "ConditionWaitOpened",
26818                1,
26819                0,
26820                "votes",
26821                "2026-11-04T03:55:10.900000+00:00",
26822            ),
26823            timer("TimerScheduled", "2026-11-04T03:55:10.901000+00:00"),
26824            member(
26825                "ConditionWaitOpened",
26826                3,
26827                2,
26828                "approvals",
26829                "2026-11-04T03:55:10.902000+00:00",
26830            ),
26831            timer("TimerFired", "2026-11-04T03:55:15.901000+00:00"),
26832            approval_signal("vote", "v1", "2026-11-04T03:55:16.000000+00:00"),
26833            member(
26834                "ConditionWaitSatisfied",
26835                1,
26836                0,
26837                "votes",
26838                "2026-11-04T03:55:16.100000+00:00",
26839            ),
26840            member(
26841                "ConditionWaitOpened",
26842                4,
26843                0,
26844                "votes",
26845                "2026-11-04T03:55:16.101000+00:00",
26846            ),
26847            member(
26848                "ConditionWaitOpened",
26849                5,
26850                2,
26851                "approvals",
26852                "2026-11-04T03:55:16.102000+00:00",
26853            ),
26854            approval_signal("vote", "v2", "2026-11-04T03:55:30.000000+00:00"),
26855            approval_signal("approve", "a1", "2026-11-04T03:55:30.100000+00:00"),
26856        ];
26857        let ctx = workflow_context(history);
26858        let votes = ctx.clone();
26859        let approvals = ctx.clone();
26860        let mut group = Box::pin(ctx.parallel(vec![
26861            ParallelOperation::condition(
26862                ConditionWaitOptions::new("votes", "sha256:votes-v1")
26863                    .timeout(Duration::from_secs(300)),
26864                move || Ok(votes.signals("vote")?.len() >= 2),
26865            ),
26866            ParallelOperation::timer(Duration::from_secs(5)),
26867            ParallelOperation::condition(
26868                ConditionWaitOptions::new("approvals", "sha256:approvals-v1")
26869                    .timeout(Duration::from_secs(300)),
26870                move || Ok(!approvals.signals("approve")?.is_empty()),
26871            ),
26872        ]));
26873        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26874        let poll = group.as_mut().poll(&mut task_context);
26875        let Poll::Ready(Ok(results)) = poll else {
26876            panic!("the group must complete: {poll:?}");
26877        };
26878        assert_eq!(results.len(), 3);
26879        ctx.ensure_history_consumed()
26880            .expect("every member consumes its own reopen");
26881        assert!(ctx.take_commands().expect("commands").is_empty());
26882    }
26883
26884    // #191: the PHP Server 2.11.8 history for two condition members woken by
26885    // one signal. It satisfies only the resume task's member (seq 2) but
26886    // records a reopen of the other, still-open member (seq 3 after seq 1).
26887    fn two_member_condition_history(extra_signals: &[(&str, &str)]) -> Vec<HistoryEvent> {
26888        let member = |event_type: &str, seq: u64, index: u64, key: &str, at: &str| {
26889            let occurrence = format!("rust:condition-wait:{index}");
26890            timed_event(
26891                event_type,
26892                at,
26893                json!({
26894                    "sequence": seq,
26895                    "condition_wait_id": format!("condition:{seq}"),
26896                    "condition_wait_occurrence_id": occurrence,
26897                    "condition_key": key,
26898                    "condition_definition_fingerprint": format!("sha256:{key}-v1"),
26899                    "timeout_seconds": 300,
26900                    "parallel_group_id": "parallel-calls:1:2",
26901                    "parallel_group_kind": "condition",
26902                    "parallel_group_base_sequence": 1,
26903                    "parallel_group_size": 2,
26904                    "parallel_group_index": index,
26905                }),
26906            )
26907        };
26908        let mut history = vec![
26909            member(
26910                "ConditionWaitOpened",
26911                1,
26912                0,
26913                "votes",
26914                "2026-11-04T03:55:10.900000+00:00",
26915            ),
26916            member(
26917                "ConditionWaitOpened",
26918                2,
26919                1,
26920                "approvals",
26921                "2026-11-04T03:55:10.901000+00:00",
26922            ),
26923            approval_signal("vote", "v1", "2026-11-04T03:55:13.000000+00:00"),
26924            member(
26925                "ConditionWaitSatisfied",
26926                2,
26927                1,
26928                "approvals",
26929                "2026-11-04T03:55:13.100000+00:00",
26930            ),
26931            member(
26932                "ConditionWaitOpened",
26933                3,
26934                0,
26935                "votes",
26936                "2026-11-04T03:55:13.101000+00:00",
26937            ),
26938            member(
26939                "ConditionWaitOpened",
26940                4,
26941                1,
26942                "approvals",
26943                "2026-11-04T03:55:13.102000+00:00",
26944            ),
26945        ];
26946        for (index, (name, at)) in extra_signals.iter().enumerate() {
26947            history.push(approval_signal(name, &format!("x{index}"), at));
26948        }
26949        history
26950    }
26951
26952    fn poll_two_member_group(
26953        history: Vec<HistoryEvent>,
26954    ) -> (Poll<Result<Vec<ParallelResult>>>, Vec<Value>) {
26955        let ctx = workflow_context(history);
26956        let votes = ctx.clone();
26957        let approvals = ctx.clone();
26958        let mut group = Box::pin(ctx.parallel(vec![
26959            ParallelOperation::condition(
26960                ConditionWaitOptions::new("votes", "sha256:votes-v1")
26961                    .timeout(Duration::from_secs(300)),
26962                move || Ok(votes.signals("vote")?.len() >= 2),
26963            ),
26964            ParallelOperation::condition(
26965                ConditionWaitOptions::new("approvals", "sha256:approvals-v1")
26966                    .timeout(Duration::from_secs(300)),
26967                move || Ok(!approvals.signals("approve")?.is_empty()),
26968            ),
26969        ]));
26970        let mut task_context = TaskContext::from_waker(noop_waker_ref());
26971        let poll = group.as_mut().poll(&mut task_context);
26972        if matches!(poll, Poll::Ready(Ok(_))) {
26973            // Interleaved reopens (votes 1, approvals 2, votes 3, approvals 4)
26974            // must all be consumed by their own members.
26975            ctx.ensure_history_consumed()
26976                .expect("every physical reopen is consumed");
26977        }
26978        (poll, ctx.take_commands().expect("commands"))
26979    }
26980
26981    #[test]
26982    fn two_grouped_condition_members_replay_the_servers_reopen_of_a_still_open_member() {
26983        // The task after the false wake decodes and keeps both members waiting.
26984        let (poll, _) = poll_two_member_group(two_member_condition_history(&[]));
26985        assert!(matches!(poll, Poll::Pending), "{poll:?}");
26986
26987        // A second vote and an approval satisfy both members: the group completes.
26988        let (poll, commands) = poll_two_member_group(two_member_condition_history(&[
26989            ("vote", "2026-11-04T03:55:30.000000+00:00"),
26990            ("approve", "2026-11-04T03:55:30.100000+00:00"),
26991        ]));
26992        let Poll::Ready(Ok(results)) = poll else {
26993            panic!("both satisfied members must complete the group: {poll:?}");
26994        };
26995        assert_eq!(
26996            results,
26997            vec![
26998                ParallelResult::Condition(ConditionWaitResult::Satisfied),
26999                ParallelResult::Condition(ConditionWaitResult::Satisfied),
27000            ]
27001        );
27002        assert!(commands.is_empty(), "{commands:?}");
27003    }
27004
27005    // #189: the PHP Server accepts a grouped reopen only with the authored
27006    // timeout, so a parallel or select member reopens with it, not with the
27007    // remaining time an ungrouped wait uses.
27008    #[test]
27009    fn grouped_condition_reopen_sends_the_authored_timeout() {
27010        let fixture: Value = serde_json::from_str(include_str!(
27011            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
27012        ))
27013        .expect("grouped condition fixture");
27014        let base = fixture["history"].as_array().expect("fixture history")[..2].to_vec();
27015        for mode in ["parallel", "select"] {
27016            let mut history = base
27017                .iter()
27018                .map(|event| {
27019                    let mut payload = event["payload"].clone();
27020                    if mode == "select" {
27021                        let index = payload["parallel_group_index"].as_u64().unwrap();
27022                        payload["parallel_group_id"] = json!("select-calls:1:2");
27023                        payload["parallel_group_mode"] = json!("select");
27024                        payload["selection_member_key"] =
27025                            json!(if index == 0 { "timer" } else { "votes" });
27026                        payload["selection_member_index"] = json!(index);
27027                        payload["selection_member_base_sequence"] = json!(index + 1);
27028                        payload["selection_member_size"] = json!(1);
27029                        payload["selection_member_kind"] =
27030                            json!(if index == 0 { "timer" } else { "condition" });
27031                    }
27032                    if event["event_type"] == "ConditionWaitOpened" {
27033                        payload["timeout_seconds"] = json!(300);
27034                    }
27035                    timed_event(
27036                        event["event_type"].as_str().unwrap(),
27037                        "2026-11-04T02:36:05.000000+00:00",
27038                        payload,
27039                    )
27040                })
27041                .collect::<Vec<_>>();
27042            history.push(approval_signal(
27043                "vote",
27044                "v1",
27045                "2026-11-04T02:36:17.000000+00:00",
27046            ));
27047            let ctx = workflow_context(history);
27048            let condition = ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1")
27049                .timeout(Duration::from_secs(300));
27050            let mut task_context = TaskContext::from_waker(noop_waker_ref());
27051            let poll = if mode == "parallel" {
27052                let mut group = Box::pin(ctx.parallel(vec![
27053                    ParallelOperation::timer(Duration::from_secs(300)),
27054                    ParallelOperation::condition(condition, || Ok(false)),
27055                ]));
27056                group
27057                    .as_mut()
27058                    .poll(&mut task_context)
27059                    .map(|result| result.map(|_| ()))
27060            } else {
27061                let mut group = Box::pin(ctx.select_keyed(vec![
27062                    ("timer", ParallelOperation::timer(Duration::from_secs(300))),
27063                    (
27064                        "votes",
27065                        ParallelOperation::condition(condition, || Ok(false)),
27066                    ),
27067                ]));
27068                group
27069                    .as_mut()
27070                    .poll(&mut task_context)
27071                    .map(|result| result.map(|_| ()))
27072            };
27073            assert!(matches!(poll, Poll::Pending), "{mode}: {poll:?}");
27074            let commands = ctx.take_commands().expect("commands");
27075            let reopens = commands
27076                .iter()
27077                .filter(|command| command["type"] == "open_condition_wait")
27078                .collect::<Vec<_>>();
27079            assert_eq!(reopens.len(), 1, "{mode}: {commands:?}");
27080            assert_eq!(
27081                reopens[0]["condition_wait_occurrence_id"],
27082                json!("rust:condition-wait:0"),
27083                "{mode}"
27084            );
27085            assert_eq!(reopens[0]["timeout_seconds"], json!(300), "{mode}");
27086        }
27087    }
27088
27089    // #187: a grouped reopen carries the remaining time, so the next task must
27090    // accept a smaller recorded timeout and still refuse a larger or missing one.
27091    #[test]
27092    fn grouped_condition_reopen_accepts_a_remaining_time_timeout() {
27093        let fixture: Value = serde_json::from_str(include_str!(
27094            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
27095        ))
27096        .expect("grouped condition fixture");
27097        let mut original = fixture["history"]
27098            .as_array()
27099            .expect("fixture history")
27100            .clone();
27101        for index in [1, 2, 3] {
27102            original[index]["payload"]["timeout_seconds"] = json!(30);
27103        }
27104        let decode = |events: &[Value]| {
27105            let history = events
27106                .iter()
27107                .map(|event| {
27108                    history_event(
27109                        event["event_type"].as_str().unwrap(),
27110                        event["payload"].clone(),
27111                    )
27112                })
27113                .collect::<Vec<_>>();
27114            recorded_commands(
27115                &history,
27116                DEFAULT_CODEC,
27117                WorkflowIdentity {
27118                    workflow_id: None,
27119                    run_id: None,
27120                },
27121            )
27122        };
27123        // The same history as select members, as reopened_selection_condition_history builds it.
27124        let selection = original
27125            .iter()
27126            .map(|event| {
27127                let mut event = event.clone();
27128                let payload = &mut event["payload"];
27129                let index = payload["parallel_group_index"].as_u64().unwrap();
27130                payload["parallel_group_id"] = json!("select-calls:1:2");
27131                payload["parallel_group_mode"] = json!("select");
27132                payload["selection_member_key"] = json!(if index == 0 { "timer" } else { "votes" });
27133                payload["selection_member_index"] = json!(index);
27134                payload["selection_member_base_sequence"] = json!(index + 1);
27135                payload["selection_member_size"] = json!(1);
27136                payload["selection_member_kind"] =
27137                    json!(if index == 0 { "timer" } else { "condition" });
27138                event
27139            })
27140            .collect::<Vec<_>>();
27141        for (mode, history) in [("parallel", &original), ("select", &selection)] {
27142            assert!(
27143                decode(history).is_ok(),
27144                "{mode}: full-timeout reopen still replays"
27145            );
27146            for (reopen, accepted) in [
27147                (json!(18), true),
27148                (json!(0), true),
27149                (json!(31), false),
27150                (Value::Null, false),
27151            ] {
27152                let mut changed = history.clone();
27153                changed[3]["payload"]["timeout_seconds"] = reopen.clone();
27154                let result = decode(&changed);
27155                assert_eq!(
27156                    result.is_ok(),
27157                    accepted,
27158                    "{mode} reopen timeout {reopen}: {result:?}"
27159                );
27160                if let Err(Error::NonDeterministicReplay(failure)) = result {
27161                    assert_eq!(failure.reason, "condition_wait_group_reopen_mismatch");
27162                }
27163            }
27164        }
27165    }
27166
27167    #[test]
27168    fn grouped_condition_replay_rejects_unproven_physical_reopens() {
27169        let fixture: Value = serde_json::from_str(include_str!(
27170            "../tests/fixtures/replay-regressions/grouped-condition-physical-reopen.json"
27171        ))
27172        .expect("grouped condition fixture");
27173        let original = fixture["history"].as_array().expect("fixture history");
27174        let decode = |events: &[Value]| {
27175            let history = events
27176                .iter()
27177                .map(|event| {
27178                    history_event(
27179                        event["event_type"].as_str().unwrap(),
27180                        event["payload"].clone(),
27181                    )
27182                })
27183                .collect::<Vec<_>>();
27184            recorded_commands(
27185                &history,
27186                DEFAULT_CODEC,
27187                WorkflowIdentity {
27188                    workflow_id: None,
27189                    run_id: None,
27190                },
27191            )
27192        };
27193        assert!(decode(original).is_ok());
27194        for field in [
27195            "condition_wait_occurrence_id",
27196            "condition_key",
27197            "condition_definition_fingerprint",
27198            "timeout_seconds",
27199            "parallel_group_id",
27200            "parallel_group_size",
27201            "parallel_group_index",
27202        ] {
27203            let mut changed = original.clone();
27204            changed[3]["payload"][field] = match field {
27205                "timeout_seconds" | "parallel_group_size" => json!(30),
27206                "parallel_group_index" => json!(0),
27207                _ => json!("changed"),
27208            };
27209            assert!(
27210                decode(&changed).is_err(),
27211                "reopen must reject changed {field}"
27212            );
27213        }
27214        // #191: the PHP Server records a grouped re-send of a still-open member
27215        // as a new physical open. A predecessor that was unresolved when the
27216        // reopen opened (never resolved, or resolved only later) is the same
27217        // logical member, decided by the state at that open.
27218        let mut unsettled = original.clone();
27219        unsettled.remove(2);
27220        assert!(
27221            decode(&unsettled).is_ok(),
27222            "an unresolved predecessor is a repeated open"
27223        );
27224        let mut late_resolution = original.clone();
27225        late_resolution.swap(2, 3);
27226        assert!(
27227            decode(&late_resolution).is_ok(),
27228            "a predecessor resolved after the reopen was still open when it opened"
27229        );
27230        let mut timed_out = original.clone();
27231        timed_out[2]["event_type"] = json!("ConditionWaitTimedOut");
27232        assert!(decode(&timed_out).is_err(), "timeout is terminal");
27233    }
27234
27235    #[test]
27236    fn condition_wait_replays_repeated_physical_opens_as_one_logical_wait() {
27237        let history = vec![
27238            history_event(
27239                "ConditionWaitOpened",
27240                json!({
27241                    "sequence": 3,
27242                    "condition_wait_id": "condition:3",
27243                    "condition_wait_occurrence_id": "rust:condition-wait:0",
27244                    "condition_key": "two-votes",
27245                    "condition_definition_fingerprint": "sha256:two-votes-v1",
27246                }),
27247            ),
27248            history_event(
27249                "SignalReceived",
27250                json!({
27251                    "workflow_sequence": 3,
27252                    "signal_name": "vote",
27253                    "arguments": fixture_envelope(json!(["first"])),
27254                }),
27255            ),
27256            history_event(
27257                "ConditionWaitSatisfied",
27258                json!({
27259                    "sequence": 3,
27260                    "condition_wait_id": "condition:3",
27261                    "condition_wait_occurrence_id": "rust:condition-wait:0",
27262                    "condition_key": "two-votes",
27263                    "condition_definition_fingerprint": "sha256:two-votes-v1",
27264                }),
27265            ),
27266            history_event(
27267                "ConditionWaitOpened",
27268                json!({
27269                    "sequence": 5,
27270                    "condition_wait_id": "condition:5",
27271                    "condition_wait_occurrence_id": "rust:condition-wait:0",
27272                    "condition_key": "two-votes",
27273                    "condition_definition_fingerprint": "sha256:two-votes-v1",
27274                }),
27275            ),
27276            history_event(
27277                "SignalReceived",
27278                json!({
27279                    "workflow_sequence": 5,
27280                    "signal_name": "vote",
27281                    "arguments": fixture_envelope(json!(["second"])),
27282                }),
27283            ),
27284            history_event(
27285                "ConditionWaitSatisfied",
27286                json!({
27287                    "sequence": 5,
27288                    "condition_wait_id": "condition:5",
27289                    "condition_wait_occurrence_id": "rust:condition-wait:0",
27290                    "condition_key": "two-votes",
27291                    "condition_definition_fingerprint": "sha256:two-votes-v1",
27292                }),
27293            ),
27294        ];
27295        for _cold_worker_or_restart in 0..2 {
27296            let ctx = workflow_context(history.clone());
27297            let predicate_ctx = ctx.clone();
27298            let mut wait = Box::pin(ctx.wait_condition(
27299                ConditionWaitOptions::new("two-votes", "sha256:two-votes-v1"),
27300                move || Ok(predicate_ctx.signals("vote")?.len() >= 2),
27301            ));
27302            let mut task_context = TaskContext::from_waker(noop_waker_ref());
27303
27304            assert!(matches!(
27305                wait.as_mut().poll(&mut task_context),
27306                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
27307            ));
27308            assert!(ctx.take_commands().expect("commands").is_empty());
27309            ctx.ensure_history_consumed()
27310                .expect("every physical wait-open is consumed");
27311        }
27312    }
27313
27314    #[test]
27315    fn condition_wait_replays_update_driven_physical_opens_as_one_occurrence() {
27316        let history = vec![
27317            history_event(
27318                "ConditionWaitOpened",
27319                json!({
27320                    "sequence": 3,
27321                    "condition_wait_id": "condition:3",
27322                    "condition_wait_occurrence_id": "rust:condition-wait:0",
27323                    "condition_key": "approved",
27324                    "condition_definition_fingerprint": "sha256:approved-v1",
27325                }),
27326            ),
27327            history_event(
27328                "UpdateApplied",
27329                json!({
27330                    "sequence": 3,
27331                    "update_id": "update-1",
27332                    "update_name": "approve",
27333                    "arguments": fixture_envelope(json!([false])),
27334                }),
27335            ),
27336            history_event(
27337                "ConditionWaitOpened",
27338                json!({
27339                    "sequence": 5,
27340                    "condition_wait_id": "condition:5",
27341                    "condition_wait_occurrence_id": "rust:condition-wait:0",
27342                    "condition_key": "approved",
27343                    "condition_definition_fingerprint": "sha256:approved-v1",
27344                }),
27345            ),
27346            history_event(
27347                "UpdateApplied",
27348                json!({
27349                    "sequence": 5,
27350                    "update_id": "update-2",
27351                    "update_name": "approve",
27352                    "arguments": fixture_envelope(json!([true])),
27353                }),
27354            ),
27355        ];
27356
27357        for _cold_worker_or_restart in 0..2 {
27358            let ctx = workflow_context(history.clone());
27359            let predicate_ctx = ctx.clone();
27360            let mut wait = Box::pin(ctx.wait_condition(
27361                ConditionWaitOptions::new("approved", "sha256:approved-v1"),
27362                move || {
27363                    Ok(predicate_ctx
27364                        .updates("approve")?
27365                        .last()
27366                        .and_then(|arguments| arguments.first())
27367                        .and_then(Value::as_bool)
27368                        == Some(true))
27369                },
27370            ));
27371            let mut task_context = TaskContext::from_waker(noop_waker_ref());
27372
27373            assert!(matches!(
27374                wait.as_mut().poll(&mut task_context),
27375                Poll::Ready(Ok(ConditionWaitResult::Satisfied))
27376            ));
27377            assert!(ctx.take_commands().expect("commands").is_empty());
27378            ctx.ensure_history_consumed()
27379                .expect("every update-driven reopen is consumed");
27380        }
27381    }
27382
27383    #[test]
27384    fn condition_wait_replay_keeps_every_adjacent_authored_occurrence_distinct() {
27385        for (first_key, first_fingerprint, second_key, second_fingerprint) in [
27386            ("shared", "sha256:first", "shared", "sha256:second"),
27387            ("first", "sha256:shared", "second", "sha256:shared"),
27388            ("shared", "sha256:shared", "shared", "sha256:shared"),
27389            ("first", "sha256:first", "second", "sha256:second"),
27390        ] {
27391            let history = vec![
27392                history_event(
27393                    "ConditionWaitOpened",
27394                    json!({
27395                        "sequence": 3,
27396                        "condition_wait_id": "condition:3",
27397                        "condition_wait_occurrence_id": "rust:condition-wait:0",
27398                        "condition_key": first_key,
27399                        "condition_definition_fingerprint": first_fingerprint,
27400                    }),
27401                ),
27402                history_event(
27403                    "ConditionWaitSatisfied",
27404                    json!({
27405                        "sequence": 3,
27406                        "condition_wait_id": "condition:3",
27407                        "condition_wait_occurrence_id": "rust:condition-wait:0",
27408                        "condition_key": first_key,
27409                        "condition_definition_fingerprint": first_fingerprint,
27410                    }),
27411                ),
27412                history_event(
27413                    "ConditionWaitOpened",
27414                    json!({
27415                        "sequence": 4,
27416                        "condition_wait_id": "condition:4",
27417                        "condition_wait_occurrence_id": "rust:condition-wait:1",
27418                        "condition_key": second_key,
27419                        "condition_definition_fingerprint": second_fingerprint,
27420                    }),
27421                ),
27422                history_event(
27423                    "ConditionWaitSatisfied",
27424                    json!({
27425                        "sequence": 4,
27426                        "condition_wait_id": "condition:4",
27427                        "condition_wait_occurrence_id": "rust:condition-wait:1",
27428                        "condition_key": second_key,
27429                        "condition_definition_fingerprint": second_fingerprint,
27430                    }),
27431                ),
27432            ];
27433            for _cold_worker_or_restart in 0..2 {
27434                let ctx = workflow_context(history.clone());
27435                let mut task_context = TaskContext::from_waker(noop_waker_ref());
27436                let mut first = Box::pin(ctx.wait_condition(
27437                    ConditionWaitOptions::new(first_key, first_fingerprint),
27438                    || Ok(false),
27439                ));
27440                assert!(matches!(
27441                    first.as_mut().poll(&mut task_context),
27442                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
27443                ));
27444
27445                let mut second = Box::pin(ctx.wait_condition(
27446                    ConditionWaitOptions::new(second_key, second_fingerprint),
27447                    || Ok(false),
27448                ));
27449                assert!(matches!(
27450                    second.as_mut().poll(&mut task_context),
27451                    Poll::Ready(Ok(ConditionWaitResult::Satisfied))
27452                ));
27453                assert!(ctx.take_commands().expect("commands").is_empty());
27454                ctx.ensure_history_consumed()
27455                    .expect("each authored wait consumes one occurrence");
27456            }
27457        }
27458    }
27459
27460    #[test]
27461    fn cold_workers_replay_adjacent_condition_waits_from_one_loop_call_site() {
27462        fn worker() -> Worker {
27463            let client = Client::new("http://127.0.0.1:8080").expect("client");
27464            let mut worker = Worker::new(client, "rust-workers");
27465            worker.register_workflow("rust.condition-loop", |ctx, _input| async move {
27466                let mut outcomes = Vec::new();
27467                for _ in 0..2 {
27468                    outcomes.push(
27469                        ctx.wait_condition(
27470                            ConditionWaitOptions::new("shared", "sha256:shared"),
27471                            || Ok(false),
27472                        )
27473                        .await?,
27474                    );
27475                }
27476                Ok(json!(outcomes))
27477            });
27478            worker
27479        }
27480
27481        let task = workflow_task(
27482            "rust.condition-loop",
27483            vec![
27484                history_event(
27485                    "ConditionWaitOpened",
27486                    json!({
27487                        "sequence": 1,
27488                        "condition_wait_id": "condition:1",
27489                        "condition_wait_occurrence_id": "rust:condition-wait:0",
27490                        "condition_key": "shared",
27491                        "condition_definition_fingerprint": "sha256:shared",
27492                    }),
27493                ),
27494                history_event(
27495                    "ConditionWaitSatisfied",
27496                    json!({
27497                        "sequence": 1,
27498                        "condition_wait_id": "condition:1",
27499                        "condition_wait_occurrence_id": "rust:condition-wait:0",
27500                        "condition_key": "shared",
27501                        "condition_definition_fingerprint": "sha256:shared",
27502                    }),
27503                ),
27504                history_event(
27505                    "ConditionWaitOpened",
27506                    json!({
27507                        "sequence": 2,
27508                        "condition_wait_id": "condition:2",
27509                        "condition_wait_occurrence_id": "rust:condition-wait:1",
27510                        "condition_key": "shared",
27511                        "condition_definition_fingerprint": "sha256:shared",
27512                    }),
27513                ),
27514                history_event(
27515                    "ConditionWaitSatisfied",
27516                    json!({
27517                        "sequence": 2,
27518                        "condition_wait_id": "condition:2",
27519                        "condition_wait_occurrence_id": "rust:condition-wait:1",
27520                        "condition_key": "shared",
27521                        "condition_definition_fingerprint": "sha256:shared",
27522                    }),
27523                ),
27524            ],
27525            DEFAULT_CODEC,
27526        );
27527
27528        for _cold_worker_or_restart in 0..2 {
27529            let commands = worker()
27530                .execute_workflow_task(task.clone())
27531                .expect("adjacent loop waits replay deterministically");
27532            assert_eq!(commands.len(), 1);
27533            assert_eq!(commands[0]["type"], "complete_workflow");
27534            assert_eq!(
27535                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
27536                json!(["satisfied", "satisfied"])
27537            );
27538        }
27539    }
27540
27541    fn timed_event(event_type: &str, at: &str, payload: Value) -> HistoryEvent {
27542        let mut event = history_event(event_type, payload);
27543        event.raw.insert("timestamp".into(), json!(at));
27544        event
27545    }
27546
27547    fn approval_wait_open(sequence: u64, at: &str, timeout_seconds: u64) -> HistoryEvent {
27548        timed_event(
27549            "ConditionWaitOpened",
27550            at,
27551            json!({
27552                "sequence": sequence,
27553                "condition_wait_id": format!("condition:{sequence}"),
27554                "condition_wait_occurrence_id": "rust:condition-wait:0",
27555                "condition_key": "approval",
27556                "condition_definition_fingerprint": "sha256:approval-v1",
27557                "timeout_seconds": timeout_seconds,
27558            }),
27559        )
27560    }
27561
27562    fn approval_signal(name: &str, id: &str, at: &str) -> HistoryEvent {
27563        timed_event(
27564            "SignalReceived",
27565            at,
27566            json!({
27567                "signal_id": id,
27568                "workflow_command_id": format!("command-{id}"),
27569                "signal_name": name,
27570                "arguments": encode_value_envelope(&json!(["proposal-1"]), DEFAULT_CODEC)
27571                    .expect("signal input"),
27572            }),
27573        )
27574    }
27575
27576    fn poll_approval_wait(
27577        history: Vec<HistoryEvent>,
27578    ) -> (Poll<Result<ConditionWaitResult>>, Vec<Value>) {
27579        let ctx = workflow_context(history);
27580        let predicate_ctx = ctx.clone();
27581        let mut wait = Box::pin(
27582            ctx.wait_condition(
27583                ConditionWaitOptions::new("approval", "sha256:approval-v1")
27584                    .timeout(Duration::from_secs(300)),
27585                move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
27586            ),
27587        );
27588        let mut task_context = TaskContext::from_waker(noop_waker_ref());
27589        let poll = wait.as_mut().poll(&mut task_context);
27590        (poll, ctx.take_commands().expect("commands"))
27591    }
27592
27593    fn approval_wait_open_at(
27594        sequence: u64,
27595        occurrence: u64,
27596        at: &str,
27597        timeout_seconds: u64,
27598    ) -> HistoryEvent {
27599        let mut event = approval_wait_open(sequence, at, timeout_seconds);
27600        event.payload["condition_wait_occurrence_id"] =
27601            json!(format!("rust:condition-wait:{occurrence}"));
27602        event
27603    }
27604
27605    fn approval_wait_timed_out(sequence: u64, at: &str) -> HistoryEvent {
27606        timed_event(
27607            "ConditionWaitTimedOut",
27608            at,
27609            json!({
27610                "sequence": sequence,
27611                "condition_wait_id": format!("condition:{sequence}"),
27612                "condition_wait_occurrence_id": "rust:condition-wait:0",
27613                "condition_key": "approval",
27614                "condition_definition_fingerprint": "sha256:approval-v1",
27615            }),
27616        )
27617    }
27618
27619    /// `if wait(300) { approved } else if wait(grace) { late } else { expired }`,
27620    /// both waits on the same key and predicate. Returns the outcome so far and
27621    /// any new commands.
27622    fn poll_grace_wait(
27623        history: Vec<HistoryEvent>,
27624        grace_seconds: u64,
27625    ) -> (Poll<Result<&'static str>>, Vec<Value>) {
27626        let ctx = workflow_context(history);
27627        let wait = |seconds| {
27628            let predicate_ctx = ctx.clone();
27629            ctx.wait_condition(
27630                ConditionWaitOptions::new("approval", "sha256:approval-v1")
27631                    .timeout(Duration::from_secs(seconds)),
27632                move || Ok(!predicate_ctx.signals("approve")?.is_empty()),
27633            )
27634        };
27635        let mut task_context = TaskContext::from_waker(noop_waker_ref());
27636        let mut first = Box::pin(wait(300));
27637        let poll = match first.as_mut().poll(&mut task_context) {
27638            Poll::Ready(Ok(ConditionWaitResult::Satisfied)) => Poll::Ready(Ok("approved")),
27639            Poll::Ready(Ok(ConditionWaitResult::TimedOut)) => {
27640                let mut grace = Box::pin(wait(grace_seconds));
27641                match grace.as_mut().poll(&mut task_context) {
27642                    Poll::Ready(Ok(ConditionWaitResult::Satisfied)) => Poll::Ready(Ok("late")),
27643                    Poll::Ready(Ok(ConditionWaitResult::TimedOut)) => Poll::Ready(Ok("expired")),
27644                    Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
27645                    Poll::Pending => Poll::Pending,
27646                }
27647            }
27648            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
27649            Poll::Pending => Poll::Pending,
27650        };
27651        (poll, ctx.take_commands().expect("commands"))
27652    }
27653
27654    fn decision_history(reopen: u64, orphan_fires_before_reopen: bool) -> Vec<HistoryEvent> {
27655        let wait = |seq: u64, at: &str, timeout: u64| {
27656            timed_event(
27657                "ConditionWaitOpened",
27658                at,
27659                json!({
27660                    "sequence": seq,
27661                    "condition_wait_id": format!("condition:{seq}"),
27662                    "condition_wait_occurrence_id": "rust:condition-wait:0",
27663                    "condition_key": "decision-1",
27664                    "condition_definition_fingerprint": "sha256:decision-v1",
27665                    "timeout_seconds": timeout,
27666                }),
27667            )
27668        };
27669        let timer = |kind: &str, seq: u64, at: &str, delay: u64| {
27670            timed_event(
27671                kind,
27672                at,
27673                json!({
27674                    "sequence": seq,
27675                    "timer_id": format!("condition-timer:{seq}"),
27676                    "timer_kind": "condition_timeout",
27677                    "condition_wait_id": format!("condition:{seq}"),
27678                    "delay_seconds": delay,
27679                }),
27680            )
27681        };
27682        let orphan_fire = timer("TimerFired", 1, "2026-11-04T04:12:36.956000+00:00", 300);
27683        let mut history = vec![
27684            wait(1, "2026-11-04T04:07:36.890000+00:00", 300),
27685            timer("TimerScheduled", 1, "2026-11-04T04:07:36.891000+00:00", 300),
27686        ];
27687        if orphan_fires_before_reopen {
27688            // Control: the first wait really timed out before the next open.
27689            history.push(orphan_fire.clone());
27690        }
27691        history.extend([
27692            wait(2, "2026-11-04T04:07:36.908000+00:00", 300),
27693            timer("TimerScheduled", 2, "2026-11-04T04:07:36.909000+00:00", 300),
27694            approval_signal("decision", "s1", "2026-11-04T04:09:36.979000+00:00"),
27695            timed_event(
27696                "ConditionWaitSatisfied",
27697                "2026-11-04T04:09:37.008000+00:00",
27698                json!({
27699                    "sequence": 2,
27700                    "condition_wait_id": "condition:2",
27701                    "condition_wait_occurrence_id": "rust:condition-wait:0",
27702                    "condition_key": "decision-1",
27703                    "condition_definition_fingerprint": "sha256:decision-v1",
27704                }),
27705            ),
27706            timer("TimerCancelled", 2, "2026-11-04T04:09:37.009000+00:00", 300),
27707            wait(3, "2026-11-04T04:09:37.010000+00:00", reopen),
27708            timer(
27709                "TimerScheduled",
27710                3,
27711                "2026-11-04T04:09:37.011000+00:00",
27712                reopen,
27713            ),
27714        ]);
27715        if !orphan_fires_before_reopen {
27716            history.push(orphan_fire);
27717        }
27718        history
27719    }
27720
27721    fn poll_decision_wait(
27722        history: Vec<HistoryEvent>,
27723    ) -> (Poll<Result<ConditionWaitResult>>, Vec<Value>) {
27724        let ctx = workflow_context(history);
27725        let mut wait = Box::pin(
27726            ctx.wait_condition(
27727                ConditionWaitOptions::new("decision-1", "sha256:decision-v1")
27728                    .timeout(Duration::from_secs(300)),
27729                || Ok(false),
27730            ),
27731        );
27732        let mut task_context = TaskContext::from_waker(noop_waker_ref());
27733        let poll = wait.as_mut().poll(&mut task_context);
27734        (poll, ctx.take_commands().expect("commands"))
27735    }
27736
27737    // #192 (sdk-php#283 shape): a duplicate open left the first wait orphaned;
27738    // its timer firing later must not end the logical wait, because the next
27739    // same-occurrence wait opened while it was still open.
27740    #[test]
27741    fn an_orphaned_duplicate_wait_timing_out_later_does_not_end_the_logical_wait() {
27742        for reopen in [300, 180] {
27743            // Only the orphan's timer has fired: the chain continues, and the
27744            // deadline from the first open has passed, so it reopens with 0.
27745            let (poll, commands) = poll_decision_wait(decision_history(reopen, false));
27746            assert!(matches!(poll, Poll::Pending), "reopen {reopen}: {poll:?}");
27747            assert_eq!(commands.len(), 1, "reopen {reopen}: {commands:?}");
27748            assert_eq!(commands[0]["type"], json!("open_condition_wait"));
27749            assert_eq!(commands[0]["timeout_seconds"], json!(0), "reopen {reopen}");
27750
27751            // The reopened wait's own timer fires as well: the logical wait
27752            // times out, as the workflow intended.
27753            let mut history = decision_history(reopen, false);
27754            history.push(timed_event(
27755                "TimerFired",
27756                "2026-11-04T04:12:37.216000+00:00",
27757                json!({
27758                    "sequence": 3,
27759                    "timer_id": "condition-timer:3",
27760                    "timer_kind": "condition_timeout",
27761                    "condition_wait_id": "condition:3",
27762                    "delay_seconds": reopen,
27763                }),
27764            ));
27765            let (poll, commands) = poll_decision_wait(history);
27766            assert!(
27767                matches!(poll, Poll::Ready(Ok(ConditionWaitResult::TimedOut))),
27768                "reopen {reopen}: {poll:?}"
27769            );
27770            assert!(commands.is_empty());
27771        }
27772
27773        // A genuine timeout before the next open still ends the wait: reopening
27774        // it is non-deterministic.
27775        let (poll, _) = poll_decision_wait(decision_history(300, true));
27776        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) = poll else {
27777            panic!("a reopen after a real timeout must fail replay: {poll:?}");
27778        };
27779        assert_eq!(failure.reason, "condition_wait_reopened_after_timeout");
27780        assert_eq!(failure.sequence, Some(2));
27781    }
27782
27783    // A separate wait after a timed-out one is its own logical wait: it
27784    // measures from its own open and never inherits the earlier deadline
27785    // (General's sdk-php#271 review vectors).
27786    #[test]
27787    fn a_wait_after_a_timed_out_wait_measures_from_its_own_open() {
27788        let timed_out_first = || {
27789            vec![
27790                approval_wait_open_at(1, 0, "2026-11-04T02:36:05.000000+00:00", 300),
27791                approval_wait_timed_out(1, "2026-11-04T02:41:05.000000+00:00"),
27792            ]
27793        };
27794        for (label, grace, signal, expected) in [
27795            ("grace wait, wrong signal", 60, "reject", 31),
27796            ("equal-timeout wait, wrong signal", 300, "reject", 271),
27797        ] {
27798            let mut history = timed_out_first();
27799            history.push(approval_wait_open_at(
27800                2,
27801                1,
27802                "2026-11-04T02:41:05.500000+00:00",
27803                grace,
27804            ));
27805            history.push(approval_signal(
27806                signal,
27807                "s1",
27808                "2026-11-04T02:41:35.000000+00:00",
27809            ));
27810            let (poll, commands) = poll_grace_wait(history, grace);
27811            assert!(matches!(poll, Poll::Pending), "{label}: {poll:?}");
27812            assert_eq!(commands.len(), 1, "{label}: {commands:?}");
27813            assert_eq!(
27814                commands[0]["condition_wait_occurrence_id"],
27815                json!("rust:condition-wait:1"),
27816                "{label}"
27817            );
27818            assert_eq!(commands[0]["timeout_seconds"], json!(expected), "{label}");
27819        }
27820
27821        let mut history = timed_out_first();
27822        history.push(approval_wait_open_at(
27823            2,
27824            1,
27825            "2026-11-04T02:41:05.500000+00:00",
27826            60,
27827        ));
27828        history.push(approval_signal(
27829            "approve",
27830            "a1",
27831            "2026-11-04T02:41:35.000000+00:00",
27832        ));
27833        let (poll, commands) = poll_grace_wait(history, 60);
27834        assert!(
27835            matches!(poll, Poll::Ready(Ok("late"))),
27836            "grace wait, approve: {poll:?}"
27837        );
27838        assert!(commands.is_empty());
27839    }
27840
27841    // The same vectors as sdk-php#271 (#187): a false wake satisfies the Server's
27842    // wait, and the reopen keeps the deadline of the first open.
27843    #[test]
27844    fn reopened_condition_wait_keeps_its_first_opening_deadline() {
27845        let opened = || approval_wait_open(1, "2026-11-04T02:36:05.295000+00:00", 300);
27846        let satisfied = || {
27847            timed_event(
27848                "ConditionWaitSatisfied",
27849                "2026-11-04T02:38:05.397000+00:00",
27850                json!({
27851                    "sequence": 1,
27852                    "condition_wait_id": "condition:1",
27853                    "condition_wait_occurrence_id": "rust:condition-wait:0",
27854                    "condition_key": "approval",
27855                    "condition_definition_fingerprint": "sha256:approval-v1",
27856                }),
27857            )
27858        };
27859        let reopened = |timeout| approval_wait_open(2, "2026-11-04T02:38:05.402000+00:00", timeout);
27860        let wrong = |id, at| approval_signal("reject", id, at);
27861        for (label, history, expected) in [
27862            (
27863                "first false wake",
27864                vec![opened(), wrong("w1", "2026-11-04T02:38:05.345000+00:00")],
27865                180,
27866            ),
27867            (
27868                "second false wake after a full-timeout reopen",
27869                vec![
27870                    opened(),
27871                    wrong("w1", "2026-11-04T02:38:05.345000+00:00"),
27872                    satisfied(),
27873                    reopened(300),
27874                    wrong("w2", "2026-11-04T02:40:05.000000+00:00"),
27875                ],
27876                61,
27877            ),
27878            (
27879                "second false wake after a remaining-time reopen",
27880                vec![
27881                    opened(),
27882                    wrong("w1", "2026-11-04T02:38:05.345000+00:00"),
27883                    satisfied(),
27884                    reopened(180),
27885                    wrong("w2", "2026-11-04T02:40:05.000000+00:00"),
27886                ],
27887                61,
27888            ),
27889            (
27890                "false wake after the deadline",
27891                vec![opened(), wrong("w1", "2026-11-04T02:41:06.000000+00:00")],
27892                0,
27893            ),
27894        ] {
27895            let (poll, commands) = poll_approval_wait(history);
27896            assert!(matches!(poll, Poll::Pending), "{label}: {poll:?}");
27897            assert_eq!(commands.len(), 1, "{label}: {commands:?}");
27898            assert_eq!(commands[0]["type"], json!("open_condition_wait"), "{label}");
27899            assert_eq!(commands[0]["condition_key"], json!("approval"), "{label}");
27900            assert_eq!(
27901                commands[0]["condition_wait_occurrence_id"],
27902                json!("rust:condition-wait:0"),
27903                "{label}"
27904            );
27905            assert_eq!(commands[0]["timeout_seconds"], json!(expected), "{label}");
27906        }
27907
27908        let (poll, commands) = poll_approval_wait(vec![
27909            opened(),
27910            wrong("w1", "2026-11-04T02:38:05.345000+00:00"),
27911            satisfied(),
27912            reopened(180),
27913            approval_signal("approve", "a1", "2026-11-04T02:39:00.000000+00:00"),
27914        ]);
27915        assert!(
27916            matches!(poll, Poll::Ready(Ok(ConditionWaitResult::Satisfied))),
27917            "a true wake after a remaining-time reopen completes: {poll:?}"
27918        );
27919        assert!(commands.is_empty());
27920
27921        // Without recorded times the authored timeout is kept, as before.
27922        let mut untimed = vec![opened(), wrong("w1", "2026-11-04T02:38:05.345000+00:00")];
27923        for event in &mut untimed {
27924            event.raw.remove("timestamp");
27925        }
27926        let (_, commands) = poll_approval_wait(untimed);
27927        assert_eq!(commands[0]["timeout_seconds"], json!(300));
27928    }
27929
27930    #[test]
27931    fn a_reopen_longer_than_the_authored_timeout_is_not_the_same_wait() {
27932        let history = vec![
27933            approval_wait_open(1, "2026-11-04T02:36:05.295000+00:00", 300),
27934            timed_event(
27935                "ConditionWaitSatisfied",
27936                "2026-11-04T02:38:05.397000+00:00",
27937                json!({
27938                    "sequence": 1,
27939                    "condition_wait_id": "condition:1",
27940                    "condition_wait_occurrence_id": "rust:condition-wait:0",
27941                    "condition_key": "approval",
27942                    "condition_definition_fingerprint": "sha256:approval-v1",
27943                }),
27944            ),
27945            approval_wait_open(2, "2026-11-04T02:38:05.402000+00:00", 301),
27946        ];
27947        let (poll, _) = poll_approval_wait(history);
27948        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) = poll else {
27949            panic!("a longer reopen must fail replay: {poll:?}");
27950        };
27951        assert_eq!(failure.reason, "condition_wait_timeout_mismatch");
27952        assert_eq!(failure.sequence, Some(2));
27953    }
27954
27955    #[test]
27956    fn condition_wait_replay_rejects_identity_predicate_and_timeout_changes() {
27957        let history = vec![history_event(
27958            "ConditionWaitOpened",
27959            json!({
27960                "sequence": 12,
27961                "condition_wait_id": "condition:12",
27962                "condition_wait_occurrence_id": "rust:condition-wait:0",
27963                "condition_key": "approval",
27964                "condition_definition_fingerprint": "sha256:approval-v1",
27965                "timeout_seconds": 30,
27966            }),
27967        )];
27968        for (options, expected_reason) in [
27969            (
27970                ConditionWaitOptions::new("changed", "sha256:approval-v1")
27971                    .timeout(Duration::from_secs(30)),
27972                "condition_wait_key_mismatch",
27973            ),
27974            (
27975                ConditionWaitOptions::new("approval", "sha256:approval-v2")
27976                    .timeout(Duration::from_secs(30)),
27977                "condition_wait_predicate_mismatch",
27978            ),
27979            (
27980                ConditionWaitOptions::new("approval", "sha256:approval-v1")
27981                    .timeout(Duration::from_secs(29)),
27982                "condition_wait_timeout_mismatch",
27983            ),
27984        ] {
27985            let ctx = workflow_context(history.clone());
27986            let mut wait = Box::pin(ctx.wait_condition(options, || Ok(false)));
27987            let mut task_context = TaskContext::from_waker(noop_waker_ref());
27988            let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
27989                wait.as_mut().poll(&mut task_context)
27990            else {
27991                panic!("changed condition definition must fail replay");
27992            };
27993            assert_eq!(failure.reason, expected_reason);
27994            assert_eq!(failure.sequence, Some(12));
27995        }
27996    }
27997
27998    #[test]
27999    fn condition_wait_history_requires_the_canonical_predicate_fingerprint() {
28000        let error = WorkflowState::new(
28001            vec![history_event(
28002                "ConditionWaitOpened",
28003                json!({
28004                    "sequence": 12,
28005                    "condition_wait_id": "condition:12",
28006                    "condition_wait_occurrence_id": "rust:condition-wait:0",
28007                    "condition_key": "approval",
28008                }),
28009            )],
28010            "rust-workers".to_string(),
28011            DEFAULT_CODEC.to_string(),
28012            None,
28013        )
28014        .expect_err("condition history without a predicate fingerprint must fail");
28015
28016        assert!(matches!(
28017            error,
28018            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
28019                if reason == "condition_wait_predicate_fingerprint_missing"
28020        ));
28021    }
28022
28023    #[test]
28024    fn condition_wait_history_requires_authored_occurrence_identity() {
28025        let error = WorkflowState::new(
28026            vec![history_event(
28027                "ConditionWaitOpened",
28028                json!({
28029                    "sequence": 12,
28030                    "condition_wait_id": "condition:12",
28031                    "condition_key": "approval",
28032                    "condition_definition_fingerprint": "sha256:approval-v1",
28033                }),
28034            )],
28035            "rust-workers".to_string(),
28036            DEFAULT_CODEC.to_string(),
28037            None,
28038        )
28039        .expect_err("condition history without occurrence identity must fail");
28040
28041        assert!(matches!(
28042            error,
28043            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
28044                if reason == "condition_wait_occurrence_id_missing"
28045        ));
28046    }
28047
28048    #[test]
28049    fn typed_search_attribute_updates_validate_emit_and_replay() {
28050        let update = SearchAttributeUpdate::new()
28051            .keyword("OrderStatus", " waiting ")
28052            .expect("keyword")
28053            .int("Attempt", 3)
28054            .expect("int")
28055            .bool("Escalated", false)
28056            .expect("bool")
28057            .keyword_list("Regions", ["us-east", "eu-west"])
28058            .expect("list")
28059            .datetime("UpdatedAt", "2026-08-22T04:00:00Z")
28060            .expect("datetime")
28061            .delete("LegacyStatus")
28062            .expect("delete");
28063        let ctx = workflow_context(Vec::new());
28064        ctx.upsert_search_attributes(update.clone())
28065            .expect("typed update");
28066        assert_eq!(
28067            ctx.take_commands().expect("search-attribute command"),
28068            vec![json!({
28069                "type": "upsert_search_attributes",
28070                "attributes": {
28071                    "Attempt": 3,
28072                    "Escalated": false,
28073                    "LegacyStatus": null,
28074                    "OrderStatus": "waiting",
28075                    "Regions": ["us-east", "eu-west"],
28076                    "UpdatedAt": "2026-08-22T04:00:00Z",
28077                },
28078                "attribute_types": {
28079                    "Attempt": "int",
28080                    "Escalated": "bool",
28081                    "OrderStatus": "keyword",
28082                    "Regions": "keyword_list",
28083                    "UpdatedAt": "datetime",
28084                },
28085            })]
28086        );
28087
28088        let replay = workflow_context(vec![history_event(
28089            "SearchAttributesUpserted",
28090            json!({
28091                "sequence": 6,
28092                "attributes": {
28093                    "Attempt": 3,
28094                    "Escalated": false,
28095                    "LegacyStatus": null,
28096                    "OrderStatus": "waiting",
28097                    "Regions": ["us-east", "eu-west"],
28098                    "UpdatedAt": "2026-08-22T04:00:00Z",
28099                },
28100                "attribute_types": {
28101                    "Attempt": "int",
28102                    "Escalated": "bool",
28103                    "OrderStatus": "keyword",
28104                    "Regions": "keyword_list",
28105                    "UpdatedAt": "datetime",
28106                },
28107                "merged": {},
28108            }),
28109        )]);
28110        replay
28111            .upsert_search_attributes(update)
28112            .expect("matching update replays");
28113        assert!(replay.take_commands().expect("commands").is_empty());
28114        replay.ensure_history_consumed().expect("history consumed");
28115
28116        let type_drift = workflow_context(vec![history_event(
28117            "SearchAttributesUpserted",
28118            json!({
28119                "sequence": 7,
28120                "attributes": {"OrderStatus": "waiting"},
28121                "attribute_types": {"OrderStatus": "keyword"},
28122                "merged": {"OrderStatus": "waiting"},
28123            }),
28124        )]);
28125        let error = type_drift
28126            .upsert_search_attributes(
28127                SearchAttributeUpdate::new()
28128                    .string("OrderStatus", "waiting")
28129                    .expect("string update"),
28130            )
28131            .expect_err("same JSON value with a changed type must fail replay");
28132        assert!(matches!(
28133            error,
28134            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
28135                if reason == "search_attribute_type_mismatch"
28136        ));
28137
28138        let malformed_types = WorkflowState::new(
28139            vec![history_event(
28140                "SearchAttributesUpserted",
28141                json!({
28142                    "sequence": 8,
28143                    "attributes": {"OrderStatus": "waiting"},
28144                    "attribute_types": {"OrderStatus": "unsupported"},
28145                    "merged": {"OrderStatus": "waiting"},
28146                }),
28147            )],
28148            "rust-workers".to_string(),
28149            DEFAULT_CODEC.to_string(),
28150            None,
28151        )
28152        .expect_err("unsupported search-attribute type metadata must fail");
28153        assert!(matches!(
28154            malformed_types,
28155            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
28156                if reason == "search_attribute_types_malformed"
28157        ));
28158
28159        assert!(matches!(
28160            SearchAttributeUpdate::new().keyword("bad key", "value"),
28161            Err(SearchAttributeUpdateError::InvalidKey(_))
28162        ));
28163        assert!(matches!(
28164            SearchAttributeUpdate::new().float("Ratio", f64::NAN),
28165            Err(SearchAttributeUpdateError::NonFiniteFloat(_))
28166        ));
28167        assert!(matches!(
28168            SearchAttributeUpdate::new().keyword("UnicodeKeyword", "é".repeat(128)),
28169            Err(SearchAttributeUpdateError::ValueTooLong { .. })
28170        ));
28171        assert!(matches!(
28172            SearchAttributeUpdate::new().datetime("UpdatedAt", "2026-02-30T04:00:00Z"),
28173            Err(SearchAttributeUpdateError::InvalidDateTime(_))
28174        ));
28175        assert!(matches!(
28176            workflow_context(Vec::new()).upsert_search_attributes(SearchAttributeUpdate::new()),
28177            Err(Error::InvalidSearchAttributeUpdate(
28178                SearchAttributeUpdateError::Empty
28179            ))
28180        ));
28181    }
28182
28183    #[test]
28184    fn typed_search_attribute_text_uses_the_runtime_byte_limit() {
28185        let ascii = "a".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH);
28186        let utf8 = "é".repeat(MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2);
28187
28188        assert!(SearchAttributeUpdate::new()
28189            .string("AsciiDescription", ascii)
28190            .is_ok());
28191        assert!(SearchAttributeUpdate::new()
28192            .string("Utf8Description", utf8)
28193            .is_ok());
28194        assert!(matches!(
28195            SearchAttributeUpdate::new().string(
28196                "TooLongDescription",
28197                "é".repeat((MAX_SEARCH_ATTRIBUTE_STRING_LENGTH / 2) + 1),
28198            ),
28199            Err(SearchAttributeUpdateError::ValueTooLong {
28200                kind: "string",
28201                limit: MAX_SEARCH_ATTRIBUTE_STRING_LENGTH,
28202                ..
28203            })
28204        ));
28205    }
28206
28207    #[test]
28208    fn workflow_history_rejects_unpaired_or_mismatched_timer_events() {
28209        let lone_fire = WorkflowState::new(
28210            vec![history_event(
28211                "TimerFired",
28212                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28213            )],
28214            "rust-workers".to_string(),
28215            DEFAULT_CODEC.to_string(),
28216            None,
28217        )
28218        .expect_err("TimerFired requires TimerScheduled");
28219        assert!(matches!(
28220            lone_fire,
28221            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
28222                if reason == "timer_schedule_missing_or_duplicate"
28223        ));
28224
28225        let wrong_identity = WorkflowState::new(
28226            vec![
28227                history_event(
28228                    "TimerScheduled",
28229                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28230                ),
28231                history_event(
28232                    "TimerFired",
28233                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
28234                ),
28235            ],
28236            "rust-workers".to_string(),
28237            DEFAULT_CODEC.to_string(),
28238            None,
28239        )
28240        .expect_err("fire must match scheduled timer identity");
28241        assert!(matches!(
28242            wrong_identity,
28243            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
28244                if reason == "timer_identity_mismatch"
28245        ));
28246
28247        let duplicate_fire = WorkflowState::new(
28248            vec![
28249                history_event(
28250                    "TimerScheduled",
28251                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28252                ),
28253                history_event(
28254                    "TimerFired",
28255                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28256                ),
28257                history_event(
28258                    "TimerFired",
28259                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28260                ),
28261            ],
28262            "rust-workers".to_string(),
28263            DEFAULT_CODEC.to_string(),
28264            None,
28265        )
28266        .expect_err("a durable timer cannot fire twice");
28267        assert!(matches!(
28268            duplicate_fire,
28269            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
28270                if reason == "duplicate_timer_fire"
28271        ));
28272
28273        let wrong_fired_delay = WorkflowState::new(
28274            vec![
28275                history_event(
28276                    "TimerScheduled",
28277                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28278                ),
28279                history_event(
28280                    "TimerFired",
28281                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 6}),
28282                ),
28283            ],
28284            "rust-workers".to_string(),
28285            DEFAULT_CODEC.to_string(),
28286            None,
28287        )
28288        .expect_err("timer schedule and fire delays must agree");
28289        assert!(matches!(
28290            wrong_fired_delay,
28291            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
28292                if reason == "timer_history_delay_mismatch"
28293        ));
28294    }
28295
28296    #[test]
28297    fn replay_rejects_activity_moved_before_recorded_timer() {
28298        let ctx = workflow_context(vec![
28299            history_event(
28300                "TimerScheduled",
28301                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28302            ),
28303            history_event(
28304                "TimerFired",
28305                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28306            ),
28307            history_event(
28308                "ActivityCompleted",
28309                json!({
28310                    "sequence": 2,
28311                    "activity_type": "after-timer",
28312                    "payload_codec": DEFAULT_CODEC,
28313                    "result": fixture_envelope(json!("done")),
28314                }),
28315            ),
28316        ]);
28317        let mut activity = Box::pin(ctx.activity("after-timer", json!([])));
28318        let mut task_context = TaskContext::from_waker(noop_waker_ref());
28319
28320        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
28321            activity.as_mut().poll(&mut task_context)
28322        else {
28323            panic!("reordered durable command must be rejected");
28324        };
28325        assert_eq!(failure.reason, "recorded_command_mismatch");
28326        assert_eq!(failure.sequence, Some(1));
28327        assert_eq!(failure.expected.as_deref(), Some("timer"));
28328        assert_eq!(failure.actual.as_deref(), Some("activity:after-timer"));
28329    }
28330
28331    #[test]
28332    fn workflow_context_emits_a_typed_named_signal_wait() {
28333        let ctx = workflow_context(Vec::new());
28334        let mut signal = Box::pin(ctx.wait_signal("finish"));
28335        let mut task_context = TaskContext::from_waker(noop_waker_ref());
28336
28337        assert!(matches!(
28338            signal.as_mut().poll(&mut task_context),
28339            Poll::Pending
28340        ));
28341        assert_eq!(
28342            ctx.take_commands().expect("signal-wait command"),
28343            vec![json!({
28344                "type": "open_signal_wait",
28345                "signal_name": "finish",
28346            })]
28347        );
28348    }
28349
28350    #[test]
28351    fn runtime_message_stream_transport_cannot_be_opened_as_a_user_signal() {
28352        let ctx = workflow_context(Vec::new());
28353        let mut signal = Box::pin(ctx.wait_signal(MESSAGE_STREAM_SIGNAL));
28354        let mut task_context = TaskContext::from_waker(noop_waker_ref());
28355
28356        let Poll::Ready(Err(Error::Codec(message))) = signal.as_mut().poll(&mut task_context)
28357        else {
28358            panic!("runtime-reserved signal should be rejected");
28359        };
28360        assert!(message.contains("reserved by the workflow runtime"));
28361        assert!(ctx.take_commands().expect("commands").is_empty());
28362    }
28363
28364    #[tokio::test]
28365    async fn runtime_message_stream_transport_cannot_be_sent_as_a_user_signal() {
28366        let client = Client::builder("http://127.0.0.1:9")
28367            .build()
28368            .expect("client");
28369        let error = client
28370            .signal_workflow("workflow-1", MESSAGE_STREAM_SIGNAL, json!(["forged"]))
28371            .await
28372            .expect_err("runtime-reserved signal should be rejected before transport");
28373
28374        assert!(
28375            matches!(error, Error::Codec(ref message) if message.contains("reserved by the workflow runtime"))
28376        );
28377    }
28378
28379    #[test]
28380    fn message_stream_worker_task_consumes_current_contiguous_bounded_batch() {
28381        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
28382            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
28383                value.to_string(),
28384            )]))
28385            .expect("message payload");
28386            json!({
28387                "schema": MESSAGE_STREAM_SCHEMA,
28388                "stream_name": "orders",
28389                "message_id": message_id,
28390                "position": position,
28391                "payload_envelope": payload,
28392            })
28393        }
28394
28395        fn opened(sequence: u64) -> HistoryEvent {
28396            history_event(
28397                "SignalWaitOpened",
28398                json!({
28399                    "sequence": sequence,
28400                    "signal_name": MESSAGE_STREAM_SIGNAL,
28401                }),
28402            )
28403        }
28404
28405        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
28406            history_event(
28407                "SignalApplied",
28408                json!({
28409                    "sequence": sequence,
28410                    "signal_name": MESSAGE_STREAM_SIGNAL,
28411                    "value": fixture_envelope(json!([delivery])),
28412                }),
28413            )
28414        }
28415
28416        fn received(delivery: Value) -> HistoryEvent {
28417            history_event(
28418                "SignalReceived",
28419                json!({
28420                    "signal_name": MESSAGE_STREAM_SIGNAL,
28421                    "arguments": fixture_envelope(json!([delivery])),
28422                    "payload_codec": DEFAULT_CODEC,
28423                }),
28424            )
28425        }
28426
28427        let client = Client::new("http://127.0.0.1:8080").expect("client");
28428        let mut worker = Worker::new(client, "rust-workers");
28429        worker.register_workflow("rust.message-stream-batch", |ctx, _input| async move {
28430            let messages = ctx.message_stream("orders")?.receive(2).await?;
28431            Ok(json!(messages
28432                .into_iter()
28433                .map(|message| message.message_id)
28434                .collect::<Vec<_>>()))
28435        });
28436
28437        let first = delivery("message-1", 1, "one");
28438        let second = delivery("message-2", 2, "two");
28439        let batch = worker
28440            .execute_workflow_task_decision(workflow_task(
28441                "rust.message-stream-batch",
28442                vec![
28443                    opened(1),
28444                    received(first.clone()),
28445                    applied(1, first.clone()),
28446                    received(first.clone()),
28447                    received(second),
28448                ],
28449                DEFAULT_CODEC,
28450            ))
28451            .expect("worker task consumes the available batch");
28452
28453        assert_eq!(batch.commands.len(), 1);
28454        assert_eq!(batch.commands[0]["type"], "complete_workflow");
28455        assert_eq!(
28456            decode_wire_value(&batch.commands[0]["result"], DEFAULT_CODEC)
28457                .expect("workflow result"),
28458            json!(["message-1", "message-2"])
28459        );
28460        assert_eq!(
28461            batch.message_stream_cursors,
28462            vec![json!({"stream_name": "orders", "through_position": 2})]
28463        );
28464        assert!(batch.message_stream_waits.is_empty());
28465
28466        let partial = worker
28467            .execute_workflow_task_decision(workflow_task(
28468                "rust.message-stream-batch",
28469                vec![opened(1), received(first.clone()), applied(1, first)],
28470                DEFAULT_CODEC,
28471            ))
28472            .expect("worker task returns without waiting for a missing second item");
28473        assert_eq!(partial.commands.len(), 1);
28474        assert_eq!(partial.commands[0]["type"], "complete_workflow");
28475        assert_eq!(
28476            decode_wire_value(&partial.commands[0]["result"], DEFAULT_CODEC)
28477                .expect("workflow result"),
28478            json!(["message-1"])
28479        );
28480        assert_eq!(
28481            partial.message_stream_cursors,
28482            vec![json!({"stream_name": "orders", "through_position": 1})]
28483        );
28484        assert!(partial.message_stream_waits.is_empty());
28485    }
28486
28487    #[test]
28488    fn message_stream_replay_preserves_partial_batch_boundary_before_later_wait() {
28489        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
28490            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
28491                value.to_string(),
28492            )]))
28493            .expect("message payload");
28494            json!({
28495                "schema": MESSAGE_STREAM_SCHEMA,
28496                "stream_name": "orders",
28497                "message_id": message_id,
28498                "position": position,
28499                "payload_envelope": payload,
28500            })
28501        }
28502
28503        fn opened(sequence: u64) -> HistoryEvent {
28504            history_event(
28505                "SignalWaitOpened",
28506                json!({
28507                    "sequence": sequence,
28508                    "signal_name": MESSAGE_STREAM_SIGNAL,
28509                }),
28510            )
28511        }
28512
28513        fn received(delivery: Value) -> HistoryEvent {
28514            history_event(
28515                "SignalReceived",
28516                json!({
28517                    "signal_name": MESSAGE_STREAM_SIGNAL,
28518                    "arguments": fixture_envelope(json!([delivery])),
28519                    "payload_codec": DEFAULT_CODEC,
28520                }),
28521            )
28522        }
28523
28524        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
28525            history_event(
28526                "SignalApplied",
28527                json!({
28528                    "sequence": sequence,
28529                    "signal_name": MESSAGE_STREAM_SIGNAL,
28530                    "value": fixture_envelope(json!([delivery])),
28531                }),
28532            )
28533        }
28534
28535        let client = Client::new("http://127.0.0.1:8080").expect("client");
28536        let mut worker = Worker::new(client, "rust-workers");
28537        worker.register_workflow(
28538            "rust.message-stream-partial-batches",
28539            |ctx, _input| async move {
28540                let stream = ctx.message_stream("orders")?;
28541                let first = stream.receive(10).await?;
28542                let second = stream.receive(10).await?;
28543                Ok(json!([
28544                    first
28545                        .into_iter()
28546                        .map(|message| message.message_id)
28547                        .collect::<Vec<_>>(),
28548                    second
28549                        .into_iter()
28550                        .map(|message| message.message_id)
28551                        .collect::<Vec<_>>(),
28552                ]))
28553            },
28554        );
28555
28556        let first = delivery("message-1", 1, "one");
28557        let second = delivery("message-2", 2, "two");
28558        let decision = worker
28559            .execute_workflow_task_decision(workflow_task(
28560                "rust.message-stream-partial-batches",
28561                vec![
28562                    opened(1),
28563                    received(first.clone()),
28564                    applied(1, first),
28565                    opened(2),
28566                    received(second.clone()),
28567                    applied(2, second),
28568                ],
28569                DEFAULT_CODEC,
28570            ))
28571            .expect("cold replay preserves both authored receive boundaries");
28572
28573        assert_eq!(decision.commands.len(), 1);
28574        assert_eq!(decision.commands[0]["type"], "complete_workflow");
28575        assert_eq!(
28576            decode_wire_value(&decision.commands[0]["result"], DEFAULT_CODEC)
28577                .expect("workflow result"),
28578            json!([["message-1"], ["message-2"]])
28579        );
28580        assert_eq!(
28581            decision.message_stream_cursors,
28582            vec![json!({"stream_name": "orders", "through_position": 2})]
28583        );
28584        assert!(decision.message_stream_waits.is_empty());
28585    }
28586
28587    #[test]
28588    fn empty_message_stream_opens_internal_signal_wait_and_reports_position() {
28589        let ctx = workflow_context(Vec::new());
28590        let stream = ctx.message_stream("orders").expect("message stream");
28591        let mut receive = Box::pin(stream.receive(10));
28592        let mut task_context = TaskContext::from_waker(noop_waker_ref());
28593
28594        assert!(matches!(
28595            receive.as_mut().poll(&mut task_context),
28596            Poll::Pending
28597        ));
28598        assert_eq!(
28599            ctx.take_commands().expect("message-stream wait command"),
28600            vec![json!({
28601                "type": "open_signal_wait",
28602                "signal_name": MESSAGE_STREAM_SIGNAL,
28603            })]
28604        );
28605        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
28606        assert!(cursors.is_empty());
28607        assert_eq!(
28608            waits,
28609            vec![json!({"stream_name": "orders", "after_position": 0})]
28610        );
28611    }
28612
28613    #[test]
28614    fn continue_as_new_cursor_checkpoint_preserves_global_pending_position() {
28615        let ctx = workflow_context(vec![history_event(
28616            "SignalReceived",
28617            json!({
28618                "signal_name": MESSAGE_STREAM_SIGNAL,
28619                "arguments": fixture_envelope(json!([{
28620                    "schema": MESSAGE_STREAM_CURSOR_SCHEMA,
28621                    "stream_name": "orders",
28622                    "through_position": 2,
28623                }])),
28624                "payload_codec": DEFAULT_CODEC,
28625            }),
28626        )]);
28627        let stream = ctx.message_stream("orders").expect("message stream");
28628        let mut receive = Box::pin(stream.receive(10));
28629        let mut task_context = TaskContext::from_waker(noop_waker_ref());
28630
28631        assert!(matches!(
28632            receive.as_mut().poll(&mut task_context),
28633            Poll::Pending
28634        ));
28635        let (cursors, waits) = ctx.message_stream_metadata().expect("stream metadata");
28636        assert_eq!(
28637            cursors,
28638            vec![json!({"stream_name": "orders", "through_position": 2})]
28639        );
28640        assert_eq!(
28641            waits,
28642            vec![json!({"stream_name": "orders", "after_position": 2})]
28643        );
28644    }
28645
28646    #[test]
28647    fn message_stream_delivery_preserves_typed_avro_arguments_across_replay() {
28648        let mut empty_map = BTreeMap::new();
28649        let mut nested = BTreeMap::new();
28650        nested.insert(
28651            "value".to_string(),
28652            AvroValue::Array(vec![AvroValue::Bytes(b"nested".to_vec())]),
28653        );
28654        let values = vec![
28655            AvroValue::Bytes(vec![0, 255]),
28656            AvroValue::Long(1),
28657            AvroValue::Double(1.0),
28658            AvroValue::Array(Vec::new()),
28659            AvroValue::Map(std::mem::take(&mut empty_map)),
28660            AvroValue::Map(nested),
28661        ];
28662        let payload = encode_avro_value(&AvroValue::Array(values.clone())).expect("payload");
28663        let transport = vec![json!({
28664            "schema": MESSAGE_STREAM_SCHEMA,
28665            "stream_name": "orders",
28666            "message_id": "message-1",
28667            "position": 1,
28668            "payload_envelope": payload,
28669        })];
28670
28671        for _ in 0..2 {
28672            let Some(MessageStreamDelivery::Message(message)) =
28673                decode_message_stream_delivery(transport.clone()).expect("delivery")
28674            else {
28675                panic!("message delivery expected");
28676            };
28677            assert_eq!(message.arguments, values);
28678            assert!(matches!(message.arguments[1], AvroValue::Long(1)));
28679            assert!(matches!(message.arguments[2], AvroValue::Double(1.0)));
28680        }
28681    }
28682
28683    #[test]
28684    fn cold_worker_replacement_consumes_message_stream_wait_arrivals_once_in_order() {
28685        fn delivery(message_id: &str, position: u64, value: &str) -> Value {
28686            let payload = encode_avro_value(&AvroValue::Array(vec![AvroValue::String(
28687                value.to_string(),
28688            )]))
28689            .expect("message payload");
28690            json!({
28691                "schema": MESSAGE_STREAM_SCHEMA,
28692                "stream_name": "orders",
28693                "message_id": message_id,
28694                "position": position,
28695                "payload_envelope": payload,
28696            })
28697        }
28698
28699        fn opened(sequence: u64) -> HistoryEvent {
28700            history_event(
28701                "SignalWaitOpened",
28702                json!({
28703                    "sequence": sequence,
28704                    "signal_name": MESSAGE_STREAM_SIGNAL,
28705                }),
28706            )
28707        }
28708
28709        fn applied(sequence: u64, delivery: Value) -> HistoryEvent {
28710            history_event(
28711                "SignalApplied",
28712                json!({
28713                    "sequence": sequence,
28714                    "signal_name": MESSAGE_STREAM_SIGNAL,
28715                    "value": fixture_envelope(json!([delivery])),
28716                }),
28717            )
28718        }
28719
28720        fn worker() -> Worker {
28721            let client = Client::new("http://127.0.0.1:8080").expect("client");
28722            let mut worker = Worker::new(client, "rust-workers");
28723            worker.register_workflow("rust.message-stream", |ctx, _input| async move {
28724                let stream = ctx.message_stream("orders")?;
28725                let first = stream.receive_one().await?;
28726                let second = stream.receive_one().await?;
28727                Ok(json!([first.message_id, second.message_id]))
28728            });
28729            worker
28730        }
28731
28732        fn task_with_resume(history: Vec<HistoryEvent>, delivery: Value) -> WorkflowTask {
28733            let mut task = workflow_task("rust.message-stream", history, DEFAULT_CODEC);
28734            task.signal_name = Some(MESSAGE_STREAM_SIGNAL.to_string());
28735            task.signal_arguments = Some(fixture_envelope(json!([delivery])));
28736            task
28737        }
28738
28739        let waiting = worker()
28740            .execute_workflow_task_decision(workflow_task(
28741                "rust.message-stream",
28742                Vec::new(),
28743                DEFAULT_CODEC,
28744            ))
28745            .expect("first worker opens the stream wait");
28746        assert_eq!(
28747            waiting.commands,
28748            vec![json!({
28749                "type": "open_signal_wait",
28750                "signal_name": MESSAGE_STREAM_SIGNAL,
28751            })]
28752        );
28753        assert!(waiting.message_stream_cursors.is_empty());
28754        assert_eq!(
28755            waiting.message_stream_waits,
28756            vec![json!({"stream_name": "orders", "after_position": 0})]
28757        );
28758
28759        let first_delivery = delivery("message-1", 1, "one");
28760        let first_arrival = worker()
28761            .execute_workflow_task_decision(task_with_resume(
28762                vec![opened(1)],
28763                first_delivery.clone(),
28764            ))
28765            .expect("replacement worker consumes the first arrival");
28766        assert_eq!(
28767            first_arrival.commands,
28768            vec![json!({
28769                "type": "open_signal_wait",
28770                "signal_name": MESSAGE_STREAM_SIGNAL,
28771            })]
28772        );
28773        assert_eq!(
28774            first_arrival.message_stream_cursors,
28775            vec![json!({"stream_name": "orders", "through_position": 1})]
28776        );
28777        assert_eq!(
28778            first_arrival.message_stream_waits,
28779            vec![json!({"stream_name": "orders", "after_position": 1})]
28780        );
28781
28782        let second_delivery = delivery("message-2", 2, "two");
28783        let first_applied = applied(1, first_delivery);
28784        let completed = worker()
28785            .execute_workflow_task_decision(task_with_resume(
28786                vec![opened(1), first_applied.clone(), opened(2)],
28787                second_delivery.clone(),
28788            ))
28789            .expect("next replacement worker consumes the second arrival");
28790        assert_eq!(completed.commands.len(), 1);
28791        assert_eq!(completed.commands[0]["type"], "complete_workflow");
28792        assert_eq!(
28793            decode_wire_value(&completed.commands[0]["result"], DEFAULT_CODEC)
28794                .expect("workflow result"),
28795            json!(["message-1", "message-2"])
28796        );
28797        assert_eq!(
28798            completed.message_stream_cursors,
28799            vec![json!({"stream_name": "orders", "through_position": 2})]
28800        );
28801        assert!(completed.message_stream_waits.is_empty());
28802
28803        let replay_history = vec![
28804            opened(1),
28805            first_applied,
28806            opened(2),
28807            applied(2, second_delivery),
28808        ];
28809        for _cold_worker_or_restart in 0..2 {
28810            let replayed = worker()
28811                .execute_workflow_task_decision(workflow_task(
28812                    "rust.message-stream",
28813                    replay_history.clone(),
28814                    DEFAULT_CODEC,
28815                ))
28816                .expect("cold worker replays each logical message exactly once");
28817            assert_eq!(replayed.commands.len(), 1);
28818            assert_eq!(
28819                decode_wire_value(&replayed.commands[0]["result"], DEFAULT_CODEC)
28820                    .expect("replayed workflow result"),
28821                json!(["message-1", "message-2"])
28822            );
28823            assert_eq!(
28824                replayed.message_stream_cursors,
28825                vec![json!({"stream_name": "orders", "through_position": 2})]
28826            );
28827            assert!(replayed.message_stream_waits.is_empty());
28828        }
28829    }
28830
28831    #[test]
28832    fn message_stream_capability_and_completion_require_protocol_one_fifteen() {
28833        assert!(!worker_protocol_supports_message_streams("1.14"));
28834        assert!(worker_protocol_supports_message_streams("1.15"));
28835        assert!(worker_protocol_supports_message_streams("1.16"));
28836        assert!(worker_protocol_supports_message_streams(
28837            WORKER_PROTOCOL_VERSION
28838        ));
28839        assert_eq!(MESSAGE_STREAMS_MINIMUM_WORKER_PROTOCOL_VERSION, "1.15");
28840    }
28841
28842    #[test]
28843    fn condition_wait_history_cannot_be_consumed_as_a_typed_signal_wait() {
28844        let ctx = workflow_context(vec![
28845            history_event(
28846                "ConditionWaitOpened",
28847                json!({
28848                    "sequence": 1,
28849                    "condition_wait_id": "condition:1",
28850                    "condition_wait_occurrence_id": "rust:condition-wait:0",
28851                    "condition_key": "signal:finish",
28852                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
28853                }),
28854            ),
28855            history_event(
28856                "ConditionWaitSatisfied",
28857                json!({
28858                    "sequence": 1,
28859                    "condition_wait_id": "condition:1",
28860                    "condition_wait_occurrence_id": "rust:condition-wait:0",
28861                    "condition_key": "signal:finish",
28862                    "condition_definition_fingerprint": "sha256:signal-finish-v1",
28863                }),
28864            ),
28865            history_event(
28866                "SignalReceived",
28867                json!({"signal_name": "finish", "arguments": []}),
28868            ),
28869        ]);
28870        let mut signal = Box::pin(ctx.wait_signal("finish"));
28871        let mut task_context = TaskContext::from_waker(noop_waker_ref());
28872
28873        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
28874            signal.as_mut().poll(&mut task_context)
28875        else {
28876            panic!("condition history must not resolve as a typed signal wait");
28877        };
28878        assert_eq!(failure.reason, "recorded_command_mismatch");
28879        assert_eq!(failure.expected.as_deref(), Some("condition wait"));
28880    }
28881
28882    #[tokio::test]
28883    async fn replay_reports_the_authored_activity_before_a_recorded_timer() {
28884        let history = vec![history_event(
28885            "TimerScheduled",
28886            json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28887        )];
28888        let ctx = workflow_context(history.clone());
28889        let authored_line = line!() + 1;
28890        let result = ctx.activity("hello", json!([])).await;
28891        let Err(Error::NonDeterministicReplay(failure)) = result else {
28892            panic!("activity reordered before a recorded timer must fail");
28893        };
28894        assert_eq!(failure.reason, "recorded_command_mismatch");
28895        assert_eq!(failure.sequence, Some(1));
28896        assert_eq!(failure.expected.as_deref(), Some("timer"));
28897        assert!(failure
28898            .message
28899            .ends_with(&format!(" Authored at lib.rs:{authored_line}.")));
28900        assert!(!failure.message.contains("src/lib.rs"));
28901
28902        let ctx = workflow_context(history);
28903        let result = ctx.activity_avro_value("hello", json!([])).await;
28904        let Err(Error::NonDeterministicReplay(failure)) = result else {
28905            panic!("the Avro wrapper must preserve the determinism error");
28906        };
28907        assert!(!failure.message.contains("Authored at"));
28908    }
28909
28910    #[test]
28911    fn replay_orders_signal_waits_and_timers_in_one_command_stream() {
28912        let signal_then_timer = vec![
28913            history_event(
28914                "SignalWaitOpened",
28915                json!({"sequence": 1, "signal_name": "go"}),
28916            ),
28917            history_event(
28918                "SignalApplied",
28919                json!({
28920                    "sequence": 1,
28921                    "signal_name": "go",
28922                    "value": fixture_envelope(json!(["now"])),
28923                }),
28924            ),
28925            history_event(
28926                "TimerScheduled",
28927                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
28928            ),
28929            history_event(
28930                "TimerFired",
28931                json!({"sequence": 2, "timer_id": "timer-2", "delay_seconds": 5}),
28932            ),
28933        ];
28934
28935        let ctx = workflow_context(signal_then_timer.clone());
28936        let mut signal = Box::pin(ctx.wait_signal("go"));
28937        let mut task_context = TaskContext::from_waker(noop_waker_ref());
28938        assert!(matches!(
28939            signal.as_mut().poll(&mut task_context),
28940            Poll::Ready(Ok(arguments)) if arguments == vec![json!("now")]
28941        ));
28942        let mut timer = Box::pin(ctx.sleep(Duration::from_secs(5)));
28943        assert!(matches!(
28944            timer.as_mut().poll(&mut task_context),
28945            Poll::Ready(Ok(()))
28946        ));
28947        ctx.ensure_history_consumed()
28948            .expect("signal and timer history consumed in order");
28949
28950        let reordered = workflow_context(signal_then_timer);
28951        let authored_line = line!() + 1;
28952        let mut timer_first = Box::pin(reordered.sleep(Duration::from_secs(5)));
28953        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
28954            timer_first.as_mut().poll(&mut task_context)
28955        else {
28956            panic!("timer cannot consume signal-wait-first history");
28957        };
28958        assert_eq!(failure.reason, "recorded_command_mismatch");
28959        assert_eq!(failure.sequence, Some(1));
28960        assert_eq!(failure.expected.as_deref(), Some("signal wait"));
28961        assert!(failure
28962            .message
28963            .ends_with(&format!(" Authored at lib.rs:{authored_line}.")));
28964
28965        let timer_then_signal = vec![
28966            history_event(
28967                "TimerScheduled",
28968                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28969            ),
28970            history_event(
28971                "TimerFired",
28972                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
28973            ),
28974            history_event(
28975                "SignalWaitOpened",
28976                json!({"sequence": 2, "signal_name": "go"}),
28977            ),
28978            history_event(
28979                "SignalApplied",
28980                json!({
28981                    "sequence": 2,
28982                    "signal_name": "go",
28983                    "value": fixture_envelope(json!([])),
28984                }),
28985            ),
28986        ];
28987        let reordered = workflow_context(timer_then_signal);
28988        let mut signal_first = Box::pin(reordered.wait_signal("go"));
28989        let Poll::Ready(Err(Error::NonDeterministicReplay(failure))) =
28990            signal_first.as_mut().poll(&mut task_context)
28991        else {
28992            panic!("signal wait cannot consume timer-first history");
28993        };
28994        assert_eq!(failure.reason, "recorded_command_mismatch");
28995        assert_eq!(failure.sequence, Some(1));
28996        assert_eq!(failure.expected.as_deref(), Some("timer"));
28997    }
28998
28999    #[test]
29000    fn workflow_history_rejects_duplicate_or_colliding_command_sequences() {
29001        let duplicate_timer = WorkflowState::new(
29002            vec![
29003                history_event(
29004                    "TimerScheduled",
29005                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
29006                ),
29007                history_event(
29008                    "TimerScheduled",
29009                    json!({"sequence": 1, "timer_id": "timer-2", "delay_seconds": 5}),
29010                ),
29011            ],
29012            "rust-workers".to_string(),
29013            DEFAULT_CODEC.to_string(),
29014            None,
29015        )
29016        .expect_err("one workflow sequence cannot schedule two timers");
29017        assert!(matches!(
29018            duplicate_timer,
29019            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
29020                if reason == "timer_schedule_missing_or_duplicate"
29021        ));
29022
29023        let colliding_kinds = WorkflowState::new(
29024            vec![
29025                history_event(
29026                    "TimerScheduled",
29027                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
29028                ),
29029                history_event(
29030                    "ActivityCompleted",
29031                    json!({"sequence": 1, "activity_type": "same-sequence"}),
29032                ),
29033            ],
29034            "rust-workers".to_string(),
29035            DEFAULT_CODEC.to_string(),
29036            None,
29037        )
29038        .expect_err("one workflow sequence cannot identify two command kinds");
29039        assert!(matches!(
29040            colliding_kinds,
29041            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
29042                if reason == "durable_command_sequence_collision"
29043        ));
29044
29045        let duplicate_signal_wait = WorkflowState::new(
29046            vec![
29047                history_event(
29048                    "SignalWaitOpened",
29049                    json!({"sequence": 1, "signal_name": "go"}),
29050                ),
29051                history_event(
29052                    "SignalWaitOpened",
29053                    json!({"sequence": 1, "signal_name": "go"}),
29054                ),
29055            ],
29056            "rust-workers".to_string(),
29057            DEFAULT_CODEC.to_string(),
29058            None,
29059        )
29060        .expect_err("one workflow sequence cannot open two signal waits");
29061        assert!(matches!(
29062            duplicate_signal_wait,
29063            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
29064                if reason == "signal_wait_open_missing_or_duplicate"
29065        ));
29066    }
29067
29068    #[test]
29069    fn workflow_history_accepts_a_first_command_after_global_sequence_gaps() {
29070        let result = encode_value_envelope(&json!({"captured": true}), DEFAULT_CODEC)
29071            .expect("side-effect result");
29072        let ctx = workflow_context(vec![history_event(
29073            "SideEffectRecorded",
29074            json!({"sequence": 99, "result": result}),
29075        )]);
29076
29077        let replayed: Value = ctx
29078            .side_effect(|| panic!("recorded side effect must not run"))
29079            .expect("positive global workflow sequence is valid");
29080        assert_eq!(replayed, json!({"captured": true}));
29081        ctx.ensure_history_consumed().expect("history consumed");
29082    }
29083
29084    #[test]
29085    fn workflow_history_rejects_zero_and_descending_command_sequences() {
29086        let result =
29087            encode_value_envelope(&json!("captured"), DEFAULT_CODEC).expect("side-effect result");
29088        let zero = WorkflowState::new(
29089            vec![history_event(
29090                "SideEffectRecorded",
29091                json!({"sequence": 0, "result": result.clone()}),
29092            )],
29093            "rust-workers".to_string(),
29094            DEFAULT_CODEC.to_string(),
29095            None,
29096        )
29097        .expect_err("durable command sequences must be positive");
29098        assert!(matches!(
29099            zero,
29100            Error::NonDeterministicReplay(ReplayFailure { ref reason, .. })
29101                if reason == "durable_command_sequence_invalid"
29102        ));
29103
29104        let descending = WorkflowState::new(
29105            vec![
29106                history_event(
29107                    "SideEffectRecorded",
29108                    json!({"sequence": 3, "result": result}),
29109                ),
29110                history_event(
29111                    "VersionMarkerRecorded",
29112                    json!({
29113                        "sequence": 2,
29114                        "change_id": "descending-marker",
29115                        "version": 1,
29116                        "min_supported": 1,
29117                        "max_supported": 1,
29118                    }),
29119                ),
29120            ],
29121            "rust-workers".to_string(),
29122            DEFAULT_CODEC.to_string(),
29123            None,
29124        )
29125        .expect_err("new durable commands must remain strictly ordered");
29126        let Error::NonDeterministicReplay(failure) = descending else {
29127            panic!("expected typed replay failure");
29128        };
29129        assert_eq!(failure.reason, "durable_command_sequence_mismatch");
29130        assert_eq!(failure.sequence, Some(2));
29131        assert_eq!(
29132            failure.expected.as_deref(),
29133            Some("workflow sequence greater than 3")
29134        );
29135        assert_eq!(failure.actual.as_deref(), Some("2"));
29136    }
29137
29138    #[test]
29139    fn workflow_task_replay_completes_after_signals_create_sequence_gaps() {
29140        fn worker() -> Worker {
29141            let client = Client::new("http://127.0.0.1:8080").expect("client");
29142            let mut worker = Worker::new(client, "rust-workers");
29143            worker.register_workflow("rust.finish-after-gaps", |ctx, _input| async move {
29144                ctx.wait_signal("finish").await?;
29145                let marker: String =
29146                    ctx.side_effect(|| panic!("recorded side effect must not run"))?;
29147                assert_eq!(marker, "after-finish");
29148                Ok(json!("finished"))
29149            });
29150            worker
29151        }
29152
29153        let marker = encode_value_envelope(&json!("after-finish"), DEFAULT_CODEC)
29154            .expect("side-effect result");
29155        let task = workflow_task(
29156            "rust.finish-after-gaps",
29157            vec![
29158                history_event(
29159                    "SignalWaitOpened",
29160                    json!({"sequence": 1, "signal_name": "finish"}),
29161                ),
29162                history_event(
29163                    "SignalReceived",
29164                    json!({
29165                        "signal_id": "increment-3",
29166                        "signal_name": "increment",
29167                        "workflow_sequence": 2,
29168                        "payload_codec": DEFAULT_CODEC,
29169                        "arguments": fixture_envelope(json!([3])),
29170                    }),
29171                ),
29172                history_event(
29173                    "SignalReceived",
29174                    json!({
29175                        "signal_id": "increment-5",
29176                        "signal_name": "increment",
29177                        "workflow_sequence": 3,
29178                        "payload_codec": DEFAULT_CODEC,
29179                        "arguments": fixture_envelope(json!([5])),
29180                    }),
29181                ),
29182                history_event(
29183                    "SignalReceived",
29184                    json!({
29185                        "signal_id": "finish",
29186                        "signal_name": "finish",
29187                        "workflow_sequence": 4,
29188                        "payload_codec": DEFAULT_CODEC,
29189                        "arguments": fixture_envelope(json!([])),
29190                    }),
29191                ),
29192                history_event(
29193                    "SignalApplied",
29194                    json!({
29195                        "sequence": 1,
29196                        "signal_id": "finish",
29197                        "signal_name": "finish",
29198                        "payload_codec": DEFAULT_CODEC,
29199                        "value": fixture_envelope(json!([])),
29200                    }),
29201                ),
29202                history_event(
29203                    "SideEffectRecorded",
29204                    json!({"sequence": 5, "result": marker}),
29205                ),
29206            ],
29207            DEFAULT_CODEC,
29208        );
29209
29210        for _original_or_cold_worker in 0..2 {
29211            let commands = worker()
29212                .execute_workflow_task(task.clone())
29213                .expect("signal gaps preserve deterministic replay");
29214            assert_eq!(commands.len(), 1, "replay emits only terminal completion");
29215            assert_eq!(commands[0]["type"], "complete_workflow");
29216            assert_eq!(
29217                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("workflow output"),
29218                json!("finished")
29219            );
29220        }
29221    }
29222
29223    #[test]
29224    fn workflow_sleep_rejects_unrepresentable_rounded_duration() {
29225        let ctx = workflow_context(Vec::new());
29226        let mut sleep = Box::pin(ctx.start_timer(Duration::new(u64::MAX, 1)));
29227        let mut task_context = TaskContext::from_waker(noop_waker_ref());
29228        assert!(matches!(
29229            sleep.as_mut().poll(&mut task_context),
29230            Poll::Ready(Err(Error::TimerDurationOverflow))
29231        ));
29232        assert!(ctx.take_commands().expect("commands").is_empty());
29233    }
29234
29235    #[test]
29236    fn workflow_memo_update_emits_canonical_command_and_replays_once() {
29237        let entries = AvroValue::Map(BTreeMap::from([
29238            ("text".to_string(), AvroValue::String("same".to_string())),
29239            (
29240                "nested".to_string(),
29241                AvroValue::Map(BTreeMap::from([
29242                    ("beta".to_string(), AvroValue::Long(2)),
29243                    ("alpha".to_string(), AvroValue::Long(1)),
29244                ])),
29245            ),
29246            ("long".to_string(), AvroValue::Long(7)),
29247            ("double".to_string(), AvroValue::Double(7.0)),
29248            ("binary".to_string(), AvroValue::Bytes(b"same".to_vec())),
29249        ]));
29250        let ctx = workflow_context(Vec::new());
29251        ctx.upsert_memo(entries.clone()).expect("valid memo update");
29252        let commands = ctx.take_commands().expect("commands");
29253
29254        assert_eq!(commands.len(), 1);
29255        assert_eq!(commands[0]["type"], "upsert_memo");
29256        let server_entries = json!({
29257            "codec": "avro",
29258            "blob": "wwHioz3/VYAiNw4KDGJpbmFyeQgIc2FtZQxkb3VibGUGAAAAAAAAHEAIbG9uZwQODG5lc3RlZA4ECmFscGhhBAIIYmV0YQQEAAh0ZXh0CghzYW1lAA==",
29259        });
29260        assert_eq!(
29261            commands[0]["entries"]
29262                .as_object()
29263                .expect("entries envelope")
29264                .keys()
29265                .collect::<Vec<_>>(),
29266            vec!["blob", "codec"]
29267        );
29268        assert_eq!(commands[0]["entries"], server_entries);
29269        let wire_entries =
29270            decode_wire_avro_value(&commands[0]["entries"], DEFAULT_CODEC).expect("memo entries");
29271        assert_eq!(wire_entries, entries);
29272
29273        let history = vec![history_event(
29274            "MemoUpserted",
29275            json!({
29276                "sequence": 1,
29277                "entries": server_entries.clone(),
29278                "merged": server_entries,
29279            }),
29280        )];
29281        let replay = workflow_context(history.clone());
29282        replay
29283            .upsert_memo(entries.clone())
29284            .expect("matching replay identity");
29285        assert!(replay.take_commands().expect("replay commands").is_empty());
29286
29287        let changed_types = AvroValue::Map(BTreeMap::from([
29288            ("text".to_string(), AvroValue::Bytes(b"same".to_vec())),
29289            (
29290                "nested".to_string(),
29291                AvroValue::Map(BTreeMap::from([
29292                    ("alpha".to_string(), AvroValue::Long(1)),
29293                    ("beta".to_string(), AvroValue::Long(2)),
29294                ])),
29295            ),
29296            ("long".to_string(), AvroValue::Double(7.0)),
29297            ("double".to_string(), AvroValue::Long(7)),
29298            ("binary".to_string(), AvroValue::String("same".to_string())),
29299        ]));
29300        let error = workflow_context(history)
29301            .upsert_memo(changed_types)
29302            .expect_err("memo replay identity must preserve Avro value types");
29303        assert!(matches!(
29304            error,
29305            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
29306        ));
29307    }
29308
29309    #[test]
29310    fn workflow_memo_update_rejects_changed_replay_identity_and_invalid_keys() {
29311        let original = encode_value_envelope(&json!({"stage": "original"}), DEFAULT_CODEC)
29312            .expect("memo envelope");
29313        let replay = workflow_context(vec![history_event(
29314            "MemoUpserted",
29315            json!({
29316                "sequence": 1,
29317                "entries": original.clone(),
29318                "merged": original
29319            }),
29320        )]);
29321        let error = replay
29322            .upsert_memo(json!({"stage": "changed"}))
29323            .expect_err("changed memo update must fail replay");
29324        assert!(matches!(
29325            error,
29326            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
29327        ));
29328
29329        let invalid = workflow_context(Vec::new())
29330            .upsert_memo(
29331                json!({"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": true}),
29332            )
29333            .expect_err("oversized key");
29334        assert!(matches!(invalid, Error::InvalidMemoUpdate(_)));
29335    }
29336
29337    #[test]
29338    fn workflow_memo_replay_distinguishes_signed_zero_identity() {
29339        let negative_zero = AvroValue::Map(BTreeMap::from([(
29340            "reading".to_string(),
29341            AvroValue::Double(-0.0),
29342        )]));
29343        let negative_zero_envelope =
29344            encode_typed_envelope(&negative_zero, DEFAULT_CODEC).expect("negative zero envelope");
29345        let history = vec![history_event(
29346            "MemoUpserted",
29347            json!({
29348                "sequence": 1,
29349                "entries": negative_zero_envelope.clone(),
29350                "merged": negative_zero_envelope,
29351            }),
29352        )];
29353
29354        workflow_context(history.clone())
29355            .upsert_memo(negative_zero)
29356            .expect("matching negative-zero history identity");
29357
29358        let error = workflow_context(history)
29359            .upsert_memo(AvroValue::Map(BTreeMap::from([(
29360                "reading".to_string(),
29361                AvroValue::Double(0.0),
29362            )])))
29363            .expect_err("positive zero must not consume negative-zero memo history");
29364        assert!(matches!(
29365            error,
29366            Error::NonDeterministicReplay(ref failure) if failure.reason == "memo_update_mismatch"
29367        ));
29368    }
29369
29370    #[test]
29371    fn workflow_memo_capability_requires_flag_and_command_advertisement() {
29372        let supported = json!({
29373            "workflow_memo_updates": {"supported": true, "minimum_protocol_version": "1.14"},
29374            "supported_workflow_task_commands": ["complete_workflow", "upsert_memo"]
29375        });
29376        assert!(runtime_supports_workflow_memo_updates(Some(&supported)));
29377        assert!(!runtime_supports_workflow_memo_updates(Some(&json!({
29378            "workflow_memo_updates": {"supported": false},
29379            "supported_workflow_task_commands": ["upsert_memo"]
29380        }))));
29381        assert!(commands_use_workflow_memo_updates(&[json!({
29382            "type": "upsert_memo",
29383            "entries": {"stage": "processing"}
29384        })]));
29385    }
29386
29387    #[test]
29388    fn workflow_task_replay_completes_without_rescheduling_recorded_commands() {
29389        let client = Client::new("http://127.0.0.1:8080").expect("client");
29390        let mut worker = Worker::new(client, "rust-workers");
29391        worker.register_workflow("rust.timer", |ctx, _input| async move {
29392            ctx.sleep(Duration::from_secs(5)).await?;
29393            ctx.activity("after-timer", json!([])).await
29394        });
29395
29396        let task = |history_events| WorkflowTask {
29397            task_id: "wft-rust-timer-1".to_string(),
29398            observability_context: None,
29399            dispatch_observability_context: None,
29400            observability_links: None,
29401            workflow_command_id: None,
29402            workflow_id: Some("wf-rust-timer".to_string()),
29403            run_id: Some("run-rust-timer".to_string()),
29404            workflow_type: "rust.timer".to_string(),
29405            cancel_requested: false,
29406            payload_codec: DEFAULT_CODEC.to_string(),
29407            arguments: Some(
29408                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
29409            ),
29410            history_events,
29411            total_history_events: None,
29412            history_size_bytes: None,
29413            continue_as_new_recommended: None,
29414            history_budget_pressure: None,
29415            next_history_page_token: None,
29416            workflow_task_attempt: 1,
29417            workflow_signal_id: None,
29418            signal_name: None,
29419            signal_arguments: None,
29420            workflow_update_id: None,
29421            update_name: None,
29422            lease_owner: Some("rust-worker".to_string()),
29423        };
29424
29425        let initial = worker
29426            .execute_workflow_task(task(Vec::new()))
29427            .expect("initial timer task");
29428        assert_eq!(
29429            initial,
29430            vec![json!({"type": "start_timer", "delay_seconds": 5})]
29431        );
29432
29433        let activity_result =
29434            encode_value_envelope(&json!("done"), DEFAULT_CODEC).expect("activity result");
29435        let replayed = worker
29436            .execute_workflow_task(task(vec![
29437                history_event(
29438                    "TimerScheduled",
29439                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
29440                ),
29441                history_event(
29442                    "TimerFired",
29443                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
29444                ),
29445                history_event(
29446                    "ActivityCompleted",
29447                    json!({
29448                        "sequence": 2,
29449                        "activity_type": "after-timer",
29450                        "payload_codec": DEFAULT_CODEC,
29451                        "result": activity_result,
29452                    }),
29453                ),
29454            ]))
29455            .expect("replayed workflow task");
29456        assert_eq!(replayed.len(), 1);
29457        assert_eq!(replayed[0]["type"], "complete_workflow");
29458        assert_eq!(
29459            decode_wire_value(&replayed[0]["result"], DEFAULT_CODEC).expect("result"),
29460            json!("done")
29461        );
29462    }
29463
29464    #[test]
29465    fn workflow_continue_as_new_emits_arguments_type_and_queue_once() {
29466        let client = Client::new("http://127.0.0.1:8080").expect("client");
29467        let mut worker = Worker::new(client, "rust-workers");
29468        worker.register_workflow("rust.continue", |ctx, _input| async move {
29469            ctx.continue_as_new_with_options(
29470                ContinueAsNewOptions::new()
29471                    .workflow_type("rust.next")
29472                    .task_queue("next-workers"),
29473                json!([2, {"cursor": "next"}]),
29474            )
29475        });
29476
29477        let commands = worker
29478            .execute_workflow_task(workflow_task("rust.continue", Vec::new(), DEFAULT_CODEC))
29479            .expect("continue-as-new command");
29480
29481        assert_eq!(commands.len(), 1);
29482        assert_eq!(commands[0]["type"], "continue_as_new");
29483        assert_eq!(commands[0]["workflow_type"], "rust.next");
29484        assert_eq!(commands[0]["queue"], "next-workers");
29485        assert_eq!(
29486            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC)
29487                .expect("continue-as-new arguments"),
29488            json!([2, {"cursor": "next"}])
29489        );
29490    }
29491
29492    #[test]
29493    fn continue_as_new_preserves_typed_arguments() {
29494        let client = Client::new("http://127.0.0.1:8080").expect("client");
29495        let mut worker = Worker::new(client, "rust-workers");
29496        worker.register_workflow_avro_value("rust.typed-continue", |ctx, _input| async move {
29497            ctx.continue_as_new(AvroValue::Array(vec![typed_fidelity_probe()]))?;
29498            unreachable!("continue-as-new returns a control-flow error")
29499        });
29500
29501        let commands = worker
29502            .execute_workflow_task(workflow_task(
29503                "rust.typed-continue",
29504                Vec::new(),
29505                DEFAULT_CODEC,
29506            ))
29507            .expect("typed continue-as-new command");
29508
29509        assert_eq!(commands[0]["type"], "continue_as_new");
29510        assert_eq!(
29511            decode_wire_avro_value(&commands[0]["arguments"], DEFAULT_CODEC)
29512                .expect("typed continue arguments"),
29513            AvroValue::Array(vec![typed_fidelity_probe()])
29514        );
29515    }
29516
29517    #[test]
29518    fn recorded_continue_as_new_is_consumed_without_duplicate_successor_command() {
29519        let client = Client::new("http://127.0.0.1:8080").expect("client");
29520        let mut worker = Worker::new(client, "rust-workers");
29521        worker.register_workflow("rust.continue", |ctx, _input| async move {
29522            ctx.continue_as_new(json!([2]))
29523        });
29524        let task = workflow_task(
29525            "rust.continue",
29526            vec![history_event(
29527                "WorkflowContinuedAsNew",
29528                json!({"sequence": 1, "continued_to_run_id": "run-next"}),
29529            )],
29530            DEFAULT_CODEC,
29531        );
29532
29533        for _worker_restart_or_redelivery in 0..2 {
29534            let commands = worker
29535                .execute_workflow_task(task.clone())
29536                .expect("recorded transition replays");
29537            assert!(
29538                commands.is_empty(),
29539                "replay must not emit another successor"
29540            );
29541        }
29542    }
29543
29544    #[test]
29545    fn continue_as_new_rejects_invalid_overrides_before_emitting_a_command() {
29546        let ctx = workflow_context(Vec::new());
29547        let error = ctx
29548            .continue_as_new_with_options(ContinueAsNewOptions::new().task_queue("  "), json!([1]))
29549            .expect_err("blank queue must be rejected");
29550
29551        let Error::InvalidContinueAsNewOptions(error) = error else {
29552            panic!("expected typed continue-as-new validation error");
29553        };
29554        assert_eq!(error.field, "task_queue");
29555        assert!(ctx.take_commands().expect("commands").is_empty());
29556    }
29557
29558    #[test]
29559    fn workflow_context_exposes_server_history_budget() {
29560        let client = Client::new("http://127.0.0.1:8080").expect("client");
29561        let mut worker = Worker::new(client, "rust-workers");
29562        worker.register_workflow("rust.history-budget", |ctx, _input| async move {
29563            let budget = ctx.history_budget()?;
29564            Ok(json!({
29565                "events": budget.event_count,
29566                "bytes": budget.size_bytes,
29567                "recommended": budget.continue_as_new_recommended,
29568                "pressure": budget.pressure,
29569            }))
29570        });
29571        let task: WorkflowTask = serde_json::from_value(json!({
29572            "task_id": "task-history-budget",
29573            "workflow_type": "rust.history-budget",
29574            "payload_codec": DEFAULT_CODEC,
29575            "history_events": [],
29576            "total_history_events": 480,
29577            "history_size_bytes": 1_048_576,
29578            "continue_as_new_recommended": true,
29579            "history_budget_pressure": "continue_as_new_recommended",
29580        }))
29581        .expect("published workflow task");
29582
29583        let commands = worker
29584            .execute_workflow_task(task)
29585            .expect("history-budget workflow");
29586        let result = decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("result");
29587        assert_eq!(result["events"], 480);
29588        assert_eq!(result["bytes"], 1_048_576);
29589        assert_eq!(result["recommended"], true);
29590        assert_eq!(result["pressure"], "continue_as_new_recommended");
29591    }
29592
29593    #[test]
29594    fn uncaught_workflow_handler_error_emits_terminal_failure_command() {
29595        let client = Client::new("http://127.0.0.1:8080").expect("client");
29596        let mut worker = Worker::new(client, "rust-workers");
29597        worker.register_workflow("rust.failing", |_ctx, _input| async move {
29598            Err(Error::Codec("rust_conformance_failure".to_string()))
29599        });
29600        let task = WorkflowTask {
29601            task_id: "wft-rust-failing-1".to_string(),
29602            observability_context: None,
29603            dispatch_observability_context: None,
29604            observability_links: None,
29605            workflow_command_id: None,
29606            workflow_id: Some("wf-rust-failing".to_string()),
29607            run_id: Some("run-rust-failing".to_string()),
29608            workflow_type: "rust.failing".to_string(),
29609            cancel_requested: false,
29610            payload_codec: DEFAULT_CODEC.to_string(),
29611            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
29612            history_events: Vec::new(),
29613            total_history_events: Some(0),
29614            history_size_bytes: None,
29615            continue_as_new_recommended: None,
29616            history_budget_pressure: None,
29617            next_history_page_token: None,
29618            workflow_task_attempt: 1,
29619            workflow_signal_id: None,
29620            signal_name: None,
29621            signal_arguments: None,
29622            workflow_update_id: None,
29623            update_name: None,
29624            lease_owner: Some("rust-worker".to_string()),
29625        };
29626
29627        let commands = worker
29628            .execute_workflow_task(task)
29629            .expect("handler failure becomes a workflow command");
29630
29631        assert_eq!(commands.len(), 1);
29632        assert_eq!(commands[0]["type"], "fail_workflow");
29633        assert_eq!(commands[0]["exception_type"], "RustWorkflowError");
29634        assert_eq!(commands[0]["exception_class"], "durable_workflow::Error");
29635        assert_eq!(commands[0]["non_retryable"], false);
29636        assert_eq!(
29637            commands[0]["message"],
29638            "codec error: rust_conformance_failure"
29639        );
29640        assert_eq!(
29641            commands[0]["exception"]["message"],
29642            "codec error: rust_conformance_failure"
29643        );
29644    }
29645
29646    #[test]
29647    fn ordinary_handler_error_preserves_commands_queued_in_the_same_decision() {
29648        let client = Client::new("http://127.0.0.1:8080").expect("client");
29649        let mut worker = Worker::new(client, "rust-workers");
29650        worker.register_workflow("rust.failing-after-side-effect", |ctx, _input| async move {
29651            let _: String = ctx.side_effect(|| "captured".to_string())?;
29652            Err(Error::WorkerLoop("application failure".to_string()))
29653        });
29654
29655        let commands = worker
29656            .execute_workflow_task(workflow_task(
29657                "rust.failing-after-side-effect",
29658                Vec::new(),
29659                DEFAULT_CODEC,
29660            ))
29661            .expect("ordinary failure remains a workflow decision");
29662
29663        assert_eq!(commands.len(), 2);
29664        assert_eq!(commands[0]["type"], "record_side_effect");
29665        assert_eq!(commands[1]["type"], "fail_workflow");
29666    }
29667
29668    #[test]
29669    fn uncaught_recorded_activity_failure_claims_only_its_persisted_boundary() {
29670        let client = Client::new("http://127.0.0.1:8080").expect("client");
29671        let mut worker = Worker::new(client, "rust-workers");
29672        worker.register_workflow("rust.redrive", |ctx, _input| async move {
29673            ctx.activity("greet", json!([])).await?;
29674            Ok(Value::Null)
29675        });
29676        worker.register_workflow("rust.redrive-translated", |ctx, _input| async move {
29677            match ctx.activity("greet", json!([])).await {
29678                Err(Error::ActivityFailed(_)) => Err(Error::WorkerLoop("translated".to_string())),
29679                result => result,
29680            }
29681        });
29682
29683        let failed = history_event(
29684            "ActivityFailed",
29685            json!({
29686                "sequence": 1,
29687                "activity_type": "greet",
29688                "activity_execution_id": "activity-1",
29689                "message": "failed"
29690            }),
29691        );
29692        let commands = worker
29693            .execute_workflow_task(workflow_task(
29694                "rust.redrive",
29695                vec![failed.clone()],
29696                DEFAULT_CODEC,
29697            ))
29698            .expect("recorded failure becomes a workflow command");
29699        assert_eq!(commands[0]["type"], "fail_workflow");
29700        assert_eq!(commands[0]["failed_step_sequence"], 1);
29701        assert_eq!(commands[0]["failed_activity_execution_id"], "activity-1");
29702
29703        let translated = worker
29704            .execute_workflow_task(workflow_task(
29705                "rust.redrive-translated",
29706                vec![failed],
29707                DEFAULT_CODEC,
29708            ))
29709            .expect("translated failure becomes a workflow command");
29710        assert_eq!(translated[0]["type"], "fail_workflow");
29711        assert!(translated[0].get("failed_step_sequence").is_none());
29712        assert!(translated[0].get("failed_activity_execution_id").is_none());
29713
29714        let without_identity = worker
29715            .execute_workflow_task(workflow_task(
29716                "rust.redrive",
29717                vec![history_event(
29718                    "ActivityFailed",
29719                    json!({"sequence": 1, "activity_type": "greet", "message": "failed"}),
29720                )],
29721                DEFAULT_CODEC,
29722            ))
29723            .expect("incomplete identity still fails the workflow");
29724        assert!(without_identity[0].get("failed_step_sequence").is_none());
29725
29726        let timed_out = worker
29727            .execute_workflow_task(workflow_task(
29728                "rust.redrive",
29729                vec![history_event(
29730                    "ActivityTimedOut",
29731                    json!({
29732                        "sequence": 1,
29733                        "activity_type": "greet",
29734                        "activity_execution_id": "activity-timeout",
29735                    }),
29736                )],
29737                DEFAULT_CODEC,
29738            ))
29739            .expect("timeout still fails the workflow");
29740        assert!(timed_out[0].get("failed_step_sequence").is_none());
29741    }
29742
29743    #[test]
29744    fn redriven_history_reuses_completed_prefix_and_reschedules_only_failed_step() {
29745        let client = Client::new("http://127.0.0.1:8080").expect("client");
29746        let mut worker = Worker::new(client, "rust-workers");
29747        worker.register_workflow("rust.redrive-successor", |ctx, _input| async move {
29748            let first = ctx.activity("first", json!([])).await?;
29749            let second = ctx.activity("second", json!([first.clone()])).await?;
29750            Ok(json!({"first": first, "second": second}))
29751        });
29752        let first = history_event(
29753            "ActivityCompleted",
29754            json!({
29755                "sequence": 1,
29756                "activity_type": "first",
29757                "result": encode_value_envelope(&json!("recorded"), DEFAULT_CODEC).expect("first result"),
29758                "payload_codec": DEFAULT_CODEC,
29759                "reused_from_run_id": "failed-run",
29760                "reused_activity_execution_id": "original-first",
29761            }),
29762        );
29763
29764        let retry = worker
29765            .execute_workflow_task(workflow_task(
29766                "rust.redrive-successor",
29767                vec![first.clone()],
29768                DEFAULT_CODEC,
29769            ))
29770            .expect("reused result replays before failed step");
29771        assert_eq!(retry.len(), 1);
29772        assert_eq!(retry[0]["type"], "schedule_activity");
29773        assert_eq!(retry[0]["activity_type"], "second");
29774        assert_eq!(
29775            decode_wire_value(&retry[0]["arguments"], DEFAULT_CODEC).expect("second arguments"),
29776            json!(["recorded"]),
29777        );
29778
29779        let second = history_event(
29780            "ActivityCompleted",
29781            json!({
29782                "sequence": 2,
29783                "activity_type": "second",
29784                "result": encode_value_envelope(&json!("retried"), DEFAULT_CODEC).expect("second result"),
29785                "payload_codec": DEFAULT_CODEC,
29786            }),
29787        );
29788        let completed = worker
29789            .execute_workflow_task(workflow_task(
29790                "rust.redrive-successor",
29791                vec![first, second],
29792                DEFAULT_CODEC,
29793            ))
29794            .expect("retried step completes the successor");
29795        assert_eq!(completed.len(), 1);
29796        assert_eq!(completed[0]["type"], "complete_workflow");
29797        assert_eq!(
29798            decode_wire_value(&completed[0]["result"], DEFAULT_CODEC).expect("workflow result"),
29799            json!({"first": "recorded", "second": "retried"}),
29800        );
29801    }
29802
29803    #[test]
29804    fn handler_error_cannot_hide_an_unconsumed_committed_side_effect() {
29805        let client = Client::new("http://127.0.0.1:8080").expect("client");
29806        let mut worker = Worker::new(client, "rust-workers");
29807        worker.register_workflow("rust.removed-side-effect", |_ctx, _input| async move {
29808            Err(Error::WorkerLoop("application failure".to_string()))
29809        });
29810        let result =
29811            encode_value_envelope(&json!("committed"), DEFAULT_CODEC).expect("side-effect result");
29812
29813        let error = worker
29814            .execute_workflow_task(workflow_task(
29815                "rust.removed-side-effect",
29816                vec![history_event(
29817                    "SideEffectRecorded",
29818                    json!({"sequence": 1, "result": result}),
29819                )],
29820                DEFAULT_CODEC,
29821            ))
29822            .expect_err("removed committed history must not become fail_workflow");
29823
29824        let Error::NonDeterministicReplay(failure) = error else {
29825            panic!("expected typed replay failure");
29826        };
29827        assert_eq!(failure.reason, "recorded_commands_unconsumed");
29828        assert_eq!(failure.sequence, Some(1));
29829        assert_eq!(failure.expected.as_deref(), Some("side effect"));
29830    }
29831
29832    #[test]
29833    fn replay_error_discards_side_effect_queued_before_incompatible_marker_check() {
29834        let client = Client::new("http://127.0.0.1:8080").expect("client");
29835        let mut worker = Worker::new(client, "rust-workers");
29836        worker.register_workflow(
29837            "rust.side-effect-before-marker-error",
29838            |ctx, _input| async move {
29839                assert_eq!(ctx.get_version("restart-safe", 1, 1)?, 1);
29840                let _: String = ctx.side_effect(|| "must-not-commit".to_string())?;
29841                ctx.get_version("restart-safe", 2, 2)?;
29842                Ok(Value::Null)
29843            },
29844        );
29845
29846        let error = worker
29847            .execute_workflow_task(workflow_task(
29848                "rust.side-effect-before-marker-error",
29849                vec![history_event(
29850                    "VersionMarkerRecorded",
29851                    json!({
29852                        "sequence": 1,
29853                        "change_id": "restart-safe",
29854                        "version": 1,
29855                        "min_supported": 1,
29856                        "max_supported": 1,
29857                    }),
29858                )],
29859                DEFAULT_CODEC,
29860            ))
29861            .expect_err("replay error must return no queued workflow commands");
29862
29863        let Error::NonDeterministicReplay(failure) = error else {
29864            panic!("expected typed replay failure");
29865        };
29866        assert_eq!(failure.reason, "version_marker_incompatible_range");
29867        assert_eq!(failure.sequence, Some(1));
29868    }
29869
29870    #[test]
29871    fn workflow_task_replay_keeps_recorded_unfired_timer_pending_without_rescheduling() {
29872        let client = Client::new("http://127.0.0.1:8080").expect("client");
29873        let mut worker = Worker::new(client, "rust-workers");
29874        worker.register_workflow("rust.timer.pending", |ctx, _input| async move {
29875            ctx.sleep(Duration::from_secs(5)).await?;
29876            Ok(json!({"status": "timer fired"}))
29877        });
29878
29879        let task = WorkflowTask {
29880            task_id: "wft-rust-timer-pending".to_string(),
29881            observability_context: None,
29882            dispatch_observability_context: None,
29883            observability_links: None,
29884            workflow_command_id: None,
29885            workflow_id: Some("wf-rust-timer".to_string()),
29886            run_id: Some("run-rust-timer".to_string()),
29887            workflow_type: "rust.timer.pending".to_string(),
29888            cancel_requested: false,
29889            payload_codec: DEFAULT_CODEC.to_string(),
29890            arguments: Some(
29891                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
29892            ),
29893            history_events: vec![history_event(
29894                "TimerScheduled",
29895                json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
29896            )],
29897            total_history_events: Some(1),
29898            history_size_bytes: None,
29899            continue_as_new_recommended: None,
29900            history_budget_pressure: None,
29901            next_history_page_token: None,
29902            workflow_task_attempt: 1,
29903            workflow_signal_id: None,
29904            signal_name: None,
29905            signal_arguments: None,
29906            workflow_update_id: None,
29907            update_name: None,
29908            lease_owner: Some("rust-worker".to_string()),
29909        };
29910
29911        for _redelivery_or_restart in 0..2 {
29912            let commands = worker
29913                .execute_workflow_task(task.clone())
29914                .expect("recorded timer remains pending");
29915            assert!(
29916                commands.is_empty(),
29917                "recorded timer must not be rescheduled"
29918            );
29919        }
29920    }
29921
29922    #[test]
29923    fn workflow_task_rejects_recorded_command_removed_from_workflow_code() {
29924        let client = Client::new("http://127.0.0.1:8080").expect("client");
29925        let mut worker = Worker::new(client, "rust-workers");
29926        worker.register_workflow("rust.timer.removed", |_ctx, _input| async move {
29927            Ok(json!({"status": "completed"}))
29928        });
29929        let task = WorkflowTask {
29930            task_id: "wft-rust-timer-removed".to_string(),
29931            observability_context: None,
29932            dispatch_observability_context: None,
29933            observability_links: None,
29934            workflow_command_id: None,
29935            workflow_id: Some("wf-rust-timer".to_string()),
29936            run_id: Some("run-rust-timer".to_string()),
29937            workflow_type: "rust.timer.removed".to_string(),
29938            cancel_requested: false,
29939            payload_codec: DEFAULT_CODEC.to_string(),
29940            arguments: Some(
29941                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
29942            ),
29943            history_events: vec![
29944                history_event(
29945                    "TimerScheduled",
29946                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
29947                ),
29948                history_event(
29949                    "TimerFired",
29950                    json!({"sequence": 1, "timer_id": "timer-1", "delay_seconds": 5}),
29951                ),
29952            ],
29953            total_history_events: Some(2),
29954            history_size_bytes: None,
29955            continue_as_new_recommended: None,
29956            history_budget_pressure: None,
29957            next_history_page_token: None,
29958            workflow_task_attempt: 1,
29959            workflow_signal_id: None,
29960            signal_name: None,
29961            signal_arguments: None,
29962            workflow_update_id: None,
29963            update_name: None,
29964            lease_owner: Some("rust-worker".to_string()),
29965        };
29966
29967        let Error::NonDeterministicReplay(failure) = worker
29968            .execute_workflow_task(task)
29969            .expect_err("removed timer must fail replay")
29970        else {
29971            panic!("expected typed replay failure");
29972        };
29973        assert_eq!(failure.reason, "recorded_commands_unconsumed");
29974        assert_eq!(failure.sequence, Some(1));
29975    }
29976
29977    #[test]
29978    fn workflow_context_emits_explicit_child_workflow_contract() {
29979        let ctx = WorkflowContext {
29980            cancellation_scope_id: "root".into(),
29981            state: Arc::new(Mutex::new(
29982                WorkflowState::new_with_identity(
29983                    Vec::new(),
29984                    Some("wf-parent".to_string()),
29985                    Some("run-parent".to_string()),
29986                    "parent-workers".to_string(),
29987                    DEFAULT_CODEC.to_string(),
29988                    None,
29989                )
29990                .expect("workflow state"),
29991            )),
29992        };
29993        let options = ChildWorkflowOptions::new("python-workers")
29994            .parent_close_policy(ParentClosePolicy::RequestCancel)
29995            .retry_policy(ChildWorkflowRetryPolicy {
29996                max_attempts: Some(3),
29997                backoff_seconds: vec![1, 5],
29998                non_retryable_error_types: vec!["ValidationError".to_string()],
29999            })
30000            .execution_timeout_seconds(600)
30001            .run_timeout_seconds(120);
30002        let mut call = Box::pin(ctx.start_child_workflow(
30003            "python.fulfil-order",
30004            options,
30005            json!([{"order_id": "order-42"}]),
30006        ));
30007        let mut task_context = TaskContext::from_waker(noop_waker_ref());
30008
30009        assert!(matches!(
30010            call.as_mut().poll(&mut task_context),
30011            Poll::Pending
30012        ));
30013        let commands = ctx.take_commands().expect("commands");
30014        assert_eq!(commands.len(), 1);
30015        let command = &commands[0];
30016        assert_eq!(command["type"], "start_child_workflow");
30017        assert_eq!(command["workflow_type"], "python.fulfil-order");
30018        assert_eq!(command["queue"], "python-workers");
30019        assert_eq!(command["parent_close_policy"], "request_cancel");
30020        assert_eq!(command["retry_policy"]["max_attempts"], 3);
30021        assert_eq!(command["execution_timeout_seconds"], 600);
30022        assert_eq!(command["run_timeout_seconds"], 120);
30023        assert_eq!(
30024            decode_wire_value(&command["arguments"], DEFAULT_CODEC).expect("child args"),
30025            json!([{"order_id": "order-42"}])
30026        );
30027    }
30028
30029    fn child_parent_worker() -> Worker {
30030        let client = Client::new("http://127.0.0.1:8080").expect("client");
30031        let mut worker = Worker::new(client, "rust-parent-workers");
30032        worker.register_workflow("rust.parent", |ctx, _input| async move {
30033            let child = ctx
30034                .start_child_workflow(
30035                    "python.child",
30036                    ChildWorkflowOptions::new("python-child-workers")
30037                        .parent_close_policy(ParentClosePolicy::Terminate),
30038                    json!([{"codec_probe": [1, true, "rust"]}]),
30039                )
30040                .await?;
30041            Ok(json!({
30042                "parent_workflow_id": child.parent.workflow_id,
30043                "parent_run_id": child.parent.run_id,
30044                "child_workflow_id": child.child.workflow_id,
30045                "child_run_id": child.child.run_id,
30046                "child_workflow_type": child.child_workflow_type,
30047                "result": child.result,
30048            }))
30049        });
30050        worker
30051    }
30052
30053    fn child_parent_task(event_type: &str, payload: Value) -> WorkflowTask {
30054        WorkflowTask {
30055            task_id: "wft-child-parent".to_string(),
30056            observability_context: None,
30057            dispatch_observability_context: None,
30058            observability_links: None,
30059            workflow_command_id: None,
30060            workflow_id: Some("wf-parent".to_string()),
30061            run_id: Some("run-parent".to_string()),
30062            workflow_type: "rust.parent".to_string(),
30063            cancel_requested: false,
30064            payload_codec: DEFAULT_CODEC.to_string(),
30065            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
30066            history_events: vec![
30067                HistoryEvent {
30068                    event_type: "ChildWorkflowScheduled".to_string(),
30069                    payload: json!({
30070                        "sequence": 1,
30071                        "child_call_id": "call-child",
30072                        "child_workflow_instance_id": "wf-child",
30073                        "child_workflow_run_id": "run-child",
30074                        "child_workflow_type": "python.child",
30075                        "parent_close_policy": "terminate",
30076                    }),
30077                    raw: HashMap::new(),
30078                },
30079                HistoryEvent {
30080                    event_type: event_type.to_string(),
30081                    payload,
30082                    raw: HashMap::new(),
30083                },
30084            ],
30085            total_history_events: Some(2),
30086            history_size_bytes: None,
30087            continue_as_new_recommended: None,
30088            history_budget_pressure: None,
30089            next_history_page_token: None,
30090            workflow_task_attempt: 1,
30091            workflow_signal_id: None,
30092            signal_name: None,
30093            signal_arguments: None,
30094            workflow_update_id: None,
30095            update_name: None,
30096            lease_owner: Some("rust-worker".to_string()),
30097        }
30098    }
30099
30100    #[test]
30101    fn committed_child_result_replays_without_starting_a_duplicate() {
30102        let worker = child_parent_worker();
30103        let task = child_parent_task(
30104            "ChildRunCompleted",
30105            json!({
30106                "sequence": 1,
30107                "child_call_id": "call-child",
30108                "child_workflow_instance_id": "wf-child",
30109                "child_workflow_run_id": "run-child",
30110                "child_workflow_type": "python.child",
30111                "payload_codec": DEFAULT_CODEC,
30112                "result": fixture_envelope(json!({"from":"python","ok":true})),
30113            }),
30114        );
30115
30116        for _restart in 0..2 {
30117            let commands = worker
30118                .execute_workflow_task(task.clone())
30119                .expect("replayed parent task");
30120            assert_eq!(commands.len(), 1);
30121            assert_eq!(commands[0]["type"], "complete_workflow");
30122            assert!(!commands
30123                .iter()
30124                .any(|command| command["type"] == "start_child_workflow"));
30125            let output =
30126                decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
30127            assert_eq!(output["parent_workflow_id"], "wf-parent");
30128            assert_eq!(output["parent_run_id"], "run-parent");
30129            assert_eq!(output["child_workflow_id"], "wf-child");
30130            assert_eq!(output["child_run_id"], "run-child");
30131            assert_eq!(output["result"], json!({"from": "python", "ok": true}));
30132        }
30133    }
30134
30135    #[test]
30136    fn typed_child_arguments_and_results_survive_replay() {
30137        let client = Client::new("http://127.0.0.1:8080").expect("client");
30138        let mut worker = Worker::new(client, "rust-parent-workers");
30139        worker.register_workflow_avro_value("rust.typed-parent", |ctx, _input| async move {
30140            let child = ctx
30141                .start_child_workflow_avro_value(
30142                    "python.typed-child",
30143                    ChildWorkflowOptions::new("python-workers"),
30144                    AvroValue::Array(vec![typed_fidelity_probe()]),
30145                )
30146                .await?;
30147            Ok(child.result)
30148        });
30149
30150        let initial = worker
30151            .execute_workflow_task(workflow_task(
30152                "rust.typed-parent",
30153                Vec::new(),
30154                DEFAULT_CODEC,
30155            ))
30156            .expect("typed child start");
30157        assert_eq!(initial[0]["type"], "start_child_workflow");
30158        assert_eq!(
30159            decode_wire_avro_value(&initial[0]["arguments"], DEFAULT_CODEC)
30160                .expect("typed child arguments"),
30161            AvroValue::Array(vec![typed_fidelity_probe()])
30162        );
30163
30164        let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
30165            .expect("typed child result");
30166        let task = workflow_task(
30167            "rust.typed-parent",
30168            vec![
30169                history_event(
30170                    "ChildWorkflowScheduled",
30171                    json!({
30172                        "sequence": 1,
30173                        "child_call_id": "call-typed",
30174                        "child_workflow_instance_id": "wf-child",
30175                        "child_workflow_run_id": "run-child",
30176                        "child_workflow_type": "python.typed-child",
30177                    }),
30178                ),
30179                history_event(
30180                    "ChildRunCompleted",
30181                    json!({
30182                        "sequence": 1,
30183                        "child_call_id": "call-typed",
30184                        "child_workflow_instance_id": "wf-child",
30185                        "child_workflow_run_id": "run-child",
30186                        "child_workflow_type": "python.typed-child",
30187                        "payload_codec": DEFAULT_CODEC,
30188                        "result": result,
30189                    }),
30190                ),
30191            ],
30192            DEFAULT_CODEC,
30193        );
30194
30195        let commands = worker
30196            .execute_workflow_task(task)
30197            .expect("typed child replay");
30198        assert_eq!(commands[0]["type"], "complete_workflow");
30199        assert_eq!(
30200            decode_wire_avro_value(&commands[0]["result"], DEFAULT_CODEC)
30201                .expect("typed parent result"),
30202            typed_fidelity_probe()
30203        );
30204    }
30205
30206    #[test]
30207    fn pending_child_replays_after_restart_without_starting_a_duplicate() {
30208        let worker = child_parent_worker();
30209        let mut task = child_parent_task("unused", Value::Null);
30210        task.history_events.truncate(1);
30211        task.total_history_events = Some(1);
30212
30213        for _redelivery_or_restart in 0..2 {
30214            let commands = worker
30215                .execute_workflow_task(task.clone())
30216                .expect("recorded child remains pending");
30217            assert!(
30218                commands.is_empty(),
30219                "recorded pending child must not be started again"
30220            );
30221        }
30222    }
30223
30224    #[test]
30225    fn child_cancellation_becomes_stable_parent_failure_command() {
30226        let worker = child_parent_worker();
30227        let task = child_parent_task(
30228            "ChildRunCancelled",
30229            json!({
30230                "sequence": 1,
30231                "child_workflow_instance_id": "wf-child",
30232                "child_workflow_run_id": "run-child",
30233                "child_workflow_type": "python.child",
30234                "failure_id": "failure-child",
30235                "failure_category": "cancelled",
30236                "message": "cancelled by parent-close policy",
30237            }),
30238        );
30239
30240        let commands = worker
30241            .execute_workflow_task(task)
30242            .expect("parent settlement");
30243        assert_eq!(commands.len(), 1);
30244        assert_eq!(commands[0]["type"], "fail_workflow");
30245        assert_eq!(commands[0]["exception_type"], "ChildWorkflowCancelled");
30246        assert_eq!(
30247            commands[0]["exception"]["properties"]["reason"],
30248            "cancelled"
30249        );
30250        assert_eq!(
30251            commands[0]["exception"]["properties"]["child_workflow_run_id"],
30252            "run-child"
30253        );
30254    }
30255
30256    #[test]
30257    fn workflow_can_handle_typed_child_failure() {
30258        let client = Client::new("http://127.0.0.1:8080").expect("client");
30259        let mut worker = Worker::new(client, "rust-parent-workers");
30260        worker.register_workflow("rust.handled-parent", |ctx, _input| async move {
30261            match ctx
30262                .start_child_workflow(
30263                    "python.child",
30264                    ChildWorkflowOptions::new("python-child-workers"),
30265                    json!([]),
30266                )
30267                .await
30268            {
30269                Err(Error::ChildWorkflowFailed(failure)) => Ok(json!({
30270                    "reason": failure.reason,
30271                    "failure_id": failure.failure_id,
30272                    "exception_class": failure.exception_class,
30273                    "child_run_id": failure.child_workflow_run_id,
30274                })),
30275                Err(error) => Err(error),
30276                Ok(_) => Err(Error::WorkerLoop(
30277                    "child unexpectedly succeeded".to_string(),
30278                )),
30279            }
30280        });
30281        let mut task = child_parent_task(
30282            "ChildRunFailed",
30283            json!({
30284                "sequence": 1,
30285                "child_workflow_instance_id": "wf-child",
30286                "child_workflow_run_id": "run-child",
30287                "child_workflow_type": "python.child",
30288                "failure_id": "failure-child",
30289                "failure_category": "child_workflow",
30290                "message": "payment rejected",
30291                "exception": {
30292                    "type": "PaymentRejected",
30293                    "class": "payments.PaymentRejected",
30294                    "message": "payment rejected"
30295                }
30296            }),
30297        );
30298        task.workflow_type = "rust.handled-parent".to_string();
30299        task.history_events[0].payload["parent_close_policy"] = json!("abandon");
30300
30301        let commands = worker.execute_workflow_task(task).expect("handled failure");
30302        assert_eq!(commands[0]["type"], "complete_workflow");
30303        let output =
30304            decode_wire_value(&commands[0]["result"], DEFAULT_CODEC).expect("parent output");
30305        assert_eq!(output["reason"], "child_workflow");
30306        assert_eq!(output["failure_id"], "failure-child");
30307        assert_eq!(output["exception_class"], "payments.PaymentRejected");
30308        assert_eq!(output["child_run_id"], "run-child");
30309    }
30310
30311    #[test]
30312    fn rust_hello_world_uses_signal_arguments_from_resume_payload() {
30313        let client = Client::new("http://127.0.0.1:8080").expect("client");
30314        let mut worker = Worker::new(client, "rust-workers");
30315
30316        worker.register_workflow("rust.hello_workflow", |ctx, _input| async move {
30317            let signal = ctx.wait_signal("start").await?;
30318            let name = signal
30319                .first()
30320                .and_then(|value| value.as_str())
30321                .unwrap_or("world");
30322            let greeting = ctx.activity("rust.hello_activity", json!([name])).await?;
30323            Ok(json!({
30324                "greeting": greeting,
30325                "language": "rust"
30326            }))
30327        });
30328
30329        let signal_arguments =
30330            encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC).expect("signal arguments");
30331        let task = WorkflowTask {
30332            task_id: "wft-rust-signal-1".to_string(),
30333            observability_context: None,
30334            dispatch_observability_context: None,
30335            observability_links: None,
30336            workflow_command_id: None,
30337            workflow_id: Some("wf-rust-hello".to_string()),
30338            run_id: Some("run-rust-hello".to_string()),
30339            workflow_type: "rust.hello_workflow".to_string(),
30340            cancel_requested: false,
30341            payload_codec: DEFAULT_CODEC.to_string(),
30342            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
30343            history_events: vec![HistoryEvent {
30344                event_type: "SignalReceived".to_string(),
30345                payload: json!({
30346                    "signal_id": "sig-rust-1",
30347                    "signal_name": "start"
30348                }),
30349                raw: HashMap::new(),
30350            }],
30351            total_history_events: Some(1),
30352            history_size_bytes: None,
30353            continue_as_new_recommended: None,
30354            history_budget_pressure: None,
30355            next_history_page_token: None,
30356            workflow_task_attempt: 1,
30357            workflow_signal_id: Some("sig-rust-1".to_string()),
30358            signal_name: Some("start".to_string()),
30359            signal_arguments: Some(signal_arguments),
30360            workflow_update_id: None,
30361            update_name: None,
30362            lease_owner: Some("rust-worker".to_string()),
30363        };
30364
30365        let commands = worker.execute_workflow_task(task).expect("workflow task");
30366
30367        assert_eq!(commands.len(), 1);
30368        assert_eq!(commands[0]["type"], "schedule_activity");
30369        assert_eq!(commands[0]["activity_type"], "rust.hello_activity");
30370        assert_eq!(
30371            decode_wire_value(&commands[0]["arguments"], DEFAULT_CODEC).expect("activity args"),
30372            json!(["Rust"])
30373        );
30374    }
30375
30376    #[test]
30377    fn workflow_task_appends_paginated_history_events() {
30378        let mut task = WorkflowTask {
30379            task_id: "wft-rust-pages-1".to_string(),
30380            observability_context: None,
30381            dispatch_observability_context: None,
30382            observability_links: None,
30383            workflow_command_id: None,
30384            workflow_id: Some("wf-rust-pages".to_string()),
30385            run_id: Some("run-rust-pages".to_string()),
30386            workflow_type: "rust.hello_workflow".to_string(),
30387            cancel_requested: false,
30388            payload_codec: DEFAULT_CODEC.to_string(),
30389            arguments: Some(encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("input")),
30390            history_events: vec![HistoryEvent {
30391                event_type: "WorkflowStarted".to_string(),
30392                payload: json!({}),
30393                raw: HashMap::new(),
30394            }],
30395            total_history_events: Some(3),
30396            history_size_bytes: None,
30397            continue_as_new_recommended: None,
30398            history_budget_pressure: None,
30399            next_history_page_token: Some("MQ==".to_string()),
30400            workflow_task_attempt: 1,
30401            workflow_signal_id: None,
30402            signal_name: None,
30403            signal_arguments: None,
30404            workflow_update_id: None,
30405            update_name: None,
30406            lease_owner: Some("rust-worker".to_string()),
30407        };
30408
30409        task.append_history_page(WorkflowTaskHistoryPage {
30410            history_events: vec![
30411                HistoryEvent {
30412                    event_type: "SignalReceived".to_string(),
30413                    payload: json!({
30414                        "signal_id": "sig-rust-1",
30415                        "signal_name": "start",
30416                        "arguments": encode_value_envelope(&json!(["Rust"]), DEFAULT_CODEC)
30417                            .expect("signal arguments")
30418                    }),
30419                    raw: HashMap::new(),
30420                },
30421                HistoryEvent {
30422                    event_type: "MarkerRecorded".to_string(),
30423                    payload: json!({"sequence": 3}),
30424                    raw: HashMap::new(),
30425                },
30426            ],
30427            total_history_events: Some(3),
30428            next_history_page_token: None,
30429        });
30430
30431        assert_eq!(task.history_events.len(), 3);
30432        assert_eq!(task.total_history_events, Some(3));
30433        assert_eq!(task.next_history_page_token, None);
30434
30435        let signal = task
30436            .history_events
30437            .iter()
30438            .find(|event| event.event_type == "SignalReceived")
30439            .expect("signal event");
30440        assert_eq!(
30441            decode_signal_event_arguments(signal, DEFAULT_CODEC).expect("signal arguments"),
30442            vec![AvroValue::String("Rust".to_string())]
30443        );
30444    }
30445
30446    #[tokio::test]
30447    async fn query_handler_reads_ordered_cross_codec_signals_without_commands() {
30448        let client = Client::new("http://127.0.0.1:8080").expect("client");
30449        let mut worker = Worker::new(client, "rust-workers");
30450        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
30451        worker.register_query("counter", "current", |ctx, _args| async move {
30452            let mut count = 0_i64;
30453            for signal in ctx.signal_events() {
30454                let value = signal
30455                    .arguments
30456                    .first()
30457                    .and_then(Value::as_i64)
30458                    .unwrap_or_default();
30459                match signal.name.as_str() {
30460                    "increment" => count += value,
30461                    "set" => count = value,
30462                    _ => {}
30463                }
30464            }
30465            Ok(json!(count))
30466        });
30467
30468        let task = QueryTask {
30469            query_task_id: "query-rust-counter".to_string(),
30470            observability_context: None,
30471            dispatch_observability_context: None,
30472            observability_links: None,
30473            query_task_attempt: 1,
30474            lease_owner: Some("rust-worker".to_string()),
30475            workflow_id: Some("counter-1".to_string()),
30476            run_id: Some("run-counter-1".to_string()),
30477            workflow_type: "counter".to_string(),
30478            query_name: "current".to_string(),
30479            payload_codec: DEFAULT_CODEC.to_string(),
30480            workflow_arguments: Some(
30481                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("workflow input"),
30482            ),
30483            query_arguments: Some(
30484                encode_value_envelope(&json!([]), DEFAULT_CODEC).expect("query arguments"),
30485            ),
30486            history_events: vec![
30487                HistoryEvent {
30488                    event_type: "SignalReceived".to_string(),
30489                    payload: json!({
30490                        "signal_id": "php-signal-1",
30491                        "signal_name": "increment",
30492                        "workflow_sequence": 1,
30493                        "payload_codec": DEFAULT_CODEC,
30494                        "arguments": encode_value_envelope(&json!([3]), DEFAULT_CODEC).expect("php avro signal")
30495                    }),
30496                    raw: HashMap::new(),
30497                },
30498                HistoryEvent {
30499                    event_type: "SignalReceived".to_string(),
30500                    payload: json!({
30501                        "signal_id": "python-signal-2",
30502                        "signal_name": "increment",
30503                        "workflow_sequence": 2,
30504                        "payload_codec": DEFAULT_CODEC,
30505                        "arguments": encode_value_envelope(&json!([5]), DEFAULT_CODEC).expect("python avro signal")
30506                    }),
30507                    raw: HashMap::new(),
30508                },
30509                HistoryEvent {
30510                    event_type: "SignalReceived".to_string(),
30511                    payload: json!({
30512                        "signal_id": "rust-signal-3",
30513                        "signal_name": "set",
30514                        "workflow_sequence": 3,
30515                        "payload_codec": DEFAULT_CODEC,
30516                        "arguments": encode_value_envelope(&json!([0]), DEFAULT_CODEC).expect("rust avro signal")
30517                    }),
30518                    raw: HashMap::new(),
30519                },
30520            ],
30521            history_export: None,
30522            run_status: Some("completed".to_string()),
30523        };
30524
30525        let result = worker.execute_query_task(task).await.expect("query result");
30526        assert_eq!(result.into_json().expect("query projection"), json!(0));
30527    }
30528
30529    #[tokio::test]
30530    async fn replayed_queries_read_running_completed_and_cold_restarted_instance_state() {
30531        let worker = replay_counter_worker();
30532        let running_history = json!([
30533            {
30534                "type": "ActivityCompleted",
30535                "payload": {
30536                    "sequence": 1,
30537                    "activity_type": "load-counter",
30538                    "payload_codec": DEFAULT_CODEC,
30539                    "result": fixture_envelope(json!("loaded"))
30540                }
30541            },
30542            {
30543                "type": "SignalWaitOpened",
30544                "payload": {
30545                    "sequence": 3,
30546                    "signal_name": "increment"
30547                }
30548            },
30549            {
30550                "type": "SignalReceived",
30551                "payload": {
30552                    "signal_id": "signal-3",
30553                    "signal_name": "increment",
30554                    "workflow_sequence": 2,
30555                    "payload_codec": DEFAULT_CODEC,
30556                    "arguments": fixture_envelope(json!([3]))
30557                }
30558            },
30559            {
30560                "type": "SignalApplied",
30561                "payload": {
30562                    "sequence": 3,
30563                    "signal_id": "signal-3",
30564                    "signal_name": "increment",
30565                    "payload_codec": DEFAULT_CODEC,
30566                    "value": fixture_envelope(json!([3]))
30567                }
30568            }
30569        ]);
30570
30571        let running = worker
30572            .execute_query_task(replay_counter_query(
30573                "current",
30574                running_history.clone(),
30575                "running",
30576            ))
30577            .await
30578            .expect("running replay query");
30579        assert_eq!(
30580            running.clone().into_json().expect("query projection"),
30581            json!({"loaded": "loaded", "count": 3, "finished": false})
30582        );
30583
30584        let detached = worker
30585            .execute_query_task(replay_counter_query(
30586                "detached-mutation",
30587                running_history.clone(),
30588                "running",
30589            ))
30590            .await
30591            .expect("query mutates only its detached state clone");
30592        assert_eq!(detached.into_json().expect("query projection"), json!(999));
30593        let failed = worker
30594            .execute_query_task(replay_counter_query(
30595                "failed-mutation",
30596                running_history.clone(),
30597                "running",
30598            ))
30599            .await
30600            .expect_err("failed query");
30601        assert_eq!(failed.reason, "query_rejected");
30602        let unchanged = worker
30603            .execute_query_task(replay_counter_query("current", running_history, "running"))
30604            .await
30605            .expect("later query reconstructs unchanged state");
30606        assert_eq!(unchanged, running);
30607
30608        let restarted_worker = replay_counter_worker();
30609        let empty_arguments = fixture_envelope(json!([]));
30610        let loaded_result = fixture_envelope(json!("loaded"));
30611        let signal_three = fixture_blob(json!([3]));
30612        let signal_five = fixture_blob(json!([5]));
30613        let restarted_task: QueryTask = serde_json::from_value(json!({
30614            "query_task_id": "query-after-restart",
30615            "workflow_id": "counter-1",
30616            "run_id": "run-counter-1",
30617            "workflow_type": "replay-counter",
30618            "query_name": "current",
30619            "payload_codec": DEFAULT_CODEC,
30620            "workflow_arguments": empty_arguments.clone(),
30621            "query_arguments": empty_arguments,
30622            "history_events": [],
30623            "history_export": {
30624                "payloads": {"codec": DEFAULT_CODEC},
30625                "history_events": [
30626                    {
30627                        "type": "ActivityCompleted",
30628                        "payload": {
30629                            "sequence": 1,
30630                            "activity_type": "load-counter",
30631                            "payload_codec": DEFAULT_CODEC,
30632                            "result": null
30633                        }
30634                    },
30635                    {
30636                        "type": "SignalWaitOpened",
30637                        "payload": {
30638                            "sequence": 3,
30639                            "signal_name": "increment"
30640                        }
30641                    },
30642                    {
30643                        "type": "SignalReceived",
30644                        "payload": {
30645                            "signal_id": "signal-3",
30646                            "signal_name": "increment",
30647                            "workflow_sequence": 2
30648                        }
30649                    },
30650                    {
30651                        "type": "SignalApplied",
30652                        "payload": {
30653                            "sequence": 3,
30654                            "signal_id": "signal-3",
30655                            "signal_name": "increment"
30656                        }
30657                    },
30658                    {
30659                        "type": "SignalWaitOpened",
30660                        "payload": {
30661                            "sequence": 5,
30662                            "signal_name": "increment"
30663                        }
30664                    },
30665                    {
30666                        "type": "SignalReceived",
30667                        "payload": {
30668                            "signal_id": "signal-5",
30669                            "signal_name": "increment",
30670                            "workflow_sequence": 4
30671                        }
30672                    },
30673                    {
30674                        "type": "SignalApplied",
30675                        "payload": {
30676                            "sequence": 5,
30677                            "signal_id": "signal-5",
30678                            "signal_name": "increment"
30679                        }
30680                    }
30681                ],
30682                "activities": [{
30683                    "sequence": 1,
30684                    "activity_type": "load-counter",
30685                    "payload_codec": DEFAULT_CODEC,
30686                    "result": loaded_result
30687                }],
30688                "signals": [
30689                    {
30690                        "id": "signal-3",
30691                        "name": "increment",
30692                        "workflow_sequence": 2,
30693                        "payload_codec": DEFAULT_CODEC,
30694                        "arguments": signal_three
30695                    },
30696                    {
30697                        "id": "signal-5",
30698                        "name": "increment",
30699                        "workflow_sequence": 4,
30700                        "payload_codec": DEFAULT_CODEC,
30701                        "arguments": signal_five
30702                    }
30703                ]
30704            },
30705            "run_status": "completed"
30706        }))
30707        .expect("cold replay query task");
30708        let completed = restarted_worker
30709            .execute_query_task(restarted_task)
30710            .await
30711            .expect("completed cold replay query");
30712        assert_eq!(
30713            completed.into_json().expect("query projection"),
30714            json!({"loaded": "loaded", "count": 8, "finished": true})
30715        );
30716    }
30717
30718    #[tokio::test]
30719    async fn replayed_query_replay_failures_are_machine_readable() {
30720        let worker = replay_counter_worker();
30721        let task = replay_counter_query(
30722            "current",
30723            json!([{
30724                "type": "ActivityCompleted",
30725                "payload": {
30726                    "sequence": 1,
30727                    "payload_codec": DEFAULT_CODEC,
30728                    "result": {"codec": DEFAULT_CODEC, "blob": "{"}
30729                }
30730            }]),
30731            "running",
30732        );
30733        let failure = worker
30734            .execute_query_task(task)
30735            .await
30736            .expect_err("invalid replay history payload");
30737        assert_eq!(failure.reason, "query_payload_decode_failed");
30738        assert_eq!(failure.failure_type, "QueryPayloadDecodeFailed");
30739        assert!(failure.message.contains("invalid_payload_framing"));
30740    }
30741
30742    #[tokio::test]
30743    async fn query_task_restores_compact_history_from_export() {
30744        let client = Client::new("http://127.0.0.1:8080").expect("client");
30745        let mut worker = Worker::new(client, "rust-workers");
30746        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
30747        worker.register_query("counter", "current", |ctx, _args| async move {
30748            Ok(json!(ctx.signals("increment")[0][0]))
30749        });
30750        let empty_arguments = fixture_envelope(json!([]));
30751        let exported_signal = fixture_blob(json!([9]));
30752        let task: QueryTask = serde_json::from_value(json!({
30753            "query_task_id": "query-export",
30754            "workflow_type": "counter",
30755            "query_name": "current",
30756            "payload_codec": DEFAULT_CODEC,
30757            "workflow_arguments": empty_arguments.clone(),
30758            "query_arguments": empty_arguments,
30759            "history_events": [],
30760            "history_export": {
30761                "payloads": {"codec": DEFAULT_CODEC},
30762                "history_events": [{
30763                    "type": "SignalReceived",
30764                    "payload": {"signal_id": "signal-export", "signal_name": "increment"}
30765                }],
30766                "signals": [{
30767                    "id": "signal-export",
30768                    "name": "increment",
30769                    "status": "applied",
30770                    "workflow_sequence": 1,
30771                    "payload_codec": DEFAULT_CODEC,
30772                    "arguments": exported_signal
30773                }]
30774            }
30775        }))
30776        .expect("query task");
30777
30778        let result = worker.execute_query_task(task).await.expect("query result");
30779        assert_eq!(result.into_json().expect("query projection"), json!(9));
30780    }
30781
30782    #[tokio::test]
30783    async fn query_task_failures_have_stable_reasons() {
30784        let client = Client::new("http://127.0.0.1:8080").expect("client");
30785        let mut worker = Worker::new(client, "rust-workers");
30786        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
30787        worker.register_query(
30788            "counter",
30789            "current",
30790            |_ctx, _args| async move { Ok(json!(0)) },
30791        );
30792
30793        let base_task = QueryTask {
30794            query_task_id: "query-errors".to_string(),
30795            observability_context: None,
30796            dispatch_observability_context: None,
30797            observability_links: None,
30798            query_task_attempt: 1,
30799            lease_owner: None,
30800            workflow_id: Some("counter-errors".to_string()),
30801            run_id: Some("run-errors".to_string()),
30802            workflow_type: "counter".to_string(),
30803            query_name: "missing".to_string(),
30804            payload_codec: DEFAULT_CODEC.to_string(),
30805            workflow_arguments: Some(fixture_envelope(json!([]))),
30806            query_arguments: Some(fixture_envelope(json!([]))),
30807            history_events: Vec::new(),
30808            history_export: None,
30809            run_status: Some("running".to_string()),
30810        };
30811
30812        let unknown = worker
30813            .execute_query_task(base_task.clone())
30814            .await
30815            .expect_err("unknown query");
30816        assert_eq!(unknown.reason, "rejected_unknown_query");
30817
30818        let mut malformed = base_task;
30819        malformed.query_name = "current".to_string();
30820        malformed.query_arguments = Some(json!({"codec": DEFAULT_CODEC, "blob": "{"}));
30821        let malformed = worker
30822            .execute_query_task(malformed)
30823            .await
30824            .expect_err("malformed payload");
30825        assert_eq!(malformed.reason, "query_payload_decode_failed");
30826
30827        let client = Client::new("http://127.0.0.1:8080").expect("client");
30828        let mut unavailable_worker = Worker::new(client, "rust-workers");
30829        unavailable_worker
30830            .register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
30831        let empty_arguments = fixture_envelope(json!([]));
30832        let unavailable_task: QueryTask = serde_json::from_value(json!({
30833            "query_task_id": "query-unavailable",
30834            "workflow_type": "counter",
30835            "query_name": "current",
30836            "payload_codec": DEFAULT_CODEC,
30837            "workflow_arguments": empty_arguments.clone(),
30838            "query_arguments": empty_arguments
30839        }))
30840        .expect("query task");
30841        let unavailable = unavailable_worker
30842            .execute_query_task(unavailable_task)
30843            .await
30844            .expect_err("query handler unavailable");
30845        assert_eq!(unavailable.reason, "query_handler_unavailable");
30846    }
30847
30848    #[tokio::test]
30849    async fn client_query_decodes_result_and_typed_failure() {
30850        let server = MockWorkerServer::start();
30851        let client = Client::builder(server.base_url())
30852            .timeout(Duration::from_secs(2))
30853            .build()
30854            .expect("client");
30855
30856        let result = client
30857            .query_workflow("counter-1", "current", json!([]))
30858            .await
30859            .expect("query result");
30860        assert_eq!(result, json!({"count": 8}));
30861
30862        let error = client
30863            .query_workflow("counter-1", "missing", json!([]))
30864            .await
30865            .expect_err("unknown query");
30866        let Error::QueryFailed(failure) = error else {
30867            panic!("expected typed query failure");
30868        };
30869        assert_eq!(failure.status, 404);
30870        assert_eq!(failure.reason, "rejected_unknown_query");
30871    }
30872
30873    const KEYED_SIGNAL_PATH: &str = "/api/workflows/keyed-1/signal/approve";
30874    const KEYED_RUN_SIGNAL_PATH: &str = "/api/workflows/keyed-1/runs/run-keyed-1/signal/approve";
30875    const KEYED_UPDATE_PATH: &str = "/api/workflows/keyed-1/update/adjust";
30876
30877    #[cfg(feature = "telemetry")]
30878    #[tokio::test]
30879    async fn optional_observability_client_uses_actual_discovery_and_preserves_business_intent() {
30880        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
30881        static PHASE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
30882        PHASE.store(0, Ordering::SeqCst);
30883        use opentelemetry::{
30884            propagation::TextMapPropagator,
30885            trace::{FutureExt, TracerProvider},
30886        };
30887        use opentelemetry_sdk::propagation::TraceContextPropagator;
30888        struct Restore;
30889        impl Drop for Restore {
30890            fn drop(&mut self) {
30891                opentelemetry::global::set_text_map_propagator(
30892                    opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
30893                );
30894            }
30895        }
30896        let _restore = Restore;
30897        opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());
30898        let headers = HashMap::from([(
30899            "traceparent".to_string(),
30900            "00-12345678901234567890123456789012-1234567890123456-01".to_string(),
30901        )]);
30902        let parent = TraceContextPropagator::new().extract(&headers);
30903        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
30904            request_override: Some(|path, body, _number| {
30905                if path == "/api/cluster/info" {
30906                    return Some(if PHASE.load(Ordering::SeqCst) == 2 {
30907                        ("503 Service Unavailable", "{}".into())
30908                    } else {
30909                        ("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
30910                            "supported": true, "schema": "durable-workflow.trace-context", "version": if PHASE.load(Ordering::SeqCst) == 0 {1} else {99},
30911                            "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
30912                            "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
30913                        }}}}).to_string())
30914                    });
30915                }
30916                let body: Value = serde_json::from_str(body).ok()?;
30917                Some(("200 OK", json!({"workflow_id": "order", "run_id": "run", "workflow_type": "orders",
30918                    "outcome": "accepted", "command_id": "command", "request_id": body["request_id"],
30919                    "result": "original"}).to_string()))
30920            }),
30921            ..MockWorkerBehavior::default()
30922        });
30923        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder().build();
30924        let client = Client::new(server.base_url()).unwrap().with_telemetry(
30925            telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test")),
30926        );
30927        let input = json!([{"observability_context": {"business": "preserved"}}]);
30928        async {
30929            client
30930                .start_workflow("orders", "orders", "order", &input)
30931                .await
30932                .unwrap();
30933            assert!(server
30934                .request_body("/api/workflows")
30935                .get("observability_context")
30936                .is_none());
30937            client.cluster_info().await.unwrap();
30938            client
30939                .start_workflow("orders", "orders", "order", &input)
30940                .await
30941                .unwrap();
30942            client
30943                .signal_workflow_with_request_id("order", "ready", &input, "signal-original")
30944                .await
30945                .unwrap();
30946            client
30947                .update_workflow("order", "status", &input, Some("update-original"))
30948                .await
30949                .unwrap();
30950            client
30951                .cancel_workflow("order", WorkflowCommandOptions::default())
30952                .await
30953                .unwrap();
30954            for path in [
30955                "/api/workflows",
30956                "/api/workflows/order/signal/ready",
30957                "/api/workflows/order/update/status",
30958                "/api/workflows/order/cancel",
30959            ] {
30960                let bodies = server.request_bodies(path);
30961                let body = bodies.last().unwrap();
30962                assert_eq!(
30963                    body["observability_context"]["carrier"]["traceparent"],
30964                    headers["traceparent"]
30965                );
30966                assert!(body["observability_context"]["carrier"]
30967                    .get("baggage")
30968                    .is_none());
30969            }
30970            let starts = server.request_bodies("/api/workflows");
30971            assert_eq!(
30972                decode_wire_value(&starts[1]["input"], DEFAULT_CODEC).unwrap(),
30973                input
30974            );
30975            assert_eq!(
30976                server.request_body("/api/workflows/order/signal/ready")["request_id"],
30977                "signal-original"
30978            );
30979            assert_eq!(
30980                server.request_body("/api/workflows/order/update/status")["request_id"],
30981                "update-original"
30982            );
30983            PHASE.store(1, Ordering::SeqCst);
30984            client.cluster_info().await.unwrap();
30985            client
30986                .start_workflow("orders", "orders", "order", &input)
30987                .await
30988                .unwrap();
30989            assert!(server
30990                .request_bodies("/api/workflows")
30991                .last()
30992                .unwrap()
30993                .get("observability_context")
30994                .is_none());
30995            PHASE.store(2, Ordering::SeqCst);
30996            assert!(client.cluster_info().await.is_err());
30997            let before = server.captured_paths().len();
30998            client
30999                .start_workflow("orders", "orders", "order", &input)
31000                .await
31001                .unwrap();
31002            assert_eq!(server.captured_paths().len(), before + 1);
31003            assert!(server
31004                .request_bodies("/api/workflows")
31005                .last()
31006                .unwrap()
31007                .get("observability_context")
31008                .is_none());
31009        }
31010        .with_context(parent)
31011        .await;
31012    }
31013
31014    #[cfg(feature = "telemetry")]
31015    fn observability_worker_server(
31016        path: &str,
31017        _body: &str,
31018        _: usize,
31019    ) -> Option<(&'static str, String)> {
31020        let context = json!({"schema": "durable-workflow.trace-context", "version": 1,
31021            "carrier": {"traceparent": "00-12345678901234567890123456789012-1234567890123456-01",
31022                        "baggage": "credential=private"}});
31023        let link_context = json!({"schema": "durable-workflow.trace-context", "version": 1,
31024            "carrier": {"traceparent": "00-abcdef78901234567890123456789012-abcdef7890123456-01"}});
31025        if path == "/api/cluster/info" {
31026            return Some(("200 OK", json!({"worker_protocol": {"server_capabilities": {"observability_context": {
31027                "supported": true, "schema": "durable-workflow.trace-context", "version": 1,
31028                "dispatch_schema": "durable-workflow.queue-trace", "links_schema": "durable-workflow.trace-links",
31029                "max_context_bytes": 4096, "max_links": 32, "max_links_bytes": 4096
31030            }}}}).to_string()));
31031        }
31032        if path.ends_with("/complete") {
31033            return Some(("200 OK", json!({"recorded": true}).to_string()));
31034        }
31035        let task_id = match path {
31036            "/api/worker/workflow-tasks/poll" => "workflow-task",
31037            "/api/worker/activity-tasks/poll" => "activity-task",
31038            "/api/worker/query-tasks/poll" => "query-task",
31039            _ => return None,
31040        };
31041        let input = encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap();
31042        let mut task = json!({"task_id": task_id, "query_task_id": task_id,
31043        "workflow_id": "workflow", "run_id": "run", "workflow_type": "wire.workflow",
31044        "activity_type": "wire.activity", "activity_execution_id": "activity",
31045        "activity_attempt_id": "attempt", "attempt_number": 3, "workflow_task_attempt": 1,
31046        "query_task_attempt": 1, "query_name": "state", "lease_owner": "test-worker",
31047        "namespace": "shipping", "task_queue": "shipping", "lease_expires_at": "2099-01-01T00:00:00Z",
31048        "payload_codec": DEFAULT_CODEC, "arguments": input, "workflow_arguments": input,
31049        "query_arguments": input, "history_events": [], "observability_context": context,
31050        "dispatch_observability_context": {"schema": "durable-workflow.queue-trace", "version": 1,
31051            "task_id": task_id, "context": link_context},
31052        "observability_links": {"schema": "durable-workflow.trace-links", "version": 1,
31053            "task_id": task_id, "run_id": "run", "namespace": "shipping", "links": [
31054                {"kind": "command", "command_id": "accepted-command", "context": link_context},
31055                {"kind": "child_outcome", "workflow_link_id": "link", "child_run_id": "child",
31056                 "child_task_id": null, "event_id": "terminal", "sequence": 7,
31057                 "event_type": "WorkflowCancelled", "context": link_context}
31058            ]}});
31059        if task_id == "workflow-task" {
31060            task["arguments"] = encode_value_envelope(
31061                &json!([{"observability_context": {"business": "preserved"}}]),
31062                DEFAULT_CODEC,
31063            )
31064            .unwrap();
31065        }
31066        Some((
31067            "200 OK",
31068            json!({"task": task, "poll_status": "leased"}).to_string(),
31069        ))
31070    }
31071
31072    #[cfg(feature = "telemetry")]
31073    #[tokio::test]
31074    async fn observability_polled_tasks_recover_parent_links_and_capture_the_actual_child_producer()
31075    {
31076        use opentelemetry::trace::TracerProvider;
31077        let _propagator_guard = OBSERVABILITY_PROPAGATOR_TEST_LOCK.lock().await;
31078        opentelemetry::global::set_text_map_propagator(
31079            opentelemetry_sdk::propagation::TraceContextPropagator::new(),
31080        );
31081        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
31082        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
31083            .with_simple_exporter(exporter.clone())
31084            .build();
31085        let telemetry = telemetry::ExecutionTelemetry::from_tracer(provider.tracer("test"));
31086        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31087            request_override: Some(observability_worker_server),
31088            ..MockWorkerBehavior::default()
31089        });
31090        let client = Client::builder(server.base_url())
31091            .namespace("shipping")
31092            .build()
31093            .unwrap();
31094        client.cluster_info().await.unwrap();
31095        let mut worker = Worker::new(client, "shipping")
31096            .worker_id("test-worker")
31097            .telemetry(telemetry);
31098        worker.register_workflow("wire.workflow", |ctx, input| async move {
31099            assert_eq!(telemetry::current_log_context()["workflow_run_id"], "run");
31100            assert_eq!(
31101                input,
31102                json!([{"observability_context": {"business": "preserved"}}])
31103            );
31104            ctx.start_child_workflow("child", ChildWorkflowOptions::new("child-workers"), input)
31105                .await?;
31106            Ok(Value::Null)
31107        });
31108        worker.register_activity("wire.activity", |_, _| async {
31109            let fields = telemetry::current_log_context();
31110            assert_eq!(fields["workflow_run_id"], "run");
31111            assert_eq!(fields["activity_id"], "activity");
31112            assert_eq!(fields["activity_attempt_id"], "attempt");
31113            assert_eq!(fields["activity_attempt_number"], "3");
31114            Ok(json!("original-result"))
31115        });
31116        worker.register_query("wire.workflow", "state", |_, _| async {
31117            assert_eq!(telemetry::current_log_context()["task_id"], "query-task");
31118            Ok(json!("original-query"))
31119        });
31120        assert_eq!(worker.run_once().await.unwrap(), 3);
31121        let spans = exporter.get_finished_spans().unwrap();
31122        assert_eq!(spans.len(), 4);
31123        let origin_trace = "12345678901234567890123456789012";
31124        for span in spans
31125            .iter()
31126            .filter(|span| span.name.as_ref() != "durable.activity.attempt")
31127        {
31128            assert_eq!(span.span_context.trace_id().to_string(), origin_trace);
31129            assert_eq!(span.parent_span_id.to_string(), "1234567890123456");
31130            assert_eq!(span.links.len(), 3);
31131            assert!(!format!("{:?}", span.attributes).contains("credential"));
31132        }
31133        let task = spans
31134            .iter()
31135            .find(|span| span.name.as_ref() == "durable.workflow.task")
31136            .unwrap();
31137        let body = server.request_body("/api/worker/workflow-tasks/workflow-task/complete");
31138        assert_eq!(body["commands"][0]["type"], "start_child_workflow");
31139        let parent = body["commands"][0]["observability_context"]["carrier"]["traceparent"]
31140            .as_str()
31141            .unwrap();
31142        assert_eq!(&parent[36..52], task.span_context.span_id().to_string());
31143        assert!(telemetry::current_log_context().is_empty());
31144        opentelemetry::global::set_text_map_propagator(
31145            opentelemetry::propagation::TextMapCompositePropagator::new(Vec::new()),
31146        );
31147    }
31148
31149    #[cfg(feature = "telemetry")]
31150    #[tokio::test]
31151    async fn observability_never_enters_a_query_with_a_refused_original_claim() {
31152        use opentelemetry::trace::TracerProvider;
31153        static REFUSAL: AtomicUsize = AtomicUsize::new(0);
31154        fn refused_query(path: &str, body: &str, count: usize) -> Option<(&'static str, String)> {
31155            let (status, reply) = observability_worker_server(path, body, count)?;
31156            if path != "/api/worker/query-tasks/poll" {
31157                return Some((status, reply));
31158            }
31159            let mut reply: Value = serde_json::from_str(&reply).unwrap();
31160            match REFUSAL.load(Ordering::SeqCst) {
31161                0 => reply["task"]["lease_owner"] = json!("other-worker"),
31162                1 => reply["task"]["query_task_attempt"] = json!(0),
31163                _ => reply["task"]["lease_expires_at"] = json!("2000-01-01T00:00:00Z"),
31164            }
31165            Some((status, reply.to_string()))
31166        }
31167        let exporter = opentelemetry_sdk::trace::InMemorySpanExporter::default();
31168        let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
31169            .with_simple_exporter(exporter.clone())
31170            .build();
31171        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31172            request_override: Some(refused_query),
31173            ..MockWorkerBehavior::default()
31174        });
31175        let client = Client::builder(server.base_url())
31176            .namespace("shipping")
31177            .build()
31178            .unwrap();
31179        client.cluster_info().await.unwrap();
31180        let mut worker = Worker::new(client, "shipping")
31181            .worker_id("test-worker")
31182            .telemetry(telemetry::ExecutionTelemetry::from_tracer(
31183                provider.tracer("test"),
31184            ));
31185        let calls = Arc::new(AtomicUsize::new(0));
31186        let query_calls = calls.clone();
31187        worker.register_query("wire.workflow", "state", move |_, _| {
31188            query_calls.fetch_add(1, Ordering::SeqCst);
31189            async { Ok(Value::Null) }
31190        });
31191        for refusal in 0..3 {
31192            REFUSAL.store(refusal, Ordering::SeqCst);
31193            assert!(matches!(
31194                worker.poll_query_once().await.unwrap(),
31195                ManagedPollOutcome::Handled
31196            ));
31197            assert_eq!(calls.load(Ordering::SeqCst), 0);
31198            assert!(exporter.get_finished_spans().unwrap().is_empty());
31199            assert!(telemetry::current_log_context().is_empty());
31200        }
31201        assert!(!server
31202            .captured_paths()
31203            .iter()
31204            .any(|path| path.ends_with("/complete") || path.ends_with("/fail")));
31205    }
31206
31207    fn keyed_command_request(path: &str, body: &str) -> Option<Value> {
31208        if path != KEYED_SIGNAL_PATH && path != KEYED_RUN_SIGNAL_PATH && path != KEYED_UPDATE_PATH {
31209            return None;
31210        }
31211        serde_json::from_str(body).ok()
31212    }
31213
31214    /// A #216 Server: echoes the key with `retained` and `intent_verified`.
31215    fn keyed_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
31216        let request = keyed_command_request(path, body)?;
31217        let mut receipt = json!({
31218            "outcome": "accepted",
31219            "command_status": "accepted",
31220            "command_id": "cmd-keyed-1",
31221            "request_id": request["request_id"],
31222            "retained": false,
31223            "intent_verified": true,
31224        });
31225        if path == KEYED_UPDATE_PATH {
31226            receipt["update_id"] = json!("upd-keyed-1");
31227            receipt["result_envelope"] =
31228                encode_typed_envelope(&AvroValue::Long(42), DEFAULT_CODEC).expect("result");
31229        }
31230        Some(("202 Accepted", receipt.to_string()))
31231    }
31232
31233    /// A Server released before #216: accepts the body field but echoes nothing.
31234    fn legacy_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
31235        keyed_command_request(path, body)?;
31236        Some((
31237            "202 Accepted",
31238            r#"{"outcome":"accepted","command_status":"accepted","command_id":"cmd-legacy"}"#
31239                .to_string(),
31240        ))
31241    }
31242
31243    fn retained_command_server(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
31244        let request = keyed_command_request(path, body)?;
31245        Some((
31246            "202 Accepted",
31247            json!({
31248                "outcome": "accepted",
31249                "command_status": "accepted",
31250                "command_id": "cmd-first",
31251                "request_id": request["request_id"],
31252                "retained": true,
31253                "intent_verified": true,
31254            })
31255            .to_string(),
31256        ))
31257    }
31258
31259    fn conflicting_command_server(
31260        path: &str,
31261        body: &str,
31262        _: usize,
31263    ) -> Option<(&'static str, String)> {
31264        let request = keyed_command_request(path, body)?;
31265        let retained_type = if path == KEYED_UPDATE_PATH {
31266            "update"
31267        } else {
31268            "signal"
31269        };
31270        Some((
31271            "409 Conflict",
31272            json!({
31273                "reason": "request_id_conflict",
31274                "message": format!("request id is retained for a different {retained_type} intent"),
31275                "request_id": request["request_id"],
31276                "retained_command_id": "cmd-retained-1",
31277                "retained_command_type": retained_type,
31278                "retained_outcome": "accepted",
31279                "conflict": ["arguments", "target"],
31280                "control_plane": {"operation": retained_type},
31281            })
31282            .to_string(),
31283        ))
31284    }
31285
31286    /// A native Server 3.9.0 (server#934): the original intent is `["ok"]` on
31287    /// the instance. Its retry gets the retained receipt, and any other input or
31288    /// run target is refused exactly as native refuses it, without echoing the key.
31289    fn native_command_key_server(
31290        path: &str,
31291        body: &str,
31292        _: usize,
31293    ) -> Option<(&'static str, String)> {
31294        let request = keyed_command_request(path, body)?;
31295        let original = encode_typed_envelope(
31296            &normalize_avro_arguments(AvroValue::from_serialize(&json!(["ok"])).expect("input")),
31297            DEFAULT_CODEC,
31298        )
31299        .expect("envelope");
31300        let command_type = if path == KEYED_UPDATE_PATH {
31301            "update"
31302        } else {
31303            "signal"
31304        };
31305        if path == KEYED_RUN_SIGNAL_PATH || request["input"] != original {
31306            let part = if path == KEYED_RUN_SIGNAL_PATH {
31307                "target_or_arguments"
31308            } else {
31309                "arguments"
31310            };
31311            return Some((
31312                "409 Conflict",
31313                json!({
31314                    "workflow_id": "keyed-1",
31315                    "reason": "request_id_conflict",
31316                    "outcome": "rejected_request_id_conflict",
31317                    "command_status": "rejected",
31318                    "rejection_reason": "request_id_conflict",
31319                    "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."),
31320                    "intent_verified": true,
31321                    "retained": true,
31322                    "retained_command_id": "cmd-native-1",
31323                    "retained_outcome": "signal_received",
31324                    "conflict": [part],
31325                })
31326                .to_string(),
31327            ));
31328        }
31329        let mut receipt = json!({
31330            "workflow_id": "keyed-1",
31331            "run_id": "run-keyed-1",
31332            "command_id": "cmd-native-1",
31333            "command_status": "accepted",
31334            "outcome": "signal_received",
31335            "retained": true,
31336            "intent_verified": true,
31337        });
31338        if path == KEYED_UPDATE_PATH {
31339            receipt["update_id"] = json!("upd-native-1");
31340            receipt["result_envelope"] =
31341                encode_typed_envelope(&AvroValue::Long(7), DEFAULT_CODEC).expect("result");
31342        }
31343        Some(("200 OK", receipt.to_string()))
31344    }
31345
31346    /// A native Server 3.13.0 answer for a key that matches more than one
31347    /// legacy row: no receipt is selected and nothing is written. Native does
31348    /// not always echo the key.
31349    fn ambiguous_command_server(
31350        path: &str,
31351        body: &str,
31352        _: usize,
31353    ) -> Option<(&'static str, String)> {
31354        let request = keyed_command_request(path, body)?;
31355        let mut refusal = json!({
31356            "reason": "request_id_ambiguous",
31357            "message": "The request_id matches more than one retained command on workflow [keyed-1].",
31358            "retained": true,
31359            "intent_verified": false,
31360            "retryable": false,
31361        });
31362        if path == KEYED_SIGNAL_PATH {
31363            refusal["request_id"] = request["request_id"].clone();
31364        }
31365        Some(("409 Conflict", refusal.to_string()))
31366    }
31367
31368    /// A native Server 3.13.0 readback of a key retained before intent was
31369    /// compared: the original identities with `intent_verified: false`.
31370    fn legacy_unverified_command_server(
31371        path: &str,
31372        body: &str,
31373        _: usize,
31374    ) -> Option<(&'static str, String)> {
31375        let request = keyed_command_request(path, body)?;
31376        let mut receipt = json!({
31377            "workflow_id": "keyed-1",
31378            "run_id": "run-keyed-1",
31379            "command_id": "cmd-legacy-1",
31380            "command_status": "accepted",
31381            "request_id": request["request_id"],
31382            "retained": true,
31383            "intent_verified": false,
31384        });
31385        if path == KEYED_UPDATE_PATH {
31386            receipt["update_id"] = json!("upd-legacy-1");
31387            receipt["update_status"] = json!("completed");
31388            receipt["result_envelope"] =
31389                encode_typed_envelope(&AvroValue::Long(5), DEFAULT_CODEC).expect("result");
31390        }
31391        Some(("200 OK", receipt.to_string()))
31392    }
31393
31394    fn closed_run_command_server(
31395        path: &str,
31396        body: &str,
31397        _: usize,
31398    ) -> Option<(&'static str, String)> {
31399        let request = keyed_command_request(path, body)?;
31400        Some((
31401            "409 Conflict",
31402            json!({
31403                "reason": "run_not_active",
31404                "message": "run is closed",
31405                "request_id": request["request_id"],
31406            })
31407            .to_string(),
31408        ))
31409    }
31410
31411    fn drop_first_keyed_signal(path: &str, request_number: usize) -> bool {
31412        path == KEYED_SIGNAL_PATH && request_number == 1
31413    }
31414
31415    fn keyed_client(server: &MockWorkerServer) -> Client {
31416        Client::builder(server.base_url())
31417            .timeout(Duration::from_secs(2))
31418            .build()
31419            .expect("client")
31420    }
31421
31422    fn keyed_handle(client: &Client) -> WorkflowHandle {
31423        WorkflowHandle {
31424            client: client.clone(),
31425            workflow_id: "keyed-1".to_string(),
31426            run_id: Some("run-keyed-1".to_string()),
31427            workflow_type: "keyed".to_string(),
31428        }
31429    }
31430
31431    fn assert_generated_request_id(request_id: &str, prefix: &str) {
31432        let suffix = request_id
31433            .strip_prefix(prefix)
31434            .unwrap_or_else(|| panic!("{request_id:?} does not start with {prefix:?}"));
31435        assert_eq!(suffix.len(), 32, "uuid4 simple hex suffix: {request_id:?}");
31436        assert!(
31437            suffix
31438                .bytes()
31439                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()),
31440            "lowercase hex suffix: {request_id:?}"
31441        );
31442        assert!(request_id.len() <= MAX_REQUEST_ID_CHARACTERS);
31443    }
31444
31445    fn assert_key_sent_only_in_body(server: &MockWorkerServer, path: &str) {
31446        let headers = server.request_headers(path);
31447        assert!(!headers.is_empty(), "no request captured for {path}");
31448        for headers in headers {
31449            let header_names: Vec<String> = headers
31450                .lines()
31451                .skip(1)
31452                .filter_map(|line| line.split_once(':'))
31453                .map(|(name, _)| name.trim().to_ascii_lowercase())
31454                .collect();
31455            assert!(
31456                !header_names.iter().any(|name| name == "x-request-id"),
31457                "the caller command key is a body field, never an X-Request-Id header: {headers}"
31458            );
31459        }
31460    }
31461
31462    #[tokio::test]
31463    async fn signal_without_key_sends_a_generated_sdk_rust_signal_key_and_returns_it() {
31464        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31465            request_override: Some(legacy_command_server),
31466            ..MockWorkerBehavior::default()
31467        });
31468        let client = keyed_client(&server);
31469
31470        let receipt = client
31471            .signal_workflow("keyed-1", "approve", json!(["ok"]))
31472            .await
31473            .expect("signal receipt");
31474
31475        let sent = server.request_body(KEYED_SIGNAL_PATH);
31476        let request_id = sent["request_id"].as_str().expect("generated request_id");
31477        assert_generated_request_id(request_id, "sdk-rust-signal-");
31478        assert_eq!(
31479            receipt,
31480            json!({
31481                "outcome": "accepted",
31482                "command_status": "accepted",
31483                "command_id": "cmd-legacy",
31484                "request_id": request_id,
31485            }),
31486            "the sent key is added when an older Server omits it"
31487        );
31488        assert_key_sent_only_in_body(&server, KEYED_SIGNAL_PATH);
31489
31490        let receipt = keyed_handle(&client)
31491            .signal_selected_run("approve", json!(["ok"]))
31492            .await
31493            .expect("selected-run signal receipt");
31494        let run_sent = server.request_body(KEYED_RUN_SIGNAL_PATH);
31495        let run_request_id = run_sent["request_id"]
31496            .as_str()
31497            .expect("generated request_id");
31498        assert_generated_request_id(run_request_id, "sdk-rust-signal-");
31499        assert_eq!(receipt["request_id"], run_request_id);
31500        assert_ne!(
31501            run_request_id, request_id,
31502            "each logical call gets its own key"
31503        );
31504        assert_key_sent_only_in_body(&server, KEYED_RUN_SIGNAL_PATH);
31505    }
31506
31507    #[tokio::test]
31508    async fn update_without_key_sends_a_generated_sdk_rust_update_key() {
31509        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31510            request_override: Some(keyed_command_server),
31511            ..MockWorkerBehavior::default()
31512        });
31513        let client = keyed_client(&server);
31514
31515        let result = client
31516            .update_workflow("keyed-1", "adjust", json!([1]), None)
31517            .await
31518            .expect("update result");
31519        assert_eq!(
31520            result,
31521            json!(42),
31522            "the decoded update result is returned unchanged"
31523        );
31524        let typed = client
31525            .update_workflow_avro_value("keyed-1", "adjust", json!([1]), None)
31526            .await
31527            .expect("typed update result");
31528        assert_eq!(typed, AvroValue::Long(42));
31529        keyed_handle(&client)
31530            .update("adjust", json!([1]), None)
31531            .await
31532            .expect("handle update result");
31533
31534        let bodies = server.request_bodies(KEYED_UPDATE_PATH);
31535        assert_eq!(bodies.len(), 3);
31536        for body in &bodies {
31537            assert_generated_request_id(
31538                body["request_id"].as_str().expect("generated request_id"),
31539                "sdk-rust-update-",
31540            );
31541            assert_eq!(body["wait_for"], "completed");
31542        }
31543        assert_ne!(bodies[0]["request_id"], bodies[1]["request_id"]);
31544        assert_ne!(bodies[1]["request_id"], bodies[2]["request_id"]);
31545        assert_key_sent_only_in_body(&server, KEYED_UPDATE_PATH);
31546    }
31547
31548    fn segment_server(path: &str, _: &str, _: usize) -> Option<(&'static str, String)> {
31549        if path.contains("/update/") {
31550            return Some((
31551                "200 OK",
31552                json!({"update_id": "upd-1", "update_status": "completed",
31553                    "result_envelope": encode_typed_envelope(&AvroValue::Long(1), DEFAULT_CODEC).ok()})
31554                .to_string(),
31555            ));
31556        }
31557        path.starts_with("/api/workflows/").then(|| {
31558            (
31559                "200 OK",
31560                json!({"workflow_id": "x", "run_id": "run-1", "status": "running"}).to_string(),
31561            )
31562        })
31563    }
31564
31565    #[tokio::test]
31566    async fn describe_and_update_keep_each_identifier_in_one_encoded_segment() {
31567        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31568            request_override: Some(segment_server),
31569            ..MockWorkerBehavior::default()
31570        });
31571        let client = keyed_client(&server);
31572
31573        client
31574            .describe_workflow("orders/2026?x#y")
31575            .await
31576            .expect("describe");
31577        assert_eq!(
31578            server.method_for("/api/workflows/orders%2F2026%3Fx%23y"),
31579            Some("GET".to_string()),
31580            "the workflow id stays one segment: {:?}",
31581            server.captured_paths()
31582        );
31583        client
31584            .update_workflow("order 1/a", "re/name", json!([1]), Some("key-1"))
31585            .await
31586            .expect("update");
31587        assert_eq!(
31588            server.request_body("/api/workflows/order%201%2Fa/update/re%2Fname")["request_id"],
31589            "key-1"
31590        );
31591    }
31592
31593    #[tokio::test]
31594    async fn dot_segment_and_empty_identifiers_are_refused_before_any_request() {
31595        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31596            request_override: Some(segment_server),
31597            ..MockWorkerBehavior::default()
31598        });
31599        let client = keyed_client(&server);
31600
31601        for workflow_id in ["", ".", ".."] {
31602            let error = client
31603                .describe_workflow(workflow_id)
31604                .await
31605                .expect_err("a dot segment would describe another route");
31606            assert!(
31607                matches!(
31608                    error,
31609                    Error::InvalidPathSegment {
31610                        field: "workflow_id"
31611                    }
31612                ),
31613                "{workflow_id:?}: {error:?}"
31614            );
31615            let error = client
31616                .update_workflow(workflow_id, "adjust", json!([1]), None)
31617                .await
31618                .expect_err("a dot segment would update another route");
31619            assert!(
31620                matches!(
31621                    error,
31622                    Error::InvalidPathSegment {
31623                        field: "workflow_id"
31624                    }
31625                ),
31626                "{workflow_id:?}: {error:?}"
31627            );
31628        }
31629        for update_name in ["", ".", ".."] {
31630            let error = client
31631                .update_workflow("order-1", update_name, json!([1]), None)
31632                .await
31633                .expect_err("a dot segment update name is refused");
31634            assert!(
31635                matches!(
31636                    error,
31637                    Error::InvalidPathSegment {
31638                        field: "update_name"
31639                    }
31640                ),
31641                "{update_name:?}: {error:?}"
31642            );
31643        }
31644        assert!(
31645            server.captured_paths().is_empty(),
31646            "nothing was sent: {:?}",
31647            server.captured_paths()
31648        );
31649    }
31650
31651    #[tokio::test]
31652    async fn explicit_command_keys_are_sent_verbatim_as_the_request_id_body_field() {
31653        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31654            request_override: Some(keyed_command_server),
31655            ..MockWorkerBehavior::default()
31656        });
31657        let client = keyed_client(&server);
31658        let handle = keyed_handle(&client);
31659
31660        let receipt = client
31661            .signal_workflow_with_request_id(
31662                "keyed-1",
31663                "approve",
31664                json!(["ok"]),
31665                "Order-42/approve",
31666            )
31667            .await
31668            .expect("signal receipt");
31669        assert_eq!(receipt["request_id"], "Order-42/approve");
31670        assert_eq!(receipt["retained"], false);
31671        assert_eq!(receipt["intent_verified"], true);
31672        handle
31673            .signal_with_request_id("approve", json!(["ok"]), "handle-signal-key")
31674            .await
31675            .expect("handle signal receipt");
31676        client
31677            .signal_workflow_run_with_request_id(
31678                "keyed-1",
31679                "run-keyed-1",
31680                "approve",
31681                json!(["ok"]),
31682                "run-signal-key",
31683            )
31684            .await
31685            .expect("selected-run signal receipt");
31686        handle
31687            .signal_selected_run_with_request_id("approve", json!(["ok"]), "handle-run-signal-key")
31688            .await
31689            .expect("handle selected-run signal receipt");
31690        let result = client
31691            .update_workflow("keyed-1", "adjust", json!([1]), Some("update-key"))
31692            .await
31693            .expect("update result");
31694        assert_eq!(result, json!(42));
31695        handle
31696            .update("adjust", json!([1]), Some("handle-update-key"))
31697            .await
31698            .expect("handle update result");
31699        handle
31700            .update_avro_value("adjust", json!([1]), Some("handle-typed-update-key"))
31701            .await
31702            .expect("handle typed update result");
31703
31704        let signal_keys: Vec<Value> = server
31705            .request_bodies(KEYED_SIGNAL_PATH)
31706            .into_iter()
31707            .map(|body| body["request_id"].clone())
31708            .collect();
31709        assert_eq!(
31710            signal_keys,
31711            [json!("Order-42/approve"), json!("handle-signal-key")]
31712        );
31713        let run_signal_keys: Vec<Value> = server
31714            .request_bodies(KEYED_RUN_SIGNAL_PATH)
31715            .into_iter()
31716            .map(|body| body["request_id"].clone())
31717            .collect();
31718        assert_eq!(
31719            run_signal_keys,
31720            [json!("run-signal-key"), json!("handle-run-signal-key")]
31721        );
31722        let update_keys: Vec<Value> = server
31723            .request_bodies(KEYED_UPDATE_PATH)
31724            .into_iter()
31725            .map(|body| body["request_id"].clone())
31726            .collect();
31727        assert_eq!(
31728            update_keys,
31729            [
31730                json!("update-key"),
31731                json!("handle-update-key"),
31732                json!("handle-typed-update-key")
31733            ]
31734        );
31735        for path in [KEYED_SIGNAL_PATH, KEYED_RUN_SIGNAL_PATH, KEYED_UPDATE_PATH] {
31736            assert_key_sent_only_in_body(&server, path);
31737        }
31738    }
31739
31740    #[tokio::test]
31741    async fn retained_receipts_are_returned_unchanged() {
31742        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31743            request_override: Some(retained_command_server),
31744            ..MockWorkerBehavior::default()
31745        });
31746        let client = keyed_client(&server);
31747
31748        let receipt = client
31749            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "retry-key")
31750            .await
31751            .expect("retained receipt");
31752
31753        assert_eq!(
31754            receipt,
31755            json!({
31756                "outcome": "accepted",
31757                "command_status": "accepted",
31758                "command_id": "cmd-first",
31759                "request_id": "retry-key",
31760                "retained": true,
31761                "intent_verified": true,
31762            })
31763        );
31764    }
31765
31766    #[tokio::test]
31767    async fn request_id_conflict_refusal_keeps_error_http_and_classifies_the_sent_key() {
31768        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31769            request_override: Some(conflicting_command_server),
31770            ..MockWorkerBehavior::default()
31771        });
31772        let client = keyed_client(&server);
31773
31774        let error = client
31775            .signal_workflow_with_request_id(
31776                "keyed-1",
31777                "approve",
31778                json!(["changed"]),
31779                "Order-42/approve",
31780            )
31781            .await
31782            .expect_err("different intent under a retained key");
31783        assert!(
31784            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT),
31785            "existing Error::Http matching keeps working: {error:?}"
31786        );
31787        assert!(error.is_request_id_conflict());
31788        assert_eq!(error.request_id().as_deref(), Some("Order-42/approve"));
31789        let conflict = error.request_id_conflict().expect("conflict details");
31790        assert_eq!(conflict.status, 409);
31791        assert_eq!(conflict.request_id, "Order-42/approve");
31792        assert_eq!(
31793            conflict.message,
31794            "request id is retained for a different signal intent"
31795        );
31796        assert_eq!(
31797            conflict.retained_command_id.as_deref(),
31798            Some("cmd-retained-1")
31799        );
31800        assert_eq!(conflict.retained_command_type.as_deref(), Some("signal"));
31801        assert_eq!(conflict.retained_outcome.as_deref(), Some("accepted"));
31802        assert_eq!(conflict.conflict, ["arguments", "target"]);
31803        assert_eq!(conflict.body["control_plane"]["operation"], "signal");
31804
31805        let error = client
31806            .update_workflow("keyed-1", "adjust", json!([2]), None)
31807            .await
31808            .expect_err("different intent under a retained generated key");
31809        let sent = server.request_body(KEYED_UPDATE_PATH);
31810        assert_eq!(
31811            error.request_id(),
31812            sent["request_id"].as_str().map(str::to_string)
31813        );
31814        assert_eq!(
31815            error
31816                .request_id_conflict()
31817                .expect("conflict details")
31818                .retained_command_type
31819                .as_deref(),
31820            Some("update")
31821        );
31822    }
31823
31824    #[tokio::test]
31825    async fn native_request_id_conflict_is_typed_carries_the_sent_key_and_is_sent_once() {
31826        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31827            request_override: Some(native_command_key_server),
31828            ..MockWorkerBehavior::default()
31829        });
31830        let client = keyed_client(&server);
31831
31832        let error = client
31833            .signal_workflow_with_request_id("keyed-1", "approve", json!(["changed"]), "approve-1")
31834            .await
31835            .expect_err("changed arguments under a retained key");
31836        assert!(
31837            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT),
31838            "{error:?}"
31839        );
31840        assert!(error.is_request_id_conflict());
31841        assert_eq!(error.request_id().as_deref(), Some("approve-1"));
31842        let conflict = error.request_id_conflict().expect("conflict details");
31843        assert_eq!(conflict.status, 409);
31844        assert_eq!(conflict.request_id, "approve-1");
31845        assert_eq!(
31846            conflict.retained_command_id.as_deref(),
31847            Some("cmd-native-1")
31848        );
31849        assert_eq!(conflict.retained_command_type, None);
31850        assert_eq!(
31851            conflict.retained_outcome.as_deref(),
31852            Some("signal_received")
31853        );
31854        assert_eq!(conflict.conflict, ["arguments"]);
31855        assert_eq!(conflict.body["outcome"], "rejected_request_id_conflict");
31856        assert_eq!(
31857            server.request_bodies(KEYED_SIGNAL_PATH).len(),
31858            1,
31859            "never resent"
31860        );
31861
31862        let error = client
31863            .signal_workflow_run_with_request_id(
31864                "keyed-1",
31865                "run-keyed-1",
31866                "approve",
31867                json!(["ok"]),
31868                "approve-1",
31869            )
31870            .await
31871            .expect_err("another run target under a retained key");
31872        let conflict = error.request_id_conflict().expect("conflict details");
31873        assert_eq!(conflict.conflict, ["target_or_arguments"]);
31874        assert_eq!(conflict.request_id, "approve-1");
31875        assert_eq!(server.request_bodies(KEYED_RUN_SIGNAL_PATH).len(), 1);
31876
31877        let error = client
31878            .update_workflow("keyed-1", "adjust", json!(["changed"]), None)
31879            .await
31880            .expect_err("changed update under a retained generated key");
31881        let sent = server.request_body(KEYED_UPDATE_PATH);
31882        let conflict = error.request_id_conflict().expect("conflict details");
31883        assert_eq!(
31884            Some(conflict.request_id.as_str()),
31885            sent["request_id"].as_str()
31886        );
31887        assert_eq!(error.request_id().as_deref(), sent["request_id"].as_str());
31888        assert_eq!(conflict.conflict, ["arguments"]);
31889        assert_eq!(
31890            server.request_bodies(KEYED_UPDATE_PATH).len(),
31891            1,
31892            "never resent"
31893        );
31894    }
31895
31896    #[tokio::test]
31897    async fn native_identical_retry_returns_the_original_receipt() {
31898        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31899            request_override: Some(native_command_key_server),
31900            ..MockWorkerBehavior::default()
31901        });
31902        let client = keyed_client(&server);
31903
31904        let receipt = client
31905            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "approve-1")
31906            .await
31907            .expect("retained signal receipt");
31908        assert_eq!(receipt["command_id"], "cmd-native-1");
31909        assert_eq!(receipt["retained"], true);
31910        assert_eq!(receipt["intent_verified"], true);
31911        assert_eq!(receipt["request_id"], "approve-1");
31912
31913        let result = client
31914            .update_workflow("keyed-1", "adjust", json!(["ok"]), Some("adjust-1"))
31915            .await
31916            .expect("retained update result");
31917        assert_eq!(result, json!(7));
31918    }
31919
31920    #[tokio::test]
31921    async fn older_server_without_command_keys_is_unchanged() {
31922        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31923            request_override: Some(legacy_command_server),
31924            ..MockWorkerBehavior::default()
31925        });
31926        let client = keyed_client(&server);
31927
31928        // Before native 3.9.0 the same key with other input is admitted again.
31929        for input in [json!(["ok"]), json!(["changed"])] {
31930            let receipt = client
31931                .signal_workflow_with_request_id("keyed-1", "approve", input, "approve-1")
31932                .await
31933                .expect("legacy receipt");
31934            assert_eq!(receipt["request_id"], "approve-1");
31935            assert_eq!(receipt.get("retained"), None);
31936        }
31937        assert_eq!(server.request_bodies(KEYED_SIGNAL_PATH).len(), 2);
31938    }
31939
31940    #[test]
31941    fn a_sent_key_is_added_only_to_conflicts_that_do_not_echo_one() {
31942        let conflict = Error::Http {
31943            status: reqwest::StatusCode::CONFLICT,
31944            body: r#"{"reason":"request_id_conflict","retained_command_id":"cmd-1","conflict":["name"]}"#
31945                .to_string(),
31946        }
31947        .with_sent_request_id("sent");
31948        assert_eq!(conflict.request_id().as_deref(), Some("sent"));
31949
31950        let echoed = Error::Http {
31951            status: reqwest::StatusCode::CONFLICT,
31952            body: r#"{"reason":"request_id_conflict","request_id":"echoed"}"#.to_string(),
31953        }
31954        .with_sent_request_id("sent");
31955        assert_eq!(echoed.request_id().as_deref(), Some("echoed"));
31956
31957        let other = r#"{"reason":"run_not_active"}"#;
31958        let refused = Error::Http {
31959            status: reqwest::StatusCode::CONFLICT,
31960            body: other.to_string(),
31961        }
31962        .with_sent_request_id("sent");
31963        assert!(matches!(refused, Error::Http { ref body, .. } if body == other));
31964        assert!(matches!(
31965            Error::Timeout.with_sent_request_id("sent"),
31966            Error::Timeout
31967        ));
31968    }
31969
31970    #[tokio::test]
31971    async fn request_id_ambiguous_is_typed_carries_the_sent_key_and_is_sent_once() {
31972        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
31973            request_override: Some(ambiguous_command_server),
31974            ..MockWorkerBehavior::default()
31975        });
31976        let client = keyed_client(&server);
31977
31978        let error = client
31979            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "legacy-key")
31980            .await
31981            .expect_err("ambiguous legacy key");
31982        assert!(
31983            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT),
31984            "existing Error::Http matching keeps working: {error:?}"
31985        );
31986        assert!(error.is_request_id_ambiguous());
31987        assert!(
31988            !error.is_request_id_conflict(),
31989            "ambiguity is not a conflict"
31990        );
31991        let ambiguous = error.request_id_ambiguous().expect("ambiguity details");
31992        assert_eq!(ambiguous.status, 409);
31993        assert_eq!(ambiguous.request_id, "legacy-key");
31994        assert!(ambiguous.message.contains("more than one retained command"));
31995        assert_eq!(ambiguous.body["intent_verified"], false);
31996        assert_eq!(
31997            ambiguous.body.get("command_id"),
31998            None,
31999            "no receipt selected"
32000        );
32001        assert_eq!(
32002            server.request_bodies(KEYED_SIGNAL_PATH).len(),
32003            1,
32004            "never resent"
32005        );
32006
32007        // The update refusal does not echo the key; the SDK names the one it sent.
32008        let error = client
32009            .update_workflow("keyed-1", "adjust", json!([1]), None)
32010            .await
32011            .expect_err("ambiguous generated update key");
32012        let sent = server.request_body(KEYED_UPDATE_PATH);
32013        let ambiguous = error.request_id_ambiguous().expect("ambiguity details");
32014        assert_eq!(
32015            Some(ambiguous.request_id.as_str()),
32016            sent["request_id"].as_str()
32017        );
32018        assert_eq!(error.request_id().as_deref(), sent["request_id"].as_str());
32019        assert!(!matches!(error, Error::UpdateStillPending(_)));
32020        let error = client
32021            .update_workflow_receipt("keyed-1", "adjust", json!([1]), Some("legacy-key"))
32022            .await
32023            .expect_err("the receipt form refuses ambiguity too");
32024        assert!(error.is_request_id_ambiguous());
32025        assert_eq!(
32026            server.request_bodies(KEYED_UPDATE_PATH).len(),
32027            2,
32028            "one send per call"
32029        );
32030    }
32031
32032    #[test]
32033    fn ambiguity_and_conflict_classifiers_do_not_overlap() {
32034        let conflict = Error::Http {
32035            status: reqwest::StatusCode::CONFLICT,
32036            body: r#"{"reason":"request_id_conflict"}"#.to_string(),
32037        };
32038        assert!(conflict.is_request_id_conflict() && !conflict.is_request_id_ambiguous());
32039        let ambiguous = Error::Http {
32040            status: reqwest::StatusCode::CONFLICT,
32041            body: r#"{"reason":"request_id_ambiguous"}"#.to_string(),
32042        }
32043        .with_sent_request_id("sent");
32044        assert!(ambiguous.is_request_id_ambiguous() && !ambiguous.is_request_id_conflict());
32045        assert_eq!(ambiguous.request_id().as_deref(), Some("sent"));
32046        let echoed = Error::Http {
32047            status: reqwest::StatusCode::CONFLICT,
32048            body: r#"{"reason":"request_id_ambiguous","request_id":"echoed"}"#.to_string(),
32049        }
32050        .with_sent_request_id("sent");
32051        assert_eq!(echoed.request_id().as_deref(), Some("echoed"));
32052        assert!(!Error::Timeout.is_request_id_ambiguous());
32053    }
32054
32055    #[tokio::test]
32056    async fn legacy_unverified_readback_is_returned_with_its_flags_not_as_a_verified_match() {
32057        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32058            request_override: Some(legacy_unverified_command_server),
32059            ..MockWorkerBehavior::default()
32060        });
32061        let client = keyed_client(&server);
32062        let handle = keyed_handle(&client);
32063
32064        let receipt = client
32065            .signal_workflow_with_request_id("keyed-1", "approve", json!(["changed"]), "old-key")
32066            .await
32067            .expect("legacy readback is a receipt, not an error");
32068        assert_eq!(receipt["retained"], true);
32069        assert_eq!(receipt["intent_verified"], false);
32070        assert_eq!(receipt["command_id"], "cmd-legacy-1");
32071
32072        let receipt = client
32073            .update_workflow_receipt("keyed-1", "adjust", json!(["changed"]), Some("old-key"))
32074            .await
32075            .expect("update receipt");
32076        assert_eq!(receipt["retained"], true);
32077        assert_eq!(receipt["intent_verified"], false);
32078        assert_eq!(receipt["update_id"], "upd-legacy-1");
32079        assert_eq!(receipt["request_id"], "old-key");
32080        let receipt = handle
32081            .update_receipt("adjust", json!(["changed"]), Some("old-key"))
32082            .await
32083            .expect("handle update receipt");
32084        assert_eq!(receipt["intent_verified"], false);
32085        assert_eq!(
32086            client
32087                .update_workflow("keyed-1", "adjust", json!(["changed"]), Some("old-key"))
32088                .await
32089                .expect("result form"),
32090            json!(5)
32091        );
32092        let bodies = server.request_bodies(KEYED_UPDATE_PATH);
32093        assert_eq!(bodies.len(), 3, "one send per call");
32094        assert!(bodies.iter().all(|body| body["request_id"] == "old-key"));
32095    }
32096
32097    #[tokio::test]
32098    async fn update_receipt_returns_a_pending_receipt_instead_of_an_error() {
32099        fn pending(path: &str, body: &str, _: usize) -> Option<(&'static str, String)> {
32100            let request = keyed_command_request(path, body)?;
32101            Some((
32102                "202 Accepted",
32103                json!({"workflow_id":"keyed-1","run_id":"run-keyed-1","update_id":"upd-1",
32104                    "update_status":"accepted","wait_timed_out":true,
32105                    "request_id":request["request_id"],"retained":false,"intent_verified":true})
32106                .to_string(),
32107            ))
32108        }
32109        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32110            request_override: Some(pending),
32111            ..MockWorkerBehavior::default()
32112        });
32113        let client = keyed_client(&server);
32114        let receipt = client
32115            .update_workflow_receipt("keyed-1", "adjust", json!([1]), None)
32116            .await
32117            .expect("pending receipt");
32118        assert_eq!(receipt["update_status"], "accepted");
32119        assert_generated_request_id(
32120            receipt["request_id"].as_str().expect("key"),
32121            "sdk-rust-update-",
32122        );
32123        assert!(matches!(
32124            client
32125                .update_workflow("keyed-1", "adjust", json!([1]), None)
32126                .await,
32127            Err(Error::UpdateStillPending(_))
32128        ));
32129    }
32130
32131    #[tokio::test]
32132    async fn other_refusals_echoing_the_key_are_not_request_id_conflicts() {
32133        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32134            request_override: Some(closed_run_command_server),
32135            ..MockWorkerBehavior::default()
32136        });
32137        let client = keyed_client(&server);
32138
32139        let error = client
32140            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), "closed-key")
32141            .await
32142            .expect_err("closed run");
32143
32144        assert!(matches!(error, Error::Http { status, .. } if status.as_u16() == 409));
32145        assert!(!error.is_request_id_conflict());
32146        assert_eq!(error.request_id_conflict(), None);
32147        assert_eq!(error.request_id().as_deref(), Some("closed-key"));
32148    }
32149
32150    #[tokio::test]
32151    async fn transport_failure_keeps_error_transport_and_the_held_key_retries_identically() {
32152        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
32153            request_override: Some(keyed_command_server),
32154            drop_request: Some(drop_first_keyed_signal),
32155            ..MockWorkerBehavior::default()
32156        });
32157        let client = keyed_client(&server);
32158        let request_id = Client::generate_signal_request_id();
32159
32160        let error = client
32161            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
32162            .await
32163            .expect_err("connection closed before any response");
32164        assert!(
32165            matches!(error, Error::Transport(_)),
32166            "the transport variant is unchanged: {error:?}"
32167        );
32168        assert_eq!(
32169            error.request_id(),
32170            None,
32171            "nothing was echoed; the application holds the key it chose"
32172        );
32173
32174        let receipt = client
32175            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &request_id)
32176            .await
32177            .expect("manual retry with the same key");
32178        assert_eq!(receipt["request_id"], request_id);
32179        let bodies = server.request_bodies(KEYED_SIGNAL_PATH);
32180        assert_eq!(bodies.len(), 2, "one attempt per call, no automatic retry");
32181        assert_eq!(
32182            bodies[0], bodies[1],
32183            "the retry resends the identical key and input"
32184        );
32185        assert_eq!(bodies[0]["request_id"], request_id);
32186    }
32187
32188    #[tokio::test]
32189    async fn invalid_command_keys_are_refused_before_sending() {
32190        let server = MockWorkerServer::start();
32191        let client = keyed_client(&server);
32192        let too_long = "k".repeat(MAX_REQUEST_ID_CHARACTERS + 1);
32193
32194        for request_id in ["", too_long.as_str()] {
32195            let error = client
32196                .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), request_id)
32197                .await
32198                .expect_err("invalid signal key");
32199            assert!(
32200                matches!(error, Error::Codec(ref message) if message.contains("1 to 255 Unicode characters")),
32201                "{error:?}"
32202            );
32203            let error = client
32204                .update_workflow("keyed-1", "adjust", json!([1]), Some(request_id))
32205                .await
32206                .expect_err("invalid update key");
32207            assert!(matches!(error, Error::Codec(_)), "{error:?}");
32208        }
32209        assert!(server.captured_paths().is_empty(), "nothing was sent");
32210
32211        let longest = "k".repeat(MAX_REQUEST_ID_CHARACTERS);
32212        let _ = client
32213            .signal_workflow_with_request_id("keyed-1", "approve", json!(["ok"]), &longest)
32214            .await;
32215        assert_eq!(
32216            server.request_body(KEYED_SIGNAL_PATH)["request_id"],
32217            longest
32218        );
32219    }
32220
32221    #[test]
32222    fn generated_command_keys_are_distinct_and_well_formed() {
32223        let signal = Client::generate_signal_request_id();
32224        let update = Client::generate_update_request_id();
32225        assert_generated_request_id(&signal, "sdk-rust-signal-");
32226        assert_generated_request_id(&update, "sdk-rust-update-");
32227        assert_ne!(Client::generate_signal_request_id(), signal);
32228        assert!(validate_request_id(&signal).is_ok());
32229    }
32230
32231    #[test]
32232    fn command_keys_preserve_the_published_server_unicode_character_limit() {
32233        assert!(validate_request_id(&"é".repeat(255)).is_ok());
32234        assert!(validate_request_id(&"😀".repeat(255)).is_ok());
32235        assert!(validate_request_id(&"é".repeat(256)).is_err());
32236    }
32237
32238    #[test]
32239    fn request_id_accessors_read_only_echoed_refusal_bodies() {
32240        let conflict = Error::Http {
32241            status: reqwest::StatusCode::CONFLICT,
32242            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(),
32243        };
32244        assert!(conflict.is_request_id_conflict());
32245        assert_eq!(conflict.request_id().as_deref(), Some("k1"));
32246        let details = conflict.request_id_conflict().expect("conflict details");
32247        assert_eq!(details.conflict, ["name"]);
32248        assert_eq!(
32249            details.message,
32250            "request id is retained for a different command intent"
32251        );
32252
32253        let echoed = Error::Http {
32254            status: reqwest::StatusCode::CONFLICT,
32255            body: r#"{"reason":"run_not_active","request_id":"k2"}"#.to_string(),
32256        };
32257        assert!(!echoed.is_request_id_conflict());
32258        assert_eq!(echoed.request_id().as_deref(), Some("k2"));
32259
32260        let blank = Error::Http {
32261            status: reqwest::StatusCode::UNPROCESSABLE_ENTITY,
32262            body: r#"{"request_id":""}"#.to_string(),
32263        };
32264        assert_eq!(blank.request_id(), None);
32265        let text = Error::Http {
32266            status: reqwest::StatusCode::BAD_GATEWAY,
32267            body: "upstream unavailable".to_string(),
32268        };
32269        assert_eq!(text.request_id(), None);
32270        assert!(!text.is_request_id_conflict());
32271
32272        let rejection = Error::WorkflowCommandRejected(WorkflowCommandRejection {
32273            command: WorkflowCommandKind::Cancel,
32274            status: 409,
32275            reason: "request_id_conflict".to_string(),
32276            message: "retained".to_string(),
32277            workflow_id: "wf".to_string(),
32278            run_id: None,
32279            target_scope: None,
32280            body: json!({"reason": "request_id_conflict", "request_id": "k3", "conflict": []}),
32281        });
32282        assert!(rejection.is_request_id_conflict());
32283        assert_eq!(rejection.request_id().as_deref(), Some("k3"));
32284
32285        assert_eq!(Error::Timeout.request_id(), None);
32286        assert!(!Error::Codec("local".to_string()).is_request_id_conflict());
32287    }
32288
32289    #[tokio::test]
32290    async fn public_client_surfaces_send_and_receive_lossless_avro_values() {
32291        let server = MockWorkerServer::start();
32292        let client = Client::builder(server.base_url())
32293            .timeout(Duration::from_secs(2))
32294            .build()
32295            .expect("client");
32296        let arguments = AvroValue::Array(vec![typed_fidelity_probe()]);
32297
32298        client
32299            .start_workflow(
32300                "typed.echo",
32301                "rust-workers",
32302                "typed-start",
32303                arguments.clone(),
32304            )
32305            .await
32306            .expect("typed workflow start");
32307        assert_eq!(
32308            decode_wire_avro_value(
32309                &server.request_body("/api/workflows")["input"],
32310                DEFAULT_CODEC,
32311            )
32312            .expect("typed start input"),
32313            arguments
32314        );
32315
32316        client
32317            .signal_workflow("typed-1", "changed", arguments.clone())
32318            .await
32319            .expect("typed signal");
32320        assert_eq!(
32321            decode_wire_avro_value(
32322                &server.request_body("/api/workflows/typed-1/signal/changed")["input"],
32323                DEFAULT_CODEC,
32324            )
32325            .expect("typed signal input"),
32326            arguments
32327        );
32328
32329        assert_eq!(
32330            client
32331                .query_workflow_avro_value("typed-1", "inspect", arguments.clone())
32332                .await
32333                .expect("typed query"),
32334            typed_fidelity_probe()
32335        );
32336        assert_eq!(
32337            decode_wire_avro_value(
32338                &server.request_body("/api/workflows/typed-1/query/inspect")["input"],
32339                DEFAULT_CODEC,
32340            )
32341            .expect("typed query input"),
32342            arguments
32343        );
32344
32345        assert_eq!(
32346            client
32347                .update_workflow_avro_value(
32348                    "typed-1",
32349                    "replace",
32350                    arguments.clone(),
32351                    Some("typed-request"),
32352                )
32353                .await
32354                .expect("typed update"),
32355            typed_fidelity_probe()
32356        );
32357        let update = server.request_body("/api/workflows/typed-1/update/replace");
32358        assert_eq!(update["request_id"], "typed-request");
32359        assert_eq!(
32360            decode_wire_avro_value(&update["input"], DEFAULT_CODEC).expect("typed update input"),
32361            arguments
32362        );
32363
32364        let handle = WorkflowHandle {
32365            client: client.clone(),
32366            workflow_id: "typed-1".to_string(),
32367            run_id: Some("run-typed-1".to_string()),
32368            workflow_type: "typed.echo".to_string(),
32369        };
32370        assert_eq!(
32371            handle
32372                .result_avro_value(WorkflowResultOptions::default())
32373                .await
32374                .expect("typed workflow result"),
32375            typed_fidelity_probe()
32376        );
32377
32378        client
32379            .complete_activity_task(
32380                "activity-typed",
32381                "attempt-typed",
32382                "rust-worker",
32383                typed_fidelity_probe(),
32384                DEFAULT_CODEC,
32385            )
32386            .await
32387            .expect("typed activity completion");
32388        assert_eq!(
32389            decode_wire_avro_value(
32390                &server.request_body("/api/worker/activity-tasks/activity-typed/complete")
32391                    ["result"],
32392                DEFAULT_CODEC,
32393            )
32394            .expect("typed activity result"),
32395            typed_fidelity_probe()
32396        );
32397        client
32398            .fail_activity_task(
32399                "activity-typed",
32400                "attempt-typed",
32401                "rust-worker",
32402                "typed failure",
32403                true,
32404            )
32405            .await
32406            .expect("activity failure");
32407    }
32408
32409    #[tokio::test]
32410    async fn lifecycle_commands_support_instance_and_selected_run_targets() {
32411        let server = MockWorkerServer::start();
32412        let client = Client::builder(server.base_url())
32413            .timeout(Duration::from_secs(2))
32414            .build()
32415            .expect("client");
32416
32417        let options = WorkflowCommandOptions::new()
32418            .reason("cleanup requested")
32419            .request_id("cancel-17");
32420        let cancelled = client
32421            .cancel_workflow("wf-lifecycle", options)
32422            .await
32423            .expect("instance cancellation");
32424        assert_eq!(cancelled.command, WorkflowCommandKind::Cancel);
32425        assert_eq!(cancelled.run_id.as_deref(), Some("run-current"));
32426        assert_eq!(cancelled.outcome.as_deref(), Some("cancelled"));
32427        assert_eq!(
32428            server.request_body("/api/workflows/wf-lifecycle/cancel"),
32429            json!({"reason":"cleanup requested","request_id":"cancel-17"})
32430        );
32431
32432        let terminated = client
32433            .terminate_workflow(
32434                "wf-lifecycle",
32435                WorkflowCommandOptions::new().reason("forced stop"),
32436            )
32437            .await
32438            .expect("instance termination");
32439        assert_eq!(terminated.command, WorkflowCommandKind::Terminate);
32440        assert_eq!(terminated.outcome.as_deref(), Some("terminated"));
32441
32442        client
32443            .cancel_workflow_run(
32444                "wf-lifecycle",
32445                "run-current",
32446                WorkflowCommandOptions::default(),
32447            )
32448            .await
32449            .expect("selected run cancellation");
32450        client
32451            .terminate_workflow_run(
32452                "wf-lifecycle",
32453                "run-current",
32454                WorkflowCommandOptions::default(),
32455            )
32456            .await
32457            .expect("selected run termination");
32458
32459        for (command, error) in [
32460            (
32461                WorkflowCommandKind::Cancel,
32462                client
32463                    .cancel_workflow_run(
32464                        "wf-lifecycle",
32465                        "run-stale",
32466                        WorkflowCommandOptions::default(),
32467                    )
32468                    .await
32469                    .expect_err("stale cancellation must be rejected"),
32470            ),
32471            (
32472                WorkflowCommandKind::Terminate,
32473                client
32474                    .terminate_workflow_run(
32475                        "wf-lifecycle",
32476                        "run-stale",
32477                        WorkflowCommandOptions::default(),
32478                    )
32479                    .await
32480                    .expect_err("stale termination must be rejected"),
32481            ),
32482        ] {
32483            let Error::WorkflowCommandRejected(rejection) = error else {
32484                panic!("expected typed command rejection");
32485            };
32486            assert_eq!(rejection.command, command);
32487            assert_eq!(rejection.status, 409);
32488            assert_eq!(rejection.reason, "historical_run_command_rejected");
32489            assert_eq!(rejection.run_id.as_deref(), Some("run-stale"));
32490            assert_eq!(rejection.target_scope.as_deref(), Some("run"));
32491        }
32492    }
32493
32494    #[tokio::test]
32495    async fn redrive_targets_a_failed_run_and_returns_successor_identity() {
32496        let server = MockWorkerServer::start();
32497        let client = Client::builder(server.base_url())
32498            .timeout(Duration::from_secs(2))
32499            .build()
32500            .expect("client");
32501
32502        let result = client
32503            .redrive_workflow_run("wf-lifecycle", "run-failed", Some("retry-1"))
32504            .await
32505            .expect("redrive accepted");
32506        assert_eq!(result.workflow_id, "wf-lifecycle");
32507        assert_eq!(result.source_run_id, "run-failed");
32508        assert_eq!(result.run_id, "run-successor");
32509        assert_eq!(result.resume_step_sequence, 2);
32510        assert_eq!(
32511            server.request_body("/api/workflows/wf-lifecycle/runs/run-failed/redrive"),
32512            json!({"request_id":"retry-1"})
32513        );
32514
32515        let repeated = client
32516            .redrive_workflow_run("wf-lifecycle", "run-failed-existing", Some("retry-1"))
32517            .await
32518            .expect("idempotent redrive response accepted");
32519        assert_eq!(repeated.run_id, "run-successor");
32520
32521        let error = client
32522            .redrive_workflow_run("wf-lifecycle", "run-completed", None)
32523            .await
32524            .expect_err("completed run must be rejected");
32525        let Error::Http { status, body } = error else {
32526            panic!("expected HTTP redrive rejection");
32527        };
32528        assert_eq!(status.as_u16(), 409);
32529        assert!(body.contains("run_not_failed"));
32530        assert_eq!(
32531            server.request_body("/api/workflows/wf-lifecycle/runs/run-completed/redrive"),
32532            json!({})
32533        );
32534
32535        let handle = WorkflowHandle {
32536            client: client.clone(),
32537            workflow_id: "wf-lifecycle".to_string(),
32538            run_id: Some("run-failed".to_string()),
32539            workflow_type: "test".to_string(),
32540        };
32541        assert_eq!(
32542            handle.redrive(None).await.expect("handle redrive").run_id,
32543            "run-successor"
32544        );
32545        let missing_run = WorkflowHandle {
32546            run_id: None,
32547            ..handle
32548        };
32549        assert!(matches!(
32550            missing_run.redrive(None).await,
32551            Err(Error::Codec(_))
32552        ));
32553    }
32554
32555    #[tokio::test]
32556    async fn workflow_start_options_send_server_enforced_deadlines() {
32557        let server = MockWorkerServer::start();
32558        let client = Client::builder(server.base_url())
32559            .timeout(Duration::from_secs(2))
32560            .build()
32561            .expect("client");
32562
32563        let handle = client
32564            .start_workflow_with_options(
32565                "rust.timeout",
32566                "rust-timeouts",
32567                "wf-start-options",
32568                WorkflowStartOptions::new()
32569                    .execution_timeout_seconds(30)
32570                    .run_timeout_seconds(1),
32571                json!([]),
32572            )
32573            .await
32574            .expect("workflow start");
32575
32576        assert_eq!(handle.run_id.as_deref(), Some("run-start-options"));
32577        let body = server.request_body("/api/workflows");
32578        assert_eq!(body["execution_timeout_seconds"], 30);
32579        assert_eq!(body["run_timeout_seconds"], 1);
32580
32581        let invalid = client
32582            .start_workflow_with_options(
32583                "rust.timeout",
32584                "rust-timeouts",
32585                "wf-invalid-options",
32586                WorkflowStartOptions::new()
32587                    .execution_timeout_seconds(1)
32588                    .run_timeout_seconds(2),
32589                json!([]),
32590            )
32591            .await
32592            .expect_err("invalid deadline ordering");
32593        assert!(invalid
32594            .to_string()
32595            .contains("run_timeout_seconds cannot exceed execution_timeout_seconds"));
32596    }
32597
32598    async fn terminal_error(client: &Client, workflow_id: &str, run_id: Option<&str>) -> Error {
32599        WorkflowHandle {
32600            client: client.clone(),
32601            workflow_id: workflow_id.to_string(),
32602            run_id: run_id.map(str::to_string),
32603            workflow_type: "terminal".to_string(),
32604        }
32605        .result(WorkflowResultOptions {
32606            poll_interval: Duration::ZERO,
32607            timeout: Duration::from_secs(1),
32608        })
32609        .await
32610        .expect_err("terminal outcome")
32611    }
32612
32613    #[tokio::test]
32614    async fn workflow_result_fills_missing_terminal_detail_from_history() {
32615        let server = MockWorkerServer::start();
32616        let client = Client::builder(server.base_url())
32617            .timeout(Duration::from_secs(2))
32618            .build()
32619            .expect("client");
32620
32621        let Error::WorkflowFailed(failed) = terminal_error(&client, "wf-native-failed", None).await
32622        else {
32623            panic!("expected WorkflowFailed");
32624        };
32625        assert_eq!(failed.run_id.as_deref(), Some("run-native-failed"));
32626        assert_eq!(failed.reason, "failed");
32627        assert_eq!(failed.exception_type.as_deref(), Some("ActivityFailed"));
32628        assert_eq!(
32629            failed.exception_class.as_deref(),
32630            Some("durable_workflow::ActivityFailure")
32631        );
32632        assert_eq!(
32633            failed.message.as_deref(),
32634            Some("activity failed (activity): rejected bob")
32635        );
32636        assert_eq!(failed.non_retryable, Some(true));
32637        assert_eq!(failed.failure_category.as_deref(), Some("application"));
32638        assert_eq!(failed.failure_id.as_deref(), Some("failure-native"));
32639        assert_eq!(
32640            failed.exception.as_ref().and_then(|e| e.get("type")),
32641            Some(&json!("ActivityFailed"))
32642        );
32643
32644        // The same detail is filled for an explicitly selected run.
32645        let Error::WorkflowFailed(selected) =
32646            terminal_error(&client, "wf-native-failed", Some("run-native-failed")).await
32647        else {
32648            panic!("expected WorkflowFailed");
32649        };
32650        assert_eq!(selected.exception_type.as_deref(), Some("ActivityFailed"));
32651
32652        let Error::WorkflowTimedOut(timed_out) =
32653            terminal_error(&client, "wf-native-timed-out", None).await
32654        else {
32655            panic!("expected WorkflowTimedOut");
32656        };
32657        assert_eq!(timed_out.reason, "execution_timeout");
32658        assert_eq!(timed_out.failure_category.as_deref(), Some("timeout"));
32659        assert_eq!(
32660            timed_out.message.as_deref(),
32661            Some("Workflow execution deadline expired.")
32662        );
32663
32664        let Error::WorkflowFailed(paged) = terminal_error(&client, "wf-native-paged", None).await
32665        else {
32666            panic!("expected WorkflowFailed");
32667        };
32668        assert_eq!(paged.exception_type.as_deref(), Some("PagedFailure"));
32669        assert_eq!(paged.message.as_deref(), Some("found on page two"));
32670
32671        // An unavailable history keeps the describe-only outcome.
32672        let Error::WorkflowFailed(bare) =
32673            terminal_error(&client, "wf-native-no-history", None).await
32674        else {
32675            panic!("expected WorkflowFailed");
32676        };
32677        assert_eq!(bare.reason, "failed");
32678        assert_eq!(bare.exception_type, None);
32679        assert_eq!(bare.message, None);
32680        assert_eq!(
32681            server
32682                .method_for(
32683                    "/api/workflows/wf-native-no-history/runs/run-native-no-history/history"
32684                )
32685                .as_deref(),
32686            Some("GET")
32687        );
32688
32689        // A complete description, and a non-failure terminal state, never read history.
32690        let Error::WorkflowFailed(complete) =
32691            terminal_error(&client, "wf-failed", Some("run-failed")).await
32692        else {
32693            panic!("expected WorkflowFailed");
32694        };
32695        assert_eq!(complete.exception_type.as_deref(), Some("PaymentError"));
32696        assert!(matches!(
32697            terminal_error(&client, "wf-cancelled", None).await,
32698            Error::WorkflowCancelled(_)
32699        ));
32700        assert!(matches!(
32701            terminal_error(&client, "wf-timed-out", None).await,
32702            Error::WorkflowTimedOut(_)
32703        ));
32704        for path in [
32705            "/api/workflows/wf-failed/runs/run-failed/history",
32706            "/api/workflows/wf-cancelled/runs/run-cancelled/history",
32707            "/api/workflows/wf-timed-out/runs/run-timed-out/history",
32708        ] {
32709            assert_eq!(server.method_for(path), None, "{path} must not be read");
32710        }
32711    }
32712
32713    #[tokio::test]
32714    async fn workflow_result_returns_each_typed_terminal_outcome() {
32715        let server = MockWorkerServer::start();
32716        let client = Client::builder(server.base_url())
32717            .timeout(Duration::from_secs(2))
32718            .build()
32719            .expect("client");
32720        let options = WorkflowResultOptions {
32721            poll_interval: Duration::ZERO,
32722            timeout: Duration::from_secs(1),
32723        };
32724
32725        let failed = WorkflowHandle {
32726            client: client.clone(),
32727            workflow_id: "wf-failed".to_string(),
32728            run_id: Some("run-failed".to_string()),
32729            workflow_type: "failure".to_string(),
32730        }
32731        .result(options)
32732        .await
32733        .expect_err("failed outcome");
32734        let Error::WorkflowFailed(failure) = failed else {
32735            panic!("expected WorkflowFailed");
32736        };
32737        assert_eq!(failure.workflow_id, "wf-failed");
32738        assert_eq!(failure.run_id.as_deref(), Some("run-failed"));
32739        assert_eq!(failure.failure_id.as_deref(), Some("failure-17"));
32740        assert_eq!(failure.failure_category.as_deref(), Some("application"));
32741        assert_eq!(failure.exception_type.as_deref(), Some("PaymentError"));
32742        assert_eq!(
32743            failure.exception_class.as_deref(),
32744            Some("billing::PaymentError")
32745        );
32746        assert_eq!(failure.non_retryable, Some(true));
32747
32748        for (workflow_id, expected_kind, expected_reason) in [
32749            (
32750                "wf-cancelled",
32751                WorkflowTerminalKind::Cancelled,
32752                "cleanup requested",
32753            ),
32754            (
32755                "wf-terminated",
32756                WorkflowTerminalKind::Terminated,
32757                "forced stop",
32758            ),
32759            (
32760                "wf-timed-out",
32761                WorkflowTerminalKind::TimedOut,
32762                "run_timeout",
32763            ),
32764        ] {
32765            let error = WorkflowHandle {
32766                client: client.clone(),
32767                workflow_id: workflow_id.to_string(),
32768                run_id: None,
32769                workflow_type: "terminal".to_string(),
32770            }
32771            .result(options)
32772            .await
32773            .expect_err("typed terminal outcome");
32774            let outcome = match error {
32775                Error::WorkflowCancelled(outcome) => outcome,
32776                Error::WorkflowTerminated(outcome) => outcome,
32777                Error::WorkflowTimedOut(outcome) => outcome,
32778                other => panic!("unexpected terminal error: {other}"),
32779            };
32780            assert_eq!(outcome.kind, expected_kind);
32781            assert_eq!(outcome.workflow_id, workflow_id);
32782            assert_eq!(outcome.reason, expected_reason);
32783        }
32784
32785        let wait_timeout = WorkflowHandle {
32786            client,
32787            workflow_id: "wf-waiting".to_string(),
32788            run_id: Some("run-waiting".to_string()),
32789            workflow_type: "waiting".to_string(),
32790        }
32791        .result(WorkflowResultOptions {
32792            poll_interval: Duration::ZERO,
32793            timeout: Duration::ZERO,
32794        })
32795        .await
32796        .expect_err("client wait timeout");
32797        let Error::WorkflowTimedOut(timeout) = wait_timeout else {
32798            panic!("expected typed client timeout");
32799        };
32800        assert_eq!(timeout.reason, "result_wait_timeout");
32801        assert_eq!(timeout.failure_category.as_deref(), Some("client_timeout"));
32802        assert_eq!(timeout.run_id.as_deref(), Some("run-waiting"));
32803    }
32804
32805    #[tokio::test]
32806    async fn workflow_result_follows_chain_and_selected_result_preserves_history() {
32807        let server = MockWorkerServer::start();
32808        let client = Client::builder(server.base_url())
32809            .timeout(Duration::from_secs(2))
32810            .build()
32811            .expect("client");
32812
32813        let handle = WorkflowHandle {
32814            client,
32815            workflow_id: "wf-selected".to_string(),
32816            run_id: Some("run-selected".to_string()),
32817            workflow_type: "selected".to_string(),
32818        };
32819        let options = WorkflowResultOptions {
32820            poll_interval: Duration::ZERO,
32821            timeout: Duration::from_secs(1),
32822        };
32823
32824        let current = handle
32825            .result(options)
32826            .await
32827            .expect("instance result follows the current run");
32828        assert_eq!(current, json!("current run output"));
32829
32830        let error = handle
32831            .result_selected_run(options)
32832            .await
32833            .expect_err("the selected run is cancelled even though the current run completed");
32834
32835        let Error::WorkflowCancelled(outcome) = error else {
32836            panic!("expected selected run cancellation");
32837        };
32838        assert_eq!(outcome.run_id.as_deref(), Some("run-selected"));
32839        assert_eq!(outcome.reason, "selected run cancelled");
32840        assert_eq!(
32841            server.request_count("/api/workflows/wf-selected/runs/run-selected"),
32842            1
32843        );
32844        assert_eq!(server.request_count("/api/workflows/wf-selected"), 1);
32845    }
32846
32847    #[tokio::test]
32848    async fn poll_responses_decode_http_conflict_drain_as_a_stable_stop() {
32849        let server = MockWorkerServer::draining_polls();
32850        let client = Client::builder(server.base_url())
32851            .timeout(Duration::from_secs(2))
32852            .build()
32853            .expect("client");
32854
32855        let workflow = client
32856            .poll_workflow_task_response("draining-worker", "rust-workers", Duration::ZERO)
32857            .await
32858            .expect("workflow drain response");
32859        let activity = client
32860            .poll_activity_task_response("draining-worker", "rust-workers", Duration::ZERO)
32861            .await
32862            .expect("activity drain response");
32863        let query = client
32864            .poll_query_task_response("draining-worker", "rust-workers", Duration::ZERO)
32865            .await
32866            .expect("query drain response");
32867
32868        for outcome in [workflow.outcome(), activity.outcome(), query.outcome()] {
32869            assert_eq!(
32870                outcome,
32871                WorkerPollOutcome::Stop {
32872                    poll_status: Some("draining".to_string()),
32873                    reason: Some("worker_draining".to_string()),
32874                }
32875            );
32876        }
32877
32878        assert!(client
32879            .poll_workflow_task("draining-worker", "rust-workers", Duration::ZERO)
32880            .await
32881            .expect("compatibility poll")
32882            .is_none());
32883    }
32884
32885    #[tokio::test]
32886    async fn managed_worker_honors_drain_stop_for_every_task_family() {
32887        let server = MockWorkerServer::draining_polls();
32888        let client = Client::builder(server.base_url())
32889            .timeout(Duration::from_secs(2))
32890            .build()
32891            .expect("client");
32892
32893        let mut workflow_worker = Worker::new(client.clone(), "rust-workers")
32894            .worker_id("draining-workflow-worker")
32895            .poll_timeout(Duration::ZERO);
32896        workflow_worker.register_workflow("counter", |_ctx, _args| async { Ok(Value::Null) });
32897        workflow_worker
32898            .run()
32899            .await
32900            .expect("workflow drain is a clean stop");
32901
32902        let mut activity_worker = Worker::new(client.clone(), "rust-workers")
32903            .worker_id("draining-activity-worker")
32904            .poll_timeout(Duration::ZERO);
32905        activity_worker.register_activity("write", |_ctx, _args| async { Ok(Value::Null) });
32906        activity_worker
32907            .run()
32908            .await
32909            .expect("activity drain is a clean stop");
32910
32911        let mut query_worker = Worker::new(client, "rust-workers")
32912            .worker_id("draining-query-worker")
32913            .poll_timeout(Duration::ZERO);
32914        query_worker.register_query("counter", "current", |_ctx, _args| async {
32915            Ok(Value::Null)
32916        });
32917        query_worker
32918            .run()
32919            .await
32920            .expect("query drain is a clean stop");
32921    }
32922
32923    #[tokio::test]
32924    async fn activity_cancellation_and_late_completion_remain_machine_readable() {
32925        let server = MockWorkerServer::start();
32926        let client = Client::builder(server.base_url())
32927            .timeout(Duration::from_secs(2))
32928            .build()
32929            .expect("client");
32930
32931        let details: Value = serde_json::from_str(include_str!(
32932            "../tests/fixtures/activity-heartbeat-progress.json"
32933        ))
32934        .expect("heartbeat progress fixture");
32935        // Every individual field fits Server's progress contract, while the
32936        // obsolete encoded envelope exceeded its 191-character string limit.
32937        assert!(
32938            encode_typed_envelope(&AvroValue::from_serialize(&details).unwrap(), DEFAULT_CODEC)
32939                .unwrap()["blob"]
32940                .as_str()
32941                .unwrap()
32942                .len()
32943                > 191
32944        );
32945        let heartbeat = client
32946            .heartbeat_activity_task("activity-cancel", "attempt-cancel", "rust-worker", &details)
32947            .await
32948            .expect("cancellation heartbeat");
32949        assert!(heartbeat.cancel_requested);
32950        assert!(heartbeat.should_stop());
32951        assert_eq!(heartbeat.reason.as_deref(), Some("run_cancelled"));
32952        assert_eq!(heartbeat.run_closed_reason.as_deref(), Some("cancelled"));
32953        let heartbeat_body =
32954            server.request_body("/api/worker/activity-tasks/activity-cancel/heartbeat");
32955        assert_eq!(heartbeat_body["details"], details);
32956        assert_eq!(heartbeat_body["activity_attempt_id"], "attempt-cancel");
32957        assert_eq!(heartbeat_body["lease_owner"], "rust-worker");
32958
32959        let error = client
32960            .complete_activity_task(
32961                "activity-cancel",
32962                "attempt-cancel",
32963                "rust-worker",
32964                json!({"late":true}),
32965                DEFAULT_CODEC,
32966            )
32967            .await
32968            .expect_err("late completion must be refused");
32969        assert!(activity_task_rejection_is_final(&error));
32970        let Error::ActivityTaskRejected(rejection) = error else {
32971            panic!("expected typed activity rejection");
32972        };
32973        assert_eq!(rejection.status, 409);
32974        assert_eq!(rejection.reason, "run_cancelled");
32975        assert!(rejection.cancel_requested);
32976        assert_eq!(rejection.can_continue, Some(false));
32977    }
32978
32979    #[tokio::test]
32980    async fn managed_worker_survives_late_completion_and_restart_during_cancellation() {
32981        let server = MockWorkerServer::cancelled_activity();
32982        let client = Client::builder(server.base_url())
32983            .timeout(Duration::from_secs(2))
32984            .build()
32985            .expect("client");
32986        let cancellation_observed = Arc::new(AtomicBool::new(false));
32987        let observed = Arc::clone(&cancellation_observed);
32988        let mut worker = Worker::new(client.clone(), "rust-workers")
32989            .worker_id("rust-cancel-worker")
32990            .poll_timeout(Duration::from_millis(10));
32991        worker.register_activity("cancel-aware", move |ctx, _args| {
32992            let observed = Arc::clone(&observed);
32993            async move {
32994                let heartbeat = ctx.heartbeat(json!({"stage":"running"})).await?;
32995                observed.store(heartbeat.should_stop(), Ordering::SeqCst);
32996                Ok(json!({"late":"completion"}))
32997            }
32998        });
32999
33000        assert_eq!(
33001            worker.run_once().await.expect("cancelled attempt handled"),
33002            1
33003        );
33004        assert!(cancellation_observed.load(Ordering::SeqCst));
33005        assert_eq!(
33006            server.request_count("/api/worker/activity-tasks/activity-cancel/complete"),
33007            1
33008        );
33009
33010        let mut restarted = Worker::new(client, "rust-workers")
33011            .worker_id("rust-cancel-worker-restarted")
33012            .poll_timeout(Duration::from_millis(10));
33013        restarted.register_activity("cancel-aware", |_ctx, _args| async move { Ok(Value::Null) });
33014        assert_eq!(
33015            restarted
33016                .run_once()
33017                .await
33018                .expect("replacement worker continues polling"),
33019            0
33020        );
33021    }
33022
33023    #[tokio::test]
33024    async fn managed_worker_absorbs_selected_run_terminal_timeout_completion_race() {
33025        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"}"#;
33026        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
33027        let client = Client::builder(server.base_url())
33028            .timeout(Duration::from_secs(2))
33029            .build()
33030            .expect("client");
33031
33032        let direct_error = client
33033            .complete_workflow_task(
33034                "workflow-timeout-task",
33035                "timeout-worker",
33036                3,
33037                vec![json!({
33038                    "type": "complete_workflow",
33039                    "result": fixture_envelope(Value::Null)
33040                })],
33041            )
33042            .await
33043            .expect_err("the low-level client preserves the completion rejection");
33044        let Error::Http { status, body } = direct_error else {
33045            panic!("expected the original HTTP completion rejection");
33046        };
33047        assert_eq!(status, reqwest::StatusCode::CONFLICT);
33048        assert_eq!(
33049            serde_json::from_str::<Value>(&body).expect("response body")["reason"],
33050            "run_timed_out"
33051        );
33052
33053        let mut worker = Worker::new(client, "rust-workers")
33054            .worker_id("timeout-worker")
33055            .poll_timeout(Duration::from_millis(10));
33056        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
33057            Ok(json!({"late": "result"}))
33058        });
33059
33060        assert_eq!(
33061            worker
33062                .run_once()
33063                .await
33064                .expect("authoritative selected-run timeout settles the tick"),
33065            1
33066        );
33067        assert_eq!(
33068            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
33069            2,
33070            "both the direct client proof and managed worker must see the rejection"
33071        );
33072    }
33073
33074    #[tokio::test]
33075    async fn managed_worker_absorbs_selected_run_terminal_timeout_failure_races() {
33076        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"}"#;
33077        for (surface, decision) in workflow_timeout_failure_decisions() {
33078            let server = MockWorkerServer::workflow_completion("409 Conflict", response);
33079            let client = Client::builder(server.base_url())
33080                .timeout(Duration::from_secs(2))
33081                .build()
33082                .expect("client");
33083            let error = client
33084                .fail_workflow_task(
33085                    "workflow-timeout-task",
33086                    "timeout-worker",
33087                    3,
33088                    "fixture failure",
33089                )
33090                .await
33091                .expect_err("low-level failure reporting preserves the HTTP refusal");
33092            assert!(
33093                matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT)
33094            );
33095
33096            let worker = Worker::new(client, "rust-workers");
33097            assert_eq!(
33098                worker
33099                    .settle_workflow_task_decision(
33100                        "workflow-timeout-task",
33101                        "timeout-worker",
33102                        3,
33103                        Some("run-selected-timeout"),
33104                        decision,
33105                        false,
33106                        None,
33107                    )
33108                    .await
33109                    .expect(surface),
33110                ManagedPollOutcome::Handled,
33111            );
33112            assert_eq!(
33113                server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/fail"),
33114                2
33115            );
33116        }
33117    }
33118
33119    fn workflow_timeout_failure_decisions() -> [(&'static str, Result<WorkflowTaskDecision>); 4] {
33120        [
33121            (
33122                "history wait",
33123                Ok(WorkflowTaskDecision::without_message_streams(vec![])),
33124            ),
33125            (
33126                "unsupported memo",
33127                Ok(WorkflowTaskDecision::without_message_streams(vec![
33128                    json!({"type":"upsert_memo"}),
33129                ])),
33130            ),
33131            (
33132                "ordinary failure",
33133                Err(Error::WorkerLoop("fixture failure".into())),
33134            ),
33135            (
33136                "entry argument mismatch",
33137                Err(handler_type_error::<bool>(
33138                    HandlerKind::Workflow,
33139                    "timeout.workflow",
33140                    HandlerValueKind::Input,
33141                    "fixture mismatch",
33142                )),
33143            ),
33144        ]
33145    }
33146
33147    #[tokio::test]
33148    async fn managed_worker_preserves_nonmatching_timeout_failure_refusals() {
33149        let valid = json!({"task_id":"workflow-timeout-task","workflow_task_attempt":3,
33150            "outcome":"completed","recorded":false,"run_id":"run-selected-timeout",
33151            "run_status":"failed","created_task_ids":[],"reason":"run_timed_out"});
33152        let mut cases = vec![
33153            ("malformed JSON", "409 Conflict", "{broken".to_owned()),
33154            ("wrong status", "403 Forbidden", valid.to_string()),
33155            (
33156                "authentication failure",
33157                "401 Unauthorized",
33158                valid.to_string(),
33159            ),
33160            (
33161                "validation failure",
33162                "422 Unprocessable Entity",
33163                valid.to_string(),
33164            ),
33165            (
33166                "server failure",
33167                "503 Service Unavailable",
33168                valid.to_string(),
33169            ),
33170        ];
33171        for (field, value) in [
33172            ("task_id", json!("another-task")),
33173            ("workflow_task_attempt", json!(4)),
33174            ("run_id", json!("another-run")),
33175            ("run_status", json!("waiting")),
33176            ("recorded", json!(true)),
33177            ("reason", json!("lease_expired")),
33178            ("run_id", Value::Null),
33179            ("workflow_task_attempt", Value::Null),
33180        ] {
33181            let mut body = valid.clone();
33182            body[field] = value;
33183            cases.push((field, "409 Conflict", body.to_string()));
33184        }
33185        for (name, status, response) in cases {
33186            // The mock response callback has a static lifetime, so retain each
33187            // bounded response for the duration of this test process.
33188            let response = Box::leak(response.into_boxed_str());
33189            for (surface, decision) in workflow_timeout_failure_decisions() {
33190                let server = MockWorkerServer::workflow_completion(status, response);
33191                let client = Client::builder(server.base_url())
33192                    .timeout(Duration::from_secs(2))
33193                    .build()
33194                    .expect("client");
33195                let worker = Worker::new(client, "rust-workers");
33196                let error = worker
33197                    .settle_workflow_task_decision(
33198                        "workflow-timeout-task",
33199                        "timeout-worker",
33200                        3,
33201                        Some("run-selected-timeout"),
33202                        decision,
33203                        false,
33204                        None,
33205                    )
33206                    .await
33207                    .expect_err(&format!("{surface}: {name} must remain an error"));
33208                assert!(
33209                    matches!(error, Error::Http { .. }),
33210                    "{surface}: {name}: {error}"
33211                );
33212            }
33213        }
33214    }
33215
33216    // durable-workflow/.github#228: native Server 3.6.0 refuses a completion
33217    // over its aggregate limit with a typed 413.
33218    fn completion_size_refusal(
33219        path: &str,
33220        _body: &str,
33221        request: usize,
33222    ) -> Option<(&'static str, String)> {
33223        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.",
33224            "reason":"payload_too_large","limit":33_554_432,"limit_kind":"workflow_task_completion_bytes",
33225            "protocol_version":"1.20","server_capabilities":{}});
33226        let recorded = json!({"outcome":"completed","recorded":true}).to_string();
33227        match (path, request) {
33228            ("/api/worker/workflow-tasks/typed-413/complete", 1)
33229            | ("/api/worker/workflow-tasks/typed-413-unrecorded/complete", 1) => {
33230                Some(("413 Payload Too Large", typed.to_string()))
33231            }
33232            ("/api/worker/workflow-tasks/typed-413/complete", _) => Some(("200 OK", recorded)),
33233            ("/api/worker/workflow-tasks/typed-413-unrecorded/complete", _) => Some((
33234                "500 Internal Server Error",
33235                json!({"message":"fixture"}).to_string(),
33236            )),
33237            ("/api/worker/workflow-tasks/plain-413/complete", _) => Some((
33238                "413 Payload Too Large",
33239                json!({"message":"Request payload exceeds the maximum allowed size of 2097152 bytes.",
33240                    "reason":"payload_too_large","limit":2_097_152}).to_string(),
33241            )),
33242            ("/api/worker/workflow-tasks/other-kind-413/complete", _) => {
33243                let mut other = typed.clone();
33244                other["limit_kind"] = json!("payload_size_bytes");
33245                Some(("413 Payload Too Large", other.to_string()))
33246            }
33247            ("/api/worker/workflow-tasks/server-503/complete", _) => Some((
33248                "503 Service Unavailable",
33249                json!({"message":"fixture"}).to_string(),
33250            )),
33251            _ => None,
33252        }
33253    }
33254
33255    fn fan_out_commands() -> Vec<Value> {
33256        (0..10)
33257            .map(|index| {
33258                json!({"type":"schedule_activity","activity_type":"fan.out",
33259                    "arguments":fixture_envelope(json!([index, "x".repeat(1024)]))})
33260            })
33261            .collect()
33262    }
33263
33264    fn completion_size_worker() -> (MockWorkerServer, Worker) {
33265        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33266            request_override: Some(completion_size_refusal),
33267            ..MockWorkerBehavior::default()
33268        });
33269        let client = Client::builder(server.base_url())
33270            .timeout(Duration::from_secs(2))
33271            .build()
33272            .expect("client");
33273        (server, Worker::new(client, "rust-workers"))
33274    }
33275
33276    #[tokio::test]
33277    async fn typed_completion_size_refusal_is_a_typed_error_and_is_not_resent() {
33278        let (server, worker) = completion_size_worker();
33279        let error = worker
33280            .client
33281            .complete_workflow_task("typed-413", "fan-worker", 2, fan_out_commands())
33282            .await
33283            .expect_err("the typed 413 is an error");
33284        let path = "/api/worker/workflow-tasks/typed-413/complete";
33285        let sent = server.request_bodies(path);
33286        assert_eq!(sent.len(), 1, "the oversized completion is sent once");
33287        let Error::WorkflowTaskCompletionTooLarge(refusal) = &error else {
33288            panic!("expected a typed completion size refusal, got {error:?}");
33289        };
33290        assert_eq!(refusal.status, 413);
33291        assert_eq!(refusal.limit_kind, "workflow_task_completion_bytes");
33292        assert_eq!(refusal.limit, Some(33_554_432));
33293        assert_eq!(refusal.size, sent[0].to_string().len() as u64);
33294        assert!(refusal
33295            .message
33296            .starts_with("Workflow task completion exceeds"));
33297        let text = error.to_string();
33298        assert!(
33299            text.starts_with("Structural limit exceeded: workflow_task_completion_bytes:"),
33300            "{text}"
33301        );
33302        assert!(
33303            text.contains(&format!("is {} bytes", refusal.size)),
33304            "{text}"
33305        );
33306        assert!(text.contains("server limit of 33554432 bytes"), "{text}");
33307        assert!(text.contains("child workflows"), "{text}");
33308        assert!(!worker_operation_is_retryable(&error));
33309    }
33310
33311    #[tokio::test]
33312    async fn managed_worker_fails_the_run_once_on_a_typed_completion_size_refusal() {
33313        let (server, worker) = completion_size_worker();
33314        let outcome = worker
33315            .settle_workflow_task_decision(
33316                "typed-413",
33317                "fan-worker",
33318                2,
33319                Some("fan-run"),
33320                Ok(WorkflowTaskDecision::without_message_streams(
33321                    fan_out_commands(),
33322                )),
33323                false,
33324                None,
33325            )
33326            .await
33327            .expect("the structural-limit failure settles the task");
33328        assert!(matches!(outcome, ManagedPollOutcome::Handled));
33329        let sent = server.request_bodies("/api/worker/workflow-tasks/typed-413/complete");
33330        assert_eq!(sent.len(), 2, "one oversized completion, then one failure");
33331        assert_eq!(sent[0]["commands"].as_array().unwrap().len(), 10);
33332        let size = sent[0].to_string().len();
33333        assert_eq!(sent[1]["lease_owner"], "fan-worker");
33334        assert_eq!(sent[1]["workflow_task_attempt"], 2);
33335        let commands = sent[1]["commands"].as_array().unwrap();
33336        assert_eq!(commands.len(), 1, "the oversized commands are not resent");
33337        let failure = &commands[0];
33338        assert_eq!(failure["type"], "fail_workflow");
33339        assert_eq!(failure["non_retryable"], true);
33340        assert_eq!(failure["exception_type"], "StructuralLimitExceeded");
33341        let message = failure["message"].as_str().unwrap();
33342        assert!(
33343            message.starts_with("Structural limit exceeded: workflow_task_completion_bytes:"),
33344            "{message}"
33345        );
33346        assert!(message.contains(&format!("is {size} bytes")), "{message}");
33347        assert!(message.contains("33554432 bytes"), "{message}");
33348        let properties = &failure["exception"]["properties"];
33349        assert_eq!(
33350            properties["structural_limit_kind"],
33351            "workflow_task_completion_bytes"
33352        );
33353        assert_eq!(properties["structural_limit_value"], size);
33354        assert_eq!(properties["structural_limit_configured"], 33_554_432);
33355        // The Server's free-text message is not recorded with the failure.
33356        assert!(properties.get("server_message").is_none(), "{properties}");
33357        assert_eq!(
33358            server.request_count("/api/worker/workflow-tasks/typed-413/fail"),
33359            0,
33360            "a failed task would be retried into the same refusal"
33361        );
33362    }
33363
33364    #[tokio::test]
33365    async fn managed_worker_keeps_the_typed_refusal_when_the_failure_is_not_recorded() {
33366        let (server, worker) = completion_size_worker();
33367        let error = worker
33368            .settle_workflow_task_decision(
33369                "typed-413-unrecorded",
33370                "fan-worker",
33371                2,
33372                Some("fan-run"),
33373                Ok(WorkflowTaskDecision::without_message_streams(
33374                    fan_out_commands(),
33375                )),
33376                false,
33377                None,
33378            )
33379            .await
33380            .expect_err("an unrecorded failure stays an error");
33381        assert!(
33382            matches!(error, Error::WorkflowTaskCompletionTooLarge(_)),
33383            "{error:?}"
33384        );
33385        let sent =
33386            server.request_bodies("/api/worker/workflow-tasks/typed-413-unrecorded/complete");
33387        assert_eq!(sent.len(), 2, "no resend and no retry loop");
33388        assert_eq!(sent[1]["commands"][0]["type"], "fail_workflow");
33389    }
33390
33391    #[tokio::test]
33392    async fn managed_worker_leaves_other_413_and_5xx_completion_refusals_unchanged() {
33393        for (task, status) in [
33394            ("plain-413", reqwest::StatusCode::PAYLOAD_TOO_LARGE),
33395            ("other-kind-413", reqwest::StatusCode::PAYLOAD_TOO_LARGE),
33396            ("server-503", reqwest::StatusCode::SERVICE_UNAVAILABLE),
33397        ] {
33398            let (server, worker) = completion_size_worker();
33399            let error = worker
33400                .settle_workflow_task_decision(
33401                    task,
33402                    "fan-worker",
33403                    2,
33404                    Some("fan-run"),
33405                    Ok(WorkflowTaskDecision::without_message_streams(
33406                        fan_out_commands(),
33407                    )),
33408                    false,
33409                    None,
33410                )
33411                .await
33412                .expect_err("the refusal remains an error");
33413            assert!(
33414                matches!(&error, Error::Http { status: observed, .. } if *observed == status),
33415                "{task}: {error:?}"
33416            );
33417            let sent =
33418                server.request_bodies(&format!("/api/worker/workflow-tasks/{task}/complete"));
33419            assert_eq!(sent.len(), 1, "{task}");
33420            assert_eq!(sent[0]["commands"].as_array().unwrap().len(), 10, "{task}");
33421        }
33422    }
33423
33424    #[tokio::test]
33425    async fn managed_worker_polls_unrelated_work_after_history_wait_timeout() {
33426        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33427            request_override: Some(history_wait_timeout_then_unrelated_work),
33428            ..MockWorkerBehavior::default()
33429        });
33430        let client = Client::builder(server.base_url())
33431            .timeout(Duration::from_secs(2))
33432            .build()
33433            .expect("client");
33434        let executed = Arc::new(AtomicBool::new(false));
33435        let observed = Arc::clone(&executed);
33436        let mut worker = Worker::new(client, "rust-workers")
33437            .worker_id("timeout-worker")
33438            .poll_timeout(Duration::from_millis(10));
33439        worker.register_workflow("timeout.workflow", |ctx, _input| async move {
33440            ctx.sleep(Duration::from_secs(5)).await?;
33441            Ok(Value::Null)
33442        });
33443        worker.register_workflow("unrelated.workflow", move |_ctx, _input| {
33444            let observed = Arc::clone(&observed);
33445            async move {
33446                observed.store(true, Ordering::SeqCst);
33447                Ok(Value::Null)
33448            }
33449        });
33450        assert_eq!(
33451            worker
33452                .run_once()
33453                .await
33454                .expect("terminal history-wait timeout settles the tick"),
33455            1
33456        );
33457        assert_eq!(
33458            worker
33459                .run_once()
33460                .await
33461                .expect("same worker processes an unrelated workflow"),
33462            1
33463        );
33464        assert!(executed.load(Ordering::SeqCst));
33465        assert_eq!(
33466            server.request_count("/api/worker/workflow-tasks/workflow-timeout-task/fail"),
33467            1
33468        );
33469        assert_eq!(
33470            server.request_count("/api/worker/workflow-tasks/unrelated-task/complete"),
33471            1
33472        );
33473    }
33474
33475    fn history_wait_timeout_then_unrelated_work(
33476        path: &str,
33477        _body: &str,
33478        request: usize,
33479    ) -> Option<(&'static str, String)> {
33480        if path == "/api/worker/workflow-tasks/poll" && request <= 2 {
33481            let waiting = request == 1;
33482            let task = json!({"task_id":if waiting {"workflow-timeout-task"} else {"unrelated-task"},
33483                "workflow_id":if waiting {"reused-workflow-id"} else {"unrelated-workflow"},
33484                "run_id":if waiting {"run-selected-timeout"} else {"unrelated-run"},
33485                "workflow_type":if waiting {"timeout.workflow"} else {"unrelated.workflow"},
33486                "payload_codec":"avro","arguments":fixture_envelope(json!([])),
33487                "history_events":if waiting {vec![json!({"event_type":"TimerScheduled","payload":{"sequence":1,"timer_id":"timer-1","delay_seconds":5}})]} else {vec![]},
33488                "workflow_task_attempt":3,"lease_owner":"timeout-worker"});
33489            return Some(("200 OK", json!({"task":task}).to_string()));
33490        }
33491        match path {
33492            "/api/worker/workflow-tasks/workflow-timeout-task/fail" => Some(("409 Conflict",
33493                json!({"task_id":"workflow-timeout-task","workflow_task_attempt":3,"outcome":"completed",
33494                    "recorded":false,"run_id":"run-selected-timeout","run_status":"failed",
33495                    "created_task_ids":[],"reason":"run_timed_out"}).to_string())),
33496            "/api/worker/workflow-tasks/unrelated-task/complete" => Some(("200 OK", json!({"outcome":"completed","recorded":true}).to_string())),
33497            _ => None,
33498        }
33499    }
33500
33501    #[tokio::test]
33502    async fn managed_worker_settles_matching_task_not_leased_receipt_and_keeps_polling() {
33503        // Published PHP Server 2.11.8 answered a completion after cancellation
33504        // with this receipt; the 4.10.2 managed worker exited on it (#157).
33505        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"}"#;
33506        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
33507        let client = Client::builder(server.base_url())
33508            .timeout(Duration::from_secs(2))
33509            .build()
33510            .expect("client");
33511
33512        let direct_error = client
33513            .complete_workflow_task(
33514                "workflow-timeout-task",
33515                "timeout-worker",
33516                3,
33517                vec![json!({"type": "complete_workflow", "result": fixture_envelope(Value::Null)})],
33518            )
33519            .await
33520            .expect_err("the low-level client preserves the completion rejection");
33521        assert!(
33522            matches!(direct_error, Error::Http { status, .. } if status == reqwest::StatusCode::CONFLICT)
33523        );
33524
33525        let mut worker = Worker::new(client, "rust-workers")
33526            .worker_id("timeout-worker")
33527            .poll_timeout(Duration::from_millis(10));
33528        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
33529            Ok(json!({"late": "result"}))
33530        });
33531        assert_eq!(
33532            worker
33533                .run_once()
33534                .await
33535                .expect("a matching task_not_leased receipt settles the tick"),
33536            1
33537        );
33538        assert_eq!(
33539            worker
33540                .run_once()
33541                .await
33542                .expect("the managed worker keeps polling"),
33543            0
33544        );
33545    }
33546
33547    #[tokio::test]
33548    async fn managed_worker_keeps_nearby_task_not_leased_conflicts_as_errors() {
33549        for (name, response) in [
33550            (
33551                "recorded",
33552                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","reason":"task_not_leased"}"#,
33553            ),
33554            (
33555                "recorded missing",
33556                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"run_id":"run-selected-timeout","reason":"task_not_leased"}"#,
33557            ),
33558            (
33559                "different task",
33560                r#"{"task_id":"other-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","reason":"task_not_leased"}"#,
33561            ),
33562            (
33563                "different attempt",
33564                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","reason":"task_not_leased"}"#,
33565            ),
33566            (
33567                "different run",
33568                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-other","reason":"task_not_leased"}"#,
33569            ),
33570            (
33571                "other reason",
33572                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","reason":"lease_owner_mismatch"}"#,
33573            ),
33574        ] {
33575            let server = MockWorkerServer::workflow_completion("409 Conflict", response);
33576            let client = Client::builder(server.base_url())
33577                .timeout(Duration::from_secs(2))
33578                .build()
33579                .expect("client");
33580            let mut worker = Worker::new(client, "rust-workers")
33581                .worker_id("timeout-worker")
33582                .poll_timeout(Duration::from_millis(10));
33583            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
33584                Ok(json!({"late": "result"}))
33585            });
33586            let error = worker
33587                .run_once()
33588                .await
33589                .expect_err(&format!("{name} must remain an error"));
33590            assert!(
33591                matches!(error, Error::Http { .. }),
33592                "{name}: unexpected error {error}"
33593            );
33594        }
33595    }
33596
33597    /// Native Server's full not-recorded `run_closed` receipt (server#994) for
33598    /// the mock's selected task, after the run closed by another path. The
33599    /// guard's body and the receipt fields follow Server PR #999; the
33600    /// capability manifest is elided.
33601    fn run_closed_receipt(close: &str) -> Value {
33602        let (run_status, stop_reason, closed_reason, task_status, cancel_requested) = match close {
33603            "completed" => (
33604                "completed",
33605                "run_completed",
33606                "completed",
33607                "completed",
33608                false,
33609            ),
33610            "failed" => ("failed", "run_failed", "failed", "failed", false),
33611            "timed_out" => ("failed", "run_failed", "timed_out", "completed", false),
33612            "cancelled" => ("cancelled", "run_cancelled", "cancelled", "cancelled", true),
33613            "terminated" => (
33614                "terminated",
33615                "run_terminated",
33616                "terminated",
33617                "cancelled",
33618                true,
33619            ),
33620            other => panic!("unknown close {other}"),
33621        };
33622        json!({"task_id":"workflow-timeout-task","workflow_task_attempt":3,
33623            "error":"Workflow run is already closed.","reason":"run_closed","protocol_version":"1.20",
33624            "server_capabilities":{},"stop_reason":stop_reason,"cancel_requested":cancel_requested,
33625            "can_continue":false,"run_status":run_status,"run_closed_reason":closed_reason,
33626            "run_closed_at":"2026-11-03T12:00:00.000000Z","task_status":task_status,
33627            "lease_owner":"timeout-worker","lease_expires_at":null,
33628            "recorded":false,"run_id":"run-selected-timeout"})
33629    }
33630
33631    /// Every request except task polls and the read-only capability probe:
33632    /// the reports and any retry, lease or other state-changing call.
33633    fn state_requests(server: &MockWorkerServer) -> Vec<String> {
33634        server
33635            .captured_paths()
33636            .into_iter()
33637            .filter(|path| !path.ends_with("/poll") && path != "/api/cluster/info")
33638            .collect()
33639    }
33640
33641    const RUN_CLOSED_CLOSES: [&str; 5] = [
33642        "completed",
33643        "failed",
33644        "timed_out",
33645        "cancelled",
33646        "terminated",
33647    ];
33648
33649    fn assert_original_http_error(
33650        error: Error,
33651        status: reqwest::StatusCode,
33652        response: &str,
33653        context: &str,
33654    ) {
33655        let Error::Http {
33656            status: actual,
33657            body,
33658        } = error
33659        else {
33660            panic!("{context}: expected the original HTTP error, got {error}");
33661        };
33662        assert_eq!(actual, status, "{context}");
33663        assert_eq!(body, response, "{context}: the response body is unchanged");
33664    }
33665
33666    #[tokio::test]
33667    async fn managed_worker_settles_exact_run_closed_receipts_without_advancing_state() {
33668        let complete = "/api/worker/workflow-tasks/workflow-timeout-task/complete";
33669        let fail = "/api/worker/workflow-tasks/workflow-timeout-task/fail";
33670        for close in RUN_CLOSED_CLOSES {
33671            let response: &'static str =
33672                Box::leak(run_closed_receipt(close).to_string().into_boxed_str());
33673
33674            // Direct client calls keep the original HTTP error.
33675            let server = MockWorkerServer::workflow_completion("409 Conflict", response);
33676            let client = Client::builder(server.base_url())
33677                .timeout(Duration::from_secs(2))
33678                .build()
33679                .expect("client");
33680            let error = client
33681                .complete_workflow_task(
33682                    "workflow-timeout-task",
33683                    "timeout-worker",
33684                    3,
33685                    vec![json!({"type": "complete_workflow", "result": fixture_envelope(Value::Null)})],
33686                )
33687                .await
33688                .expect_err("the low-level client preserves the completion refusal");
33689            assert_original_http_error(error, reqwest::StatusCode::CONFLICT, response, close);
33690            let error = client
33691                .fail_workflow_task(
33692                    "workflow-timeout-task",
33693                    "timeout-worker",
33694                    3,
33695                    "fixture failure",
33696                )
33697                .await
33698                .expect_err("the low-level client preserves the failure refusal");
33699            assert_original_http_error(error, reqwest::StatusCode::CONFLICT, response, close);
33700
33701            // The managed completion settles with exactly one report and no
33702            // further request for the task: no retry, failure report, lease
33703            // renewal or other state change.
33704            let server = MockWorkerServer::workflow_completion("409 Conflict", response);
33705            let client = Client::builder(server.base_url())
33706                .timeout(Duration::from_secs(2))
33707                .build()
33708                .expect("client");
33709            let mut worker = Worker::new(client, "rust-workers")
33710                .worker_id("timeout-worker")
33711                .poll_timeout(Duration::from_millis(10));
33712            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
33713                Ok(json!({"late": "result"}))
33714            });
33715            assert_eq!(
33716                worker.run_once().await.unwrap_or_else(|error| panic!(
33717                    "{close}: an exact run_closed receipt settles the tick: {error}"
33718                )),
33719                1
33720            );
33721            assert_eq!(
33722                state_requests(&server),
33723                vec![complete.to_owned()],
33724                "{close}"
33725            );
33726
33727            // Every managed failure report settles the same way.
33728            for (surface, decision) in workflow_timeout_failure_decisions() {
33729                let server = MockWorkerServer::workflow_completion("409 Conflict", response);
33730                let client = Client::builder(server.base_url())
33731                    .timeout(Duration::from_secs(2))
33732                    .build()
33733                    .expect("client");
33734                let worker = Worker::new(client, "rust-workers");
33735                assert_eq!(
33736                    worker
33737                        .settle_workflow_task_decision(
33738                            "workflow-timeout-task",
33739                            "timeout-worker",
33740                            3,
33741                            Some("run-selected-timeout"),
33742                            decision,
33743                            false,
33744                            None,
33745                        )
33746                        .await
33747                        .unwrap_or_else(|error| panic!("{close} {surface}: {error}")),
33748                    ManagedPollOutcome::Handled,
33749                );
33750                assert_eq!(
33751                    server.captured_paths(),
33752                    vec![fail.to_owned()],
33753                    "{close} {surface}"
33754                );
33755            }
33756        }
33757    }
33758
33759    #[tokio::test]
33760    async fn managed_worker_keeps_polling_after_a_cancel_during_report_race() {
33761        // Native 3.0.4 answered a completion that raced a cancellation with
33762        // 409 run_closed, and the managed 4.11.1 worker exited (#170). With
33763        // server#994's full receipt the same worker settles and keeps going.
33764        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
33765            request_override: Some(cancelled_during_report_then_unrelated_work),
33766            ..MockWorkerBehavior::default()
33767        });
33768        let client = Client::builder(server.base_url())
33769            .timeout(Duration::from_secs(2))
33770            .build()
33771            .expect("client");
33772        let executed = Arc::new(AtomicBool::new(false));
33773        let observed = Arc::clone(&executed);
33774        let mut worker = Worker::new(client, "rust-workers")
33775            .worker_id("timeout-worker")
33776            .poll_timeout(Duration::from_millis(10));
33777        worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
33778            Ok(json!({"late": "result"}))
33779        });
33780        worker.register_workflow("unrelated.workflow", move |_ctx, _input| {
33781            let observed = Arc::clone(&observed);
33782            async move {
33783                observed.store(true, Ordering::SeqCst);
33784                Ok(Value::Null)
33785            }
33786        });
33787        assert_eq!(
33788            worker
33789                .run_once()
33790                .await
33791                .expect("the cancelled run's exact receipt settles the tick"),
33792            1
33793        );
33794        assert_eq!(
33795            worker
33796                .run_once()
33797                .await
33798                .expect("the same worker processes a later workflow task"),
33799            1
33800        );
33801        assert!(executed.load(Ordering::SeqCst));
33802        assert_eq!(
33803            state_requests(&server),
33804            vec![
33805                "/api/worker/workflow-tasks/workflow-timeout-task/complete".to_owned(),
33806                "/api/worker/workflow-tasks/unrelated-task/complete".to_owned(),
33807            ],
33808            "one report for the closed run, then the later task's completion"
33809        );
33810    }
33811
33812    fn cancelled_during_report_then_unrelated_work(
33813        path: &str,
33814        _body: &str,
33815        request: usize,
33816    ) -> Option<(&'static str, String)> {
33817        if path == "/api/worker/workflow-tasks/poll" && request <= 2 {
33818            let raced = request == 1;
33819            let task = json!({"task_id":if raced {"workflow-timeout-task"} else {"unrelated-task"},
33820                "workflow_id":if raced {"reused-workflow-id"} else {"unrelated-workflow"},
33821                "run_id":if raced {"run-selected-timeout"} else {"unrelated-run"},
33822                "workflow_type":if raced {"timeout.workflow"} else {"unrelated.workflow"},
33823                "payload_codec":"avro","arguments":fixture_envelope(json!([])),
33824                "history_events":[],"workflow_task_attempt":3,"lease_owner":"timeout-worker"});
33825            return Some(("200 OK", json!({"task":task}).to_string()));
33826        }
33827        match path {
33828            // The run was cancelled while the completion was in flight.
33829            "/api/worker/workflow-tasks/workflow-timeout-task/complete" => {
33830                Some(("409 Conflict", run_closed_receipt("cancelled").to_string()))
33831            }
33832            "/api/worker/workflow-tasks/unrelated-task/complete" => Some((
33833                "200 OK",
33834                json!({"outcome":"completed","recorded":true}).to_string(),
33835            )),
33836            _ => None,
33837        }
33838    }
33839
33840    #[tokio::test]
33841    async fn managed_worker_keeps_inexact_run_closed_refusals_fatal() {
33842        let valid = run_closed_receipt("cancelled");
33843        let mut cases: Vec<(String, &'static str, String)> = Vec::new();
33844        for (field, value) in [
33845            ("recorded", None),
33846            ("recorded", Some(json!(true))),
33847            ("recorded", Some(json!("false"))),
33848            ("recorded", Some(Value::Null)),
33849            ("task_id", None),
33850            ("task_id", Some(json!("other-task"))),
33851            ("workflow_task_attempt", None),
33852            ("workflow_task_attempt", Some(json!(4))),
33853            ("workflow_task_attempt", Some(json!("3"))),
33854            ("run_id", None),
33855            ("run_id", Some(json!("run-other"))),
33856            ("run_id", Some(Value::Null)),
33857            ("run_status", None),
33858            ("run_status", Some(json!("running"))),
33859            ("run_status", Some(json!("waiting"))),
33860            ("run_status", Some(json!("completed"))),
33861            ("stop_reason", None),
33862            ("stop_reason", Some(json!("run_terminated"))),
33863            ("can_continue", None),
33864            ("can_continue", Some(json!(true))),
33865            ("reason", None),
33866            ("reason", Some(json!("lease_owner_mismatch"))),
33867            ("reason", Some(json!("lease_expired"))),
33868            ("reason", Some(json!("workflow_task_attempt_mismatch"))),
33869            ("reason", Some(json!("conflicting_completion"))),
33870        ] {
33871            let mut body = valid.clone();
33872            let name = match value {
33873                Some(value) => {
33874                    let name = format!("{field}={value}");
33875                    body[field] = value;
33876                    name
33877                }
33878                None => {
33879                    body.as_object_mut().expect("receipt object").remove(field);
33880                    format!("{field} absent")
33881                }
33882            };
33883            cases.push((name, "409 Conflict", body.to_string()));
33884        }
33885        for status in [
33886            "403 Forbidden",
33887            "410 Gone",
33888            "422 Unprocessable Entity",
33889            "503 Service Unavailable",
33890        ] {
33891            cases.push((format!("HTTP {status}"), status, valid.to_string()));
33892        }
33893        cases.push(("malformed JSON".into(), "409 Conflict", "{broken".into()));
33894        // Native 3.0.4's guard body (#170) for the same task and attempt: it
33895        // lacks `recorded` and `run_id`, so it stays fatal.
33896        cases.push((
33897            "native 3.0.4 body".into(),
33898            "409 Conflict",
33899            json!({"task_id":"workflow-timeout-task","workflow_task_attempt":3,
33900                "error":"Workflow run is already closed.","reason":"run_closed","protocol_version":"1.20",
33901                "server_capabilities":{},"stop_reason":"run_cancelled","cancel_requested":true,
33902                "can_continue":false,"run_status":"cancelled","run_closed_reason":"cancelled",
33903                "task_status":"cancelled","lease_owner":"timeout-worker"})
33904            .to_string(),
33905        ));
33906        // A receipt that carries no closed-run state is not inferred terminal.
33907        cases.push((
33908            "receipt without run state".into(),
33909            "409 Conflict",
33910            json!({"reason":"run_closed","message":"run_closed","protocol_version":"1.20",
33911                "server_capabilities":{},"task_id":"workflow-timeout-task","workflow_task_attempt":3,
33912                "recorded":false,"run_id":"run-selected-timeout","task_status":"leased"})
33913            .to_string(),
33914        ));
33915
33916        for (name, status, response) in cases {
33917            let response: &'static str = Box::leak(response.into_boxed_str());
33918            let expected_status =
33919                reqwest::StatusCode::from_u16(status[..3].parse().expect("status code"))
33920                    .expect("status");
33921
33922            let server = MockWorkerServer::workflow_completion(status, response);
33923            let client = Client::builder(server.base_url())
33924                .timeout(Duration::from_secs(2))
33925                .build()
33926                .expect("client");
33927            let mut worker = Worker::new(client, "rust-workers")
33928                .worker_id("timeout-worker")
33929                .poll_timeout(Duration::from_millis(10));
33930            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
33931                Ok(json!({"late": "result"}))
33932            });
33933            let error = worker
33934                .run_once()
33935                .await
33936                .expect_err(&format!("{name} must remain an error"));
33937            assert_original_http_error(error, expected_status, response, &name);
33938            if expected_status == reqwest::StatusCode::CONFLICT {
33939                assert_eq!(
33940                    server
33941                        .request_count("/api/worker/workflow-tasks/workflow-timeout-task/complete"),
33942                    1,
33943                    "{name}: a refused report is not retried"
33944                );
33945            }
33946
33947            for (surface, decision) in workflow_timeout_failure_decisions() {
33948                let server = MockWorkerServer::workflow_completion(status, response);
33949                let client = Client::builder(server.base_url())
33950                    .timeout(Duration::from_secs(2))
33951                    .build()
33952                    .expect("client");
33953                let worker = Worker::new(client, "rust-workers");
33954                let error = worker
33955                    .settle_workflow_task_decision(
33956                        "workflow-timeout-task",
33957                        "timeout-worker",
33958                        3,
33959                        Some("run-selected-timeout"),
33960                        decision,
33961                        false,
33962                        None,
33963                    )
33964                    .await
33965                    .expect_err(&format!("{surface}: {name} must remain an error"));
33966                assert_original_http_error(
33967                    error,
33968                    expected_status,
33969                    response,
33970                    &format!("{surface}: {name}"),
33971                );
33972            }
33973        }
33974    }
33975
33976    #[tokio::test]
33977    async fn managed_worker_requires_the_selected_run_for_run_closed_receipts() {
33978        // Without the task's own run there is nothing to match.
33979        let response: &'static str =
33980            Box::leak(run_closed_receipt("cancelled").to_string().into_boxed_str());
33981        let server = MockWorkerServer::workflow_completion("409 Conflict", response);
33982        let client = Client::builder(server.base_url())
33983            .timeout(Duration::from_secs(2))
33984            .build()
33985            .expect("client");
33986        let worker = Worker::new(client, "rust-workers");
33987        let error = worker
33988            .settle_workflow_task_decision(
33989                "workflow-timeout-task",
33990                "timeout-worker",
33991                3,
33992                None,
33993                Err(Error::WorkerLoop("fixture failure".into())),
33994                false,
33995                None,
33996            )
33997            .await
33998            .expect_err("a task without a run never settles");
33999        assert_original_http_error(error, reqwest::StatusCode::CONFLICT, response, "no run");
34000    }
34001
34002    #[tokio::test]
34003    async fn managed_worker_does_not_swallow_nearby_completion_errors() {
34004        for (name, status, response) in [
34005            ("bare conflict", "409 Conflict", r#"{"message":"conflict"}"#),
34006            (
34007                "command was recorded",
34008                "409 Conflict",
34009                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":true,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
34010            ),
34011            (
34012                "lease conflict",
34013                "409 Conflict",
34014                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"lease_expired"}"#,
34015            ),
34016            (
34017                "nonterminal run",
34018                "409 Conflict",
34019                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"waiting","reason":"run_timed_out"}"#,
34020            ),
34021            (
34022                "different selected run",
34023                "409 Conflict",
34024                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"}"#,
34025            ),
34026            (
34027                "different task attempt",
34028                "409 Conflict",
34029                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":4,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
34030            ),
34031            (
34032                "authentication failure",
34033                "401 Unauthorized",
34034                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
34035            ),
34036            (
34037                "authorization failure",
34038                "403 Forbidden",
34039                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
34040            ),
34041            (
34042                "protocol failure",
34043                "400 Bad Request",
34044                r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.2","requested_version":"1.3"}"#,
34045            ),
34046            (
34047                "malformed command",
34048                "422 Unprocessable Entity",
34049                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
34050            ),
34051            (
34052                "transient server failure",
34053                "503 Service Unavailable",
34054                r#"{"task_id":"workflow-timeout-task","workflow_task_attempt":3,"recorded":false,"run_id":"run-selected-timeout","run_status":"failed","reason":"run_timed_out"}"#,
34055            ),
34056        ] {
34057            let server = MockWorkerServer::workflow_completion(status, response);
34058            let client = Client::builder(server.base_url())
34059                .timeout(Duration::from_secs(2))
34060                .build()
34061                .expect("client");
34062            let mut worker = Worker::new(client, "rust-workers")
34063                .worker_id("timeout-worker")
34064                .poll_timeout(Duration::from_millis(10));
34065            worker.register_workflow("timeout.workflow", |_ctx, _input| async move {
34066                Ok(json!({"late": "result"}))
34067            });
34068
34069            let error = worker
34070                .run_once()
34071                .await
34072                .expect_err(&format!("{name} must remain an error"));
34073            assert!(
34074                matches!(error, Error::Http { .. } | Error::Protocol(_)),
34075                "{name} returned an unexpected error variant: {error}"
34076            );
34077        }
34078    }
34079
34080    #[tokio::test]
34081    async fn worker_deregistration_uses_worker_plane_method_path_headers_and_result() {
34082        let server = MockWorkerServer::start();
34083        let client = Client::builder(server.base_url())
34084            .worker_token(Some("worker-secret".to_string()))
34085            .namespace("orders")
34086            .timeout(Duration::from_secs(2))
34087            .build()
34088            .expect("client");
34089        let path = "/api/worker/registrations/worker%2F%CE%B1%20space";
34090
34091        let result = client
34092            .deregister_worker_registration("worker/α space")
34093            .await
34094            .expect("deregister worker registration");
34095
34096        assert_eq!(server.method_for(path).as_deref(), Some("DELETE"));
34097        assert_eq!(
34098            server.worker_protocol_for(path).as_deref(),
34099            Some(WORKER_PROTOCOL_VERSION)
34100        );
34101        assert_eq!(server.control_protocol_for(path), None);
34102        assert_eq!(server.namespace_for(path).as_deref(), Some("orders"));
34103        assert_eq!(
34104            server.authorization_for(path).as_deref(),
34105            Some("Bearer worker-secret")
34106        );
34107        assert_eq!(
34108            result,
34109            WorkerDeregistrationEnvelope {
34110                worker_id: "deregistered-worker".to_string(),
34111                outcome: "deregistered".to_string(),
34112                recovered_workflow_task_count: 2,
34113            }
34114        );
34115    }
34116
34117    #[tokio::test]
34118    async fn low_level_registration_rejects_update_validators_before_transport() {
34119        let server = MockWorkerServer::start();
34120        let client = Client::builder(server.base_url())
34121            .timeout(Duration::from_secs(2))
34122            .build()
34123            .expect("client");
34124
34125        for update_validators in [json!(["approve"]), json!("approve")] {
34126            let error = client
34127                .register_worker_with_command_contracts(
34128                    "validator-claiming-worker",
34129                    "rust-workers",
34130                    vec!["orders".to_string()],
34131                    vec![],
34132                    1,
34133                    1,
34134                    vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
34135                    json!({
34136                        "orders": {
34137                            "queries": ["current"],
34138                            "updates": ["approve"],
34139                            "update_validators": update_validators,
34140                        },
34141                    }),
34142                )
34143                .await
34144                .expect_err("unsupported validator claims must fail before registration");
34145
34146            let Error::UnsupportedUpdateValidators { workflow_type } = error else {
34147                panic!("expected typed unsupported-validator failure");
34148            };
34149            assert_eq!(workflow_type, "orders");
34150        }
34151        assert_eq!(server.request_count("/api/worker/register"), 0);
34152    }
34153
34154    #[tokio::test]
34155    async fn worker_registers_complete_json_and_lossless_handler_argument_contracts() {
34156        let server = MockWorkerServer::start();
34157        let client = Client::builder(server.base_url())
34158            .timeout(Duration::from_secs(2))
34159            .build()
34160            .expect("client");
34161        let mut worker = Worker::new(client, "rust-workers");
34162        worker.register_workflow("orders", |_ctx, input| async move { Ok(input) });
34163        worker.register_query("orders", "z-json", |_ctx, args| async move { Ok(args) });
34164        worker.register_query_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
34165        worker.register_update("orders", "z-json", |_ctx, args| async move { Ok(args) });
34166        worker.register_update_avro_value("orders", "a-avro", |_ctx, args| async move { Ok(args) });
34167        worker
34168            .declare_workflow_signals("orders", &["z-json", "a-avro", "z-json"])
34169            .expect("declare workflow signals");
34170
34171        worker.register().await.expect("register handler contracts");
34172
34173        let declaration =
34174            &server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"];
34175        let expected_contracts = json!([
34176            {
34177                "name": "a-avro",
34178                "parameters": [{
34179                    "name": "args", "position": 0, "required": false,
34180                    "variadic": true, "type": null, "allows_null": true,
34181                    "default_available": false, "default": null,
34182                }],
34183            },
34184            {
34185                "name": "z-json",
34186                "parameters": [{
34187                    "name": "args", "position": 0, "required": false,
34188                    "variadic": true, "type": null, "allows_null": true,
34189                    "default_available": false, "default": null,
34190                }],
34191            },
34192        ]);
34193        assert_eq!(declaration["queries"], json!(["a-avro", "z-json"]));
34194        assert_eq!(declaration["query_contracts"], expected_contracts);
34195        assert_eq!(declaration["updates"], json!(["a-avro", "z-json"]));
34196        assert_eq!(declaration["update_contracts"], expected_contracts);
34197        assert_eq!(declaration["signals"], json!(["a-avro", "z-json"]));
34198        assert_eq!(declaration["signal_contracts"], expected_contracts);
34199        assert_eq!(declaration["update_validators"], json!([]));
34200    }
34201
34202    #[tokio::test]
34203    async fn workflow_signal_declarations_reject_invalid_configuration_without_mutation() {
34204        let server = MockWorkerServer::start();
34205        let client = Client::new(server.base_url()).expect("client");
34206        let mut worker = Worker::new(client, "rust-workers");
34207        worker.register_workflow("orders", |_ctx, args| async move { Ok(args) });
34208        assert!(worker
34209            .declare_workflow_signals("missing", &["finish"])
34210            .is_err());
34211        worker
34212            .declare_workflow_signals("orders", &["finish"])
34213            .unwrap();
34214        for names in [&[""][..], &[" finish"][..], &["finish "][..]] {
34215            assert!(worker.declare_workflow_signals("orders", names).is_err());
34216        }
34217        worker.register().await.unwrap();
34218        assert_eq!(
34219            server.request_body("/api/worker/register")["workflow_command_contracts"]["orders"]
34220                ["signals"],
34221            json!(["finish"])
34222        );
34223        worker.declare_workflow_signals("orders", &[]).unwrap();
34224        worker.register().await.unwrap();
34225        let registrations = server.request_bodies("/api/worker/register");
34226        assert_eq!(
34227            registrations[1]["workflow_command_contracts"]["orders"]["signals"],
34228            json!([])
34229        );
34230        assert_eq!(
34231            registrations[1]["workflow_command_contracts"]["orders"]["signal_contracts"],
34232            json!([])
34233        );
34234    }
34235
34236    #[tokio::test]
34237    async fn low_level_registration_preserves_query_and_update_contracts() {
34238        let server = MockWorkerServer::start();
34239        let client = Client::builder(server.base_url())
34240            .timeout(Duration::from_secs(2))
34241            .build()
34242            .expect("client");
34243        let contracts = json!({
34244            "orders": {
34245                "queries": ["current"],
34246                "updates": ["approve"],
34247                "update_validators": [],
34248            },
34249            "payments": {
34250                "queries": ["status"],
34251                "updates": ["capture"],
34252            },
34253        });
34254
34255        client
34256            .register_worker_with_command_contracts(
34257                "command-worker",
34258                "rust-workers",
34259                vec!["orders".to_string(), "payments".to_string()],
34260                vec![],
34261                1,
34262                1,
34263                vec![WORKFLOW_UPDATES_CAPABILITY.to_string()],
34264                contracts.clone(),
34265            )
34266            .await
34267            .expect("query and update contracts must remain supported");
34268
34269        assert_eq!(
34270            server.request_body("/api/worker/register")["workflow_command_contracts"],
34271            contracts
34272        );
34273        assert!(server
34274            .request_body("/api/worker/register")
34275            .get("workflow_definition_fingerprints")
34276            .is_none());
34277    }
34278
34279    #[tokio::test]
34280    async fn rust_worker_advertises_source_identity_without_reusing_it_for_a_new_handler() {
34281        let server = MockWorkerServer::start();
34282        let client = Client::builder(server.base_url())
34283            .timeout(Duration::from_secs(2))
34284            .build()
34285            .expect("client");
34286        let mut worker = Worker::new(client.clone(), "rust-workers");
34287        worker.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
34288
34289        assert!(worker
34290            .set_workflow_definition_sources("missing", &[include_str!("lib.rs")])
34291            .is_err());
34292        assert!(worker
34293            .set_workflow_definition_sources("orders", &[])
34294            .is_err());
34295        worker
34296            .set_workflow_definition_sources("orders", &[include_str!("lib.rs")])
34297            .expect("embed workflow source");
34298        worker.register().await.expect("register worker");
34299        let first = server.request_bodies("/api/worker/register")[0]
34300            ["workflow_definition_fingerprints"]["orders"]
34301            .as_str()
34302            .expect("source-backed fingerprint")
34303            .to_string();
34304        assert!(first.starts_with("sha256:"));
34305
34306        worker
34307            .set_workflow_definition_sources("orders", &[include_str!("lib.rs"), "changed helper"])
34308            .expect("change embedded helper source");
34309        worker.register().await.expect("register changed source");
34310        let changed = server.request_bodies("/api/worker/register")[1]
34311            ["workflow_definition_fingerprints"]["orders"]
34312            .as_str()
34313            .expect("changed fingerprint")
34314            .to_string();
34315        assert_ne!(first, changed);
34316
34317        let mut replacement =
34318            Worker::new(client, "rust-workers").worker_id(worker.worker_id.clone());
34319        replacement.register_workflow("orders", |_ctx, _input| async { Ok(Value::Null) });
34320        replacement
34321            .register()
34322            .await
34323            .expect("register replacement handler");
34324        assert_eq!(
34325            server.request_bodies("/api/worker/register")[2]["workflow_definition_fingerprints"],
34326            json!({})
34327        );
34328    }
34329
34330    #[tokio::test]
34331    async fn role_scoped_tokens_are_never_used_for_the_opposite_plane() {
34332        let server = MockWorkerServer::start();
34333        let control_only = Client::builder(server.base_url())
34334            .control_token(Some("control-secret".to_string()))
34335            .build()
34336            .expect("control client");
34337
34338        let error = control_only
34339            .register_worker("worker", "queue", vec![], vec![], 1, 1)
34340            .await
34341            .expect_err("control token must not authorize a worker request");
34342        assert!(matches!(
34343            error,
34344            Error::MissingRoleCredentials { role: "worker", .. }
34345        ));
34346        assert_eq!(server.request_count("/api/worker/register"), 0);
34347
34348        let worker_only = Client::builder(server.base_url())
34349            .worker_token(Some("worker-secret".to_string()))
34350            .build()
34351            .expect("worker client");
34352        let error = worker_only
34353            .health()
34354            .await
34355            .expect_err("worker token must not authorize a control request");
34356        assert!(matches!(
34357            error,
34358            Error::MissingRoleCredentials {
34359                role: "control",
34360                ..
34361            }
34362        ));
34363        assert_eq!(server.request_count("/api/health"), 0);
34364    }
34365
34366    #[tokio::test]
34367    async fn shared_token_supports_worker_and_control_planes() {
34368        let server = MockWorkerServer::start();
34369        let client = Client::builder(server.base_url())
34370            .token(Some("shared-secret".to_string()))
34371            .build()
34372            .expect("client");
34373
34374        client.health().await.expect("control request");
34375        client
34376            .register_worker("worker", "queue", vec![], vec![], 1, 1)
34377            .await
34378            .expect("worker request");
34379
34380        assert_eq!(
34381            server.authorization_for("/api/health").as_deref(),
34382            Some("Bearer shared-secret")
34383        );
34384        assert_eq!(
34385            server.control_protocol_for("/api/health").as_deref(),
34386            Some(CONTROL_PLANE_VERSION)
34387        );
34388        assert_eq!(
34389            server.authorization_for("/api/worker/register").as_deref(),
34390            Some("Bearer shared-secret")
34391        );
34392        assert_eq!(
34393            server
34394                .worker_protocol_for("/api/worker/register")
34395                .as_deref(),
34396            Some(WORKER_PROTOCOL_VERSION)
34397        );
34398    }
34399
34400    #[tokio::test]
34401    async fn baseline_worker_endpoints_send_the_baseline_protocol() {
34402        assert_eq!(WORKER_PROTOCOL_VERSION, "1.20");
34403        let server = MockWorkerServer::start();
34404        let client = Client::builder(server.base_url())
34405            .timeout(Duration::from_secs(2))
34406            .build()
34407            .expect("client");
34408
34409        client
34410            .register_worker("capture-worker", "capture", vec![], vec![], 1, 1)
34411            .await
34412            .expect("register");
34413        client
34414            .heartbeat_worker("capture-worker", 1, 1)
34415            .await
34416            .expect("heartbeat");
34417        client
34418            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
34419            .await
34420            .expect("workflow poll");
34421        client
34422            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
34423            .await
34424            .expect("activity poll");
34425
34426        for path in [
34427            "/api/worker/register",
34428            "/api/worker/heartbeat",
34429            "/api/worker/workflow-tasks/poll",
34430            "/api/worker/activity-tasks/poll",
34431        ] {
34432            assert_eq!(
34433                server.worker_protocol_for(path).as_deref(),
34434                Some(WORKER_PROTOCOL_VERSION),
34435                "unexpected protocol for {path}"
34436            );
34437        }
34438
34439        assert_eq!(
34440            server.request_body("/api/worker/workflow-tasks/poll")["timeout_seconds"],
34441            1
34442        );
34443        assert_eq!(
34444            server.request_body("/api/worker/workflow-tasks/poll")["history_page_size"],
34445            500
34446        );
34447        assert_eq!(
34448            server.request_body("/api/worker/activity-tasks/poll")["timeout_seconds"],
34449            1
34450        );
34451        assert!(
34452            server.request_body("/api/worker/workflow-tasks/poll")["poll_request_id"]
34453                .as_str()
34454                .is_some_and(|id| id.starts_with("rust-workflow-poll-"))
34455        );
34456        assert!(
34457            server.request_body("/api/worker/activity-tasks/poll")["poll_request_id"]
34458                .as_str()
34459                .is_some_and(|id| id.starts_with("rust-activity-poll-"))
34460        );
34461        let registration = server.request_body("/api/worker/register");
34462        for optional in [
34463            "cooperative_cancellation",
34464            "local_activities",
34465            "worker_sessions",
34466            "sticky_execution",
34467        ] {
34468            assert!(!registration["capabilities"]
34469                .as_array()
34470                .is_some_and(|capabilities| capabilities
34471                    .iter()
34472                    .any(|capability| capability.as_str() == Some(optional))));
34473        }
34474    }
34475
34476    #[tokio::test]
34477    async fn explicit_previous_worker_protocol_preserves_headers() {
34478        let server = MockWorkerServer::start();
34479        let client = Client::builder(server.base_url())
34480            .worker_protocol_version(WorkerProtocolVersion::V119)
34481            .timeout(Duration::from_secs(2))
34482            .build()
34483            .expect("client");
34484        client
34485            .register_worker("legacy-worker", "capture", vec![], vec![], 1, 1)
34486            .await
34487            .expect("register");
34488        client
34489            .heartbeat_worker("legacy-worker", 1, 1)
34490            .await
34491            .expect("heartbeat");
34492        client
34493            .poll_workflow_task("legacy-worker", "capture", Duration::from_millis(10))
34494            .await
34495            .expect("workflow poll");
34496        client
34497            .poll_activity_task("legacy-worker", "capture", Duration::from_millis(10))
34498            .await
34499            .expect("activity poll");
34500        client
34501            .poll_query_task("legacy-worker", "capture", Duration::from_millis(10))
34502            .await
34503            .expect("query poll");
34504        client
34505            .deregister_worker_registration("legacy-worker")
34506            .await
34507            .expect("deregister");
34508        for path in [
34509            "/api/worker/register",
34510            "/api/worker/heartbeat",
34511            "/api/worker/workflow-tasks/poll",
34512            "/api/worker/activity-tasks/poll",
34513            "/api/worker/query-tasks/poll",
34514            "/api/worker/registrations/legacy-worker",
34515        ] {
34516            assert_eq!(
34517                server.worker_protocol_for(path).as_deref(),
34518                Some("1.19"),
34519                "{path}"
34520            );
34521            assert_eq!(server.control_protocol_for(path), None, "{path}");
34522        }
34523    }
34524
34525    #[tokio::test]
34526    async fn explicit_previous_protocol_refuses_cooperation_before_registration() {
34527        let server = MockWorkerServer::start();
34528        let client = Client::builder(server.base_url())
34529            .worker_protocol_version(WorkerProtocolVersion::V119)
34530            .timeout(Duration::from_secs(2))
34531            .build()
34532            .expect("client");
34533        let worker = Worker::new(client, "capture").cooperative_cancellation(true);
34534        let error = worker
34535            .register()
34536            .await
34537            .expect_err("legacy cooperation must be refused");
34538        assert!(matches!(
34539            error,
34540            Error::CooperativeCancellationUnavailable(_)
34541        ));
34542        assert_eq!(server.worker_protocol_for("/api/worker/register"), None);
34543    }
34544
34545    #[tokio::test]
34546    async fn query_task_endpoints_send_the_selected_worker_protocol() {
34547        let server = MockWorkerServer::start();
34548        let client = Client::builder(server.base_url())
34549            .timeout(Duration::from_secs(2))
34550            .build()
34551            .expect("client");
34552
34553        client
34554            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
34555            .await
34556            .expect("query poll");
34557        client
34558            .complete_query_task(
34559                "query-capture",
34560                "capture-worker",
34561                1,
34562                json!(8),
34563                DEFAULT_CODEC,
34564            )
34565            .await
34566            .expect("query complete");
34567        client
34568            .fail_query_task(
34569                "query-capture",
34570                "capture-worker",
34571                1,
34572                "failed",
34573                "query_rejected",
34574                "QueryFailed",
34575            )
34576            .await
34577            .expect("query fail");
34578
34579        for path in [
34580            "/api/worker/query-tasks/poll",
34581            "/api/worker/query-tasks/query-capture/complete",
34582            "/api/worker/query-tasks/query-capture/fail",
34583        ] {
34584            assert_eq!(
34585                server.worker_protocol_for(path).as_deref(),
34586                Some(WORKER_PROTOCOL_VERSION),
34587                "unexpected protocol for {path}"
34588            );
34589        }
34590
34591        assert_eq!(
34592            server.request_body("/api/worker/query-tasks/poll")["timeout_seconds"],
34593            1
34594        );
34595        assert!(
34596            server.request_body("/api/worker/query-tasks/poll")["poll_request_id"]
34597                .as_str()
34598                .is_some_and(|id| id.starts_with("rust-query-poll-"))
34599        );
34600    }
34601
34602    #[tokio::test]
34603    async fn disconnected_client_polls_retry_once_with_the_same_request_id() {
34604        let server = MockWorkerServer::transient_worker_failures();
34605        let client = Client::builder(server.base_url())
34606            .timeout(Duration::from_secs(2))
34607            .build()
34608            .expect("client");
34609
34610        client
34611            .poll_workflow_task("capture-worker", "capture", Duration::from_millis(10))
34612            .await
34613            .expect("workflow poll retry");
34614        client
34615            .poll_activity_task("capture-worker", "capture", Duration::from_millis(10))
34616            .await
34617            .expect("activity poll retry");
34618        client
34619            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
34620            .await
34621            .expect("query poll retry");
34622
34623        for path in [
34624            "/api/worker/workflow-tasks/poll",
34625            "/api/worker/activity-tasks/poll",
34626            "/api/worker/query-tasks/poll",
34627        ] {
34628            let bodies = server.request_bodies(path);
34629            assert_eq!(bodies.len(), 2, "{path} must be retried once");
34630            assert_eq!(
34631                bodies[0]["poll_request_id"], bodies[1]["poll_request_id"],
34632                "{path} must preserve the request binding across retry"
34633            );
34634        }
34635    }
34636
34637    #[tokio::test]
34638    async fn worker_poll_retries_preserve_request_id_across_consecutive_failures() {
34639        let server = MockWorkerServer::consecutive_poll_failures(2);
34640        let client = Client::builder(server.base_url())
34641            .timeout(Duration::from_secs(2))
34642            .build()
34643            .expect("client");
34644        let mut worker = Worker::new(client, "capture")
34645            .worker_id("capture-worker")
34646            .poll_timeout(Duration::from_millis(10))
34647            .retry_policy(WorkerRetryPolicy {
34648                max_retries: 2,
34649                initial_backoff: Duration::from_millis(1),
34650                max_backoff: Duration::from_millis(1),
34651            });
34652        worker.register_workflow(
34653            "capture.workflow",
34654            |_ctx, _input| async move { Ok(Value::Null) },
34655        );
34656        worker.register_activity(
34657            "capture.activity",
34658            |_ctx, _input| async move { Ok(Value::Null) },
34659        );
34660        worker.register_query("capture.workflow", "current", |_ctx, _args| async move {
34661            Ok(Value::Null)
34662        });
34663
34664        assert_eq!(worker.run_once().await.expect("poll retries"), 0);
34665
34666        for path in [
34667            "/api/worker/workflow-tasks/poll",
34668            "/api/worker/activity-tasks/poll",
34669            "/api/worker/query-tasks/poll",
34670        ] {
34671            let bodies = server.request_bodies(path);
34672            assert_eq!(bodies.len(), 3, "{path} must use exactly two retries");
34673            assert!(
34674                bodies
34675                    .iter()
34676                    .all(|body| body["poll_request_id"] == bodies[0]["poll_request_id"]),
34677                "{path} must preserve one request binding across every retry"
34678            );
34679        }
34680    }
34681
34682    fn storage_refusal(poll_id: Option<&str>, unavailable: bool, mid_poll: bool) -> Value {
34683        let reason = if unavailable {
34684            "storage_admission_unavailable"
34685        } else {
34686            "storage_pressure"
34687        };
34688        let mut body = json!({
34689            "reason": reason,
34690            "storage_state": if unavailable { "fenced" } else { "draining" },
34691            "retryable": true,
34692            "retry_after_seconds": 1,
34693        });
34694        if !mid_poll {
34695            body["request_admitted"] = json!(false);
34696        }
34697        if let Some(id) = poll_id {
34698            body["task"] = Value::Null;
34699            body["poll_status"] = json!(reason);
34700            body["poll_request_id"] = json!(id);
34701            body["retry_same_poll_request_id"] = json!(true);
34702            body["claim_admitted"] = json!(false);
34703        }
34704        body
34705    }
34706
34707    fn backend_refusal(path: &str, request: &str) -> Option<Value> {
34708        let operation = match path {
34709            "/api/worker/register" => "register_worker",
34710            "/api/worker/heartbeat" => "heartbeat_worker",
34711            "/api/worker/workflow-tasks/poll" => "poll_workflow_task",
34712            "/api/worker/activity-tasks/poll" => "poll_activity_task",
34713            "/api/worker/query-tasks/poll" => "poll_query_task",
34714            "/api/worker/update-validation-tasks/poll" => "poll_update_validation_task",
34715            _ => return None,
34716        };
34717        let request: Value = serde_json::from_str(request).ok()?;
34718        let mut response = json!({
34719            "reason": "backend_unavailable",
34720            "operation": operation,
34721            "outcome": "unknown",
34722            "retryable": true,
34723            "retry_after_seconds": 1,
34724            "worker_id": request["worker_id"],
34725            "task_queue": request.get("task_queue"),
34726        });
34727        if path.ends_with("/poll") {
34728            response["task"] = Value::Null;
34729            response["poll_status"] = json!("backend_unavailable");
34730            response["poll_request_id"] = request["poll_request_id"].clone();
34731            response["retry_same_poll_request_id"] = json!(true);
34732        }
34733        Some(response)
34734    }
34735
34736    fn backend_retry_override(
34737        path: &str,
34738        request: &str,
34739        number: usize,
34740    ) -> Option<(&'static str, String)> {
34741        if number > 8 {
34742            return None;
34743        }
34744        Some((
34745            "503 Service Unavailable",
34746            backend_refusal(path, request)?.to_string(),
34747        ))
34748    }
34749
34750    fn backend_unavailable_override(
34751        path: &str,
34752        request: &str,
34753        _number: usize,
34754    ) -> Option<(&'static str, String)> {
34755        Some((
34756            "503 Service Unavailable",
34757            backend_refusal(path, request)?.to_string(),
34758        ))
34759    }
34760
34761    fn storage_worker(server: &MockWorkerServer) -> Worker {
34762        Worker::new(Client::new(server.base_url()).expect("client"), "storage")
34763            .worker_id("storage-worker")
34764            .retry_policy(WorkerRetryPolicy {
34765                max_retries: 1,
34766                initial_backoff: Duration::from_millis(1),
34767                max_backoff: Duration::from_millis(1),
34768            })
34769    }
34770
34771    fn assert_identical_requests(server: &MockWorkerServer, path: &str, count: usize) {
34772        let requests = server.requests.lock().expect("requests");
34773        let bodies: Vec<_> = requests
34774            .iter()
34775            .filter(|request| request.path == path)
34776            .map(|request| &request.body)
34777            .collect();
34778        assert_eq!(bodies.len(), count, "{path}");
34779        assert!(bodies.iter().all(|body| body == &bodies[0]), "{path}");
34780    }
34781
34782    #[test]
34783    fn backend_recovery_requires_the_explicit_worker_contract() {
34784        for (path, operation) in [
34785            ("/worker/register", "register_worker"),
34786            ("/worker/heartbeat", "heartbeat_worker"),
34787            ("/worker/workflow-tasks/poll", "poll_workflow_task"),
34788            ("/worker/activity-tasks/poll", "poll_activity_task"),
34789            ("/worker/query-tasks/poll", "poll_query_task"),
34790            (
34791                "/worker/update-validation-tasks/poll",
34792                "poll_update_validation_task",
34793            ),
34794        ] {
34795            let poll_id = path.ends_with("/poll").then_some("same-poll");
34796            let request = json!({"worker_id":"same-worker","task_queue":"same-queue","poll_request_id":poll_id});
34797            let body = backend_refusal(&format!("/api{path}"), &request.to_string())
34798                .expect("worker operation");
34799            assert_eq!(body["operation"], operation);
34800            let error = Error::Http {
34801                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
34802                body: body.to_string(),
34803            };
34804            assert_eq!(
34805                worker_backend_unavailable_retry_after(&error, path, poll_id),
34806                Some(Duration::from_secs(1))
34807            );
34808            assert!(!worker_operation_is_retryable(&error));
34809            for (field, value) in [
34810                ("operation", json!("wrong_operation")),
34811                ("outcome", json!("completed")),
34812                ("retryable", json!(false)),
34813                ("retry_after_seconds", json!(0)),
34814                ("worker_id", json!("")),
34815            ] {
34816                let mut invalid = body.clone();
34817                invalid[field] = value;
34818                let error = Error::Http {
34819                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
34820                    body: invalid.to_string(),
34821                };
34822                assert!(
34823                    worker_backend_unavailable_retry_after(&error, path, poll_id).is_none(),
34824                    "{path}: {field}"
34825                );
34826                assert!(!worker_operation_is_retryable(&error));
34827            }
34828            if let Some(poll_id) = poll_id {
34829                for (field, value) in [
34830                    ("poll_request_id", json!("wrong-poll")),
34831                    ("poll_status", json!("empty")),
34832                    ("task", json!({"task_id":"claimed"})),
34833                    ("retry_same_poll_request_id", json!(false)),
34834                ] {
34835                    let mut invalid = body.clone();
34836                    invalid[field] = value;
34837                    let error = Error::Http {
34838                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
34839                        body: invalid.to_string(),
34840                    };
34841                    assert!(
34842                        worker_backend_unavailable_retry_after(&error, path, Some(poll_id))
34843                            .is_none(),
34844                        "{path}: {field}"
34845                    );
34846                }
34847            }
34848            let error = Error::Http {
34849                status: reqwest::StatusCode::UNAUTHORIZED,
34850                body: body.to_string(),
34851            };
34852            assert!(worker_backend_unavailable_retry_after(&error, path, poll_id).is_none());
34853            assert!(!worker_operation_is_retryable(&error));
34854        }
34855    }
34856
34857    #[tokio::test]
34858    async fn backend_recovery_outlives_generic_retry_budget_and_preserves_polls() {
34859        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
34860            request_override: Some(backend_retry_override),
34861            ..MockWorkerBehavior::default()
34862        });
34863        let mut worker =
34864            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
34865        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
34866        worker.register_activity("backend.activity", |_, _| async { Ok(Value::Null) });
34867        worker.register_query("backend.workflow", "state", |_, _| async {
34868            Ok(Value::Null)
34869        });
34870        worker.register().await.expect("registration recovery");
34871        worker
34872            .client
34873            .heartbeat_worker("storage-worker", 1, 1)
34874            .await
34875            .expect("heartbeat recovery");
34876        assert_eq!(worker.run_once().await.expect("poll recovery"), 0);
34877        for path in [
34878            "/api/worker/register",
34879            "/api/worker/heartbeat",
34880            "/api/worker/workflow-tasks/poll",
34881            "/api/worker/activity-tasks/poll",
34882            "/api/worker/query-tasks/poll",
34883        ] {
34884            assert_identical_requests(&server, path, 9);
34885        }
34886    }
34887
34888    #[tokio::test]
34889    async fn backend_recovery_wait_stops_with_worker() {
34890        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
34891            request_override: Some(backend_unavailable_override),
34892            ..MockWorkerBehavior::default()
34893        });
34894        let mut worker = storage_worker(&server).retry_policy(WorkerRetryPolicy {
34895            max_retries: 1,
34896            initial_backoff: Duration::from_secs(2),
34897            max_backoff: Duration::from_secs(2),
34898        });
34899        worker.register_workflow("backend.workflow", |_, _| async { Ok(Value::Null) });
34900        let started = tokio::time::Instant::now();
34901        let _ = tokio::time::timeout(
34902            Duration::from_secs(1),
34903            worker.run_until(tokio::time::sleep(Duration::from_millis(100))),
34904        )
34905        .await
34906        .expect("shutdown interrupts backend wait");
34907        assert!(started.elapsed() < Duration::from_secs(1));
34908        assert!(server.request_count("/api/worker/register") >= 1);
34909    }
34910
34911    #[test]
34912    fn storage_admission_requires_an_explicit_identity_preserving_contract() {
34913        for unavailable in [false, true] {
34914            for mid_poll in [false, true] {
34915                let body = storage_refusal(Some("same-poll"), unavailable, mid_poll);
34916                let error = Error::Http {
34917                    status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
34918                    body: body.to_string(),
34919                };
34920                assert_eq!(
34921                    worker_storage_admission_retry_after(&error, Some("same-poll")),
34922                    Some(Duration::from_secs(1))
34923                );
34924                assert!(
34925                    !worker_operation_is_retryable(&error),
34926                    "storage is not a bounded generic retry"
34927                );
34928                for (field, value) in [
34929                    ("poll_request_id", json!("wrong-poll")),
34930                    ("task", json!({"task_id":"claimed"})),
34931                    ("retryable", json!(false)),
34932                    ("retry_after_seconds", json!(0)),
34933                    ("retry_after_seconds", json!(true)),
34934                    ("retry_after_seconds", json!(1.0)),
34935                    ("storage_state", json!("normal")),
34936                    ("poll_status", json!("empty")),
34937                    ("claim_admitted", json!(true)),
34938                    ("retry_same_poll_request_id", json!(false)),
34939                    ("request_admitted", json!(true)),
34940                ] {
34941                    let mut invalid = body.clone();
34942                    invalid[field] = value;
34943                    let error = Error::Http {
34944                        status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
34945                        body: invalid.to_string(),
34946                    };
34947                    assert!(
34948                        worker_storage_admission_retry_after(&error, Some("same-poll")).is_none(),
34949                        "{field}"
34950                    );
34951                }
34952            }
34953        }
34954        let body = storage_refusal(None, false, false);
34955        let error = Error::Http {
34956            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
34957            body: body.to_string(),
34958        };
34959        assert!(worker_storage_admission_retry_after(&error, None).is_some());
34960        assert!(worker_storage_admission_retry_after(&error, Some("")).is_none());
34961        let error = Error::Http {
34962            status: reqwest::StatusCode::FORBIDDEN,
34963            body: body.to_string(),
34964        };
34965        assert!(worker_storage_admission_retry_after(&error, None).is_none());
34966        let body = storage_refusal(None, false, true);
34967        let error = Error::Http {
34968            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
34969            body: body.to_string(),
34970        };
34971        assert!(worker_storage_admission_retry_after(&error, None).is_none());
34972    }
34973
34974    #[tokio::test]
34975    async fn storage_poll_recovery_preserves_ambiguous_claim_identity() {
34976        for unavailable in [false, true] {
34977            for mid_poll in [false, true] {
34978                let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
34979                    poll_failures_per_path: 1,
34980                    storage_refusals: 7,
34981                    storage_path: Some("/poll"),
34982                    storage_unavailable: unavailable,
34983                    storage_mid_poll: mid_poll,
34984                    ..MockWorkerBehavior::default()
34985                });
34986                let mut worker = storage_worker(&server);
34987                worker.register_query("unused", "state", |_, _| async { Ok(Value::Null) });
34988                assert_eq!(worker.run_once().await.expect("storage recovery"), 0);
34989                for path in [
34990                    "/api/worker/workflow-tasks/poll",
34991                    "/api/worker/activity-tasks/poll",
34992                    "/api/worker/query-tasks/poll",
34993                ] {
34994                    assert_identical_requests(&server, path, 9);
34995                }
34996            }
34997        }
34998    }
34999
35000    #[tokio::test]
35001    async fn storage_refused_mutations_do_not_reserialize_or_change_client_scope() {
35002        struct CountedBody(Arc<AtomicUsize>);
35003        impl Serialize for CountedBody {
35004            fn serialize<S: Serializer>(
35005                &self,
35006                serializer: S,
35007            ) -> std::result::Result<S::Ok, S::Error> {
35008                let count = self.0.fetch_add(1, Ordering::SeqCst);
35009                json!({"serialization":count,"lease_owner":"worker","attempt":7})
35010                    .serialize(serializer)
35011            }
35012        }
35013        for path in [
35014            "/api/worker/register",
35015            "/api/worker/heartbeat",
35016            "/api/worker/workflow-tasks/storage-task/complete",
35017            "/api/worker/workflow-tasks/storage-task/fail",
35018            "/api/worker/activity-tasks/storage-task/complete",
35019            "/api/worker/activity-tasks/storage-task/fail",
35020            "/api/worker/activity-tasks/storage-task/heartbeat",
35021            "/api/worker/query-tasks/storage-task/complete",
35022            "/api/worker/query-tasks/storage-task/fail",
35023        ] {
35024            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
35025                storage_refusals: 7,
35026                storage_path: Some(path),
35027                ..MockWorkerBehavior::default()
35028            });
35029            let worker =
35030                storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
35031            let calls = Arc::new(AtomicUsize::new(0));
35032            let _: Value = worker
35033                .client
35034                .request_json(
35035                    reqwest::Method::POST,
35036                    &path[4..],
35037                    RequestProtocol::DefaultWorker,
35038                    Some(&CountedBody(Arc::clone(&calls))),
35039                )
35040                .await
35041                .expect("prepared request recovery");
35042            assert_eq!(calls.load(Ordering::SeqCst), 1);
35043            assert_identical_requests(&server, path, 8);
35044        }
35045        for worker_scope in [false, true] {
35046            let path = if worker_scope {
35047                "/api/health"
35048            } else {
35049                "/api/worker/register"
35050            };
35051            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
35052                storage_refusals: usize::MAX,
35053                storage_path: Some(path),
35054                ..MockWorkerBehavior::default()
35055            });
35056            let worker = storage_worker(&server);
35057            let client = worker.client.clone();
35058            let worker = worker.with_storage_admission(Arc::new(AtomicBool::new(false)));
35059            let error = if worker_scope {
35060                worker
35061                    .client
35062                    .health()
35063                    .await
35064                    .expect_err("control plane is not retried")
35065            } else {
35066                client
35067                    .request_json::<Value, Value>(
35068                        reqwest::Method::POST,
35069                        "/worker/register",
35070                        RequestProtocol::DefaultWorker,
35071                        Some(&json!({})),
35072                    )
35073                    .await
35074                    .expect_err("direct client is not retried")
35075            };
35076            assert!(worker_storage_admission_body(&error).is_some());
35077            assert_eq!(server.request_count(path), 1);
35078        }
35079    }
35080
35081    #[tokio::test]
35082    async fn storage_activity_outcome_is_retained_without_reexecuting_handler() {
35083        for fail in [false, true] {
35084            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
35085                storage_activity: true,
35086                storage_refusals: 7,
35087                storage_path: Some("/storage-activity/"),
35088                ..MockWorkerBehavior::default()
35089            });
35090            let mut worker = storage_worker(&server);
35091            let calls = Arc::new(AtomicUsize::new(0));
35092            let observed = Arc::clone(&calls);
35093            worker.register_activity("storage.activity", move |ctx, _| {
35094                let calls = Arc::clone(&observed);
35095                async move {
35096                    calls.fetch_add(1, Ordering::SeqCst);
35097                    ctx.heartbeat(json!({"step":2})).await?;
35098                    if fail {
35099                        Err(Error::WorkerLoop("intentional handler failure".to_string()))
35100                    } else {
35101                        Ok(json!({"receipt":true}))
35102                    }
35103                }
35104            });
35105            assert_eq!(worker.run_once().await.expect("activity settled"), 1);
35106            assert_eq!(calls.load(Ordering::SeqCst), 1);
35107            assert_identical_requests(
35108                &server,
35109                "/api/worker/activity-tasks/storage-activity/heartbeat",
35110                8,
35111            );
35112            let suffix = if fail { "fail" } else { "complete" };
35113            assert_identical_requests(
35114                &server,
35115                &format!("/api/worker/activity-tasks/storage-activity/{suffix}"),
35116                8,
35117            );
35118            let other = if fail { "complete" } else { "fail" };
35119            assert_eq!(
35120                server.request_count(&format!(
35121                    "/api/worker/activity-tasks/storage-activity/{other}"
35122                )),
35123                0
35124            );
35125        }
35126    }
35127
35128    #[tokio::test]
35129    async fn storage_waits_are_interruptible_without_false_activity_failure() {
35130        for path in [
35131            "/api/worker/register",
35132            "/api/worker/heartbeat",
35133            "/api/worker/activity-tasks/poll",
35134            "/api/worker/activity-tasks/storage-activity/heartbeat",
35135            "/api/worker/activity-tasks/storage-activity/complete",
35136        ] {
35137            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
35138                storage_activity: true,
35139                storage_refusals: usize::MAX,
35140                storage_path: Some(path),
35141                ..MockWorkerBehavior::default()
35142            });
35143            let mut worker = storage_worker(&server)
35144                .max_concurrent_workflow_tasks(1)
35145                .max_concurrent_activity_tasks(1)
35146                .retry_policy(WorkerRetryPolicy::default());
35147            worker.register_activity("storage.activity", |ctx, _| async move {
35148                ctx.heartbeat(json!({"step":2})).await?;
35149                Ok(json!({"receipt":true}))
35150            });
35151            let shutdown = async {
35152                while server.request_count(path) == 0 {
35153                    tokio::time::sleep(Duration::from_millis(1)).await;
35154                }
35155            };
35156            let result = tokio::time::timeout(Duration::from_secs(2), worker.run_until(shutdown))
35157                .await
35158                .expect("shutdown interrupts admission");
35159            assert!(
35160                result.is_err(),
35161                "a refused operation must not appear acknowledged: {path}, {result:?}"
35162            );
35163            assert_eq!(server.request_count(path), 1);
35164            assert_eq!(
35165                server.request_count("/api/worker/activity-tasks/storage-activity/fail"),
35166                0
35167            );
35168            assert_eq!(
35169                server.request_count("/api/worker/registrations/mock-worker"),
35170                usize::from(!path.ends_with("/register"))
35171            );
35172        }
35173    }
35174
35175    #[tokio::test]
35176    async fn storage_query_outcome_is_retained_without_reexecuting_handler() {
35177        for fail in [false, true] {
35178            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
35179                storage_query: true,
35180                storage_refusals: 7,
35181                storage_path: Some("/storage-query/"),
35182                ..MockWorkerBehavior::default()
35183            });
35184            let mut worker = storage_worker(&server);
35185            worker.register_workflow("storage.workflow", |_, _| async { Ok(Value::Null) });
35186            let calls = Arc::new(AtomicUsize::new(0));
35187            let observed = Arc::clone(&calls);
35188            worker.register_query("storage.workflow", "state", move |_, _| {
35189                let calls = Arc::clone(&observed);
35190                async move {
35191                    calls.fetch_add(1, Ordering::SeqCst);
35192                    if fail {
35193                        Err(Error::WorkerLoop("intentional query failure".to_string()))
35194                    } else {
35195                        Ok(json!({"state":"waiting"}))
35196                    }
35197                }
35198            });
35199            assert_eq!(worker.run_once().await.expect("query settled"), 1);
35200            assert_eq!(calls.load(Ordering::SeqCst), 1);
35201            let suffix = if fail { "fail" } else { "complete" };
35202            assert_identical_requests(
35203                &server,
35204                &format!("/api/worker/query-tasks/storage-query/{suffix}"),
35205                8,
35206            );
35207            let other = if fail { "complete" } else { "fail" };
35208            assert_eq!(
35209                server.request_count(&format!("/api/worker/query-tasks/storage-query/{other}")),
35210                0
35211            );
35212        }
35213    }
35214
35215    #[tokio::test]
35216    async fn storage_recovery_does_not_override_auth_lease_or_invalid_contract() {
35217        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
35218            storage_refusals: 7,
35219            storage_path: Some("/poll"),
35220            unauthorized_polls: true,
35221            ..MockWorkerBehavior::default()
35222        });
35223        let error = storage_worker(&server)
35224            .run_once()
35225            .await
35226            .expect_err("auth remains terminal");
35227        assert!(matches!(
35228            error,
35229            Error::Http {
35230                status: reqwest::StatusCode::UNAUTHORIZED,
35231                ..
35232            }
35233        ));
35234        assert_identical_requests(&server, "/api/worker/workflow-tasks/poll", 8);
35235
35236        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
35237            storage_refusals: 7,
35238            storage_path: Some("/activity-cancel/complete"),
35239            ..MockWorkerBehavior::default()
35240        });
35241        let worker =
35242            storage_worker(&server).with_storage_admission(Arc::new(AtomicBool::new(false)));
35243        let error = worker
35244            .client
35245            .complete_activity_task(
35246                "activity-cancel",
35247                "attempt-cancel",
35248                "worker",
35249                json!({}),
35250                DEFAULT_CODEC,
35251            )
35252            .await
35253            .expect_err("cancellation remains terminal");
35254        assert!(activity_task_rejection_is_final(&error));
35255        assert_identical_requests(
35256            &server,
35257            "/api/worker/activity-tasks/activity-cancel/complete",
35258            8,
35259        );
35260
35261        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
35262            storage_refusals: usize::MAX,
35263            storage_path: Some("/poll"),
35264            storage_wrong_poll_id: true,
35265            ..MockWorkerBehavior::default()
35266        });
35267        assert!(storage_worker(&server).run_once().await.is_err());
35268        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
35269    }
35270
35271    #[tokio::test]
35272    async fn storage_pollers_stop_when_the_run_future_is_aborted() {
35273        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
35274            storage_refusals: usize::MAX,
35275            storage_path: Some("/poll"),
35276            ..MockWorkerBehavior::default()
35277        });
35278        let mut worker = storage_worker(&server)
35279            .max_concurrent_workflow_tasks(1)
35280            .max_concurrent_activity_tasks(1)
35281            .retry_policy(WorkerRetryPolicy::default());
35282        worker.register_activity("unused", |_, _| async { Ok(Value::Null) });
35283        let run = tokio::spawn(async move { worker.run().await });
35284        tokio::time::timeout(Duration::from_secs(2), async {
35285            while server.request_count("/api/worker/activity-tasks/poll") == 0 {
35286                tokio::time::sleep(Duration::from_millis(1)).await;
35287            }
35288        })
35289        .await
35290        .expect("poll started");
35291        run.abort();
35292        assert!(run.await.expect_err("cancelled run").is_cancelled());
35293        tokio::time::sleep(Duration::from_millis(250)).await;
35294        assert_eq!(server.request_count("/api/worker/activity-tasks/poll"), 1);
35295    }
35296
35297    #[tokio::test]
35298    async fn query_protocol_rejection_from_older_server_is_typed() {
35299        let server = MockWorkerServer::reject_query_protocol();
35300        let client = Client::builder(server.base_url())
35301            .timeout(Duration::from_secs(2))
35302            .build()
35303            .expect("client");
35304
35305        let error = client
35306            .poll_query_task("capture-worker", "capture", Duration::from_millis(10))
35307            .await
35308            .expect_err("server below query protocol floor must reject");
35309        let Error::Protocol(failure) = error else {
35310            panic!("expected typed protocol failure");
35311        };
35312
35313        assert_eq!(failure.status, 400);
35314        assert_eq!(failure.reason, "unsupported_protocol_version");
35315        assert_eq!(failure.supported_version.as_deref(), Some("1.7"));
35316        assert_eq!(
35317            failure.requested_version.as_deref(),
35318            Some(WORKER_PROTOCOL_VERSION)
35319        );
35320        assert_eq!(
35321            server
35322                .worker_protocol_for("/api/worker/query-tasks/poll")
35323                .as_deref(),
35324            Some(WORKER_PROTOCOL_VERSION)
35325        );
35326    }
35327
35328    #[tokio::test]
35329    async fn run_once_without_query_handlers_keeps_pre_query_server_compatibility() {
35330        let server = MockWorkerServer::reject_query_protocol();
35331        let client = Client::builder(server.base_url())
35332            .timeout(Duration::from_secs(2))
35333            .build()
35334            .expect("client");
35335        let mut worker = Worker::new(client, "rust-workers")
35336            .worker_id("baseline-worker")
35337            .poll_timeout(Duration::from_millis(10));
35338
35339        worker.register_workflow("baseline.workflow", |_ctx, _input| async move {
35340            Ok(Value::Null)
35341        });
35342
35343        assert_eq!(worker.run_once().await.expect("baseline run once"), 0);
35344        assert_eq!(
35345            server
35346                .worker_protocol_for("/api/worker/workflow-tasks/poll")
35347                .as_deref(),
35348            Some(WORKER_PROTOCOL_VERSION)
35349        );
35350        assert_eq!(
35351            server.worker_protocol_for("/api/worker/query-tasks/poll"),
35352            None,
35353            "a worker without query handlers must not use the query-task endpoint"
35354        );
35355    }
35356
35357    #[tokio::test]
35358    async fn completion_time_query_rejection_is_typed_without_stopping_worker() {
35359        let server = MockWorkerServer::reject_query_completion();
35360        let client = Client::builder(server.base_url())
35361            .timeout(Duration::from_secs(2))
35362            .build()
35363            .expect("client");
35364
35365        let error = client
35366            .complete_query_task("query-late", "late-worker", 1, json!(8), DEFAULT_CODEC)
35367            .await
35368            .expect_err("expired completion must be rejected");
35369        let Error::QueryFailed(failure) = error else {
35370            panic!("expected typed query failure");
35371        };
35372        assert_eq!(failure.status, 409);
35373        assert_eq!(failure.reason, "query_task_timed_out");
35374
35375        let mut worker = Worker::new(client, "rust-workers")
35376            .worker_id("late-worker")
35377            .poll_timeout(Duration::from_millis(10));
35378        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
35379        worker.register_query(
35380            "counter",
35381            "current",
35382            |_ctx, _args| async move { Ok(json!(8)) },
35383        );
35384
35385        assert_eq!(worker.run_once().await.expect("late task is handled"), 1);
35386        assert_eq!(
35387            worker
35388                .run_once()
35389                .await
35390                .expect("worker continues after late completion"),
35391            0
35392        );
35393        assert_eq!(
35394            server.request_count("/api/worker/query-tasks/query-late/complete"),
35395            2
35396        );
35397        assert_eq!(
35398            server.request_count("/api/worker/query-tasks/query-late/fail"),
35399            0,
35400            "a server completion rejection must not be reported as an encoding failure"
35401        );
35402    }
35403
35404    #[tokio::test]
35405    async fn normal_shutdown_joins_pollers_and_deregisters_once() {
35406        let server = MockWorkerServer::start();
35407        let client = Client::builder(server.base_url())
35408            .timeout(Duration::from_secs(2))
35409            .build()
35410            .expect("client");
35411        let mut worker = Worker::new(client, "rust-workers")
35412            .worker_id("joined-worker")
35413            .poll_timeout(Duration::from_millis(10));
35414        worker.register_workflow(
35415            "joined.workflow",
35416            |_ctx, _input| async move { Ok(Value::Null) },
35417        );
35418        worker.register_activity(
35419            "joined.activity",
35420            |_ctx, _input| async move { Ok(Value::Null) },
35421        );
35422        worker.register_query("joined.workflow", "state", |_ctx, _input| async move {
35423            Ok(Value::Null)
35424        });
35425
35426        worker
35427            .run_until(tokio::time::sleep(Duration::from_millis(20)))
35428            .await
35429            .expect("normal shutdown");
35430
35431        let deregistration_path = "/api/worker/registrations/mock-worker";
35432        assert_eq!(server.request_count(deregistration_path), 1);
35433        for poll_path in [
35434            "/api/worker/workflow-tasks/poll",
35435            "/api/worker/activity-tasks/poll",
35436            "/api/worker/query-tasks/poll",
35437        ] {
35438            assert!(server.request_count(poll_path) > 0, "missing {poll_path}");
35439        }
35440        assert_eq!(
35441            server.captured_paths().last().map(String::as_str),
35442            Some(deregistration_path),
35443            "deregistration must start only after every poller has joined"
35444        );
35445    }
35446
35447    #[tokio::test]
35448    async fn registration_failure_does_not_deregister() {
35449        let server = MockWorkerServer::rejected_registration();
35450        let client = Client::builder(server.base_url())
35451            .timeout(Duration::from_secs(2))
35452            .build()
35453            .expect("client");
35454        let worker = Worker::new(client, "rust-workers").worker_id("never-registered");
35455
35456        let error = worker
35457            .run_until(async {})
35458            .await
35459            .expect_err("registration must fail");
35460        assert!(matches!(
35461            error,
35462            Error::Http {
35463                status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
35464                ..
35465            }
35466        ));
35467        assert!(server
35468            .captured_paths()
35469            .iter()
35470            .all(|path| !path.starts_with("/api/worker/registrations/")));
35471    }
35472
35473    #[tokio::test]
35474    async fn protocol_116_server_rejects_occurrence_identity_worker_registration() {
35475        let server = MockWorkerServer::rejected_registration_protocol();
35476        let client = Client::builder(server.base_url())
35477            .timeout(Duration::from_secs(2))
35478            .build()
35479            .expect("client");
35480        let worker = Worker::new(client, "rust-workers").worker_id("protocol-117-worker");
35481
35482        let error = worker
35483            .run_until(async {})
35484            .await
35485            .expect_err("a protocol 1.16 server must reject this worker");
35486        let Error::Protocol(failure) = error else {
35487            panic!("expected typed protocol rejection");
35488        };
35489        assert_eq!(failure.reason, "unsupported_protocol_version");
35490        assert_eq!(failure.supported_version.as_deref(), Some("1.16"));
35491        assert_eq!(failure.requested_version.as_deref(), Some("1.17"));
35492        assert_eq!(
35493            server
35494                .worker_protocol_for("/api/worker/register")
35495                .as_deref(),
35496            Some(WORKER_PROTOCOL_VERSION)
35497        );
35498    }
35499
35500    #[tokio::test]
35501    async fn declined_registration_does_not_deregister() {
35502        let server = MockWorkerServer::declined_registration();
35503        let client = Client::builder(server.base_url())
35504            .timeout(Duration::from_secs(2))
35505            .build()
35506            .expect("client");
35507        let worker = Worker::new(client, "rust-workers").worker_id("declined-worker");
35508
35509        let error = worker
35510            .run_until(async {})
35511            .await
35512            .expect_err("declined registration must fail");
35513        assert!(matches!(error, Error::WorkerLoop(_)));
35514        assert!(error.to_string().contains("was not accepted"));
35515        assert!(server
35516            .captured_paths()
35517            .iter()
35518            .all(|path| !path.starts_with("/api/worker/registrations/")));
35519    }
35520
35521    #[tokio::test]
35522    async fn deregistration_http_failure_is_returned_after_normal_shutdown() {
35523        let server = MockWorkerServer::rejected_deregistration();
35524        let client = Client::builder(server.base_url())
35525            .timeout(Duration::from_secs(2))
35526            .build()
35527            .expect("client");
35528        let worker = Worker::new(client, "rust-workers").worker_id("forbidden-cleanup");
35529
35530        let error = worker
35531            .run_until(async {})
35532            .await
35533            .expect_err("deregistration must fail");
35534        assert!(matches!(
35535            error,
35536            Error::Http {
35537                status: reqwest::StatusCode::FORBIDDEN,
35538                ..
35539            }
35540        ));
35541        assert_eq!(
35542            server.request_count("/api/worker/registrations/mock-worker"),
35543            1
35544        );
35545    }
35546
35547    #[tokio::test]
35548    async fn deregistration_protocol_failure_is_returned_after_normal_shutdown() {
35549        let server = MockWorkerServer::rejected_deregistration_protocol();
35550        let client = Client::builder(server.base_url())
35551            .timeout(Duration::from_secs(2))
35552            .build()
35553            .expect("client");
35554        let worker = Worker::new(client, "rust-workers").worker_id("protocol-cleanup");
35555
35556        let error = worker
35557            .run_until(async {})
35558            .await
35559            .expect_err("protocol rejection must fail shutdown");
35560        let Error::Protocol(failure) = error else {
35561            panic!("expected typed protocol failure");
35562        };
35563        assert_eq!(failure.reason, "unsupported_protocol_version");
35564        assert_eq!(
35565            failure.requested_version.as_deref(),
35566            Some(WORKER_PROTOCOL_VERSION)
35567        );
35568        assert_eq!(
35569            server.request_count("/api/worker/registrations/mock-worker"),
35570            1
35571        );
35572    }
35573
35574    #[tokio::test]
35575    async fn primary_poller_error_retains_deregistration_failure_context() {
35576        let server = MockWorkerServer::unauthorized_polls_and_rejected_deregistration();
35577        let client = Client::builder(server.base_url())
35578            .timeout(Duration::from_secs(2))
35579            .build()
35580            .expect("client");
35581        let mut worker = Worker::new(client, "rust-workers")
35582            .worker_id("combined-failure")
35583            .poll_timeout(Duration::from_millis(10));
35584        worker.register_workflow("combined.workflow", |_ctx, _input| async move {
35585            Ok(Value::Null)
35586        });
35587
35588        let error = worker
35589            .run()
35590            .await
35591            .expect_err("worker and cleanup must fail");
35592        let summary = error.to_string();
35593        assert!(summary.contains("authentication_failed"));
35594        assert!(summary.contains("worker cannot deregister"));
35595        let Error::WorkerShutdown {
35596            primary,
35597            deregistration,
35598        } = error
35599        else {
35600            panic!("expected combined worker shutdown error");
35601        };
35602        assert!(matches!(
35603            *primary,
35604            Error::Http {
35605                status: reqwest::StatusCode::UNAUTHORIZED,
35606                ..
35607            }
35608        ));
35609        assert!(matches!(
35610            *deregistration,
35611            Error::Http {
35612                status: reqwest::StatusCode::FORBIDDEN,
35613                ..
35614            }
35615        ));
35616        assert_eq!(
35617            server.request_count("/api/worker/registrations/mock-worker"),
35618            1
35619        );
35620    }
35621
35622    #[tokio::test]
35623    async fn activity_only_worker_can_shutdown_without_workflow_poller() {
35624        let server = MockWorkerServer::start();
35625        let client = Client::builder(server.base_url())
35626            .timeout(Duration::from_secs(2))
35627            .build()
35628            .expect("client");
35629        let mut worker = Worker::new(client, "rust-workers")
35630            .worker_id("activity-only-worker")
35631            .poll_timeout(Duration::from_millis(10));
35632
35633        worker.register_activity(
35634            "activity.only",
35635            |_ctx, _args| async move { Ok(Value::Null) },
35636        );
35637
35638        worker.run_until(async {}).await.expect("run worker");
35639    }
35640
35641    #[tokio::test]
35642    async fn workflow_only_worker_can_shutdown_without_activity_poller() {
35643        let server = MockWorkerServer::start();
35644        let client = Client::builder(server.base_url())
35645            .timeout(Duration::from_secs(2))
35646            .build()
35647            .expect("client");
35648        let mut worker = Worker::new(client, "rust-workers")
35649            .worker_id("workflow-only-worker")
35650            .poll_timeout(Duration::from_millis(10));
35651
35652        worker.register_workflow(
35653            "workflow.only",
35654            |_ctx, _input| async move { Ok(Value::Null) },
35655        );
35656
35657        worker.run_until(async {}).await.expect("run worker");
35658    }
35659
35660    #[tokio::test]
35661    async fn worker_heartbeat_observer_receives_server_acknowledgements() {
35662        let server = MockWorkerServer::start();
35663        let client = Client::builder(server.base_url())
35664            .timeout(Duration::from_secs(2))
35665            .build()
35666            .expect("client");
35667        let observations = Arc::new(Mutex::new(Vec::new()));
35668        let observed = Arc::clone(&observations);
35669        let mut worker = Worker::new(client, "rust-workers")
35670            .worker_id("observed-heartbeat-worker")
35671            .poll_timeout(Duration::from_millis(10))
35672            .on_worker_heartbeat(move |observation| {
35673                observed
35674                    .lock()
35675                    .expect("heartbeat observations")
35676                    .push(observation.clone());
35677            });
35678
35679        worker.register_workflow("workflow.observed", |_ctx, _input| async move {
35680            Ok(Value::Null)
35681        });
35682        let acknowledged = Arc::clone(&observations);
35683        worker
35684            .run_until(async move {
35685                tokio::time::timeout(Duration::from_secs(2), async move {
35686                    loop {
35687                        if !acknowledged
35688                            .lock()
35689                            .expect("heartbeat observations")
35690                            .is_empty()
35691                        {
35692                            break;
35693                        }
35694                        tokio::time::sleep(Duration::from_millis(1)).await;
35695                    }
35696                })
35697                .await
35698                .expect("heartbeat acknowledgement within timeout");
35699            })
35700            .await
35701            .expect("run worker");
35702
35703        let observations = observations.lock().expect("heartbeat observations");
35704        let first = observations.first().expect("heartbeat acknowledgement");
35705        assert_eq!(first.worker_id, "observed-heartbeat-worker");
35706        assert_eq!(first.task_queue, "rust-workers");
35707        assert!(first.acknowledged_at_unix_millis > 0);
35708        assert_eq!(first.acknowledgement, json!({}));
35709    }
35710
35711    #[tokio::test]
35712    async fn delayed_worker_heartbeat_keeps_cadence_and_pollers_live() {
35713        let server = MockWorkerServer::delayed_heartbeat_worker();
35714        let client = Client::builder(server.base_url())
35715            .timeout(Duration::from_secs(3))
35716            .build()
35717            .expect("client");
35718        let observations = Arc::new(Mutex::new(Vec::new()));
35719        let observed = Arc::clone(&observations);
35720        let mut worker = Worker::new(client, "rust-snapshot-workers")
35721            .max_concurrent_workflow_tasks(1)
35722            .max_concurrent_activity_tasks(1)
35723            .worker_id("rust-snapshot-worker")
35724            .poll_timeout(Duration::from_millis(10))
35725            .on_worker_heartbeat(move |observation| {
35726                observed
35727                    .lock()
35728                    .expect("heartbeat observations")
35729                    .push(observation.clone());
35730            });
35731
35732        worker.register_workflow("snapshot", |ctx, _input| async move {
35733            ctx.wait_signal("finish").await?;
35734            Ok(json!({"status": "finished"}))
35735        });
35736        worker.register_query("snapshot", "current", |ctx, _args| async move {
35737            Ok(json!(ctx
35738                .signals("increment")
35739                .iter()
35740                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
35741                .sum::<i64>()))
35742        });
35743        worker.register_activity("cancel-aware", |_ctx, _args| async move {
35744            Ok(json!({"late": "completion"}))
35745        });
35746
35747        worker
35748            .run_until(tokio::time::sleep(Duration::from_millis(3_800)))
35749            .await
35750            .expect("delayed heartbeat must allow a clean worker shutdown");
35751
35752        let observations = observations.lock().expect("heartbeat observations");
35753        assert!(
35754            observations.len() >= 3,
35755            "the immediate heartbeat, delayed acknowledgement, and next cadence heartbeat must complete"
35756        );
35757        assert!(
35758            observations.windows(2).all(|pair| {
35759                pair[1].acknowledged_at_unix_millis
35760                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
35761                    >= 850
35762            }),
35763            "successful acknowledgements must not catch up faster than the advertised one-second cadence: {observations:?}"
35764        );
35765        drop(observations);
35766
35767        let heartbeat_times = server.request_times("/api/worker/heartbeat");
35768        let delayed_request_at = *heartbeat_times
35769            .get(1)
35770            .expect("intentionally delayed heartbeat request");
35771        let delay_window_start = delayed_request_at + Duration::from_millis(100);
35772        let delay_window_end = delayed_request_at + Duration::from_millis(1_400);
35773        for path in [
35774            "/api/worker/workflow-tasks/poll",
35775            "/api/worker/activity-tasks/poll",
35776            "/api/worker/query-tasks/poll",
35777        ] {
35778            assert!(
35779                server
35780                    .request_times(path)
35781                    .iter()
35782                    .any(|received_at| *received_at >= delay_window_start
35783                        && *received_at <= delay_window_end),
35784                "{path} must keep polling while a heartbeat acknowledgement is delayed"
35785            );
35786        }
35787        assert!(
35788            server.request_count("/api/worker/workflow-tasks/snapshot-wait-3/fail") >= 1,
35789            "workflow work must be settled"
35790        );
35791        assert!(
35792            server.request_count("/api/worker/activity-tasks/activity-cancel/complete") >= 1,
35793            "activity work must be settled"
35794        );
35795        assert!(
35796            server.request_count("/api/worker/query-tasks/snapshot-current/complete") >= 1,
35797            "query work must be settled"
35798        );
35799    }
35800
35801    #[tokio::test]
35802    async fn retried_worker_heartbeat_restarts_the_advertised_cadence() {
35803        let server = MockWorkerServer::heartbeat_retry_worker();
35804        let client = Client::builder(server.base_url())
35805            .timeout(Duration::from_secs(2))
35806            .build()
35807            .expect("client");
35808        let observations = Arc::new(Mutex::new(Vec::new()));
35809        let observed = Arc::clone(&observations);
35810        let worker = Worker::new(client, "rust-workers")
35811            .worker_id("heartbeat-retry-worker")
35812            .retry_policy(WorkerRetryPolicy {
35813                max_retries: 1,
35814                initial_backoff: Duration::from_millis(300),
35815                max_backoff: Duration::from_millis(300),
35816            })
35817            .on_worker_heartbeat(move |observation| {
35818                observed
35819                    .lock()
35820                    .expect("heartbeat observations")
35821                    .push(observation.clone());
35822            });
35823
35824        worker
35825            .run_until(tokio::time::sleep(Duration::from_millis(2_700)))
35826            .await
35827            .expect("retryable heartbeat failure must remain bounded and recover");
35828
35829        let observations = observations.lock().expect("heartbeat observations");
35830        assert!(observations.len() >= 3, "heartbeat retry must recover");
35831        assert!(
35832            observations.windows(2).all(|pair| {
35833                pair[1]
35834                    .acknowledged_at_unix_millis
35835                    .saturating_sub(pair[0].acknowledged_at_unix_millis)
35836                    >= 850
35837            }),
35838            "a successful retry must start a fresh advertised cadence: {observations:?}"
35839        );
35840        assert_eq!(
35841            server.request_count("/api/worker/heartbeat"),
35842            observations.len() + 1,
35843            "one retryable failure must add exactly one bounded request"
35844        );
35845    }
35846
35847    #[tokio::test]
35848    async fn query_enabled_worker_ignores_unmatched_signals_then_completes_once() {
35849        let server = MockWorkerServer::waiting_query_worker();
35850        let client = Client::builder(server.base_url())
35851            .timeout(Duration::from_secs(2))
35852            .build()
35853            .expect("client");
35854        let observations = Arc::new(Mutex::new(Vec::new()));
35855        let observed = Arc::clone(&observations);
35856        let mut worker = Worker::new(client, "rust-snapshot-workers")
35857            .worker_id("rust-snapshot-worker")
35858            .poll_timeout(Duration::from_millis(10))
35859            .on_worker_heartbeat(move |observation| {
35860                observed
35861                    .lock()
35862                    .expect("heartbeat observations")
35863                    .push(observation.clone());
35864            });
35865
35866        worker.register_workflow("snapshot", |ctx, _input| async move {
35867            ctx.wait_signal("finish").await?;
35868            Ok(json!({"status": "finished"}))
35869        });
35870        worker.register_query("snapshot", "current", |ctx, _args| async move {
35871            let current = ctx
35872                .signals("increment")
35873                .iter()
35874                .filter_map(|arguments| arguments.first().and_then(Value::as_i64))
35875                .sum::<i64>();
35876            Ok(json!(current))
35877        });
35878        worker.register_update("snapshot", "replace", |_ctx, args| async move { Ok(args) });
35879        worker
35880            .declare_workflow_signals("snapshot", &["finish"])
35881            .expect("declare finish signal");
35882
35883        worker
35884            .run_until(tokio::time::sleep(Duration::from_millis(3_200)))
35885            .await
35886            .expect("pending workflow and query poller must remain live until shutdown");
35887
35888        assert!(
35889            observations.lock().expect("heartbeat observations").len() >= 4,
35890            "the immediate heartbeat and at least three advertised one-second intervals must be acknowledged"
35891        );
35892        assert!(
35893            server.request_count("/api/worker/workflow-tasks/poll") >= 3,
35894            "workflow polling must continue after empty replay acknowledgements"
35895        );
35896        assert!(
35897            server.request_count("/api/worker/query-tasks/poll") >= 2,
35898            "query polling must continue after serving the current query"
35899        );
35900        assert_eq!(
35901            server.request_body("/api/worker/register")["capabilities"],
35902            json!([
35903                CONDITION_WAIT_OCCURRENCE_IDENTITY_CAPABILITY,
35904                "workflow_entry_arguments_validation",
35905                DURABLE_SELECTION_CAPABILITY,
35906                MEMO_UPSERTS_CAPABILITY,
35907                TYPED_SEARCH_ATTRIBUTES_CAPABILITY,
35908                activity_checkpoint::CAPABILITY,
35909                QUERY_TASKS_CAPABILITY,
35910                WORKFLOW_UPDATES_CAPABILITY,
35911                MESSAGE_STREAMS_CAPABILITY
35912            ])
35913        );
35914        assert_eq!(
35915            server.request_body("/api/worker/register")["workflow_command_contracts"]["snapshot"],
35916            json!({
35917                "queries": ["current"],
35918                "query_contracts": [{
35919                    "name": "current",
35920                    "parameters": [{
35921                        "name": "args", "position": 0, "required": false,
35922                        "variadic": true, "type": null, "allows_null": true,
35923                        "default_available": false, "default": null,
35924                    }],
35925                }],
35926                "signals": ["finish"],
35927                "signal_contracts": [{
35928                    "name": "finish",
35929                    "parameters": [{
35930                        "name": "args", "position": 0, "required": false,
35931                        "variadic": true, "type": null, "allows_null": true,
35932                        "default_available": false, "default": null,
35933                    }],
35934                }],
35935                "updates": ["replace"],
35936                "update_contracts": [{
35937                    "name": "replace",
35938                    "parameters": [{
35939                        "name": "args", "position": 0, "required": false,
35940                        "variadic": true, "type": null, "allows_null": true,
35941                        "default_available": false, "default": null,
35942                    }],
35943                }],
35944                "update_validators": [],
35945            })
35946        );
35947
35948        let opened = server.request_body("/api/worker/workflow-tasks/snapshot-open/complete");
35949        assert_eq!(
35950            opened["commands"],
35951            json!([{
35952                "type": "open_signal_wait",
35953                "signal_name": "finish",
35954            }])
35955        );
35956
35957        for task_id in ["snapshot-wait-3", "snapshot-wait-5"] {
35958            let fail_path = format!("/api/worker/workflow-tasks/{task_id}/fail");
35959            let completion_path = format!("/api/worker/workflow-tasks/{task_id}/complete");
35960            let failure = server.request_body(&fail_path);
35961            assert_eq!(
35962                failure["failure"]["type"],
35963                WORKFLOW_TASK_WAITING_FOR_HISTORY_TYPE
35964            );
35965            assert_eq!(server.request_count(&completion_path), 0);
35966        }
35967
35968        let query_completion =
35969            server.request_body("/api/worker/query-tasks/snapshot-current/complete");
35970        assert_eq!(query_completion["result"], json!(8));
35971
35972        let terminal_path = "/api/worker/workflow-tasks/snapshot-finish/complete";
35973        assert_eq!(
35974            server.request_count(terminal_path),
35975            1,
35976            "the matching signal must settle the workflow exactly once"
35977        );
35978        let terminal = server.request_body(terminal_path);
35979        assert_eq!(terminal["commands"].as_array().map(Vec::len), Some(1));
35980        assert_eq!(terminal["commands"][0]["type"], "complete_workflow");
35981        assert_eq!(
35982            decode_wire_value(&terminal["commands"][0]["result"], DEFAULT_CODEC)
35983                .expect("terminal workflow result"),
35984            json!({"status": "finished"})
35985        );
35986    }
35987
35988    #[tokio::test]
35989    async fn worker_retries_poll_and_heartbeat_transport_failures_independently() {
35990        let server = MockWorkerServer::transient_worker_failures();
35991        let client = Client::builder(server.base_url())
35992            .timeout(Duration::from_secs(2))
35993            .build()
35994            .expect("client");
35995        let mut worker = Worker::new(client, "rust-workers")
35996            .max_concurrent_workflow_tasks(1)
35997            .max_concurrent_activity_tasks(1)
35998            .worker_id("retry-worker")
35999            .poll_timeout(Duration::from_millis(10))
36000            .retry_policy(WorkerRetryPolicy {
36001                max_retries: 2,
36002                initial_backoff: Duration::from_millis(1),
36003                max_backoff: Duration::from_millis(1),
36004            });
36005        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
36006        worker.register_activity(
36007            "counter.activity",
36008            |_ctx, _input| async move { Ok(Value::Null) },
36009        );
36010        worker.register_query(
36011            "counter",
36012            "current",
36013            |_ctx, _args| async move { Ok(json!(8)) },
36014        );
36015
36016        worker
36017            .run_until(tokio::time::sleep(Duration::from_millis(75)))
36018            .await
36019            .expect("transient failures must not stop the worker");
36020
36021        for path in [
36022            "/api/worker/heartbeat",
36023            "/api/worker/workflow-tasks/poll",
36024            "/api/worker/activity-tasks/poll",
36025            "/api/worker/query-tasks/poll",
36026        ] {
36027            assert!(
36028                server.request_count(path) >= 2,
36029                "{path} must continue after its transient failure"
36030            );
36031        }
36032    }
36033
36034    #[tokio::test]
36035    async fn worker_continues_after_long_poll_capacity_backpressure() {
36036        let server = MockWorkerServer::capacity_limited_activity_poll();
36037        let client = Client::builder(server.base_url())
36038            .timeout(Duration::from_secs(2))
36039            .build()
36040            .expect("client");
36041        let mut worker = Worker::new(client, "rust-workers")
36042            .worker_id("capacity-worker")
36043            .poll_timeout(Duration::from_millis(10))
36044            .retry_policy(WorkerRetryPolicy {
36045                max_retries: 0,
36046                initial_backoff: Duration::from_millis(1),
36047                max_backoff: Duration::from_millis(1),
36048            });
36049        worker.register_activity("capacity.activity", |_ctx, _input| async move {
36050            Ok(json!({"handled": true}))
36051        });
36052
36053        worker
36054            .run_until(tokio::time::sleep(Duration::from_millis(50)))
36055            .await
36056            .expect("capacity backpressure must not stop the worker");
36057
36058        assert!(
36059            server.request_count("/api/worker/activity-tasks/poll") >= 2,
36060            "the activity poller must continue after capacity backpressure"
36061        );
36062        assert_eq!(
36063            server.request_count("/api/worker/activity-tasks/capacity-activity/complete"),
36064            1,
36065            "the worker must complete work returned after capacity recovers"
36066        );
36067    }
36068
36069    #[test]
36070    fn worker_poll_capacity_backpressure_requires_the_typed_retryable_contract() {
36071        let capacity = Error::Http {
36072            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
36073            body: r#"{"poll_status":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":3}"#.to_string(),
36074        };
36075        assert_eq!(
36076            worker_poll_capacity_retry_after(&capacity),
36077            Some(Duration::from_secs(3))
36078        );
36079
36080        let rejected_capacity = Error::Http {
36081            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
36082            body: r#"{"reason":"long_poll_capacity_exhausted","retryable":false,"retry_after_seconds":3}"#.to_string(),
36083        };
36084        assert_eq!(worker_poll_capacity_retry_after(&rejected_capacity), None);
36085        assert!(!worker_operation_is_retryable(&rejected_capacity));
36086
36087        let ordinary_rate_limit = Error::Http {
36088            status: reqwest::StatusCode::TOO_MANY_REQUESTS,
36089            body: r#"{"reason":"rate_limited","retryable":true,"retry_after_seconds":3}"#
36090                .to_string(),
36091        };
36092        assert_eq!(worker_poll_capacity_retry_after(&ordinary_rate_limit), None);
36093        assert!(worker_operation_is_retryable(&ordinary_rate_limit));
36094    }
36095
36096    #[tokio::test]
36097    async fn worker_recovers_all_poll_families_and_heartbeat_beyond_retry_budget() {
36098        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36099            poll_failures_per_path: 4,
36100            heartbeat_failures: 4,
36101            ..MockWorkerBehavior::default()
36102        });
36103        let client = Client::builder(server.base_url())
36104            .timeout(Duration::from_secs(2))
36105            .build()
36106            .expect("client");
36107        let acknowledgements = Arc::new(AtomicUsize::new(0));
36108        let observed = Arc::clone(&acknowledgements);
36109        let mut worker = Worker::new(client, "rust-workers")
36110            .max_concurrent_workflow_tasks(1)
36111            .max_concurrent_activity_tasks(1)
36112            .recover_transient_outages(true)
36113            .poll_timeout(Duration::from_millis(10))
36114            .retry_policy(WorkerRetryPolicy {
36115                max_retries: 2,
36116                initial_backoff: Duration::from_millis(2),
36117                max_backoff: Duration::from_millis(5),
36118            })
36119            .on_worker_heartbeat(move |_| {
36120                observed.fetch_add(1, Ordering::SeqCst);
36121            });
36122        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
36123        worker.register_activity(
36124            "counter.activity",
36125            |_ctx, _input| async move { Ok(Value::Null) },
36126        );
36127        worker.register_query("counter", "current", |_ctx, _args| async move {
36128            Ok(Value::Null)
36129        });
36130
36131        let recovered = async {
36132            while server.request_count("/api/worker/heartbeat") < 5
36133                || [
36134                    "/api/worker/workflow-tasks/poll",
36135                    "/api/worker/activity-tasks/poll",
36136                    "/api/worker/query-tasks/poll",
36137                ]
36138                .iter()
36139                .any(|path| server.request_count(path) < 6)
36140            {
36141                tokio::time::sleep(Duration::from_millis(5)).await;
36142            }
36143        };
36144        tokio::time::timeout(Duration::from_secs(20), worker.run_until(recovered))
36145            .await
36146            .expect("every family must recover")
36147            .expect("a recoverable outage must not stop the service worker");
36148
36149        assert_eq!(acknowledgements.load(Ordering::SeqCst), 1);
36150        assert_eq!(server.request_count("/api/worker/heartbeat"), 5);
36151        for path in [
36152            "/api/worker/workflow-tasks/poll",
36153            "/api/worker/activity-tasks/poll",
36154            "/api/worker/query-tasks/poll",
36155        ] {
36156            let bodies = server.request_bodies(path);
36157            assert!(bodies.len() >= 6, "{path} must resume after recovery");
36158            let first = &bodies[0]["poll_request_id"];
36159            assert!(first.as_str().is_some_and(|id| !id.is_empty()));
36160            for body in &bodies[..5] {
36161                assert_eq!(&body["poll_request_id"], first, "{path} retry identity");
36162            }
36163            assert_ne!(&bodies[5]["poll_request_id"], first);
36164            let times = server.request_times(path);
36165            // Within the budget the policy delay applies; beyond it the
36166            // shared jittered schedule, at most 0.25 s then 0.5 s here.
36167            for pair in times[..3].windows(2) {
36168                assert!(pair[1].duration_since(pair[0]) >= Duration::from_millis(2));
36169            }
36170        }
36171    }
36172
36173    #[tokio::test]
36174    async fn worker_outage_retry_waits_are_interrupted_by_shutdown() {
36175        for heartbeat_outage in [false, true] {
36176            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36177                poll_failures_per_path: if heartbeat_outage { 0 } else { usize::MAX },
36178                heartbeat_failures: if heartbeat_outage { usize::MAX } else { 0 },
36179                ..MockWorkerBehavior::default()
36180            });
36181            let client = Client::builder(server.base_url()).build().expect("client");
36182            let mut worker = Worker::new(client, "rust-workers")
36183                .max_concurrent_workflow_tasks(1)
36184                .max_concurrent_activity_tasks(1)
36185                .recover_transient_outages(true)
36186                .retry_policy(WorkerRetryPolicy {
36187                    max_retries: 1,
36188                    initial_backoff: Duration::from_secs(5),
36189                    max_backoff: Duration::from_secs(5),
36190                });
36191            worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
36192            let started = Instant::now();
36193            worker
36194                .run_until(tokio::time::sleep(Duration::from_millis(200)))
36195                .await
36196                .expect("shutdown during an outage is a normal stop");
36197            assert!(started.elapsed() < Duration::from_secs(1));
36198            let path = if heartbeat_outage {
36199                "/api/worker/heartbeat"
36200            } else {
36201                "/api/worker/workflow-tasks/poll"
36202            };
36203            assert_eq!(server.request_count(path), 1);
36204            assert_eq!(
36205                server.request_count("/api/worker/registrations/mock-worker"),
36206                1
36207            );
36208        }
36209    }
36210
36211    #[tokio::test]
36212    async fn worker_outage_recovery_keeps_run_once_bounded() {
36213        let server = MockWorkerServer::unavailable_polls();
36214        let client = Client::builder(server.base_url()).build().expect("client");
36215        let mut worker = Worker::new(client, "rust-workers")
36216            .recover_transient_outages(true)
36217            .retry_policy(WorkerRetryPolicy {
36218                max_retries: 2,
36219                initial_backoff: Duration::from_millis(1),
36220                max_backoff: Duration::from_millis(1),
36221            });
36222        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
36223        assert!(matches!(worker.run_once().await, Err(Error::Transport(_))));
36224        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 3);
36225    }
36226
36227    #[tokio::test]
36228    async fn worker_outage_recovery_respects_disabled_retries() {
36229        let server = MockWorkerServer::unavailable_polls();
36230        let client = Client::builder(server.base_url()).build().expect("client");
36231        let mut worker = Worker::new(client, "rust-workers")
36232            .max_concurrent_workflow_tasks(1)
36233            .max_concurrent_activity_tasks(1)
36234            .recover_transient_outages(true)
36235            .retry_policy(WorkerRetryPolicy {
36236                max_retries: 0,
36237                ..WorkerRetryPolicy::default()
36238            });
36239        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
36240        assert!(matches!(worker.run().await, Err(Error::Transport(_))));
36241        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
36242    }
36243
36244    #[tokio::test]
36245    async fn worker_fatal_poll_error_interrupts_outage_heartbeat_retries() {
36246        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
36247            heartbeat_failures: usize::MAX,
36248            unauthorized_polls: true,
36249            ..MockWorkerBehavior::default()
36250        });
36251        let client = Client::builder(server.base_url()).build().expect("client");
36252        let mut worker = Worker::new(client, "rust-workers")
36253            .max_concurrent_workflow_tasks(1)
36254            .max_concurrent_activity_tasks(1)
36255            .recover_transient_outages(true)
36256            .retry_policy(WorkerRetryPolicy {
36257                max_retries: 1,
36258                initial_backoff: Duration::from_secs(5),
36259                max_backoff: Duration::from_secs(5),
36260            });
36261        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
36262        let error = tokio::time::timeout(Duration::from_secs(1), worker.run())
36263            .await
36264            .expect("fatal poll errors must interrupt heartbeat recovery")
36265            .expect_err("authentication failure is terminal");
36266        assert!(
36267            matches!(error, Error::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED)
36268        );
36269        assert_eq!(server.request_count("/api/worker/workflow-tasks/poll"), 1);
36270    }
36271
36272    #[tokio::test]
36273    async fn worker_bounds_transport_retries() {
36274        let server = MockWorkerServer::unavailable_polls();
36275        let client = Client::builder(server.base_url())
36276            .timeout(Duration::from_secs(2))
36277            .build()
36278            .expect("client");
36279        let mut worker = Worker::new(client, "rust-workers")
36280            .max_concurrent_workflow_tasks(1)
36281            .max_concurrent_activity_tasks(1)
36282            .worker_id("bounded-retry-worker")
36283            // Opting out restores the bounded contract.
36284            .recover_transient_outages(false)
36285            .poll_timeout(Duration::from_millis(10))
36286            .retry_policy(WorkerRetryPolicy {
36287                max_retries: 2,
36288                initial_backoff: Duration::from_millis(1),
36289                max_backoff: Duration::from_millis(1),
36290            });
36291        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
36292
36293        let error = worker.run().await.expect_err("retry bound must terminate");
36294        assert!(matches!(error, Error::Transport(_)));
36295        assert_eq!(
36296            server.request_count("/api/worker/workflow-tasks/poll"),
36297            3,
36298            "one initial request plus exactly two retries"
36299        );
36300    }
36301
36302    #[tokio::test]
36303    async fn worker_retry_policy_can_disable_poll_retries() {
36304        let server = MockWorkerServer::unavailable_polls();
36305        let client = Client::builder(server.base_url())
36306            .timeout(Duration::from_secs(2))
36307            .build()
36308            .expect("client");
36309        let mut worker = Worker::new(client, "rust-workers")
36310            .worker_id("no-retry-worker")
36311            .poll_timeout(Duration::from_millis(10))
36312            .retry_policy(WorkerRetryPolicy {
36313                max_retries: 0,
36314                initial_backoff: Duration::from_millis(1),
36315                max_backoff: Duration::from_millis(1),
36316            });
36317        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
36318
36319        let error = worker
36320            .run_once()
36321            .await
36322            .expect_err("disabled retries must return the first transport failure");
36323        assert!(matches!(error, Error::Transport(_)));
36324        assert_eq!(
36325            server.request_count("/api/worker/workflow-tasks/poll"),
36326            1,
36327            "max_retries=0 must send only the initial request"
36328        );
36329    }
36330
36331    #[tokio::test]
36332    async fn worker_does_not_retry_authentication_failures() {
36333        let server = MockWorkerServer::unauthorized_polls();
36334        let client = Client::builder(server.base_url())
36335            .timeout(Duration::from_secs(2))
36336            .build()
36337            .expect("client");
36338        let mut worker = Worker::new(client, "rust-workers")
36339            .max_concurrent_workflow_tasks(1)
36340            .max_concurrent_activity_tasks(1)
36341            .worker_id("unauthorized-worker")
36342            .recover_transient_outages(true)
36343            .poll_timeout(Duration::from_millis(10));
36344        worker.register_workflow("counter", |_ctx, _input| async move { Ok(Value::Null) });
36345
36346        let error = worker
36347            .run()
36348            .await
36349            .expect_err("authentication must terminate");
36350        let Error::Http { status, body } = error else {
36351            panic!("expected stable HTTP authentication error");
36352        };
36353        assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
36354        assert!(body.contains("authentication_failed"));
36355        assert_eq!(
36356            server.request_count("/api/worker/workflow-tasks/poll"),
36357            1,
36358            "authentication failures must not be retried"
36359        );
36360    }
36361
36362    #[test]
36363    fn duplicate_registration_keeps_the_original_workflow() {
36364        let client = Client::new("http://127.0.0.1:9").expect("client");
36365        let mut worker = Worker::new(client, "registration-tests");
36366        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
36367        let original = Arc::clone(&worker.workflows["same"].execute);
36368        worker
36369            .set_workflow_definition_sources("same", &["first workflow source"])
36370            .expect("source identity");
36371        let fingerprint = worker.workflows["same"].definition_fingerprint.clone();
36372        worker.register_typed_workflow("same", |_ctx, _input: Value| async { Ok(json!("second")) });
36373        assert!(Arc::ptr_eq(&original, &worker.workflows["same"].execute));
36374        assert_eq!(worker.workflows["same"].definition_fingerprint, fingerprint);
36375    }
36376
36377    #[test]
36378    fn duplicate_registration_keeps_the_original_activity() {
36379        let client = Client::new("http://127.0.0.1:9").expect("client");
36380        let mut worker = Worker::new(client, "registration-tests");
36381        worker.register_activity("same", |_ctx, _input| async { Ok(json!("first")) });
36382        let original = Arc::clone(&worker.activities["same"]);
36383        worker.register_activity_avro_value("same", |_ctx, _input| async {
36384            Ok(AvroValue::String("second".into()))
36385        });
36386        assert!(Arc::ptr_eq(&original, &worker.activities["same"]));
36387    }
36388
36389    #[test]
36390    fn duplicate_registration_keeps_original_query_and_update_handlers() {
36391        let client = Client::new("http://127.0.0.1:9").expect("client");
36392        let mut worker = Worker::new(client, "registration-tests");
36393        worker.register_query("orders", "same", |_ctx, _input| async {
36394            Ok(json!("first"))
36395        });
36396        let RegisteredQuery::Snapshot(original) = worker.queries["orders"]["same"].clone() else {
36397            panic!("snapshot query");
36398        };
36399        worker.register_replayed_query("orders", "same", |_ctx, _state: Arc<()>, _input| async {
36400            Ok(json!("second"))
36401        });
36402        let RegisteredQuery::Snapshot(retained) = &worker.queries["orders"]["same"] else {
36403            panic!("duplicate replaced the query adapter");
36404        };
36405        assert!(Arc::ptr_eq(&original, retained));
36406        worker.register_update("orders", "same", |_ctx, _input| async {
36407            Ok(json!("first"))
36408        });
36409        let original = Arc::clone(&worker.updates["orders"]["same"]);
36410        worker.register_update_avro_value("orders", "same", |_ctx, _input| async {
36411            Ok(AvroValue::Null)
36412        });
36413        assert!(Arc::ptr_eq(&original, &worker.updates["orders"]["same"]));
36414    }
36415
36416    #[tokio::test]
36417    async fn duplicate_registration_fails_before_server_contact() {
36418        let server = MockWorkerServer::start();
36419        let client = Client::builder(server.base_url()).build().expect("client");
36420        let mut worker =
36421            Worker::new(client, "registration-tests").poll_timeout(Duration::from_millis(10));
36422        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("first")) });
36423        worker.register_workflow("same", |_ctx, _input| async { Ok(json!("second")) });
36424        let error = worker
36425            .run_once()
36426            .await
36427            .expect_err("ambiguous worker must not poll");
36428        assert!(
36429            error.to_string().contains("duplicate_registration"),
36430            "{error}"
36431        );
36432        assert!(server.requests.lock().expect("requests").is_empty());
36433    }
36434
36435    #[derive(Clone, Debug)]
36436    struct CapturedRequest {
36437        headers: String,
36438        method: String,
36439        path: String,
36440        authorization: Option<String>,
36441        namespace: Option<String>,
36442        worker_protocol: Option<String>,
36443        control_protocol: Option<String>,
36444        body: String,
36445        received_at: Instant,
36446    }
36447
36448    struct MockWorkerServer {
36449        addr: SocketAddr,
36450        stop: Arc<AtomicBool>,
36451        requests: Arc<Mutex<Vec<CapturedRequest>>>,
36452        thread: Option<thread::JoinHandle<()>>,
36453    }
36454
36455    type RequestOverride = fn(&str, &str, usize) -> Option<(&'static str, String)>;
36456    type ResponseOverride = fn(&str) -> Option<(&'static str, String)>;
36457
36458    #[derive(Clone, Copy, Default)]
36459    struct MockWorkerBehavior {
36460        response_override: Option<ResponseOverride>,
36461        request_override: Option<RequestOverride>,
36462        /// Close the connection after reading the request, without any response.
36463        drop_request: Option<fn(&str, usize) -> bool>,
36464        storage_refusals: usize,
36465        storage_path: Option<&'static str>,
36466        storage_unavailable: bool,
36467        storage_mid_poll: bool,
36468        storage_activity: bool,
36469        storage_query: bool,
36470        storage_wrong_poll_id: bool,
36471        reject_query_protocol: bool,
36472        reject_query_completion: bool,
36473        waiting_query_worker: bool,
36474        decline_registration: bool,
36475        complete_named_signal: bool,
36476        poll_failures_per_path: usize,
36477        long_poll_capacity_responses_per_path: usize,
36478        heartbeat_failures: usize,
36479        heartbeat_failure_request: Option<usize>,
36480        delayed_heartbeat_request: Option<usize>,
36481        heartbeat_response_delay: Duration,
36482        concurrent_requests: bool,
36483        unauthorized_polls: bool,
36484        reject_registration: bool,
36485        reject_registration_protocol: bool,
36486        reject_deregistration: bool,
36487        reject_deregistration_protocol: bool,
36488        cancelled_activity: bool,
36489        draining_polls: bool,
36490        invalid_task_payload_codec: Option<InvalidTaskPayloadCodec>,
36491        workflow_completion_status: Option<&'static str>,
36492        workflow_completion_body: Option<&'static str>,
36493    }
36494
36495    impl MockWorkerServer {
36496        fn start() -> Self {
36497            Self::start_with_behavior(MockWorkerBehavior::default())
36498        }
36499
36500        fn reject_query_protocol() -> Self {
36501            Self::start_with_behavior(MockWorkerBehavior {
36502                reject_query_protocol: true,
36503                ..MockWorkerBehavior::default()
36504            })
36505        }
36506
36507        fn reject_query_completion() -> Self {
36508            Self::start_with_behavior(MockWorkerBehavior {
36509                reject_query_completion: true,
36510                ..MockWorkerBehavior::default()
36511            })
36512        }
36513
36514        fn waiting_query_worker() -> Self {
36515            Self::start_with_behavior(MockWorkerBehavior {
36516                waiting_query_worker: true,
36517                complete_named_signal: true,
36518                ..MockWorkerBehavior::default()
36519            })
36520        }
36521
36522        fn transient_worker_failures() -> Self {
36523            Self::start_with_behavior(MockWorkerBehavior {
36524                poll_failures_per_path: 1,
36525                heartbeat_failures: 1,
36526                ..MockWorkerBehavior::default()
36527            })
36528        }
36529
36530        fn consecutive_poll_failures(count: usize) -> Self {
36531            Self::start_with_behavior(MockWorkerBehavior {
36532                poll_failures_per_path: count,
36533                ..MockWorkerBehavior::default()
36534            })
36535        }
36536
36537        fn capacity_limited_activity_poll() -> Self {
36538            Self::start_with_behavior(MockWorkerBehavior {
36539                long_poll_capacity_responses_per_path: 1,
36540                ..MockWorkerBehavior::default()
36541            })
36542        }
36543
36544        fn delayed_heartbeat_worker() -> Self {
36545            Self::start_with_behavior(MockWorkerBehavior {
36546                waiting_query_worker: true,
36547                delayed_heartbeat_request: Some(2),
36548                heartbeat_response_delay: Duration::from_millis(1_500),
36549                concurrent_requests: true,
36550                cancelled_activity: true,
36551                ..MockWorkerBehavior::default()
36552            })
36553        }
36554
36555        fn heartbeat_retry_worker() -> Self {
36556            Self::start_with_behavior(MockWorkerBehavior {
36557                waiting_query_worker: true,
36558                heartbeat_failure_request: Some(2),
36559                concurrent_requests: true,
36560                ..MockWorkerBehavior::default()
36561            })
36562        }
36563
36564        fn unavailable_polls() -> Self {
36565            Self::start_with_behavior(MockWorkerBehavior {
36566                poll_failures_per_path: usize::MAX,
36567                ..MockWorkerBehavior::default()
36568            })
36569        }
36570
36571        fn unauthorized_polls() -> Self {
36572            Self::start_with_behavior(MockWorkerBehavior {
36573                unauthorized_polls: true,
36574                ..MockWorkerBehavior::default()
36575            })
36576        }
36577
36578        fn rejected_registration() -> Self {
36579            Self::start_with_behavior(MockWorkerBehavior {
36580                reject_registration: true,
36581                ..MockWorkerBehavior::default()
36582            })
36583        }
36584
36585        fn rejected_registration_protocol() -> Self {
36586            Self::start_with_behavior(MockWorkerBehavior {
36587                reject_registration_protocol: true,
36588                ..MockWorkerBehavior::default()
36589            })
36590        }
36591
36592        fn declined_registration() -> Self {
36593            Self::start_with_behavior(MockWorkerBehavior {
36594                decline_registration: true,
36595                ..MockWorkerBehavior::default()
36596            })
36597        }
36598
36599        fn rejected_deregistration() -> Self {
36600            Self::start_with_behavior(MockWorkerBehavior {
36601                reject_deregistration: true,
36602                ..MockWorkerBehavior::default()
36603            })
36604        }
36605
36606        fn rejected_deregistration_protocol() -> Self {
36607            Self::start_with_behavior(MockWorkerBehavior {
36608                reject_deregistration_protocol: true,
36609                ..MockWorkerBehavior::default()
36610            })
36611        }
36612
36613        fn unauthorized_polls_and_rejected_deregistration() -> Self {
36614            Self::start_with_behavior(MockWorkerBehavior {
36615                unauthorized_polls: true,
36616                reject_deregistration: true,
36617                ..MockWorkerBehavior::default()
36618            })
36619        }
36620
36621        fn cancelled_activity() -> Self {
36622            Self::start_with_behavior(MockWorkerBehavior {
36623                cancelled_activity: true,
36624                ..MockWorkerBehavior::default()
36625            })
36626        }
36627
36628        fn draining_polls() -> Self {
36629            Self::start_with_behavior(MockWorkerBehavior {
36630                draining_polls: true,
36631                ..MockWorkerBehavior::default()
36632            })
36633        }
36634
36635        fn invalid_task_payload_codec(codec: InvalidTaskPayloadCodec) -> Self {
36636            Self::start_with_behavior(MockWorkerBehavior {
36637                invalid_task_payload_codec: Some(codec),
36638                ..MockWorkerBehavior::default()
36639            })
36640        }
36641
36642        fn workflow_completion(status: &'static str, body: &'static str) -> Self {
36643            Self::start_with_behavior(MockWorkerBehavior {
36644                workflow_completion_status: Some(status),
36645                workflow_completion_body: Some(body),
36646                ..MockWorkerBehavior::default()
36647            })
36648        }
36649
36650        fn start_with_behavior(behavior: MockWorkerBehavior) -> Self {
36651            let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
36652            listener
36653                .set_nonblocking(true)
36654                .expect("configure mock listener");
36655            let addr = listener.local_addr().expect("mock server address");
36656            let stop = Arc::new(AtomicBool::new(false));
36657            let server_stop = Arc::clone(&stop);
36658            let requests = Arc::new(Mutex::new(Vec::new()));
36659            let server_requests = Arc::clone(&requests);
36660            let thread = thread::spawn(move || {
36661                let mut request_threads = Vec::new();
36662                while !server_stop.load(Ordering::SeqCst) {
36663                    match listener.accept() {
36664                        Ok((mut stream, _)) => {
36665                            // macOS/BSD accepted sockets inherit the listener's O_NONBLOCK.
36666                            let _ = stream.set_nonblocking(false);
36667                            let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
36668                            if behavior.concurrent_requests {
36669                                let requests = Arc::clone(&server_requests);
36670                                request_threads.push(thread::spawn(move || {
36671                                    handle_mock_worker_request(&mut stream, &requests, behavior)
36672                                }));
36673                            } else {
36674                                handle_mock_worker_request(&mut stream, &server_requests, behavior);
36675                            }
36676                        }
36677                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
36678                            let mut index = 0;
36679                            while index < request_threads.len() {
36680                                if request_threads[index].is_finished() {
36681                                    request_threads
36682                                        .swap_remove(index)
36683                                        .join()
36684                                        .expect("join mock request");
36685                                } else {
36686                                    index += 1;
36687                                }
36688                            }
36689                            thread::sleep(Duration::from_millis(5));
36690                        }
36691                        Err(_) => break,
36692                    }
36693                }
36694                for request_thread in request_threads {
36695                    request_thread.join().expect("join mock request");
36696                }
36697            });
36698
36699            Self {
36700                addr,
36701                stop,
36702                requests,
36703                thread: Some(thread),
36704            }
36705        }
36706
36707        fn base_url(&self) -> String {
36708            format!("http://{}", self.addr)
36709        }
36710
36711        fn worker_protocol_for(&self, path: &str) -> Option<String> {
36712            self.requests
36713                .lock()
36714                .expect("captured requests")
36715                .iter()
36716                .find(|request| request.path == path)
36717                .and_then(|request| request.worker_protocol.clone())
36718        }
36719
36720        fn control_protocol_for(&self, path: &str) -> Option<String> {
36721            self.requests
36722                .lock()
36723                .expect("captured requests")
36724                .iter()
36725                .find(|request| request.path == path)
36726                .and_then(|request| request.control_protocol.clone())
36727        }
36728
36729        fn method_for(&self, path: &str) -> Option<String> {
36730            self.requests
36731                .lock()
36732                .expect("captured requests")
36733                .iter()
36734                .find(|request| request.path == path)
36735                .map(|request| request.method.clone())
36736        }
36737
36738        fn authorization_for(&self, path: &str) -> Option<String> {
36739            self.requests
36740                .lock()
36741                .expect("captured requests")
36742                .iter()
36743                .find(|request| request.path == path)
36744                .and_then(|request| request.authorization.clone())
36745        }
36746
36747        fn namespace_for(&self, path: &str) -> Option<String> {
36748            self.requests
36749                .lock()
36750                .expect("captured requests")
36751                .iter()
36752                .find(|request| request.path == path)
36753                .and_then(|request| request.namespace.clone())
36754        }
36755
36756        fn request_count(&self, path: &str) -> usize {
36757            self.requests
36758                .lock()
36759                .expect("captured requests")
36760                .iter()
36761                .filter(|request| request.path == path)
36762                .count()
36763        }
36764
36765        fn captured_paths(&self) -> Vec<String> {
36766            self.requests
36767                .lock()
36768                .expect("captured requests")
36769                .iter()
36770                .map(|request| request.path.clone())
36771                .collect()
36772        }
36773
36774        fn request_times(&self, path: &str) -> Vec<Instant> {
36775            self.requests
36776                .lock()
36777                .expect("captured requests")
36778                .iter()
36779                .filter(|request| request.path == path)
36780                .map(|request| request.received_at)
36781                .collect()
36782        }
36783
36784        fn request_body(&self, path: &str) -> Value {
36785            let requests = self.requests.lock().expect("captured requests");
36786            let body = &requests
36787                .iter()
36788                .find(|request| request.path == path)
36789                .unwrap_or_else(|| panic!("missing request for {path}"))
36790                .body;
36791            serde_json::from_str(body).unwrap_or_else(|error| {
36792                panic!("invalid JSON request body for {path}: {error}: {body:?}")
36793            })
36794        }
36795
36796        fn request_bodies(&self, path: &str) -> Vec<Value> {
36797            self.requests
36798                .lock()
36799                .expect("captured requests")
36800                .iter()
36801                .filter(|request| request.path == path)
36802                .map(|request| {
36803                    serde_json::from_str(&request.body).unwrap_or_else(|error| {
36804                        panic!(
36805                            "invalid JSON request body for {path}: {error}: {:?}",
36806                            request.body
36807                        )
36808                    })
36809                })
36810                .collect()
36811        }
36812
36813        fn request_headers(&self, path: &str) -> Vec<String> {
36814            self.requests
36815                .lock()
36816                .expect("captured requests")
36817                .iter()
36818                .filter(|request| request.path == path)
36819                .map(|request| request.headers.clone())
36820                .collect()
36821        }
36822    }
36823
36824    impl Drop for MockWorkerServer {
36825        fn drop(&mut self) {
36826            self.stop.store(true, Ordering::SeqCst);
36827            let _ = TcpStream::connect(self.addr);
36828
36829            if let Some(thread) = self.thread.take() {
36830                thread.join().expect("join mock server");
36831            }
36832        }
36833    }
36834
36835    #[test]
36836    fn closed_mock_connection_is_not_a_worker_request() {
36837        let listener = TcpListener::bind("127.0.0.1:0").expect("bind closed connection control");
36838        let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
36839        let (mut stream, _) = listener.accept().unwrap();
36840        drop(client);
36841        let requests = Arc::new(Mutex::new(Vec::new()));
36842        handle_mock_worker_request(
36843            &mut stream,
36844            &requests,
36845            MockWorkerBehavior {
36846                request_override: Some(|_, _, _| {
36847                    panic!("closed connection cannot invoke an HTTP handler")
36848                }),
36849                ..MockWorkerBehavior::default()
36850            },
36851        );
36852        assert!(requests.lock().unwrap().is_empty());
36853    }
36854
36855    fn handle_mock_worker_request(
36856        stream: &mut TcpStream,
36857        requests: &Arc<Mutex<Vec<CapturedRequest>>>,
36858        behavior: MockWorkerBehavior,
36859    ) {
36860        let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
36861        let mut buffer = [0_u8; 8192];
36862        let mut request = Vec::new();
36863
36864        loop {
36865            match stream.read(&mut buffer) {
36866                Ok(0) => break,
36867                Ok(read) => {
36868                    request.extend_from_slice(&buffer[..read]);
36869                    if mock_request_is_complete(&request) {
36870                        break;
36871                    }
36872                }
36873                Err(error)
36874                    if matches!(
36875                        error.kind(),
36876                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
36877                    ) =>
36878                {
36879                    break;
36880                }
36881                Err(_) => return,
36882            }
36883        }
36884
36885        if !mock_request_is_complete(&request) {
36886            return;
36887        }
36888
36889        let request = String::from_utf8_lossy(&request);
36890        let body = request
36891            .split_once("\r\n\r\n")
36892            .map(|(_, body)| body)
36893            .unwrap_or_default();
36894        let path = request
36895            .lines()
36896            .next()
36897            .and_then(|line| line.split_whitespace().nth(1))
36898            .unwrap_or_default();
36899        let method = request
36900            .lines()
36901            .next()
36902            .and_then(|line| line.split_whitespace().next())
36903            .unwrap_or_default();
36904        let authorization = request.lines().find_map(|line| {
36905            let (name, value) = line.split_once(':')?;
36906            name.eq_ignore_ascii_case("Authorization")
36907                .then(|| value.trim().to_string())
36908        });
36909        let namespace = request.lines().find_map(|line| {
36910            let (name, value) = line.split_once(':')?;
36911            name.eq_ignore_ascii_case("X-Namespace")
36912                .then(|| value.trim().to_string())
36913        });
36914        let worker_protocol = request.lines().find_map(|line| {
36915            let (name, value) = line.split_once(':')?;
36916            name.eq_ignore_ascii_case("X-Durable-Workflow-Protocol-Version")
36917                .then(|| value.trim().to_string())
36918        });
36919        let control_protocol = request.lines().find_map(|line| {
36920            let (name, value) = line.split_once(':')?;
36921            name.eq_ignore_ascii_case("X-Durable-Workflow-Control-Plane-Version")
36922                .then(|| value.trim().to_string())
36923        });
36924        let request_number = {
36925            let mut requests = requests.lock().expect("captured requests");
36926            requests.push(CapturedRequest {
36927                headers: request
36928                    .split_once("\r\n\r\n")
36929                    .map_or("", |(headers, _)| headers)
36930                    .to_owned(),
36931                method: method.to_string(),
36932                path: path.to_string(),
36933                authorization,
36934                namespace,
36935                worker_protocol: worker_protocol.clone(),
36936                control_protocol,
36937                body: body.to_string(),
36938                received_at: Instant::now(),
36939            });
36940            requests
36941                .iter()
36942                .filter(|request| request.path == path)
36943                .count()
36944        };
36945
36946        if behavior
36947            .drop_request
36948            .is_some_and(|dropped| dropped(path, request_number))
36949        {
36950            return;
36951        }
36952        if let Some(response) = behavior
36953            .request_override
36954            .and_then(|handler| handler(path, body, request_number))
36955        {
36956            write_mock_response(stream, response.0, &response.1);
36957            return;
36958        }
36959        if let Some(response) = behavior.response_override.and_then(|handler| handler(path)) {
36960            write_mock_response(stream, response.0, &response.1);
36961            return;
36962        }
36963        if path.ends_with("/poll") && request_number <= behavior.poll_failures_per_path {
36964            return;
36965        }
36966        let pressure_path = behavior
36967            .storage_path
36968            .is_some_and(|part| path.contains(part));
36969        let prior_failures = if path.ends_with("/poll") {
36970            behavior.poll_failures_per_path
36971        } else {
36972            0
36973        };
36974        if pressure_path
36975            && request_number.saturating_sub(prior_failures) <= behavior.storage_refusals
36976        {
36977            let request_body: Value = serde_json::from_str(body).unwrap_or(Value::Null);
36978            let poll_id = path
36979                .ends_with("/poll")
36980                .then(|| request_body["poll_request_id"].as_str().unwrap_or(""));
36981            let mut refusal = storage_refusal(
36982                poll_id,
36983                behavior.storage_unavailable,
36984                behavior.storage_mid_poll,
36985            );
36986            if behavior.storage_wrong_poll_id {
36987                refusal["poll_request_id"] = json!("wrong-poll");
36988            }
36989            write_mock_response(stream, "503 Service Unavailable", &refusal.to_string());
36990            return;
36991        }
36992        if path.contains("/storage-task/")
36993            || path.contains("/storage-activity/")
36994            || path.contains("/storage-query/")
36995        {
36996            write_mock_response(stream, "200 OK", "{}");
36997            return;
36998        }
36999        if behavior.storage_query && path == "/api/worker/query-tasks/poll" && request_number == 1 {
37000            write_mock_response(stream, "200 OK", &json!({"task":{
37001                "query_task_id":"storage-query", "query_task_attempt":7, "workflow_type":"storage.workflow",
37002                "query_name":"state", "workflow_id":"workflow", "run_id":"run", "payload_codec":"avro",
37003                "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
37004                "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
37005                "history_events":[], "run_status":"waiting", "lease_owner":"storage-worker"
37006            }}).to_string());
37007            return;
37008        }
37009        if behavior.storage_activity
37010            && path == "/api/worker/activity-tasks/poll"
37011            && request_number == 1
37012        {
37013            write_mock_response(stream, "200 OK", &json!({"task":{
37014                "task_id":"storage-activity", "activity_attempt_id":"storage-attempt", "activity_type":"storage.activity",
37015                "payload_codec":"avro", "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC).unwrap(),
37016                "attempt_number":7, "lease_owner":"storage-worker"
37017            }}).to_string());
37018            return;
37019        }
37020
37021        if path == "/api/worker/register" {
37022            if behavior.reject_registration_protocol {
37023                write_mock_response(
37024                    stream,
37025                    "400 Bad Request",
37026                    r#"{"reason":"unsupported_protocol_version","message":"condition-wait occurrence identity requires worker protocol 1.17","supported_version":"1.16","requested_version":"1.17"}"#,
37027                );
37028                return;
37029            }
37030            if behavior.reject_registration {
37031                write_mock_response(
37032                    stream,
37033                    "503 Service Unavailable",
37034                    r#"{"reason":"registration_unavailable","message":"registration failed"}"#,
37035                );
37036                return;
37037            }
37038        }
37039
37040        if path.starts_with("/api/worker/registrations/") {
37041            if behavior.reject_deregistration_protocol {
37042                write_mock_response(
37043                    stream,
37044                    "400 Bad Request",
37045                    r#"{"reason":"unsupported_protocol_version","message":"unsupported worker protocol","supported_version":"1.17","requested_version":"1.20"}"#,
37046                );
37047            } else if behavior.reject_deregistration {
37048                write_mock_response(
37049                    stream,
37050                    "403 Forbidden",
37051                    r#"{"reason":"authorization_failed","message":"worker cannot deregister"}"#,
37052                );
37053            } else {
37054                write_mock_response(
37055                    stream,
37056                    "200 OK",
37057                    r#"{"worker_id":"deregistered-worker","outcome":"deregistered","recovered_workflow_task_count":2}"#,
37058                );
37059            }
37060            return;
37061        }
37062
37063        let is_poll = matches!(
37064            path,
37065            "/api/worker/workflow-tasks/poll"
37066                | "/api/worker/activity-tasks/poll"
37067                | "/api/worker/query-tasks/poll"
37068        );
37069        if is_poll && request_number <= behavior.long_poll_capacity_responses_per_path {
37070            write_mock_response(
37071                stream,
37072                "429 Too Many Requests",
37073                r#"{"task":null,"poll_status":"long_poll_capacity_exhausted","reason":"long_poll_capacity_exhausted","retryable":true,"retry_after_seconds":1}"#,
37074            );
37075            return;
37076        }
37077        if is_poll && request_number <= behavior.poll_failures_per_path {
37078            return;
37079        }
37080        if path == "/api/worker/heartbeat" && request_number <= behavior.heartbeat_failures {
37081            return;
37082        }
37083        if path == "/api/worker/heartbeat"
37084            && behavior.heartbeat_failure_request == Some(request_number)
37085        {
37086            return;
37087        }
37088        if path == "/api/worker/heartbeat"
37089            && behavior.delayed_heartbeat_request == Some(request_number)
37090        {
37091            thread::sleep(behavior.heartbeat_response_delay);
37092        }
37093        if behavior.unauthorized_polls && is_poll {
37094            write_mock_response(
37095                stream,
37096                "401 Unauthorized",
37097                r#"{"reason":"authentication_failed","message":"invalid worker token"}"#,
37098            );
37099            return;
37100        }
37101        if behavior.draining_polls && is_poll {
37102            write_mock_response(
37103                stream,
37104                "409 Conflict",
37105                r#"{"task":null,"poll_status":"draining","reason":"worker_draining","worker_status":"draining","drain_intent":"draining"}"#,
37106            );
37107            return;
37108        }
37109
37110        if let Some(codec_case) = behavior.invalid_task_payload_codec {
37111            if is_poll && request_number == 1 {
37112                let mut task = match path {
37113                    "/api/worker/workflow-tasks/poll" => json!({
37114                        "task_id": "codec-workflow",
37115                        "workflow_type": "codec.workflow",
37116                        "payload_codec": DEFAULT_CODEC,
37117                        "workflow_task_attempt": 1,
37118                        "lease_owner": "codec-worker"
37119                    }),
37120                    "/api/worker/activity-tasks/poll" => json!({
37121                        "task_id": "codec-activity",
37122                        "activity_attempt_id": "codec-activity-attempt",
37123                        "activity_type": "codec.activity",
37124                        "payload_codec": DEFAULT_CODEC,
37125                        "attempt_number": 1,
37126                        "lease_owner": "codec-worker"
37127                    }),
37128                    "/api/worker/query-tasks/poll" => json!({
37129                        "query_task_id": "codec-query",
37130                        "query_task_attempt": 1,
37131                        "workflow_type": "codec.workflow",
37132                        "query_name": "known",
37133                        "payload_codec": DEFAULT_CODEC,
37134                        "lease_owner": "codec-worker"
37135                    }),
37136                    _ => unreachable!("is_poll limits task codec probe paths"),
37137                };
37138                codec_case.apply(&mut task);
37139                write_mock_response(stream, "200 OK", &json!({"task": task}).to_string());
37140                return;
37141            }
37142
37143            if matches!(
37144                path,
37145                "/api/worker/workflow-tasks/codec-workflow/fail"
37146                    | "/api/worker/activity-tasks/codec-activity/fail"
37147                    | "/api/worker/query-tasks/codec-query/fail"
37148            ) {
37149                write_mock_response(stream, "200 OK", r#"{"outcome":"failed"}"#);
37150                return;
37151            }
37152        }
37153
37154        if behavior.reject_query_protocol && path.starts_with("/api/worker/query-tasks/") {
37155            let requested_version = worker_protocol.as_deref().unwrap_or("missing");
37156            let body = format!(
37157                r#"{{"reason":"unsupported_protocol_version","message":"Query tasks require worker protocol 1.8 or newer.","supported_version":"1.7","requested_version":"{requested_version}"}}"#
37158            );
37159            write_mock_response(stream, "400 Bad Request", &body);
37160            return;
37161        }
37162
37163        if behavior.reject_query_completion && path == "/api/worker/query-tasks/query-late/complete"
37164        {
37165            write_mock_response(
37166                stream,
37167                "409 Conflict",
37168                r#"{"reason":"query_task_timed_out","message":"query task timed out before completion"}"#,
37169            );
37170            return;
37171        }
37172
37173        if behavior.workflow_completion_status.is_some()
37174            && path == "/api/worker/workflow-tasks/poll"
37175            && request_number == 1
37176        {
37177            write_mock_response(
37178                stream,
37179                "200 OK",
37180                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"}}"#,
37181            );
37182            return;
37183        }
37184
37185        if matches!(
37186            path,
37187            "/api/worker/workflow-tasks/workflow-timeout-task/complete"
37188                | "/api/worker/workflow-tasks/workflow-timeout-task/fail"
37189        ) {
37190            if let (Some(status), Some(body)) = (
37191                behavior.workflow_completion_status,
37192                behavior.workflow_completion_body,
37193            ) {
37194                write_mock_response(stream, status, body);
37195                return;
37196            }
37197        }
37198
37199        if behavior.waiting_query_worker {
37200            if behavior.complete_named_signal
37201                && path == "/api/worker/workflow-tasks/poll"
37202                && request_number == 1
37203            {
37204                let body = json!({
37205                    "task": {
37206                        "task_id": "snapshot-open",
37207                        "workflow_id": "snapshot-1",
37208                        "run_id": "snapshot-run-1",
37209                        "workflow_type": "snapshot",
37210                        "payload_codec": DEFAULT_CODEC,
37211                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
37212                            .expect("Avro workflow arguments"),
37213                        "history_events": [],
37214                        "workflow_task_attempt": 1,
37215                        "lease_owner": "rust-snapshot-worker"
37216                    }
37217                })
37218                .to_string();
37219                write_mock_response(stream, "200 OK", &body);
37220                return;
37221            }
37222
37223            let signal_request = request_number - usize::from(behavior.complete_named_signal);
37224            let signal_request_limit = 2 + usize::from(behavior.complete_named_signal);
37225            if path == "/api/worker/workflow-tasks/poll"
37226                && signal_request >= 1
37227                && signal_request <= signal_request_limit
37228            {
37229                let finish = behavior.complete_named_signal && signal_request == 3;
37230                let amounts = if signal_request == 1 {
37231                    vec![3]
37232                } else {
37233                    vec![3, 5]
37234                };
37235                let task_id = if signal_request == 1 {
37236                    "snapshot-wait-3"
37237                } else if finish {
37238                    "snapshot-finish"
37239                } else {
37240                    "snapshot-wait-5"
37241                };
37242                let mut history_events = std::iter::once(json!({
37243                    "event_type": "SignalWaitOpened",
37244                    "payload": {"sequence": 1, "signal_name": "finish"}
37245                }))
37246                .chain(amounts.iter().enumerate().map(|(index, amount)| {
37247                    json!({
37248                        "event_type": "SignalReceived",
37249                        "payload": {
37250                            "signal_id": format!("increment-{amount}"),
37251                            "signal_name": "increment",
37252                            "workflow_sequence": index + 2,
37253                            "payload_codec": DEFAULT_CODEC,
37254                            "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
37255                                .expect("Avro signal envelope")
37256                        }
37257                    })
37258                }))
37259                .collect::<Vec<_>>();
37260                let (resume_id, resume_name, resume_arguments) = if finish {
37261                    history_events.push(json!({
37262                        "event_type": "SignalReceived",
37263                        "payload": {
37264                            "signal_id": "finish",
37265                            "signal_name": "finish",
37266                            "workflow_sequence": 4,
37267                            "payload_codec": DEFAULT_CODEC,
37268                            "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
37269                                .expect("Avro finish signal envelope")
37270                        }
37271                    }));
37272                    (
37273                        "finish".to_string(),
37274                        "finish".to_string(),
37275                        encode_value_envelope(&json!([]), DEFAULT_CODEC)
37276                            .expect("Avro finish resume signal"),
37277                    )
37278                } else {
37279                    let amount = amounts.last().expect("amount");
37280                    (
37281                        format!("increment-{amount}"),
37282                        "increment".to_string(),
37283                        encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
37284                            .expect("Avro increment resume signal"),
37285                    )
37286                };
37287                let body = json!({
37288                    "task": {
37289                        "task_id": task_id,
37290                        "workflow_id": "snapshot-1",
37291                        "run_id": "snapshot-run-1",
37292                        "workflow_type": "snapshot",
37293                        "payload_codec": DEFAULT_CODEC,
37294                        "arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
37295                            .expect("Avro workflow arguments"),
37296                        "history_events": history_events,
37297                        "workflow_task_attempt": 1,
37298                        "workflow_signal_id": resume_id,
37299                        "signal_name": resume_name,
37300                        "signal_arguments": resume_arguments,
37301                        "lease_owner": "rust-snapshot-worker"
37302                    }
37303                })
37304                .to_string();
37305                write_mock_response(stream, "200 OK", &body);
37306                return;
37307            }
37308
37309            if path == "/api/worker/query-tasks/poll" && request_number == 1 {
37310                let history_events = [3, 5]
37311                    .into_iter()
37312                    .enumerate()
37313                    .map(|(index, amount)| {
37314                        json!({
37315                            "event_type": "SignalReceived",
37316                            "payload": {
37317                                "signal_id": format!("increment-{amount}"),
37318                                "signal_name": "increment",
37319                                "workflow_sequence": index + 2,
37320                                "payload_codec": DEFAULT_CODEC,
37321                                "arguments": encode_value_envelope(&json!([amount]), DEFAULT_CODEC)
37322                                    .expect("Avro query signal envelope")
37323                            }
37324                        })
37325                    })
37326                    .collect::<Vec<_>>();
37327                let body = json!({
37328                    "task": {
37329                        "query_task_id": "snapshot-current",
37330                        "query_task_attempt": 1,
37331                        "lease_owner": "rust-snapshot-worker",
37332                        "workflow_id": "snapshot-1",
37333                        "run_id": "snapshot-run-1",
37334                        "workflow_type": "snapshot",
37335                        "query_name": "current",
37336                        "payload_codec": DEFAULT_CODEC,
37337                        "workflow_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
37338                            .expect("Avro workflow arguments"),
37339                        "query_arguments": encode_value_envelope(&json!([]), DEFAULT_CODEC)
37340                            .expect("Avro query arguments"),
37341                        "history_events": history_events,
37342                        "run_status": "waiting"
37343                    }
37344                })
37345                .to_string();
37346                write_mock_response(stream, "200 OK", &body);
37347                return;
37348            }
37349
37350            if path == "/api/worker/workflow-tasks/snapshot-wait-3/fail"
37351                || path == "/api/worker/workflow-tasks/snapshot-wait-5/fail"
37352            {
37353                write_mock_response(
37354                    stream,
37355                    "200 OK",
37356                    r#"{"outcome":"waiting_for_history","recorded":true}"#,
37357                );
37358                return;
37359            }
37360
37361            if path == "/api/worker/workflow-tasks/snapshot-open/complete" {
37362                write_mock_response(stream, "200 OK", r#"{"outcome":"waiting","recorded":true}"#);
37363                return;
37364            }
37365
37366            if path == "/api/worker/workflow-tasks/snapshot-finish/complete" {
37367                write_mock_response(
37368                    stream,
37369                    "200 OK",
37370                    r#"{"outcome":"completed","run_status":"completed","recorded":true}"#,
37371                );
37372                return;
37373            }
37374
37375            if path == "/api/worker/query-tasks/snapshot-current/complete" {
37376                write_mock_response(stream, "200 OK", r#"{"outcome":"completed"}"#);
37377                return;
37378            }
37379        }
37380
37381        if matches!(
37382            path,
37383            "/api/workflows/typed-1/query/inspect" | "/api/workflows/typed-1/update/replace"
37384        ) {
37385            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
37386                .expect("typed mock result");
37387            let body = json!({
37388                "result": typed_fidelity_probe().into_json().expect("result projection"),
37389                "result_envelope": result,
37390            })
37391            .to_string();
37392            write_mock_response(stream, "200 OK", &body);
37393            return;
37394        }
37395
37396        if path == "/api/workflows/typed-1" {
37397            let result = encode_typed_envelope(&typed_fidelity_probe(), DEFAULT_CODEC)
37398                .expect("typed mock result");
37399            let body = json!({
37400                "workflow_id": "typed-1",
37401                "run_id": "run-typed-1",
37402                "workflow_type": "typed.echo",
37403                "status": "completed",
37404                "output": typed_fidelity_probe().into_json().expect("output projection"),
37405                "output_envelope": result,
37406            })
37407            .to_string();
37408            write_mock_response(stream, "200 OK", &body);
37409            return;
37410        }
37411
37412        let (status, body) = match path {
37413            "/api/cluster/info" => ("200 OK", r#"{"limits":{"max_payload_bytes":2097152}}"#),
37414            "/api/health" => ("200 OK", r#"{"status":"ok"}"#),
37415            "/api/workflows" => (
37416                "201 Created",
37417                r#"{"workflow_id":"wf-start-options","run_id":"run-start-options","workflow_type":"rust.timeout"}"#,
37418            ),
37419            "/api/worker/register" if behavior.decline_registration => (
37420                "200 OK",
37421                r#"{"worker_id":"declined-worker","registered":false}"#,
37422            ),
37423            "/api/worker/register" if behavior.waiting_query_worker => (
37424                "200 OK",
37425                r#"{"worker_id":"rust-snapshot-worker","registered":true,"heartbeat_interval_seconds":1}"#,
37426            ),
37427            "/api/worker/register" => (
37428                "200 OK",
37429                r#"{"worker_id":"mock-worker","registered":true,"heartbeat_interval_seconds":3600}"#,
37430            ),
37431            "/api/worker/heartbeat" => ("200 OK", "{}"),
37432            "/api/worker/activity-tasks/poll"
37433                if behavior.cancelled_activity && request_number == 1 =>
37434            {
37435                (
37436                    "200 OK",
37437                    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"}}"#,
37438                )
37439            }
37440            "/api/worker/activity-tasks/poll"
37441                if behavior.long_poll_capacity_responses_per_path > 0
37442                    && request_number
37443                        == behavior
37444                            .long_poll_capacity_responses_per_path
37445                            .saturating_add(1) =>
37446            {
37447                (
37448                    "200 OK",
37449                    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"}}"#,
37450                )
37451            }
37452            "/api/worker/activity-tasks/poll" | "/api/worker/workflow-tasks/poll" => {
37453                ("200 OK", r#"{"task":null}"#)
37454            }
37455            "/api/worker/query-tasks/poll"
37456                if behavior.reject_query_completion && request_number == 1 =>
37457            {
37458                (
37459                    "200 OK",
37460                    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"}}"#,
37461                )
37462            }
37463            "/api/worker/query-tasks/poll" => ("200 OK", r#"{"task":null}"#),
37464            "/api/worker/query-tasks/query-capture/complete"
37465            | "/api/worker/query-tasks/query-capture/fail" => ("200 OK", "{}"),
37466            "/api/worker/activity-tasks/activity-cancel/heartbeat" => (
37467                "200 OK",
37468                r#"{"activity_attempt_id":"attempt-cancel","cancel_requested":true,"can_continue":false,"reason":"run_cancelled","run_closed_reason":"cancelled","heartbeat_recorded":false}"#,
37469            ),
37470            "/api/worker/activity-tasks/activity-cancel/complete" => (
37471                "409 Conflict",
37472                r#"{"task_id":"activity-cancel","activity_attempt_id":"attempt-cancel","reason":"run_cancelled","cancel_requested":true,"can_continue":false,"run_closed_reason":"cancelled"}"#,
37473            ),
37474            "/api/worker/activity-tasks/activity-typed/complete"
37475            | "/api/worker/activity-tasks/activity-typed/fail"
37476            | "/api/worker/activity-tasks/capacity-activity/complete"
37477            | "/api/workflows/typed-1/signal/changed" => ("200 OK", "{}"),
37478            "/api/workflows/counter-1/query/current" => (
37479                "200 OK",
37480                r#"{"workflow_id":"counter-1","query_name":"current","result":{"count":8},"result_envelope":{"codec":"avro","blob":"wwHioz3/VYAiNw4CCmNvdW50BBAA"}}"#,
37481            ),
37482            "/api/workflows/counter-1/query/missing" => (
37483                "404 Not Found",
37484                r#"{"workflow_id":"counter-1","query_name":"missing","reason":"rejected_unknown_query","message":"unknown query"}"#,
37485            ),
37486            "/api/workflows/wf-lifecycle/cancel" => (
37487                "200 OK",
37488                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","reason":"cleanup requested","command_status":"accepted"}"#,
37489            ),
37490            "/api/workflows/wf-lifecycle/terminate" => (
37491                "200 OK",
37492                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","reason":"forced stop","command_status":"accepted"}"#,
37493            ),
37494            "/api/workflows/wf-lifecycle/runs/run-current/cancel" => (
37495                "200 OK",
37496                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"cancelled","command_status":"accepted"}"#,
37497            ),
37498            "/api/workflows/wf-lifecycle/runs/run-current/terminate" => (
37499                "200 OK",
37500                r#"{"workflow_id":"wf-lifecycle","run_id":"run-current","outcome":"terminated","command_status":"accepted"}"#,
37501            ),
37502            "/api/workflows/wf-lifecycle/runs/run-failed/redrive" => (
37503                "202 Accepted",
37504                r#"{"workflow_id":"wf-lifecycle","continued_from_run_id":"run-failed","run_id":"run-successor","outcome":"redriven","command_status":"accepted","resume_step_sequence":2}"#,
37505            ),
37506            "/api/workflows/wf-lifecycle/runs/run-failed-existing/redrive" => (
37507                "200 OK",
37508                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}"#,
37509            ),
37510            "/api/workflows/wf-lifecycle/runs/run-completed/redrive" => (
37511                "409 Conflict",
37512                r#"{"workflow_id":"wf-lifecycle","run_id":"run-completed","reason":"run_not_failed","message":"Run is not failed."}"#,
37513            ),
37514            "/api/workflows/wf-lifecycle/runs/run-stale/cancel"
37515            | "/api/workflows/wf-lifecycle/runs/run-stale/terminate" => (
37516                "409 Conflict",
37517                r#"{"workflow_id":"wf-lifecycle","run_id":"run-stale","reason":"historical_run_command_rejected","target_scope":"run","message":"Commands cannot target historical runs."}"#,
37518            ),
37519            "/api/workflows/wf-failed" | "/api/workflows/wf-failed/runs/run-failed" => (
37520                "200 OK",
37521                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"}]}}"#,
37522            ),
37523            "/api/workflows/wf-cancelled" => (
37524                "200 OK",
37525                r#"{"workflow_id":"wf-cancelled","run_id":"run-cancelled","status":"cancelled","closed_reason":"cancelled","reason":"cleanup requested"}"#,
37526            ),
37527            "/api/workflows/wf-terminated" => (
37528                "200 OK",
37529                r#"{"workflow_id":"wf-terminated","run_id":"run-terminated","status":"terminated","closed_reason":"terminated","reason":"forced stop"}"#,
37530            ),
37531            "/api/workflows/wf-timed-out" => (
37532                "200 OK",
37533                r#"{"workflow_id":"wf-timed-out","run_id":"run-timed-out","status":"failed","closed_reason":"timed_out","reason":"run_timeout"}"#,
37534            ),
37535            // Native-style terminal descriptions without failure detail (#156).
37536            "/api/workflows/wf-native-failed"
37537            | "/api/workflows/wf-native-failed/runs/run-native-failed" => (
37538                "200 OK",
37539                r#"{"workflow_id":"wf-native-failed","run_id":"run-native-failed","status":"failed","closed_reason":"failed","output":null}"#,
37540            ),
37541            "/api/workflows/wf-native-failed/runs/run-native-failed/history" => (
37542                "200 OK",
37543                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"}}}]}"#,
37544            ),
37545            "/api/workflows/wf-native-timed-out" => (
37546                "200 OK",
37547                r#"{"workflow_id":"wf-native-timed-out","run_id":"run-native-timed-out","status":"failed","closed_reason":"timed_out"}"#,
37548            ),
37549            "/api/workflows/wf-native-timed-out/runs/run-native-timed-out/history" => (
37550                "200 OK",
37551                r#"{"events":[{"sequence":5,"event_type":"WorkflowTimedOut","payload":{"failure_id":"failure-deadline","timeout_kind":"execution_timeout","failure_category":"timeout","message":"Workflow execution deadline expired."}}]}"#,
37552            ),
37553            "/api/workflows/wf-native-paged" => (
37554                "200 OK",
37555                r#"{"workflow_id":"wf-native-paged","run_id":"run-native-paged","status":"failed","closed_reason":"failed"}"#,
37556            ),
37557            "/api/workflows/wf-native-paged/runs/run-native-paged/history" => (
37558                "200 OK",
37559                r#"{"events":[{"sequence":1,"event_type":"WorkflowStarted","payload":{}}],"next_page_token":"page-2"}"#,
37560            ),
37561            "/api/workflows/wf-native-paged/runs/run-native-paged/history?next_page_token=page-2" => (
37562                "200 OK",
37563                r#"{"events":[{"sequence":2,"event_type":"WorkflowFailed","payload":{"exception_type":"PagedFailure","message":"found on page two"}}]}"#,
37564            ),
37565            "/api/workflows/wf-native-no-history" => (
37566                "200 OK",
37567                r#"{"workflow_id":"wf-native-no-history","run_id":"run-native-no-history","status":"failed","closed_reason":"failed"}"#,
37568            ),
37569            "/api/workflows/wf-waiting" | "/api/workflows/wf-waiting/runs/run-waiting" => (
37570                "200 OK",
37571                r#"{"workflow_id":"wf-waiting","run_id":"run-waiting","status":"waiting"}"#,
37572            ),
37573            "/api/workflows/wf-selected" => (
37574                "200 OK",
37575                r#"{"workflow_id":"wf-selected","run_id":"run-current","status":"completed","output":"current run output"}"#,
37576            ),
37577            "/api/workflows/wf-selected/runs/run-selected" => (
37578                "200 OK",
37579                r#"{"workflow_id":"wf-selected","run_id":"run-selected","status":"cancelled","closed_reason":"cancelled","reason":"selected run cancelled"}"#,
37580            ),
37581            _ => ("404 Not Found", r#"{"message":"not found"}"#),
37582        };
37583        write_mock_response(stream, status, body);
37584    }
37585
37586    fn mock_request_is_complete(request: &[u8]) -> bool {
37587        let Some(header_end) = request
37588            .windows(4)
37589            .position(|window| window == b"\r\n\r\n")
37590            .map(|position| position + 4)
37591        else {
37592            return false;
37593        };
37594        let headers = String::from_utf8_lossy(&request[..header_end]);
37595        let content_length = headers.lines().find_map(|line| {
37596            let (name, value) = line.split_once(':')?;
37597            name.eq_ignore_ascii_case("content-length")
37598                .then(|| value.trim().parse::<usize>().ok())
37599                .flatten()
37600        });
37601
37602        request.len() >= header_end + content_length.unwrap_or(0)
37603    }
37604
37605    fn write_mock_response(stream: &mut TcpStream, status: &str, body: &str) {
37606        let response = format!(
37607            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
37608            body.len()
37609        );
37610
37611        let _ = stream.write_all(response.as_bytes());
37612        let _ = stream.flush();
37613    }
37614
37615    fn typed_activity_failure_server(
37616        path: &str,
37617        _body: &str,
37618        request_number: usize,
37619    ) -> Option<(&'static str, String)> {
37620        match path {
37621            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
37622                "200 OK",
37623                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(),
37624            )),
37625            "/api/worker/activity-tasks/typed-failure/fail" => Some(("200 OK", "{}".into())),
37626            _ => None,
37627        }
37628    }
37629
37630    #[tokio::test]
37631    async fn managed_activity_reports_application_type_and_non_retryable_marker() {
37632        for non_retryable in [false, true] {
37633            let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
37634                request_override: Some(typed_activity_failure_server),
37635                ..MockWorkerBehavior::default()
37636            });
37637            let client = Client::builder(server.base_url()).build().unwrap();
37638            let mut worker = Worker::new(client, "typed-queue").worker_id("typed-worker");
37639            worker.register_activity("typed.failure", move |_, _| async move {
37640                Err(ActivityError::new("PaymentDeclined", "card declined")
37641                    .non_retryable(non_retryable)
37642                    .into())
37643            });
37644            assert_eq!(worker.run_once().await.unwrap(), 1);
37645            assert_eq!(
37646                server.request_body("/api/worker/activity-tasks/typed-failure/fail"),
37647                json!({
37648                    "activity_attempt_id": "typed-attempt",
37649                    "lease_owner": "typed-worker",
37650                    "failure": {"type": "PaymentDeclined", "message": "card declined",
37651                                "non_retryable": non_retryable}
37652                })
37653            );
37654        }
37655    }
37656
37657    fn activity_completion_backend_recovery(
37658        path: &str,
37659        _body: &str,
37660        request_number: usize,
37661    ) -> Option<(&'static str, String)> {
37662        match path {
37663            "/api/worker/activity-tasks/poll" if request_number == 1 => Some((
37664                "200 OK",
37665                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(),
37666            )),
37667            "/api/worker/activity-tasks/recover-activity/complete" if request_number == 1 => Some((
37668                "503 Service Unavailable",
37669                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(),
37670            )),
37671            "/api/worker/activity-tasks/recover-activity/complete" => Some((
37672                "200 OK",
37673                r#"{"outcome":"completed","recorded":true}"#.to_string(),
37674            )),
37675            _ => None,
37676        }
37677    }
37678
37679    fn workflow_completion_backend_recovery(
37680        path: &str,
37681        _body: &str,
37682        request_number: usize,
37683    ) -> Option<(&'static str, String)> {
37684        match path {
37685            "/api/worker/workflow-tasks/poll" if request_number == 1 => Some((
37686                "200 OK",
37687                include_str!("../tests/fixtures/worker-completion-recovery.json").to_string(),
37688            )),
37689            "/api/worker/workflow-tasks/recover-workflow/complete" if request_number == 1 => Some((
37690                "503 Service Unavailable",
37691                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(),
37692            )),
37693            "/api/worker/workflow-tasks/recover-workflow/complete" => Some((
37694                "200 OK",
37695                r#"{"outcome":"completed","recorded":true}"#.to_string(),
37696            )),
37697            _ => None,
37698        }
37699    }
37700
37701    fn workflow_completion_lock_pressure(
37702        path: &str,
37703        body: &str,
37704        request_number: usize,
37705    ) -> Option<(&'static str, String)> {
37706        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number == 1 {
37707            return Some((
37708                "503 Service Unavailable",
37709                json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
37710                    "outcome":"deferred", "recorded":false, "retryable":true,
37711                    "retry_after_seconds":1, "task_id":"recover-workflow",
37712                    "lease_owner":"recover-worker", "workflow_task_attempt":3,
37713                    "backend":{"driver":"sqlite", "lock_pressure":true}})
37714                .to_string(),
37715            ));
37716        }
37717        workflow_completion_backend_recovery(path, body, request_number)
37718    }
37719
37720    fn workflow_completion_lock_pressure_forever(
37721        path: &str,
37722        body: &str,
37723        request_number: usize,
37724    ) -> Option<(&'static str, String)> {
37725        if path == "/api/worker/workflow-tasks/recover-workflow/complete" {
37726            return workflow_completion_lock_pressure(path, body, 1);
37727        }
37728        workflow_completion_lock_pressure(path, body, request_number)
37729    }
37730
37731    fn workflow_completion_lock_pressure_then_expired(
37732        path: &str,
37733        body: &str,
37734        request_number: usize,
37735    ) -> Option<(&'static str, String)> {
37736        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
37737            return Some(("409 Conflict", json!({"reason":"lease_expired", "recorded":false,
37738                "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3}).to_string()));
37739        }
37740        workflow_completion_lock_pressure(path, body, request_number)
37741    }
37742
37743    fn workflow_completion_lock_pressure_then_slow(
37744        path: &str,
37745        body: &str,
37746        request_number: usize,
37747    ) -> Option<(&'static str, String)> {
37748        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
37749            thread::sleep(Duration::from_secs(2));
37750        }
37751        workflow_completion_lock_pressure(path, body, request_number)
37752    }
37753
37754    fn workflow_completion_pressure_then_backend_loss(
37755        path: &str,
37756        body: &str,
37757        request_number: usize,
37758    ) -> Option<(&'static str, String)> {
37759        if path == "/api/worker/workflow-tasks/recover-workflow/complete" && request_number > 1 {
37760            return Some((
37761                "503 Service Unavailable",
37762                json!({"reason":"backend_unavailable", "operation":"complete_workflow_task",
37763                    "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
37764                    "retryable":true, "retry_after_seconds":3, "task_id":"recover-workflow",
37765                    "lease_owner":"recover-worker", "workflow_task_attempt":3})
37766                .to_string(),
37767            ));
37768        }
37769        workflow_completion_lock_pressure(path, body, request_number)
37770    }
37771
37772    fn completion_deferral_worker(server: &MockWorkerServer, calls: Arc<AtomicUsize>) -> Worker {
37773        let client = Client::builder(server.base_url())
37774            .timeout(Duration::from_secs(4))
37775            .build()
37776            .unwrap();
37777        let mut worker = Worker::new(client, "recover-queue")
37778            .worker_id("recover-worker")
37779            .poll_timeout(Duration::from_millis(10));
37780        worker.register_workflow("recover.workflow", move |_ctx, _args| {
37781            let calls = Arc::clone(&calls);
37782            async move {
37783                calls.fetch_add(1, Ordering::SeqCst);
37784                Ok(json!("done"))
37785            }
37786        });
37787        worker
37788    }
37789
37790    #[tokio::test]
37791    async fn workflow_completion_deferral_stops_at_original_cleanup_budget() {
37792        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
37793            request_override: Some(workflow_completion_lock_pressure_forever),
37794            ..MockWorkerBehavior::default()
37795        });
37796        let calls = Arc::new(AtomicUsize::new(0));
37797        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
37798            .with_storage_admission(Arc::new(AtomicBool::new(false)));
37799        worker
37800            .client
37801            .worker_storage_admission
37802            .as_mut()
37803            .unwrap()
37804            .workflow_completion_retry_deadline =
37805            Some(tokio::time::Instant::now() + Duration::from_millis(250));
37806        let result = tokio::time::timeout(Duration::from_secs(2), worker.poll_workflow_once())
37807            .await
37808            .unwrap();
37809        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
37810        assert_eq!(calls.load(Ordering::SeqCst), 1);
37811        assert_eq!(
37812            server
37813                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
37814                .len(),
37815            1
37816        );
37817    }
37818
37819    #[tokio::test]
37820    async fn workflow_completion_deferral_bounds_the_inflight_retry() {
37821        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
37822            request_override: Some(workflow_completion_lock_pressure_then_slow),
37823            ..MockWorkerBehavior::default()
37824        });
37825        let calls = Arc::new(AtomicUsize::new(0));
37826        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
37827            .with_storage_admission(Arc::new(AtomicBool::new(false)));
37828        let start = tokio::time::Instant::now();
37829        worker
37830            .client
37831            .worker_storage_admission
37832            .as_mut()
37833            .unwrap()
37834            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
37835        assert!(matches!(
37836            worker.poll_workflow_once().await,
37837            Err(Error::Timeout)
37838        ));
37839        assert!(start.elapsed() < Duration::from_secs(2));
37840        assert_eq!(calls.load(Ordering::SeqCst), 1);
37841        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
37842        assert_eq!(bodies.len(), 2);
37843        assert_eq!(bodies[0], bodies[1]);
37844    }
37845
37846    #[tokio::test]
37847    async fn workflow_completion_deferral_retains_deadline_when_backend_reason_changes() {
37848        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
37849            request_override: Some(workflow_completion_pressure_then_backend_loss),
37850            ..MockWorkerBehavior::default()
37851        });
37852        let calls = Arc::new(AtomicUsize::new(0));
37853        let mut worker = completion_deferral_worker(&server, Arc::clone(&calls))
37854            .with_storage_admission(Arc::new(AtomicBool::new(false)));
37855        let start = tokio::time::Instant::now();
37856        worker
37857            .client
37858            .worker_storage_admission
37859            .as_mut()
37860            .unwrap()
37861            .workflow_completion_retry_deadline = Some(start + Duration::from_millis(1_500));
37862        let result = worker.poll_workflow_once().await;
37863        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
37864        assert!(start.elapsed() < Duration::from_secs(2));
37865        assert_eq!(calls.load(Ordering::SeqCst), 1);
37866        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
37867        assert_eq!(bodies.len(), 2);
37868        assert_eq!(bodies[0], bodies[1]);
37869    }
37870
37871    #[tokio::test]
37872    async fn workflow_completion_deferral_shutdown_interrupts_prolonged_pressure() {
37873        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
37874            request_override: Some(workflow_completion_lock_pressure_forever),
37875            ..MockWorkerBehavior::default()
37876        });
37877        let calls = Arc::new(AtomicUsize::new(0));
37878        let stop = Arc::new(AtomicBool::new(false));
37879        let worker = completion_deferral_worker(&server, Arc::clone(&calls))
37880            .with_storage_admission(Arc::clone(&stop));
37881        let shutdown = async {
37882            while server
37883                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
37884                .is_empty()
37885            {
37886                tokio::time::sleep(Duration::from_millis(10)).await;
37887            }
37888            stop.store(true, Ordering::SeqCst);
37889        };
37890        let (result, ()) = tokio::time::timeout(Duration::from_secs(2), async {
37891            tokio::join!(worker.poll_workflow_once(), shutdown)
37892        })
37893        .await
37894        .unwrap();
37895        assert!(matches!(result, Err(Error::Http { status, .. }) if status.as_u16() == 503));
37896        assert_eq!(calls.load(Ordering::SeqCst), 1);
37897        assert_eq!(
37898            server
37899                .request_bodies("/api/worker/workflow-tasks/recover-workflow/complete")
37900                .len(),
37901            1
37902        );
37903    }
37904
37905    #[tokio::test]
37906    async fn workflow_completion_deferral_preserves_later_expiry_refusal() {
37907        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
37908            request_override: Some(workflow_completion_lock_pressure_then_expired),
37909            ..MockWorkerBehavior::default()
37910        });
37911        let calls = Arc::new(AtomicUsize::new(0));
37912        let worker = completion_deferral_worker(&server, Arc::clone(&calls));
37913        let result = worker.run_once().await;
37914        assert!(
37915            matches!(result, Err(Error::Http { status, ref body }) if status.as_u16() == 409 && body.contains("lease_expired"))
37916        );
37917        assert_eq!(calls.load(Ordering::SeqCst), 1);
37918        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
37919        assert_eq!(bodies.len(), 2);
37920        assert_eq!(bodies[0], bodies[1]);
37921        assert!(server
37922            .request_bodies("/api/worker/workflow-tasks/recover-workflow/fail")
37923            .is_empty());
37924    }
37925
37926    #[tokio::test]
37927    async fn managed_workflow_completion_deferral_preserves_bytes_and_server_delay() {
37928        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
37929            request_override: Some(workflow_completion_lock_pressure),
37930            ..MockWorkerBehavior::default()
37931        });
37932        let client = Client::builder(server.base_url())
37933            .timeout(Duration::from_secs(2))
37934            .build()
37935            .unwrap();
37936        let calls = Arc::new(AtomicUsize::new(0));
37937        let mut worker = Worker::new(client, "recover-queue")
37938            .worker_id("recover-worker")
37939            .recover_transient_outages(true)
37940            .poll_timeout(Duration::from_millis(10))
37941            .retry_policy(WorkerRetryPolicy {
37942                max_retries: 1,
37943                initial_backoff: Duration::from_millis(10),
37944                max_backoff: Duration::from_millis(10),
37945            });
37946        worker.register_workflow("recover.workflow", {
37947            let calls = Arc::clone(&calls);
37948            move |_ctx, _args| {
37949                let calls = Arc::clone(&calls);
37950                async move {
37951                    calls.fetch_add(1, Ordering::SeqCst);
37952                    Ok(json!("done"))
37953                }
37954            }
37955        });
37956        let start = tokio::time::Instant::now();
37957        assert_eq!(worker.run_once().await.unwrap(), 1);
37958        assert!(start.elapsed() >= Duration::from_secs(1));
37959        assert_eq!(calls.load(Ordering::SeqCst), 1);
37960        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
37961        assert_eq!(bodies.len(), 2);
37962        assert_eq!(bodies[0], bodies[1]);
37963    }
37964
37965    #[test]
37966    fn workflow_completion_deferral_requires_an_exact_unrecorded_fence() {
37967        let path = "/worker/workflow-tasks/recover-workflow/complete";
37968        let request = json!({"lease_owner":"recover-worker", "workflow_task_attempt":3});
37969        let response = json!({"reason":"backend_lock_pressure", "operation":"complete_workflow_task",
37970            "outcome":"deferred", "recorded":false, "retryable":true, "retry_after_seconds":1,
37971            "task_id":"recover-workflow", "lease_owner":"recover-worker", "workflow_task_attempt":3,
37972            "backend":{"driver":"sqlite", "lock_pressure":true}});
37973        let error = |body: Value| Error::Http {
37974            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
37975            body: body.to_string(),
37976        };
37977        assert_eq!(
37978            worker_deferred_workflow_completion_retry_after(
37979                &error(response.clone()),
37980                path,
37981                Some(&request)
37982            ),
37983            Some(Duration::from_secs(1))
37984        );
37985        for (field, value) in [
37986            ("reason", json!("backend_unavailable")),
37987            ("operation", json!("complete_activity_task")),
37988            ("task_id", json!("other-task")),
37989            ("lease_owner", json!("other-owner")),
37990            ("workflow_task_attempt", json!(4)),
37991            ("recorded", json!(true)),
37992            ("recorded", Value::Null),
37993            ("recorded", json!("false")),
37994            ("retryable", json!(false)),
37995            ("retry_after_seconds", json!(0)),
37996            ("retry_after_seconds", json!(-1)),
37997            ("retry_after_seconds", json!(1.0)),
37998            ("retry_after_seconds", json!("1")),
37999            ("retry_after_seconds", json!(6)),
38000            ("backend", json!({"lock_pressure":false})),
38001        ] {
38002            let mut invalid = response.clone();
38003            invalid[field] = value;
38004            assert_eq!(
38005                worker_deferred_workflow_completion_retry_after(
38006                    &error(invalid),
38007                    path,
38008                    Some(&request)
38009                ),
38010                None,
38011                "invalid {field}"
38012            );
38013        }
38014        for field in [
38015            "reason",
38016            "operation",
38017            "task_id",
38018            "lease_owner",
38019            "workflow_task_attempt",
38020            "recorded",
38021            "retryable",
38022            "retry_after_seconds",
38023            "backend",
38024        ] {
38025            let mut missing = response.clone();
38026            missing.as_object_mut().unwrap().remove(field);
38027            assert_eq!(
38028                worker_deferred_workflow_completion_retry_after(
38029                    &error(missing),
38030                    path,
38031                    Some(&request)
38032                ),
38033                None,
38034                "missing {field}"
38035            );
38036        }
38037        assert_eq!(
38038            worker_deferred_workflow_completion_retry_after(
38039                &error(response.clone()),
38040                "/worker/activity-tasks/recover-workflow/complete",
38041                Some(&request)
38042            ),
38043            None
38044        );
38045        assert_eq!(
38046            worker_deferred_workflow_completion_retry_after(&error(response.clone()), path, None),
38047            None
38048        );
38049        let wrong_status = Error::Http {
38050            status: reqwest::StatusCode::CONFLICT,
38051            body: response.to_string(),
38052        };
38053        assert_eq!(
38054            worker_deferred_workflow_completion_retry_after(&wrong_status, path, Some(&request)),
38055            None
38056        );
38057    }
38058
38059    fn activity_completion_stale_after_backend_recovery(
38060        path: &str,
38061        body: &str,
38062        request_number: usize,
38063    ) -> Option<(&'static str, String)> {
38064        if path == "/api/worker/activity-tasks/recover-activity/complete" && request_number > 1 {
38065            return Some((
38066                "409 Conflict",
38067                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(),
38068            ));
38069        }
38070        activity_completion_backend_recovery(path, body, request_number)
38071    }
38072
38073    fn activity_completion_remains_unavailable(
38074        path: &str,
38075        body: &str,
38076        request_number: usize,
38077    ) -> Option<(&'static str, String)> {
38078        if path == "/api/worker/activity-tasks/recover-activity/complete" {
38079            return activity_completion_backend_recovery(path, body, 1);
38080        }
38081        activity_completion_backend_recovery(path, body, request_number)
38082    }
38083
38084    #[tokio::test]
38085    async fn managed_activity_retries_same_fenced_completion_after_backend_loss() {
38086        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
38087            request_override: Some(activity_completion_backend_recovery),
38088            ..MockWorkerBehavior::default()
38089        });
38090        let client = Client::builder(server.base_url())
38091            .timeout(Duration::from_secs(2))
38092            .build()
38093            .expect("client");
38094        let handler_calls = Arc::new(AtomicUsize::new(0));
38095        let mut worker = Worker::new(client, "recover-queue")
38096            .worker_id("recover-worker")
38097            .poll_timeout(Duration::from_millis(10));
38098        worker.register_activity("recover.activity", {
38099            let handler_calls = Arc::clone(&handler_calls);
38100            move |_ctx, _args| {
38101                let handler_calls = Arc::clone(&handler_calls);
38102                async move {
38103                    handler_calls.fetch_add(1, Ordering::SeqCst);
38104                    Ok(json!("done"))
38105                }
38106            }
38107        });
38108
38109        assert_eq!(worker.run_once().await.expect("activity settled"), 1);
38110        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
38111        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
38112        assert_eq!(bodies.len(), 2);
38113        assert_eq!(bodies[0], bodies[1]);
38114    }
38115
38116    #[tokio::test]
38117    async fn managed_workflow_retries_same_fenced_completion_after_backend_loss() {
38118        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
38119            request_override: Some(workflow_completion_backend_recovery),
38120            ..MockWorkerBehavior::default()
38121        });
38122        let client = Client::builder(server.base_url())
38123            .timeout(Duration::from_secs(2))
38124            .build()
38125            .expect("client");
38126        let handler_calls = Arc::new(AtomicUsize::new(0));
38127        let mut worker = Worker::new(client, "recover-queue")
38128            .worker_id("recover-worker")
38129            .poll_timeout(Duration::from_millis(10));
38130        worker.register_workflow("recover.workflow", {
38131            let handler_calls = Arc::clone(&handler_calls);
38132            move |_ctx, _args| {
38133                let handler_calls = Arc::clone(&handler_calls);
38134                async move {
38135                    handler_calls.fetch_add(1, Ordering::SeqCst);
38136                    Ok(json!("done"))
38137                }
38138            }
38139        });
38140
38141        assert_eq!(worker.run_once().await.expect("workflow settled"), 1);
38142        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
38143        let bodies = server.request_bodies("/api/worker/workflow-tasks/recover-workflow/complete");
38144        assert_eq!(bodies.len(), 2);
38145        assert_eq!(bodies[0], bodies[1]);
38146    }
38147
38148    #[tokio::test]
38149    async fn managed_activity_accepts_authoritative_stale_outcome_after_unknown_completion() {
38150        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
38151            request_override: Some(activity_completion_stale_after_backend_recovery),
38152            ..MockWorkerBehavior::default()
38153        });
38154        let client = Client::builder(server.base_url())
38155            .timeout(Duration::from_secs(2))
38156            .build()
38157            .expect("client");
38158        let handler_calls = Arc::new(AtomicUsize::new(0));
38159        let mut worker = Worker::new(client, "recover-queue")
38160            .worker_id("recover-worker")
38161            .poll_timeout(Duration::from_millis(10));
38162        worker.register_activity("recover.activity", {
38163            let handler_calls = Arc::clone(&handler_calls);
38164            move |_ctx, _args| {
38165                let handler_calls = Arc::clone(&handler_calls);
38166                async move {
38167                    handler_calls.fetch_add(1, Ordering::SeqCst);
38168                    Ok(json!("done"))
38169                }
38170            }
38171        });
38172
38173        assert_eq!(
38174            worker
38175                .run_once()
38176                .await
38177                .expect("authoritative stale outcome"),
38178            1
38179        );
38180        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
38181        let bodies = server.request_bodies("/api/worker/activity-tasks/recover-activity/complete");
38182        assert_eq!(bodies.len(), 2);
38183        assert_eq!(bodies[0], bodies[1]);
38184    }
38185
38186    #[test]
38187    fn fenced_completion_retry_rejects_mismatched_or_incomplete_identity() {
38188        let request = json!({"lease_owner":"recover-worker","activity_attempt_id":"recover-attempt","result":{"codec":"avro","blob":"value"}});
38189        let response = json!({
38190            "reason":"backend_unavailable", "operation":"complete_activity_task",
38191            "outcome":"unknown", "worker_id":"recover-worker", "task_queue":null,
38192            "retryable":true, "retry_after_seconds":1, "task_id":"recover-activity",
38193            "lease_owner":"recover-worker", "activity_attempt_id":"recover-attempt"
38194        });
38195        let path = "/worker/activity-tasks/recover-activity/complete";
38196        let error = |body: Value| Error::Http {
38197            status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
38198            body: body.to_string(),
38199        };
38200        assert_eq!(
38201            worker_fenced_completion_retry_after(&error(response.clone()), path, Some(&request)),
38202            Some(Duration::from_secs(1))
38203        );
38204
38205        for (field, invalid) in [
38206            ("operation", json!("poll_activity_task")),
38207            ("outcome", json!("rejected")),
38208            ("worker_id", json!("another-worker")),
38209            ("task_queue", json!("recover-queue")),
38210            ("retryable", json!(false)),
38211            ("retry_after_seconds", json!(0)),
38212            ("task_id", json!("another-task")),
38213            ("lease_owner", json!("another-worker")),
38214            ("activity_attempt_id", json!("another-attempt")),
38215        ] {
38216            let mut invalid_response = response.clone();
38217            invalid_response[field] = invalid;
38218            assert_eq!(
38219                worker_fenced_completion_retry_after(
38220                    &error(invalid_response),
38221                    path,
38222                    Some(&request)
38223                ),
38224                None,
38225                "must not retry mismatched {field}"
38226            );
38227        }
38228        assert_eq!(
38229            worker_fenced_completion_retry_after(&error(response), path, None),
38230            None
38231        );
38232    }
38233
38234    #[tokio::test]
38235    async fn shutdown_interrupts_fenced_completion_backend_wait() {
38236        let server = MockWorkerServer::start_with_behavior(MockWorkerBehavior {
38237            request_override: Some(activity_completion_remains_unavailable),
38238            ..MockWorkerBehavior::default()
38239        });
38240        let client = Client::builder(server.base_url())
38241            .timeout(Duration::from_secs(2))
38242            .build()
38243            .expect("client");
38244        let stop = Arc::new(AtomicBool::new(false));
38245        let worker = Worker::new(client, "recover-queue")
38246            .worker_id("recover-worker")
38247            .with_storage_admission(Arc::clone(&stop));
38248        let completion = tokio::spawn(async move {
38249            worker
38250                .client
38251                .complete_activity_task(
38252                    "recover-activity",
38253                    "recover-attempt",
38254                    "recover-worker",
38255                    json!("done"),
38256                    DEFAULT_CODEC,
38257                )
38258                .await
38259        });
38260        let path = "/api/worker/activity-tasks/recover-activity/complete";
38261        tokio::time::timeout(Duration::from_secs(2), async {
38262            while server.request_count(path) == 0 {
38263                tokio::time::sleep(Duration::from_millis(10)).await;
38264            }
38265        })
38266        .await
38267        .expect("first completion request");
38268        stop.store(true, Ordering::SeqCst);
38269        let error = tokio::time::timeout(Duration::from_secs(1), completion)
38270            .await
38271            .expect("shutdown must interrupt retry wait")
38272            .expect("completion task")
38273            .expect_err("backend is still unavailable");
38274        assert!(matches!(error, Error::ActivityTaskRejected(rejection) if rejection.status == 503));
38275        assert_eq!(server.request_count(path), 1);
38276    }
38277}