Skip to main content

durable_workflow/
cooperative_cancellation.rs

1use super::*;
2use std::collections::BTreeSet;
3
4const CONTROL_BUDGET: Duration = Duration::from_secs(5);
5const MAX_REFRESH_PAGES: usize = 128;
6
7pub(super) fn assert_cancellation_scope_replay_supported(
8    events: &[HistoryEvent],
9    allow_authoring: bool,
10    allow_delivery: bool,
11) -> Result<()> {
12    if allow_delivery && !allow_authoring {
13        return Err(Error::CancellationScopeExecutionUnavailable);
14    }
15    for event in events {
16        let scope_marker = matches!(
17            event.event_type.as_str(),
18            "CancellationScopeRequested"
19                | "CancellationScopeDeliveryPrepared"
20                | "CancellationScopeDelivered"
21                | "CancellationScopeRequestConflicted"
22        );
23        let scoped_membership = std::iter::once(&event.payload)
24            .chain(
25                ["activity", "timer", "child_workflow"]
26                    .iter()
27                    .filter_map(|name| event.payload.get(name)),
28            )
29            .any(|payload| {
30                payload
31                    .get("cancellation_scope_id")
32                    .is_some_and(|scope| scope.as_str() != Some("root"))
33            });
34        if (scope_marker && !allow_delivery)
35            || (!allow_authoring
36                && (event.event_type == "CancellationScopeOpened" || scoped_membership))
37        {
38            return Err(Error::CancellationScopeExecutionUnavailable);
39        }
40    }
41    Ok(())
42}
43
44/// A delivery acknowledgment bound to one workflow task and durable run.
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct CancellationDeliveryReceipt {
47    pub task_id: String,
48    pub run_id: String,
49    pub delivery: CancellationDelivery,
50}
51
52/// Delivery either commits or parks the parent until canonical child cleanup.
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub enum CancellationDeliveryReply {
55    Delivered(CancellationDeliveryReceipt),
56    /// The current claim is completed. Return to polling without publishing
57    /// completion or failure. The awaited terminal event wakes a successor claim.
58    ClaimReleased {
59        task_id: String,
60        run_id: String,
61    },
62}
63
64/// Successful renewal of the exact workflow-task claim with optional observation.
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct WorkflowTaskHeartbeat {
67    pub task_id: String,
68    pub workflow_task_attempt: u64,
69    pub lease_owner: String,
70    pub lease_expires_at: String,
71    pub run_status: String,
72    pub cancellation_request: Option<CancellationRequest>,
73}
74
75/// One actual protocol 1.20 claim and its original pending observation.
76///
77/// The claim is read-only. Observing a request does not deliver cancellation to
78/// workflow code. Canonical history and a committed delivery are still required.
79#[derive(Clone, Debug)]
80pub struct CooperativeWorkflowTask {
81    task: WorkflowTask,
82    ordered_condition_claim: condition_input_order::Claim,
83    cancellation_request: Option<CancellationRequest>,
84    sticky_snapshot: Option<sticky_worker::StickySnapshot>,
85    verified_payloads: runtime_payloads::VerifiedPayloads,
86}
87
88impl CooperativeWorkflowTask {
89    pub fn task(&self) -> &WorkflowTask {
90        &self.task
91    }
92
93    pub fn cancellation_request(&self) -> Option<&CancellationRequest> {
94        self.cancellation_request.as_ref()
95    }
96
97    /// Renew this exact claim and retain the first observation's identity/token.
98    ///
99    /// A refused or malformed renewal leaves the claim and observation intact.
100    pub async fn heartbeat(&mut self, client: &Client) -> Result<WorkflowTaskHeartbeat> {
101        let receipt = client
102            .heartbeat_workflow_task(&self.task, self.cancellation_request.as_ref())
103            .await?;
104        self.cancellation_request = receipt.cancellation_request.clone();
105        Ok(receipt)
106    }
107}
108
109/// An explicit cooperative poll, including ordinary idle and stop outcomes.
110#[derive(Clone, Debug)]
111pub struct CooperativeWorkflowTaskPoll {
112    pub task: Option<CooperativeWorkflowTask>,
113    pub outcome: WorkerPollOutcome,
114    pub protocol_version: Option<String>,
115    pub server_capabilities: Option<Value>,
116}
117
118/// Optional reason and runtime-owned cleanup limit for a cooperative request.
119#[derive(Clone, Debug, Default, Serialize)]
120pub struct CooperativeCancellationOptions {
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub reason: Option<String>,
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub cleanup_timeout_seconds: Option<u64>,
125}
126
127/// The Server's original request identity and immutable cleanup deadline.
128#[derive(Clone, Debug, PartialEq, Eq)]
129pub struct CancellationRequest {
130    pub request_id: String,
131    pub requested_at: String,
132    pub cleanup_deadline_at: String,
133    pub history_refresh_page_token: Option<String>,
134    pub context: Option<CancellationContext>,
135}
136
137/// Acknowledgment of a request targeting the current durable run.
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct WorkflowCancellationRequest {
140    pub workflow_id: String,
141    pub run_id: String,
142    pub duplicate: bool,
143    pub cancellation_request: CancellationRequest,
144}
145
146/// Cancellation delivered at its committed authored call, with original identity.
147#[derive(Clone, Debug, Error, PartialEq, Eq)]
148#[error("workflow cancellation {request_id} was requested", request_id = .request.request_id)]
149pub struct CooperativeCancellationRequested {
150    pub request: CancellationRequest,
151    pub delivery: CancellationDelivery,
152}
153
154/// A workflow-local cleanup scope. Dropping it restores cancellation checks.
155///
156/// This does not renew or extend the Server's original cleanup deadline.
157#[derive(Debug)]
158pub struct CancellationShield {
159    state: Arc<Mutex<WorkflowState>>,
160}
161
162impl Drop for CancellationShield {
163    fn drop(&mut self) {
164        if let Ok(mut state) = self.state.lock() {
165            state.cancellation_shield_depth = state.cancellation_shield_depth.saturating_sub(1);
166        }
167    }
168}
169
170fn invalid(detail: impl Into<String>) -> Error {
171    Error::InvalidCooperativeCancellation(detail.into())
172}
173
174fn text<'a>(value: &'a Value, field: &str) -> Result<&'a str> {
175    value
176        .get(field)
177        .and_then(Value::as_str)
178        .filter(|text| !text.trim().is_empty())
179        .ok_or_else(|| invalid(format!("{field} must be a non-empty string")))
180}
181
182impl CancellationRequest {
183    /// Why this request was delivered, derived from its canonical context.
184    ///
185    /// An observation without a canonical context is an ordinary request.
186    /// Both causes arrive through [`Error::CooperativeCancellationRequested`].
187    pub fn cause(&self) -> CancellationCause {
188        self.context
189            .as_ref()
190            .map_or(CancellationCause::Requested, CancellationContext::cause)
191    }
192
193    pub(super) fn preserve_observation(&self, current: &Self) -> Result<Self> {
194        self.validate_observation()?;
195        current.validate_observation()?;
196        if self.request_id != current.request_id
197            || DateTime::parse_from_rfc3339(&self.requested_at).unwrap()
198                != DateTime::parse_from_rfc3339(&current.requested_at).unwrap()
199            || DateTime::parse_from_rfc3339(&self.cleanup_deadline_at).unwrap()
200                != DateTime::parse_from_rfc3339(&current.cleanup_deadline_at).unwrap()
201        {
202            return Err(invalid(
203                "observation changed the original request or cleanup deadline",
204            ));
205        }
206        Ok(self.clone())
207    }
208
209    pub(super) fn validate_observation(&self) -> Result<()> {
210        Self::from_observation(&json!({
211            "request_id":self.request_id, "requested_at":self.requested_at,
212            "cleanup_deadline_at":self.cleanup_deadline_at,
213            "history_refresh_page_token":self.history_refresh_page_token,
214        }))
215        .map(|_| ())
216    }
217
218    pub(crate) fn from_observation(value: &Value) -> Result<Self> {
219        let requested_at = text(value, "requested_at")?;
220        let cleanup_deadline_at = text(value, "cleanup_deadline_at")?;
221        let requested = DateTime::parse_from_rfc3339(requested_at)
222            .map_err(|_| invalid("requested_at must be a timestamp with a timezone"))?;
223        let deadline = DateTime::parse_from_rfc3339(cleanup_deadline_at)
224            .map_err(|_| invalid("cleanup_deadline_at must be a timestamp with a timezone"))?;
225        if deadline <= requested {
226            return Err(invalid("cleanup deadline must follow the original request"));
227        }
228        Ok(Self {
229            request_id: text(value, "request_id")?.to_owned(),
230            requested_at: requested_at.to_owned(),
231            cleanup_deadline_at: cleanup_deadline_at.to_owned(),
232            history_refresh_page_token: Some(text(value, "history_refresh_page_token")?.to_owned()),
233            context: None,
234        })
235    }
236}
237
238const REQUEST_EVENT: &str = "CooperativeCancellationRequested";
239const DELIVERY_EVENT: &str = "CooperativeCancellationDelivered";
240const MAX_SEQUENCE: u64 = i64::MAX as u64;
241
242/// The authored durable call where canonical cancellation is delivered.
243#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
244#[serde(rename_all = "snake_case")]
245#[non_exhaustive]
246pub enum CancellationCallKind {
247    Activity,
248    LocalActivity,
249    Timer,
250    Condition,
251    Signal,
252    Child,
253    Parallel,
254    SelectionHandle,
255    ServiceOperation,
256}
257
258/// One committed delivery marker, bound to the original cancellation request.
259#[derive(Clone, Debug, PartialEq, Eq)]
260pub struct CancellationDelivery {
261    pub request_id: String,
262    pub sequence: u64,
263    pub call_kind: CancellationCallKind,
264    pub sequence_span: u64,
265    pub operation_sequence: Option<u64>,
266    pub operation_sequence_span: u64,
267}
268
269fn positive(value: &Value, field: &str, maximum: u64) -> Result<u64> {
270    value
271        .as_u64()
272        .filter(|number| (1..=maximum).contains(number))
273        .ok_or_else(|| {
274            invalid(format!(
275                "{field} must be a positive integer within {maximum}"
276            ))
277        })
278}
279
280impl CancellationDelivery {
281    pub(crate) fn from_payload(value: &Value) -> Result<Self> {
282        let sequence = positive(&value["sequence"], "sequence", MAX_SEQUENCE)?;
283        let call_kind: CancellationCallKind = serde_json::from_value(value["call_kind"].clone())
284            .map_err(|_| invalid("delivery must name a supported durable call kind"))?;
285        let span = positive(
286            value.get("sequence_span").unwrap_or(&json!(1)),
287            "sequence_span",
288            1000,
289        )?;
290        let operation_span = positive(
291            value.get("operation_sequence_span").unwrap_or(&json!(1)),
292            "operation_sequence_span",
293            1000,
294        )?;
295        let operation = value
296            .get("operation_sequence")
297            .filter(|value| !value.is_null());
298        if (call_kind != CancellationCallKind::Parallel && span != 1)
299            || sequence > MAX_SEQUENCE - span
300        {
301            return Err(invalid(
302                "delivery call span is invalid or overflows the portable sequence range",
303            ));
304        }
305        let operation_sequence = if call_kind == CancellationCallKind::SelectionHandle {
306            let base = positive(
307                operation.unwrap_or(&Value::Null),
308                "operation_sequence",
309                MAX_SEQUENCE,
310            )?;
311            if base >= sequence || operation_span > sequence - base {
312                return Err(invalid(
313                    "selection handle must name a complete earlier operation range",
314                ));
315            }
316            Some(base)
317        } else {
318            if operation.is_some() || operation_span != 1 {
319                return Err(invalid(
320                    "only selection handles may name an operation range",
321                ));
322            }
323            None
324        };
325        Ok(Self {
326            request_id: text(value, "workflow_command_id")?.to_owned(),
327            sequence,
328            call_kind,
329            sequence_span: span,
330            operation_sequence,
331            operation_sequence_span: operation_span,
332        })
333    }
334
335    fn range(&self) -> (u64, u64) {
336        self.operation_sequence
337            .map_or((self.sequence, self.sequence_span), |base| {
338                (base, self.operation_sequence_span)
339            })
340    }
341
342    /// Whether a sequence belongs to the canonical interrupted operation range.
343    pub fn interrupts(&self, sequence: u64) -> bool {
344        let (base, span) = self.range();
345        sequence >= base && sequence - base < span
346    }
347}
348
349/// Validated canonical cancellation state for one workflow run.
350///
351/// An observation identifies a request. Only its committed delivery marker
352/// authorizes interruption at an authored call. Earlier results retain priority.
353#[derive(Clone, Debug)]
354pub struct CancellationHistory {
355    pub request: Option<CancellationRequest>,
356    pub delivery: Option<CancellationDelivery>,
357    pub request_index: usize,
358    pub delivery_index: Option<usize>,
359    resolved_before_request: BTreeSet<u64>,
360    latest_condition_sequences_before_request: BTreeMap<u64, u64>,
361    failed_before_request: BTreeSet<u64>,
362    selected_before_request: BTreeSet<(u64, u64)>,
363}
364
365impl CancellationHistory {
366    pub(super) fn bind_commands(
367        &self,
368        mut commands: Vec<RecordedCommand>,
369    ) -> Result<Vec<RecordedCommand>> {
370        let Some(delivery) = &self.delivery else {
371            return Ok(commands);
372        };
373        if delivery.call_kind == CancellationCallKind::Parallel {
374            let index = commands.partition_point(|command| command.sequence() < delivery.sequence);
375            let end = commands.partition_point(|command| {
376                command.sequence() < delivery.sequence + delivery.sequence_span
377            });
378            if commands.get(index).map(RecordedCommand::sequence) != Some(delivery.sequence) {
379                let previous = index
380                    .checked_sub(1)
381                    .map_or(0, |index| commands[index].sequence());
382                if previous.checked_add(1) != Some(delivery.sequence) {
383                    return Err(invalid_recorded_history(
384                        "cooperative_cancellation_call_mismatch",
385                        delivery.sequence,
386                        "next authored parallel group",
387                        "missing earlier call",
388                        "parallel cancellation marker skips an unrecorded authored command",
389                    ));
390                }
391            }
392            let original = commands.drain(index..end).collect();
393            commands.insert(
394                index,
395                RecordedCommand::CancellationGroup {
396                    sequence: delivery.sequence,
397                    span: delivery.sequence_span,
398                    original,
399                },
400            );
401            // Physical condition reopens retain the group's authored identity
402            // but can lie beyond its original sequence span. Bind unresolved
403            // reopens as well, so replay consumes the latest wait at delivery.
404            for command in &mut commands[index + 1..] {
405                let RecordedCommand::ConditionWait {
406                    sequence,
407                    parallel_group_path: Some(path),
408                    ..
409                } = command
410                else {
411                    continue;
412                };
413                if self.resolved_before_request.contains(sequence)
414                    || !path.first().is_some_and(|group| {
415                        group.parallel_group_base_sequence == delivery.sequence
416                            && group.parallel_group_size as u64 == delivery.sequence_span
417                    })
418                {
419                    continue;
420                }
421                *command = RecordedCommand::CancellationBoundary {
422                    sequence: *sequence,
423                    call_kind: CancellationCallKind::Condition,
424                    original: Some(Box::new(command.clone())),
425                };
426            }
427            return Ok(commands);
428        }
429        if !matches!(
430            delivery.call_kind,
431            CancellationCallKind::Activity
432                | CancellationCallKind::Timer
433                | CancellationCallKind::Condition
434                | CancellationCallKind::Signal
435                | CancellationCallKind::Child
436                | CancellationCallKind::SelectionHandle
437                | CancellationCallKind::ServiceOperation
438        ) {
439            return Ok(commands);
440        }
441        let index = commands.partition_point(|command| command.sequence() < delivery.sequence);
442        let original = if commands
443            .get(index)
444            .is_some_and(|command| command.sequence() == delivery.sequence)
445        {
446            Some(Box::new(commands.remove(index)))
447        } else {
448            let previous = index
449                .checked_sub(1)
450                .map_or(0, |index| commands[index].sequence());
451            if previous.checked_add(1) != Some(delivery.sequence) {
452                return Err(invalid_recorded_history(
453                    "cooperative_cancellation_call_mismatch",
454                    delivery.sequence,
455                    "next authored durable call",
456                    "missing earlier call",
457                    "cancellation marker skips an unrecorded authored command",
458                ));
459            }
460            None
461        };
462        commands.insert(
463            index,
464            RecordedCommand::CancellationBoundary {
465                sequence: delivery.sequence,
466                call_kind: delivery.call_kind,
467                original,
468            },
469        );
470        Ok(commands)
471    }
472
473    /// Read canonical markers without replacing original request identity.
474    pub fn from_events(
475        events: &[HistoryEvent],
476        run_id: &str,
477        observation: Option<&CancellationRequest>,
478    ) -> Result<Self> {
479        Self::read(events, run_id, observation).map_err(|error| {
480            invalid_recorded_history(
481                "cooperative_cancellation_history_invalid",
482                0,
483                "one canonical request and matching authored delivery",
484                "invalid cancellation history",
485                &error.to_string(),
486            )
487        })
488    }
489
490    fn read(
491        events: &[HistoryEvent],
492        run_id: &str,
493        observation: Option<&CancellationRequest>,
494    ) -> Result<Self> {
495        if let Some(observed) = observation {
496            let requested = DateTime::parse_from_rfc3339(&observed.requested_at)
497                .map_err(|_| invalid("observed request timestamp is invalid"))?;
498            let deadline = DateTime::parse_from_rfc3339(&observed.cleanup_deadline_at)
499                .map_err(|_| invalid("observed cleanup deadline is invalid"))?;
500            if observed.request_id.trim().is_empty()
501                || deadline <= requested
502                || observed
503                    .history_refresh_page_token
504                    .as_ref()
505                    .is_some_and(|token| token.trim().is_empty())
506            {
507                return Err(invalid(
508                    "observed request identity, deadline or history token is invalid",
509                ));
510            }
511        }
512        let mut state = Self {
513            request: observation.cloned().map(|mut request| {
514                request.context = None;
515                request
516            }),
517            delivery: None,
518            request_index: events.len(),
519            delivery_index: None,
520            resolved_before_request: BTreeSet::new(),
521            latest_condition_sequences_before_request: BTreeMap::new(),
522            failed_before_request: BTreeSet::new(),
523            selected_before_request: BTreeSet::new(),
524        };
525        let mut saw_request = false;
526        for (index, event) in events.iter().enumerate() {
527            if !matches!(event.event_type.as_str(), REQUEST_EVENT | DELIVERY_EVENT) {
528                continue;
529            }
530            let request_id = text(&event.payload, "workflow_command_id")?;
531            let event_run = text(&event.payload, "workflow_run_id")?;
532            if event
533                .raw
534                .get("workflow_command_id")
535                .is_some_and(|value| value.as_str() != Some(request_id))
536                || (!run_id.is_empty() && event_run != run_id)
537            {
538                return Err(invalid(
539                    "canonical event does not match its request or workflow run",
540                ));
541            }
542            if event.event_type == REQUEST_EVENT {
543                if saw_request || state.delivery.is_some() {
544                    return Err(invalid("history must contain one request before delivery"));
545                }
546                let recorded_at = event
547                    .raw
548                    .get("recorded_at")
549                    .or_else(|| event.raw.get("timestamp"))
550                    .and_then(Value::as_str)
551                    .ok_or_else(|| invalid("canonical request lacks its recorded timestamp"))?;
552                let requested = DateTime::parse_from_rfc3339(recorded_at)
553                    .map_err(|_| invalid("canonical request timestamp is invalid"))?;
554                let deadline_text = text(&event.payload, "cleanup_deadline_at")?;
555                let deadline = DateTime::parse_from_rfc3339(deadline_text)
556                    .map_err(|_| invalid("canonical cleanup deadline is invalid"))?;
557                let context = event
558                    .payload
559                    .get("cancellation")
560                    .map(CancellationContext::from_value)
561                    .transpose()?;
562                if let Some(context) = &context {
563                    let local = context.lineage().last().unwrap();
564                    if context.request_id() != request_id
565                        || local.workflow_run_id() != event_run
566                        || event
567                            .payload
568                            .get("workflow_instance_id")
569                            .is_some_and(|instance| {
570                                instance.as_str() != Some(local.workflow_instance_id())
571                            })
572                        || context.deadline() != deadline
573                        || context.requested_at() > requested
574                        || event
575                            .payload
576                            .get("reason")
577                            .is_some_and(|reason| match reason {
578                                Value::Null => context.reason().is_some(),
579                                Value::String(reason) => Some(reason.as_str()) != context.reason(),
580                                _ => true,
581                            })
582                    {
583                        return Err(invalid(
584                            "canonical cancellation context does not match its request event",
585                        ));
586                    }
587                } else if deadline <= requested {
588                    return Err(invalid(
589                        "canonical cleanup deadline must follow the request",
590                    ));
591                }
592                if let Some(observed) = observation {
593                    let observed_deadline =
594                        DateTime::parse_from_rfc3339(&observed.cleanup_deadline_at)
595                            .map_err(|_| invalid("observed cleanup deadline is invalid"))?;
596                    if observed.request_id != request_id || observed_deadline != deadline {
597                        return Err(invalid(
598                            "observation changes the original request or cleanup deadline",
599                        ));
600                    }
601                }
602                if context.is_some() || observation.is_none() {
603                    state.request = Some(CancellationRequest {
604                        request_id: request_id.to_owned(),
605                        requested_at: context.as_ref().map_or_else(
606                            || recorded_at.to_owned(),
607                            |context| {
608                                context
609                                    .requested_at()
610                                    .to_rfc3339_opts(chrono::SecondsFormat::Micros, true)
611                            },
612                        ),
613                        cleanup_deadline_at: deadline_text.to_owned(),
614                        history_refresh_page_token: observation
615                            .and_then(|request| request.history_refresh_page_token.clone()),
616                        context,
617                    });
618                }
619                state.request_index = index;
620                saw_request = true;
621            } else {
622                if !saw_request || state.delivery.is_some() {
623                    return Err(invalid(
624                        "delivery requires one earlier request and one marker",
625                    ));
626                }
627                let delivery = CancellationDelivery::from_payload(&event.payload)?;
628                if state
629                    .request
630                    .as_ref()
631                    .map(|request| request.request_id.as_str())
632                    != Some(delivery.request_id.as_str())
633                {
634                    return Err(invalid("delivery names a different original request"));
635                }
636                if let Some(snapshot) = event.payload.get("cancellation") {
637                    let context = CancellationContext::from_value(snapshot)?;
638                    if state
639                        .request
640                        .as_ref()
641                        .and_then(|request| request.context.as_ref())
642                        != Some(&context)
643                    {
644                        return Err(invalid(
645                            "delivery changes the canonical cancellation context",
646                        ));
647                    }
648                }
649                state.delivery = Some(delivery);
650                state.delivery_index = Some(index);
651            }
652        }
653        if state.request.is_none() {
654            return Ok(state);
655        }
656        let mut condition_occurrences = BTreeMap::new();
657        for event in &events[..state.request_index] {
658            if matches!(
659                event.event_type.as_str(),
660                "SelectionResolved" | "SelectionOperationCancelled"
661            ) {
662                let (base_field, span_field) = if event.event_type == "SelectionResolved" {
663                    ("selection_group_base_sequence", "selection_group_size")
664                } else {
665                    ("member_base_sequence", "member_size")
666                };
667                if let (Ok(base), Ok(span)) = (
668                    positive(&event.payload[base_field], base_field, MAX_SEQUENCE),
669                    positive(&event.payload[span_field], span_field, 1000),
670                ) {
671                    if base <= MAX_SEQUENCE - span {
672                        if event.event_type == "SelectionResolved" {
673                            state.selected_before_request.insert((base, span));
674                        } else {
675                            state.resolved_before_request.extend(base..base + span);
676                        }
677                    }
678                }
679            }
680            let Ok(sequence) = positive(&event.payload["sequence"], "sequence", MAX_SEQUENCE)
681            else {
682                continue;
683            };
684            // Groups deliver at their original authored span. Scalar condition
685            // delivery already names the pending physical sequence directly.
686            if event.event_type == "ConditionWaitOpened"
687                && (event.payload["parallel_group_id"].is_string()
688                    || event.payload["parallel_group_path"]
689                        .as_array()
690                        .is_some_and(|path| !path.is_empty()))
691            {
692                if let Some(occurrence) = event.payload["condition_wait_occurrence_id"].as_str() {
693                    let authored = *condition_occurrences.entry(occurrence).or_insert(sequence);
694                    state
695                        .latest_condition_sequences_before_request
696                        .insert(authored, sequence);
697                }
698            }
699            if matches!(
700                event.event_type.as_str(),
701                "ActivityCompleted"
702                    | "ActivityFailed"
703                    | "ActivityCancelled"
704                    | "ActivityTimedOut"
705                    | "TimerFired"
706                    | "TimerCancelled"
707                    | "ConditionWaitSatisfied"
708                    | "ConditionWaitTimedOut"
709                    | "SignalApplied"
710                    | "ChildRunCompleted"
711                    | "ChildRunFailed"
712                    | "ChildRunCancelled"
713                    | "ChildRunTerminated"
714                    | "ServiceCallCompleted"
715                    | "ServiceCallFailed"
716                    | "ServiceCallCancelled"
717            ) {
718                state.resolved_before_request.insert(sequence);
719                if matches!(
720                    event.event_type.as_str(),
721                    "ActivityFailed"
722                        | "ActivityCancelled"
723                        | "ActivityTimedOut"
724                        | "ChildRunFailed"
725                        | "ChildRunCancelled"
726                        | "ChildRunTerminated"
727                        | "ServiceCallFailed"
728                        | "ServiceCallCancelled"
729                ) {
730                    state.failed_before_request.insert(sequence);
731                }
732            }
733        }
734        if let Some(delivery) = &state.delivery {
735            let (base, span) = delivery.range();
736            if !state.range_eligible(base, span) {
737                return Err(invalid(
738                    "delivery cannot replace an earlier committed result",
739                ));
740            }
741        }
742        Ok(state)
743    }
744
745    fn range_eligible(&self, sequence: u64, span: u64) -> bool {
746        (1..=1000).contains(&span)
747            && sequence > 0
748            && sequence <= MAX_SEQUENCE - span
749            && !(sequence..sequence + span).all(|sequence| {
750                let latest = self
751                    .latest_condition_sequences_before_request
752                    .get(&sequence)
753                    .unwrap_or(&sequence);
754                self.resolved_before_request.contains(latest)
755            })
756            && !(sequence..sequence + span)
757                .any(|sequence| self.failed_before_request.contains(&sequence))
758            && !self.selected_before_request.contains(&(sequence, span))
759    }
760
761    /// Whether an unresolved authored call may deliver the pending request.
762    pub fn eligible(&self, sequence: u64, span: u64) -> bool {
763        self.request.is_some() && self.delivery.is_none() && self.range_eligible(sequence, span)
764    }
765}
766
767impl WorkflowState {
768    fn next_cancellation_sequence(&self) -> Result<u64> {
769        self.recorded_commands.get(self.command_cursor).map_or_else(
770            || {
771                self.max_recorded_sequence()
772                    .checked_add(self.commands.len() as u64)
773                    .and_then(|sequence| sequence.checked_add(1))
774                    .filter(|sequence| *sequence < MAX_SEQUENCE)
775                    .ok_or_else(|| invalid("authored cancellation sequence overflowed"))
776            },
777            |command| Ok(command.sequence()),
778        )
779    }
780
781    fn prepare_cancellation_delivery(&mut self, delivery: CancellationDelivery) -> Result<bool> {
782        if !self.cancellation_delivery_enabled || self.cancellation_shield_depth > 0 {
783            return Ok(false);
784        }
785        self.assert_root_cancellation_membership()?;
786        if self.cancellation_delivery_intent.is_some() {
787            self.matched_recorded_pending = true;
788            return Ok(true);
789        }
790        let (base, span) = delivery.range();
791        if !self.cancellation_history.eligible(base, span) {
792            return Ok(false);
793        }
794        let payload = json!({
795            "workflow_command_id":delivery.request_id, "sequence":delivery.sequence,
796            "call_kind":delivery.call_kind, "sequence_span":delivery.sequence_span,
797            "operation_sequence":delivery.operation_sequence,
798            "operation_sequence_span":delivery.operation_sequence_span,
799        });
800        CancellationDelivery::from_payload(&payload)?;
801        self.cancellation_delivery_command_count = self.commands.len();
802        self.cancellation_delivery_intent = Some(delivery);
803        self.matched_recorded_pending = true;
804        Ok(true)
805    }
806
807    fn assert_root_cancellation_membership(&self) -> Result<()> {
808        if self
809            .scope_delivery
810            .as_ref()
811            .is_some_and(|replay| replay.active_scope != "root")
812        {
813            return Err(Error::CancellationScopeExecutionUnavailable);
814        }
815        Ok(())
816    }
817
818    pub(super) fn prepare_scalar_cancellation(
819        &mut self,
820        index: usize,
821        kind: CancellationCallKind,
822        group_path: &[ParallelGroupMetadata],
823    ) -> Result<bool> {
824        if self.prepare_scalar_scope_cancellation(index, kind, group_path)? {
825            return Ok(true);
826        }
827        if !self.cancellation_delivery_enabled || self.cancellation_shield_depth > 0 {
828            return Ok(false);
829        }
830        // Group leaves validate their recorded calls before the enclosing
831        // parallel/select future suspends. They never choose scalar delivery.
832        if !group_path.is_empty() && self.cancellation_delivery_intent.is_none() {
833            return Ok(false);
834        }
835        let Some(request) = self.cancellation_history.request.as_ref() else {
836            return Ok(false);
837        };
838        let sequence = self.recorded_commands.get(index).map_or_else(
839            || self.next_cancellation_sequence(),
840            |command| Ok(command.sequence()),
841        )?;
842        let pending = self.prepare_cancellation_delivery(CancellationDelivery {
843            request_id: request.request_id.clone(),
844            sequence,
845            call_kind: kind,
846            sequence_span: 1,
847            operation_sequence: None,
848            operation_sequence_span: 1,
849        })?;
850        if pending && index < self.recorded_commands.len() {
851            self.command_cursor = index + 1;
852        }
853        Ok(pending)
854    }
855
856    pub(super) fn prepare_group_cancellation(
857        &mut self,
858        descriptors: &[ParallelDescriptor],
859    ) -> Result<()> {
860        let Some(request) = self.cancellation_history.request.as_ref() else {
861            return Ok(());
862        };
863        let Some(group) = descriptors.first().and_then(|leaf| leaf.group_path.first()) else {
864            return Ok(());
865        };
866        self.prepare_cancellation_delivery(CancellationDelivery {
867            request_id: request.request_id.clone(),
868            sequence: group.parallel_group_base_sequence,
869            call_kind: CancellationCallKind::Parallel,
870            sequence_span: descriptors.len() as u64,
871            operation_sequence: None,
872            operation_sequence_span: 1,
873        })?;
874        Ok(())
875    }
876
877    pub(super) fn prepare_selection_handle_cancellation(
878        &mut self,
879        handle: &DurableOperationHandle,
880    ) -> Result<bool> {
881        if !self.cancellation_delivery_enabled || self.cancellation_shield_depth > 0 {
882            return Ok(false);
883        }
884        validate_selection_delivery_handle(self, handle)?;
885        if !self
886            .cancellation_history
887            .eligible(handle.base_sequence, handle.size as u64)
888        {
889            return Ok(false);
890        }
891        let request_id = self
892            .cancellation_history
893            .request
894            .as_ref()
895            .expect("eligible request")
896            .request_id
897            .clone();
898        self.prepare_cancellation_delivery(CancellationDelivery {
899            request_id,
900            sequence: self.next_cancellation_sequence()?,
901            call_kind: CancellationCallKind::SelectionHandle,
902            sequence_span: 1,
903            operation_sequence: Some(handle.base_sequence),
904            operation_sequence_span: handle.size as u64,
905        })
906    }
907
908    pub(super) fn expand_cancellation_group(
909        &mut self,
910        descriptors: &[ParallelDescriptor],
911    ) -> Result<()> {
912        let Some(RecordedCommand::CancellationGroup {
913            sequence,
914            span,
915            original,
916        }) = self.recorded_commands.get(self.command_cursor).cloned()
917        else {
918            return Ok(());
919        };
920        self.validate_cancellation_call(
921            sequence,
922            CancellationCallKind::Parallel,
923            CancellationCallKind::Parallel,
924        )?;
925        if descriptors.len() as u64 != span {
926            return Err(invalid_recorded_history(
927                "cooperative_cancellation_call_mismatch",
928                sequence,
929                &format!("parallel group with {span} durable leaves"),
930                &format!("{} durable leaves", descriptors.len()),
931                "authored parallel group span differs from its committed cancellation",
932            ));
933        }
934        let mut original = original.into_iter().peekable();
935        let mut leaves = Vec::with_capacity(descriptors.len());
936        for descriptor in descriptors {
937            let leaf_sequence = sequence + descriptor.offset as u64;
938            let command = if original.peek().map(RecordedCommand::sequence) == Some(leaf_sequence) {
939                original.next()
940            } else {
941                None
942            };
943            if self
944                .cancellation_history
945                .resolved_before_request
946                .contains(&leaf_sequence)
947            {
948                let command = command.ok_or_else(|| {
949                    invalid_recorded_history(
950                        "cooperative_cancellation_call_mismatch",
951                        leaf_sequence,
952                        "recorded earlier result",
953                        "missing durable call",
954                        "parallel cancellation cannot discard an earlier committed result",
955                    )
956                })?;
957                leaves.push(command);
958                continue;
959            }
960            let kind = match &descriptor.operation {
961                ParallelOperation::Activity { .. } => CancellationCallKind::Activity,
962                ParallelOperation::ChildWorkflow { .. } => CancellationCallKind::Child,
963                ParallelOperation::Timer(_) => CancellationCallKind::Timer,
964                ParallelOperation::Signal(_) => CancellationCallKind::Signal,
965                ParallelOperation::Condition { .. } => CancellationCallKind::Condition,
966                ParallelOperation::Group(_) => unreachable!("descriptor is a durable leaf"),
967            };
968            leaves.push(RecordedCommand::CancellationBoundary {
969                sequence: leaf_sequence,
970                call_kind: kind,
971                original: command.map(Box::new),
972            });
973        }
974        self.recorded_commands
975            .splice(self.command_cursor..=self.command_cursor, leaves);
976        Ok(())
977    }
978
979    pub(super) fn cancellation_error(&mut self) -> Error {
980        if self.cancellation_consumed {
981            self.start_cancellation_clock();
982        }
983        match (
984            &self.cancellation_history.request,
985            &self.cancellation_history.delivery,
986        ) {
987            (Some(request), Some(delivery)) => {
988                let mut request = request.clone();
989                request.context = request.context.map(|context| {
990                    context.with_replay(cancellation_replay_clock::active_binding())
991                });
992                Error::CooperativeCancellationRequested(CooperativeCancellationRequested {
993                    request,
994                    delivery: delivery.clone(),
995                })
996            }
997            _ => Error::WorkflowCancellationRequested(WorkflowCancellationRequested),
998        }
999    }
1000
1001    fn validate_cancellation_call(
1002        &self,
1003        sequence: u64,
1004        kind: CancellationCallKind,
1005        recorded_kind: CancellationCallKind,
1006    ) -> Result<()> {
1007        if kind != recorded_kind || self.cancellation_shield_depth > 0 {
1008            return Err(invalid_recorded_history(
1009                "cooperative_cancellation_call_mismatch",
1010                sequence,
1011                "matching unshielded authored call",
1012                &format!("{kind:?}"),
1013                "committed cancellation call kind or cleanup scope changed",
1014            ));
1015        }
1016        Ok(())
1017    }
1018
1019    pub(super) fn cancellation_replay_command(
1020        &mut self,
1021        index: usize,
1022        kind: CancellationCallKind,
1023    ) -> Result<Option<RecordedCommand>> {
1024        match self.recorded_commands.get(index).cloned() {
1025            Some(RecordedCommand::CancellationBoundary {
1026                sequence,
1027                call_kind,
1028                original,
1029            }) => {
1030                if let Some(original) = original {
1031                    return Ok(Some(*original));
1032                }
1033                self.replay_scope_cancellation_at(index, kind)?;
1034                self.assert_root_cancellation_membership()?;
1035                self.validate_cancellation_call(sequence, kind, call_kind)?;
1036                self.cancellation_consumed = true;
1037                self.cancel_requested = true;
1038                self.command_cursor = index + 1;
1039                Err(self.cancellation_error())
1040            }
1041            command => Ok(command),
1042        }
1043    }
1044
1045    pub(super) fn replay_cancellation_at(
1046        &mut self,
1047        index: usize,
1048        kind: CancellationCallKind,
1049    ) -> Result<()> {
1050        self.replay_scope_cancellation_at(index, kind)?;
1051        if let Some(RecordedCommand::CancellationBoundary {
1052            sequence,
1053            call_kind,
1054            ..
1055        }) = self.recorded_commands.get(index)
1056        {
1057            self.assert_root_cancellation_membership()?;
1058            self.validate_cancellation_call(*sequence, kind, *call_kind)?;
1059            self.cancellation_consumed = true;
1060            self.cancel_requested = true;
1061            self.command_cursor = index + 1;
1062            return Err(self.cancellation_error());
1063        }
1064        Ok(())
1065    }
1066
1067    pub(super) fn replay_selection_handle_cancellation(
1068        &mut self,
1069        handle: &DurableOperationHandle,
1070    ) -> Result<()> {
1071        let Some(RecordedCommand::CancellationBoundary {
1072            sequence,
1073            call_kind,
1074            original,
1075        }) = self.recorded_commands.get(self.command_cursor)
1076        else {
1077            return Ok(());
1078        };
1079        self.validate_cancellation_call(
1080            *sequence,
1081            CancellationCallKind::SelectionHandle,
1082            *call_kind,
1083        )?;
1084        let delivery = self
1085            .cancellation_history
1086            .delivery
1087            .as_ref()
1088            .expect("bound canonical delivery");
1089        if original.is_some()
1090            || delivery.operation_sequence != Some(handle.base_sequence)
1091            || delivery.operation_sequence_span != handle.size as u64
1092        {
1093            return Err(invalid_recorded_history(
1094                "cooperative_cancellation_call_mismatch",
1095                *sequence,
1096                "selection handle for the committed operation range",
1097                &format!("{}:{}", handle.base_sequence, handle.size),
1098                "cancellation delivery targets a different authored selection member",
1099            ));
1100        }
1101        validate_selection_delivery_handle(self, handle)?;
1102        self.replay_cancellation_at(self.command_cursor, CancellationCallKind::SelectionHandle)
1103    }
1104}
1105
1106impl WorkflowContext {
1107    /// Original immutable metadata, visible only at committed delivery.
1108    pub fn cancellation_context(&self) -> Result<Option<CancellationContext>> {
1109        let state = self
1110            .state
1111            .lock()
1112            .map_err(|_| Error::WorkflowStatePoisoned)?;
1113        Ok(
1114            if state.cancellation_consumed && self.cancellation_scope_id == "root" {
1115                state
1116                    .cancellation_history
1117                    .request
1118                    .as_ref()
1119                    .and_then(|request| request.context.clone())
1120                    .map(|context| context.with_replay(Some(Arc::downgrade(&self.state))))
1121            } else {
1122                None
1123            },
1124        )
1125    }
1126
1127    /// Shield explicit cleanup from repeated cancellation checks.
1128    ///
1129    /// Keep the returned guard alive across cleanup awaits. Scopes can nest.
1130    /// The Server retains and enforces the original immutable cleanup deadline.
1131    pub fn cancellation_shield(&self) -> Result<CancellationShield> {
1132        let mut state = self
1133            .state
1134            .lock()
1135            .map_err(|_| Error::WorkflowStatePoisoned)?;
1136        state.cancellation_shield_depth = state
1137            .cancellation_shield_depth
1138            .checked_add(1)
1139            .ok_or_else(|| invalid("cancellation shield nesting overflowed"))?;
1140        Ok(CancellationShield {
1141            state: Arc::clone(&self.state),
1142        })
1143    }
1144}
1145
1146pub(super) fn supports_protocol(version: &str) -> bool {
1147    let Some((major, minor)) = version.split_once('.') else {
1148        return false;
1149    };
1150    major == "1"
1151        && !minor.is_empty()
1152        && minor.bytes().all(|byte| byte.is_ascii_digit())
1153        && minor.parse::<u64>().is_ok_and(|minor| minor >= 20)
1154}
1155
1156fn require_discovery(info: &Value) -> Result<()> {
1157    let protocol = &info["worker_protocol"];
1158    if protocol["server_capabilities"]["cooperative_cancellation"].as_bool() != Some(true)
1159        || !protocol["version"].as_str().is_some_and(supports_protocol)
1160    {
1161        return Err(Error::CooperativeCancellationUnavailable(
1162            "runtime discovery must explicitly advertise support and compatible protocol 1.20"
1163                .to_string(),
1164        ));
1165    }
1166    Ok(())
1167}
1168
1169fn acknowledgment(
1170    value: &Value,
1171    workflow_id: &str,
1172    selected_run: Option<&str>,
1173) -> Result<WorkflowCancellationRequest> {
1174    if value["accepted"].as_bool() != Some(true)
1175        || text(value, "workflow_id")? != workflow_id
1176        || selected_run.is_some_and(|run| value["run_id"].as_str() != Some(run))
1177    {
1178        return Err(invalid(
1179            "acknowledgment does not match the accepted workflow/run request",
1180        ));
1181    }
1182    Ok(WorkflowCancellationRequest {
1183        workflow_id: workflow_id.to_owned(),
1184        run_id: text(value, "run_id")?.to_owned(),
1185        duplicate: value["duplicate"]
1186            .as_bool()
1187            .ok_or_else(|| invalid("duplicate must be a boolean"))?,
1188        cancellation_request: CancellationRequest::from_observation(
1189            &value["cancellation_request"],
1190        )?,
1191    })
1192}
1193
1194impl Client {
1195    /// Report a stopped and dropped remote callback under its original claim.
1196    ///
1197    /// Call only after callback execution has ended. This explicit protocol 1.20
1198    /// operation preserves the original cancellation request and grants no lease
1199    /// or result publication authority. The request has one five-second budget.
1200    pub async fn acknowledge_activity_cancellation(
1201        &self,
1202        task_id: &str,
1203        activity_attempt_id: &str,
1204        lease_owner: &str,
1205        request_id: &str,
1206    ) -> Result<Value> {
1207        if [task_id, activity_attempt_id, lease_owner, request_id]
1208            .iter()
1209            .any(|value| value.trim().is_empty() || value.len() > 255)
1210        {
1211            return Err(invalid(
1212                "activity stop receipt requires bounded original claim and request identities",
1213            ));
1214        }
1215        tokio::time::timeout(CONTROL_BUDGET, async {
1216            let value: Value = activity_task_response(
1217                self.request_json(
1218                    reqwest::Method::POST,
1219                    &format!("/worker/activity-tasks/{}/acknowledge-cancellation", percent_encode_path_segment(task_id)),
1220                    RequestProtocol::Worker("1.20"),
1221                    Some(&json!({"activity_attempt_id":activity_attempt_id,"lease_owner":lease_owner,"request_id":request_id})),
1222                ).await,
1223                "acknowledge-cancellation", task_id, activity_attempt_id,
1224            )?;
1225            if value["task_id"].as_str() != Some(task_id)
1226                || value["activity_attempt_id"].as_str() != Some(activity_attempt_id)
1227                || value["lease_owner"].as_str() != Some(lease_owner)
1228                || value["request_id"].as_str() != Some(request_id)
1229                || value["acknowledged"].as_bool() != Some(true)
1230                || value["duplicate"].as_bool().is_none()
1231                || value.get("reason") != Some(&Value::Null)
1232                || value["heartbeat_recorded"].as_bool() != Some(false)
1233                || text(&value, "history_event_id").is_err()
1234            {
1235                return Err(invalid("activity callback-stop acknowledgment did not prove the original claim and receipt"));
1236            }
1237            Ok(value)
1238        }).await.map_err(|_| Error::Timeout)?
1239    }
1240
1241    /// Observe an exact activity attempt without renewing its lease or progress.
1242    ///
1243    /// This explicit worker-protocol 1.20 operation has one five-second budget.
1244    /// A pending workflow request alone does not cancel an activity. Its reply
1245    /// reports the runtime's current continuation authority after delivery.
1246    pub async fn activity_task_status(
1247        &self,
1248        task_id: &str,
1249        activity_attempt_id: &str,
1250        lease_owner: &str,
1251    ) -> Result<Value> {
1252        if [task_id, activity_attempt_id, lease_owner]
1253            .iter()
1254            .any(|value| value.trim().is_empty())
1255        {
1256            return Err(invalid("activity observation requires the actual claim"));
1257        }
1258        tokio::time::timeout(CONTROL_BUDGET, async {
1259            let value: Value = activity_task_response(
1260                self.request_json(
1261                    reqwest::Method::POST,
1262                    &format!(
1263                        "/worker/activity-tasks/{}/status",
1264                        percent_encode_path_segment(task_id)
1265                    ),
1266                    RequestProtocol::Worker("1.20"),
1267                    Some(&json!({
1268                        "activity_attempt_id":activity_attempt_id,"lease_owner":lease_owner
1269                    })),
1270                )
1271                .await,
1272                "status",
1273                task_id,
1274                activity_attempt_id,
1275            )?;
1276            if value["task_id"].as_str() != Some(task_id)
1277                || value["activity_attempt_id"].as_str() != Some(activity_attempt_id)
1278                || value["lease_owner"].as_str() != Some(lease_owner)
1279                || value["can_continue"].as_bool().is_none()
1280                || value["cancel_requested"].as_bool().is_none()
1281                || value["heartbeat_recorded"].as_bool() != Some(false)
1282            {
1283                return Err(invalid(
1284                    "activity observation did not acknowledge the exact claim",
1285                ));
1286            }
1287            Ok(value)
1288        })
1289        .await
1290        .map_err(|_| Error::Timeout)?
1291    }
1292
1293    /// Acquire a claim with protocol 1.20 and retain its pending observation.
1294    ///
1295    /// The Server must have admitted a capable worker registration. This method
1296    /// registers no capability and does not change ordinary [`Worker`] polling.
1297    /// It never substitutes a worker ID for a missing lease owner or invents a
1298    /// task attempt. Poll retries reuse one request ID. Poll and history loading
1299    /// share one long-poll budget plus five seconds, with at most 128 pages.
1300    /// Managed Workers separately budget claimed hydration using the Client
1301    /// timeout while maintaining task authority.
1302    pub async fn poll_cooperative_workflow_task(
1303        &self,
1304        worker_id: &str,
1305        task_queue: &str,
1306        timeout: Duration,
1307    ) -> Result<CooperativeWorkflowTaskPoll> {
1308        self.poll_cooperative_workflow_task_with_request_id(
1309            worker_id,
1310            task_queue,
1311            timeout,
1312            &unique_request_id("rust-workflow-poll"),
1313            1,
1314            false,
1315        )
1316        .await
1317    }
1318
1319    async fn poll_cooperative_workflow_task_with_request_id(
1320        &self,
1321        worker_id: &str,
1322        task_queue: &str,
1323        timeout: Duration,
1324        poll_request_id: &str,
1325        transport_retries: usize,
1326        managed: bool,
1327    ) -> Result<CooperativeWorkflowTaskPoll> {
1328        if worker_id.trim().is_empty()
1329            || task_queue.trim().is_empty()
1330            || poll_request_id.trim().is_empty()
1331        {
1332            return Err(invalid(
1333                "cooperative polling requires a worker and task queue",
1334            ));
1335        }
1336        let budget = timeout
1337            .checked_add(CONTROL_BUDGET)
1338            .ok_or_else(|| invalid("cooperative poll timeout exceeds its supported budget"))?;
1339        let body = json!({
1340            "worker_id":worker_id, "task_queue":task_queue,
1341            "poll_request_id":poll_request_id,
1342            "timeout_seconds":long_poll_timeout_seconds(timeout),
1343            "history_page_size":WORKFLOW_HISTORY_PAGE_SIZE,
1344            "build_id":self.worker_build_id,
1345        });
1346        let deadline = tokio::time::Instant::now() + budget;
1347        let mut value: Value = tokio::time::timeout(
1348            budget,
1349            self.poll_request_json_unresolved(
1350                "/worker/workflow-tasks/poll",
1351                RequestProtocol::Worker("1.20"),
1352                &body,
1353                budget,
1354                transport_retries,
1355            ),
1356        )
1357        .await
1358        .map_err(|_| Error::Timeout)??;
1359        let hydration =
1360            workflow_hydration::HydrationClaim::from_poll(&value, worker_id, &self.namespace)?
1361                .map(workflow_hydration::HydrationClaim::cooperative);
1362        let loading = workflow_hydration::HydrationClaim::protect(hydration, self, async {
1363            let mut verified_payloads = runtime_payloads::VerifiedPayloads::new();
1364            self.resolve_runtime_payloads_with_cache(
1365                &mut value,
1366                "/worker/workflow-tasks/poll",
1367                RequestProtocol::Worker("1.20"),
1368                &mut verified_payloads,
1369            )
1370            .await?;
1371            let mut response: PollWorkflowTaskResponse = serde_json::from_value(value.clone())
1372                .map_err(|_| invalid("cooperative poll returned a malformed envelope or task"))?;
1373            let outcome = response.outcome();
1374            let task = if let Some(task) = response.task.take() {
1375                let (owner, _) = cancellation_claim(&task)?;
1376                if owner != worker_id
1377                    || value["task"]["workflow_task_attempt"].as_u64()
1378                        != Some(task.workflow_task_attempt)
1379                {
1380                    return Err(invalid(
1381                        "cooperative poll did not return the caller's actual owner and attempt",
1382                    ));
1383                }
1384                let cancellation_request = match value["task"].get("cancellation_request") {
1385                    None | Some(Value::Null) => None,
1386                    Some(observation) => Some(CancellationRequest::from_observation(observation)?),
1387                };
1388                let mut claim = CooperativeWorkflowTask {
1389                    task,
1390                    ordered_condition_claim: condition_input_order::read_claim(&value["task"])
1391                        .map_err(|_| {
1392                            invalid(
1393                                "cooperative poll returned an invalid condition admission snapshot",
1394                            )
1395                        })?,
1396                    cancellation_request,
1397                    sticky_snapshot: None,
1398                    verified_payloads,
1399                };
1400                if self.sticky_cache.is_some() {
1401                    claim.sticky_snapshot = Some(
1402                        self.load_sticky_history(&mut claim.task, &value["task"], worker_id)
1403                            .await?,
1404                    );
1405                } else {
1406                    self.load_cooperative_claim_history(&mut claim).await?;
1407                }
1408                Some(claim)
1409            } else {
1410                None
1411            };
1412            Ok(CooperativeWorkflowTaskPoll {
1413                task,
1414                outcome,
1415                protocol_version: response.protocol_version,
1416                server_capabilities: response.server_capabilities,
1417            })
1418        });
1419        let (mut loaded, pending) = if managed {
1420            loading.await?
1421        } else {
1422            tokio::time::timeout_at(deadline, loading)
1423                .await
1424                .map_err(|_| Error::Timeout)??
1425        };
1426        if let (Some(claim), Some(pending)) = (loaded.task.as_mut(), pending) {
1427            claim.cancellation_request = Some(pending);
1428        }
1429        if loaded.task.is_some() {
1430            self.worker_dispatch_metrics.ready_age(
1431                "workflow",
1432                task_queue,
1433                metrics::ready_age_from_poll(&value),
1434            );
1435        }
1436        Ok(loaded)
1437    }
1438
1439    async fn load_cooperative_claim_history(
1440        &self,
1441        claim: &mut CooperativeWorkflowTask,
1442    ) -> Result<()> {
1443        let (owner, _) = cancellation_claim(&claim.task)?;
1444        let owner = owner.to_owned();
1445        let mut token = claim.task.next_history_page_token.clone();
1446        let mut seen = BTreeSet::new();
1447        while let Some(current) = token.take() {
1448            if current.trim().is_empty()
1449                || seen.len() >= MAX_REFRESH_PAGES
1450                || !seen.insert(current.clone())
1451            {
1452                return Err(invalid(
1453                    "claim history exceeded its page bound or returned an invalid/repeated token",
1454                ));
1455            }
1456            let body = json!({
1457                "lease_owner":owner,"workflow_task_attempt":claim.task.workflow_task_attempt,
1458                "next_history_page_token":current,"history_page_size":WORKFLOW_HISTORY_PAGE_SIZE,
1459            });
1460            let value: Value = self
1461                .request_json(
1462                    reqwest::Method::POST,
1463                    &format!(
1464                        "/worker/workflow-tasks/{}/history",
1465                        percent_encode_path_segment(&claim.task.task_id)
1466                    ),
1467                    RequestProtocol::Worker("1.20"),
1468                    Some(&body),
1469                )
1470                .await?;
1471            if value["task_id"].as_str() != Some(claim.task.task_id.as_str())
1472                || value["workflow_task_attempt"].as_u64() != Some(claim.task.workflow_task_attempt)
1473            {
1474                return Err(invalid(
1475                    "claim history changed the selected task or attempt",
1476                ));
1477            }
1478            let events = value["history_events"]
1479                .as_array()
1480                .ok_or_else(|| invalid("claim history page must contain an event array"))?;
1481            if events.len() > WORKFLOW_HISTORY_PAGE_SIZE {
1482                return Err(invalid(
1483                    "claim history page exceeds its requested event limit",
1484                ));
1485            }
1486            token = match value.get("next_history_page_token") {
1487                Some(Value::Null) => None,
1488                Some(Value::String(next)) if !next.trim().is_empty() && !events.is_empty() => {
1489                    Some(next.clone())
1490                }
1491                _ => return Err(invalid("claim history page token or progress is invalid")),
1492            };
1493            let page: WorkflowTaskHistoryPage = serde_json::from_value(value)
1494                .map_err(|_| invalid("claim history page contains malformed fields or events"))?;
1495            if page
1496                .history_events
1497                .iter()
1498                .any(|event| event.event_type.trim().is_empty())
1499            {
1500                return Err(invalid("claim history event type must be non-empty"));
1501            }
1502            claim.task.append_history_page(page);
1503        }
1504        Ok(())
1505    }
1506
1507    /// Renew the exact selected workflow-task lease using worker protocol 1.20.
1508    ///
1509    /// The reply must acknowledge the actual task, owner and attempt. Renewal
1510    /// neither commits cancellation delivery nor extends its cleanup deadline.
1511    pub async fn heartbeat_workflow_task(
1512        &self,
1513        task: &WorkflowTask,
1514        original: Option<&CancellationRequest>,
1515    ) -> Result<WorkflowTaskHeartbeat> {
1516        self.heartbeat_workflow_task_with_protocol(task, original, "1.20")
1517            .await
1518    }
1519
1520    pub(super) async fn heartbeat_workflow_task_with_protocol(
1521        &self,
1522        task: &WorkflowTask,
1523        original: Option<&CancellationRequest>,
1524        protocol: &'static str,
1525    ) -> Result<WorkflowTaskHeartbeat> {
1526        let (owner, _) = cancellation_claim(task)?;
1527        if let Some(original) = original {
1528            original.validate_observation()?;
1529        }
1530        tokio::time::timeout(CONTROL_BUDGET, async {
1531            let response: Value = self.request_json(
1532                reqwest::Method::POST,
1533                &format!("/worker/workflow-tasks/{}/heartbeat", percent_encode_path_segment(&task.task_id)),
1534                RequestProtocol::Worker(protocol),
1535                Some(&json!({"lease_owner":owner,"workflow_task_attempt":task.workflow_task_attempt})),
1536            ).await?;
1537            if response["task_id"].as_str() != Some(task.task_id.as_str())
1538                || response["workflow_task_attempt"].as_u64() != Some(task.workflow_task_attempt)
1539                || response["lease_owner"].as_str() != Some(owner)
1540                || response["renewed"].as_bool() != Some(true)
1541                || response.get("reason") != Some(&Value::Null)
1542                || response["task_status"].as_str() != Some("leased")
1543            {
1544                return Err(invalid("workflow heartbeat did not acknowledge the exact leased claim"));
1545            }
1546            let expires = text(&response, "lease_expires_at")?;
1547            DateTime::parse_from_rfc3339(expires).map_err(|_| invalid("workflow heartbeat lease expiry must include a timezone"))?;
1548            let run_status = text(&response, "run_status")?;
1549            if !matches!(run_status, "pending" | "running" | "waiting") {
1550                return Err(invalid("workflow heartbeat did not acknowledge an active run"));
1551            }
1552            let cancellation_request = match response.get("cancellation_request") {
1553                None | Some(Value::Null) if original.is_none() => None,
1554                None | Some(Value::Null) => return Err(invalid("workflow heartbeat omitted its original pending request")),
1555                Some(observation) => {
1556                    let current = CancellationRequest::from_observation(observation)?;
1557                    Some(match original {
1558                        Some(original) => original.preserve_observation(&current)?,
1559                        None => current,
1560                    })
1561                },
1562            };
1563            Ok(WorkflowTaskHeartbeat {
1564                task_id:task.task_id.clone(), workflow_task_attempt:task.workflow_task_attempt,
1565                lease_owner:owner.to_owned(), lease_expires_at:expires.to_owned(),
1566                run_status:run_status.to_owned(), cancellation_request,
1567            })
1568        }).await.map_err(|_| Error::Timeout)?
1569    }
1570
1571    /// Commit cooperative delivery on the exact selected workflow-task claim.
1572    ///
1573    /// This explicit worker-protocol 1.20 operation renews no lease and advertises
1574    /// no worker capability. The Server requires a previously admitted capable
1575    /// claim. Reload canonical history before exposing cancellation to workflow
1576    /// code, including when an acknowledgment is lost. A cancellation wait explicitly
1577    /// releases the claim and must return the worker to polling.
1578    pub async fn deliver_workflow_cancellation(
1579        &self,
1580        task: &WorkflowTask,
1581        delivery: &CancellationDelivery,
1582    ) -> Result<CancellationDeliveryReply> {
1583        let (owner, run_id) = cancellation_claim(task)?;
1584        let body = json!({
1585            "lease_owner":owner, "workflow_task_attempt":task.workflow_task_attempt,
1586            "request_id":delivery.request_id, "sequence":delivery.sequence,
1587            "call_kind":delivery.call_kind, "sequence_span":delivery.sequence_span,
1588            "operation_sequence":delivery.operation_sequence,
1589            "operation_sequence_span":delivery.operation_sequence_span
1590        });
1591        let mut payload = body.clone();
1592        payload["workflow_command_id"] = json!(delivery.request_id);
1593        if CancellationDelivery::from_payload(&payload)? != *delivery {
1594            return Err(invalid(
1595                "delivery must name a valid authored operation range",
1596            ));
1597        }
1598        tokio::time::timeout(CONTROL_BUDGET, async {
1599            let path = format!(
1600                "/worker/workflow-tasks/{}/deliver-cancellation",
1601                percent_encode_path_segment(&task.task_id)
1602            );
1603            let response: Value = self
1604                .request_json(
1605                    reqwest::Method::POST,
1606                    &path,
1607                    RequestProtocol::Worker("1.20"),
1608                    Some(&body),
1609                )
1610                .await?;
1611            if response["delivered"].as_bool() == Some(false)
1612                && match response["reason"].as_str() {
1613                    Some("cancellation_waiting_for_service_operation") => {
1614                        delivery.call_kind == CancellationCallKind::ServiceOperation
1615                    }
1616                    Some("cancellation_waiting_for_child") => matches!(
1617                        delivery.call_kind,
1618                        CancellationCallKind::Child
1619                            | CancellationCallKind::Parallel
1620                            | CancellationCallKind::SelectionHandle
1621                    ),
1622                    Some("cancellation_waiting_for_activity") => matches!(
1623                        delivery.call_kind,
1624                        CancellationCallKind::Activity
1625                            | CancellationCallKind::LocalActivity
1626                            | CancellationCallKind::Parallel
1627                            | CancellationCallKind::SelectionHandle
1628                    ),
1629                    _ => false,
1630                }
1631                && response["claim_released"].as_bool() == Some(true)
1632                && response["task_id"].as_str() == Some(task.task_id.as_str())
1633                && response["workflow_run_id"].as_str() == Some(run_id)
1634                && [
1635                    "request_id",
1636                    "sequence",
1637                    "call_kind",
1638                    "sequence_span",
1639                    "operation_sequence",
1640                    "operation_sequence_span",
1641                ]
1642                .iter()
1643                .all(|field| response.get(*field).is_none_or(Value::is_null))
1644            {
1645                return Ok(CancellationDeliveryReply::ClaimReleased {
1646                    task_id: task.task_id.clone(),
1647                    run_id: run_id.to_owned(),
1648                });
1649            }
1650            if response["delivered"].as_bool() != Some(true)
1651                || response["task_id"].as_str() != Some(task.task_id.as_str())
1652                || response["workflow_run_id"].as_str() != Some(run_id)
1653                || response.get("reason") != Some(&Value::Null)
1654                || [
1655                    "sequence_span",
1656                    "operation_sequence",
1657                    "operation_sequence_span",
1658                ]
1659                .iter()
1660                .any(|field| response.get(*field).is_none())
1661            {
1662                return Err(invalid(
1663                    "delivery acknowledgment does not match the selected task/run",
1664                ));
1665            }
1666            let mut recorded = response.clone();
1667            recorded["workflow_command_id"] = response["request_id"].clone();
1668            if CancellationDelivery::from_payload(&recorded)? != *delivery {
1669                return Err(invalid(
1670                    "delivery acknowledgment changed its authored operation range",
1671                ));
1672            }
1673            Ok(CancellationDeliveryReply::Delivered(
1674                CancellationDeliveryReceipt {
1675                    task_id: task.task_id.clone(),
1676                    run_id: run_id.to_owned(),
1677                    delivery: delivery.clone(),
1678                },
1679            ))
1680        })
1681        .await
1682        .map_err(|_| Error::Timeout)?
1683    }
1684
1685    /// Reload canonical history with the Server-issued token and exact claim.
1686    ///
1687    /// The refresh has one five-second budget, at most 128 pages, and the existing
1688    /// SDK page-size limit. Invalid, repeated or non-progressing tokens and pages
1689    /// fail closed. This returns fresh history without modifying the caller's
1690    /// previous task snapshot or its original request identity.
1691    pub async fn refresh_workflow_cancellation_history(
1692        &self,
1693        task: &WorkflowTask,
1694        observation: &CancellationRequest,
1695    ) -> Result<Vec<HistoryEvent>> {
1696        self.refresh_workflow_cancellation_history_with_cache(
1697            task,
1698            observation,
1699            &mut runtime_payloads::VerifiedPayloads::new(),
1700        )
1701        .await
1702    }
1703
1704    async fn refresh_workflow_cancellation_history_with_cache(
1705        &self,
1706        task: &WorkflowTask,
1707        observation: &CancellationRequest,
1708        verified_payloads: &mut runtime_payloads::VerifiedPayloads,
1709    ) -> Result<Vec<HistoryEvent>> {
1710        let (owner, run_id) = cancellation_claim(task)?;
1711        observation.validate_observation()?;
1712        let first_token = observation
1713            .history_refresh_page_token
1714            .clone()
1715            .expect("validated history token");
1716        tokio::time::timeout(CONTROL_BUDGET, async {
1717            let path = format!("/worker/workflow-tasks/{}/history", percent_encode_path_segment(&task.task_id));
1718            let mut token = Some(first_token);
1719            let mut seen = BTreeSet::new();
1720            let mut history = Vec::new();
1721            while let Some(current) = token.take() {
1722                if seen.len() >= MAX_REFRESH_PAGES || !seen.insert(current.clone()) {
1723                    return Err(invalid("canonical history refresh exceeded its page bound or repeated a token"));
1724                }
1725                let body = json!({
1726                    "lease_owner":owner, "workflow_task_attempt":task.workflow_task_attempt,
1727                    "next_history_page_token":current, "history_page_size":WORKFLOW_HISTORY_PAGE_SIZE,
1728                });
1729                let mut page: Value = self.request_json_unresolved_with_timeout(
1730                    reqwest::Method::POST, &path, RequestProtocol::Worker("1.20"), Some(&body),
1731                    CONTROL_BUDGET,
1732                ).await?;
1733                self.resolve_runtime_payloads_with_cache(&mut page, &path, RequestProtocol::Worker("1.20"), verified_payloads).await?;
1734                if page["task_id"].as_str() != Some(task.task_id.as_str())
1735                    || page["workflow_task_attempt"].as_u64() != Some(task.workflow_task_attempt)
1736                {
1737                    return Err(invalid("canonical history page changed the selected task/attempt"));
1738                }
1739                let events = page["history_events"].as_array().ok_or_else(|| invalid("canonical history page must contain an event array"))?;
1740                if events.len() > WORKFLOW_HISTORY_PAGE_SIZE {
1741                    return Err(invalid("canonical history page exceeds its requested event limit"));
1742                }
1743                token = match page.get("next_history_page_token") {
1744                    Some(Value::Null) => None,
1745                    Some(Value::String(next)) if !next.is_empty() && !events.is_empty() => Some(next.clone()),
1746                    _ => return Err(invalid("canonical history page token or progress is invalid")),
1747                };
1748                for event in events {
1749                    let event: HistoryEvent = serde_json::from_value(event.clone()).map_err(|_| invalid("canonical history page contains a malformed event"))?;
1750                    if event.event_type.trim().is_empty() {
1751                        return Err(invalid("canonical history event type must be non-empty"));
1752                    }
1753                    history.push(event);
1754                }
1755            }
1756            let canonical = CancellationHistory::from_events(&history, run_id, Some(observation))?;
1757            if canonical.request_index >= history.len() {
1758                return Err(invalid("canonical refresh omitted the original request event"));
1759            }
1760            Ok(history)
1761        }).await.map_err(|_| Error::Timeout)?
1762    }
1763
1764    /// Request bounded workflow-authored cleanup on a capable runtime.
1765    ///
1766    /// This is separate from terminal cancellation. Discovery must advertise
1767    /// cooperative support and compatible protocol 1.20. The Server also
1768    /// refuses an active workflow claim that cannot deliver cooperation.
1769    /// Repeated requests retain its original request identity and deadline.
1770    pub async fn request_workflow_cancellation(
1771        &self,
1772        workflow_id: &str,
1773        options: CooperativeCancellationOptions,
1774    ) -> Result<WorkflowCancellationRequest> {
1775        self.request_workflow_cancellation_target(workflow_id, None, options)
1776            .await
1777    }
1778
1779    /// Request cleanup only if the selected run remains current.
1780    pub async fn request_workflow_run_cancellation(
1781        &self,
1782        workflow_id: &str,
1783        run_id: &str,
1784        options: CooperativeCancellationOptions,
1785    ) -> Result<WorkflowCancellationRequest> {
1786        self.request_workflow_cancellation_target(workflow_id, Some(run_id), options)
1787            .await
1788    }
1789
1790    async fn request_workflow_cancellation_target(
1791        &self,
1792        workflow_id: &str,
1793        run_id: Option<&str>,
1794        options: CooperativeCancellationOptions,
1795    ) -> Result<WorkflowCancellationRequest> {
1796        let mut path = format!("/workflows/{}", path_segment("workflow_id", workflow_id)?);
1797        if let Some(run_id) = run_id {
1798            path.push_str(&format!("/runs/{}", path_segment("run_id", run_id)?));
1799        }
1800        path.push_str("/request-cancellation");
1801        if workflow_id.trim().is_empty() || run_id.is_some_and(|id| id.trim().is_empty()) {
1802            return Err(invalid(
1803                "workflow and selected run identities must be non-empty",
1804            ));
1805        }
1806        if options
1807            .cleanup_timeout_seconds
1808            .is_some_and(|seconds| !(1..=3600).contains(&seconds))
1809            || options
1810                .reason
1811                .as_ref()
1812                .is_some_and(|reason| reason.chars().count() > 1000)
1813        {
1814            return Err(invalid(
1815                "cleanup timeout must be 1..3600 seconds and reason at most 1000 characters",
1816            ));
1817        }
1818
1819        // Bound discovery, mutation and any storage retry by one total budget.
1820        tokio::time::timeout(CONTROL_BUDGET, async {
1821            let info: Value = self
1822                .request_json(
1823                    reqwest::Method::GET,
1824                    "/cluster/info",
1825                    RequestProtocol::ControlPlane,
1826                    Option::<&Value>::None,
1827                )
1828                .await?;
1829            require_discovery(&info)?;
1830            let response: Value = self
1831                .request_json(
1832                    reqwest::Method::POST,
1833                    &path,
1834                    RequestProtocol::ControlPlane,
1835                    Some(&options),
1836                )
1837                .await?;
1838            acknowledgment(&response, workflow_id, run_id)
1839        })
1840        .await
1841        .map_err(|_| Error::Timeout)?
1842    }
1843}
1844
1845impl Worker {
1846    pub(super) async fn settle_cooperative_activity(
1847        &self,
1848        task: worker_session::SessionActivityTask,
1849        task_metrics: &mut crate::metrics::WorkerObservation,
1850    ) -> Result<ManagedPollOutcome> {
1851        let session = self.track_session_task(task.worker_session.as_ref())?;
1852        let lease_deadline = task.lease_deadline;
1853        let metadata = task.invocation(session);
1854        let task = task.task;
1855        let guard = ActivityClaimGuard::new(&self.client, &task, &self.worker_id)?;
1856        let _abandon_on_drop = AbandonActivityOnDrop(guard.clone());
1857        if guard.observe().await.is_err() {
1858            return Ok(ManagedPollOutcome::Handled);
1859        }
1860        let mut callback_started = false;
1861        let result = {
1862            let invocation = self.execute_cooperative_activity_task(
1863                &task,
1864                &guard,
1865                &mut callback_started,
1866                metadata,
1867            );
1868            tokio::pin!(invocation);
1869            loop {
1870                tokio::select! {
1871                    biased;
1872                    _ = guard.wait_for_shutdown() => {
1873                        guard.abandon();
1874                        break None;
1875                    }
1876                    result = &mut invocation => break Some(result),
1877                    _ = tokio::time::sleep(Duration::from_secs(1)) => {
1878                        if guard.observe().await.is_err() {
1879                            break None;
1880                        }
1881                    }
1882                }
1883            }
1884        };
1885        // The invocation and its callback future are dropped before any receipt.
1886        let Some(result) = result else {
1887            if callback_started {
1888                guard.acknowledge_stopped().await?;
1889            }
1890            return Ok(ManagedPollOutcome::Handled);
1891        };
1892        // Both genuine application failures and successful results need current
1893        // authority before result upload or completion/failure publication.
1894        if matches!(result, Err(Error::ActivityExecutionAbandoned(_)))
1895            || guard.observe().await.is_err()
1896        {
1897            if callback_started {
1898                guard.acknowledge_stopped().await?;
1899            }
1900            return Ok(ManagedPollOutcome::Handled);
1901        }
1902        let mut task_outcome = if result.is_ok() {
1903            "completed"
1904        } else {
1905            "failed"
1906        };
1907        let settled = match result {
1908            Ok(value) => {
1909                let (settlement, too_large) = self
1910                    .settle_activity_completion(
1911                        &guard.task_id,
1912                        &guard.attempt_id,
1913                        &guard.owner,
1914                        lease_deadline,
1915                        &value,
1916                        &task.payload_codec,
1917                    )
1918                    .await?;
1919                if too_large {
1920                    task_outcome = "failed";
1921                }
1922                settlement
1923            }
1924            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
1925            Err(error) => {
1926                let failure = crate::ActivityError::from_error(&error, "RustActivityFailure");
1927                self.settle_activity_report(
1928                    crate::ActivityReport::Failed,
1929                    &guard.task_id,
1930                    &guard.attempt_id,
1931                    &guard.owner,
1932                    lease_deadline,
1933                    || {
1934                        self.client.fail_activity_task_with_error(
1935                            &guard.task_id,
1936                            &guard.attempt_id,
1937                            &guard.owner,
1938                            &failure,
1939                        )
1940                    },
1941                )
1942                .await?
1943            }
1944        };
1945        task_metrics.outcome(match settled {
1946            crate::ActivitySettlement::Recorded => task_outcome,
1947            crate::ActivitySettlement::Closed if task_outcome == "failed" => task_outcome,
1948            _ => "expired",
1949        });
1950        Ok(ManagedPollOutcome::Handled)
1951    }
1952
1953    async fn execute_cooperative_activity_task(
1954        &self,
1955        task: &ActivityTask,
1956        guard: &ActivityClaimGuard,
1957        callback_started: &mut bool,
1958        invocation: worker_session::ActivityInvocation,
1959    ) -> Result<AvroValue> {
1960        #[cfg(feature = "telemetry")]
1961        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
1962            !self
1963                .client
1964                .observability_context_supported
1965                .load(Ordering::SeqCst)
1966        }) {
1967            return telemetry
1968                .run(
1969                    "durable.activity.task",
1970                    self.activity_telemetry_fields(task),
1971                    false,
1972                    self.execute_cooperative_activity_task_inner(
1973                        task,
1974                        guard,
1975                        callback_started,
1976                        invocation,
1977                    ),
1978                )
1979                .await;
1980        }
1981        self.execute_cooperative_activity_task_inner(task, guard, callback_started, invocation)
1982            .await
1983    }
1984
1985    async fn execute_cooperative_activity_task_inner(
1986        &self,
1987        task: &ActivityTask,
1988        guard: &ActivityClaimGuard,
1989        callback_started: &mut bool,
1990        invocation: worker_session::ActivityInvocation,
1991    ) -> Result<AvroValue> {
1992        let worker_session::ActivityInvocation {
1993            worker_session,
1994            hydration_claim,
1995            retry_info,
1996            heartbeat_resume,
1997        } = invocation;
1998        validate_activity_task_payloads(task)?;
1999        let handler = self
2000            .activities
2001            .get(&task.activity_type)
2002            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
2003        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
2004        let context = ActivityContext {
2005            client: self.client.clone(),
2006            task_id: guard.task_id.clone(),
2007            activity_attempt_id: guard.attempt_id.clone(),
2008            lease_owner: guard.owner.clone(),
2009            activity_type: task.activity_type.clone(),
2010            attempt_number: task.attempt_number,
2011            retry_info,
2012            heartbeat_resume,
2013            activity_execution_id: task.activity_execution_id.clone(),
2014            workflow_id: task.workflow_id.clone(),
2015            run_id: task.run_id.clone(),
2016            task_queue: self.task_queue.clone(),
2017            worker_id: self.worker_id.clone(),
2018            claim_guard: Some(guard.clone()),
2019            local_heartbeats: None,
2020            worker_session,
2021        };
2022        if let Some(claim) = &hydration_claim {
2023            claim.confirm(&self.client).await?;
2024        }
2025        guard.boundary()?;
2026        *callback_started = true;
2027        #[cfg(feature = "telemetry")]
2028        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
2029            self.client
2030                .observability_context_supported
2031                .load(Ordering::SeqCst)
2032        }) {
2033            return telemetry
2034                .run_observed(
2035                    "durable.activity.task",
2036                    self.activity_telemetry_fields(task),
2037                    false,
2038                    self.activity_observations(task),
2039                    async { self.activity_callback(handler, context, args, false).await },
2040                )
2041                .await;
2042        }
2043        self.activity_callback(handler, context, args, false).await
2044    }
2045
2046    pub(super) async fn poll_cooperative_workflow_once(&self) -> Result<ManagedPollOutcome> {
2047        let mut poll_metrics = self.metrics.worker(false, "workflow", &self.task_queue);
2048        let poll_request_id = unique_request_id("rust-workflow-poll");
2049        let response = self
2050            .retry_worker_operation(|| {
2051                self.client.poll_cooperative_workflow_task_with_request_id(
2052                    &self.worker_id,
2053                    &self.task_queue,
2054                    self.poll_timeout,
2055                    &poll_request_id,
2056                    0,
2057                    true,
2058                )
2059            })
2060            .await;
2061        poll_metrics.poll(&response, |value| value.outcome.clone());
2062        drop(poll_metrics);
2063        let Some(response) = self.settle_worker_poll_response(response).await? else {
2064            return Ok(ManagedPollOutcome::Idle);
2065        };
2066        if response.outcome.should_stop() {
2067            return Ok(ManagedPollOutcome::Stop);
2068        }
2069        let memo_updates_supported =
2070            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
2071        self.observe_workflow_poll_capabilities(response.server_capabilities.as_ref());
2072        let Some(claim) = response.task else {
2073            return Ok(ManagedPollOutcome::Idle);
2074        };
2075        self.client.release_worker_poll();
2076        let mut task_metrics = self.metrics.worker(true, "workflow", &self.task_queue);
2077        task_metrics.outcome("failed");
2078        // Anchor the immutable cleanup deadline once, before replay. Deferring
2079        // completion must not grant another cleanup budget on each retry.
2080        let mut completion_worker = None;
2081        if let (Some(request), Some(_)) = (
2082            claim.cancellation_request.as_ref(),
2083            self.client.worker_storage_admission.as_ref(),
2084        ) {
2085            let mut worker = self.clone();
2086            let admission = worker.client.worker_storage_admission.as_mut().unwrap();
2087            let deadline = DateTime::parse_from_rfc3339(&request.cleanup_deadline_at)
2088                .map_err(|_| invalid("invalid original cleanup deadline"))?;
2089            let monotonic_now = tokio::time::Instant::now();
2090            let unix = SystemTime::now()
2091                .duration_since(UNIX_EPOCH)
2092                .map_err(|_| Error::Timeout)?;
2093            let now = DateTime::<chrono::Utc>::from_timestamp(
2094                i64::try_from(unix.as_secs()).map_err(|_| Error::Timeout)?,
2095                unix.subsec_nanos(),
2096            )
2097            .ok_or(Error::Timeout)?;
2098            let remaining = (deadline.with_timezone(&chrono::Utc) - now)
2099                .to_std()
2100                .unwrap_or(Duration::ZERO);
2101            admission.workflow_completion_retry_deadline = Some(monotonic_now + remaining);
2102            completion_worker = Some(worker);
2103        }
2104        // An uncertain observation, delivery or canonical refresh cannot become
2105        // an application failure or be published as a workflow-task decision.
2106        let Some(decision) = self.replay_cooperative_workflow_claim(&claim).await? else {
2107            return Ok(ManagedPollOutcome::Handled);
2108        };
2109        let (owner, _) = cancellation_claim(&claim.task)?;
2110        let task_outcome = crate::metrics::workflow_task_outcome(Some(&decision));
2111        let settled = completion_worker
2112            .as_ref()
2113            .unwrap_or(self)
2114            .settle_workflow_task_decision(
2115                &claim.task.task_id,
2116                owner,
2117                claim.task.workflow_task_attempt,
2118                claim.task.run_id.as_deref(),
2119                Ok(decision),
2120                memo_updates_supported,
2121                claim.sticky_snapshot.clone(),
2122            )
2123            .await;
2124        if settled.is_ok() {
2125            task_metrics.outcome(task_outcome);
2126        }
2127        settled
2128    }
2129
2130    async fn replay_cooperative_workflow_claim(
2131        &self,
2132        claim: &CooperativeWorkflowTask,
2133    ) -> Result<Option<WorkflowTaskDecision>> {
2134        let mut claimed_worker = self.clone();
2135        claimed_worker.ordered_condition_claim = claim.ordered_condition_claim;
2136        let mut verified_payloads = claim.verified_payloads.clone();
2137        let (owner, run_id) = cancellation_claim(&claim.task)?;
2138        if owner != self.worker_id {
2139            return Err(invalid(
2140                "cooperative replay requires this worker's actual claim",
2141            ));
2142        }
2143        let mut task = claim.task.clone();
2144        let Some(observation) = claim.cancellation_request.as_ref() else {
2145            let canonical = CancellationHistory::from_events(&task.history_events, run_id, None)?;
2146            if canonical.request.is_some() {
2147                return Err(invalid(
2148                    "cooperative replay omitted its original pending observation",
2149                ));
2150            }
2151            for _ in 0..1000 {
2152                let mut decision = claimed_worker.execute_workflow_task_decision(task.clone())?;
2153                if let Some(intent) = decision.cancellation_scope_delivery.as_ref() {
2154                    if !decision.commands.is_empty() {
2155                        decision.cancellation_scope_delivery = None;
2156                        return Ok(Some(decision));
2157                    }
2158                    let mut budget = CancellationScopeDeliveryBudget::new();
2159                    budget.restrict(intent.context.deadline())?;
2160                    let prepared = self
2161                        .client
2162                        .prepare_cancellation_scope_on_claim(
2163                            &task,
2164                            &intent.context,
2165                            &intent.boundary,
2166                            &budget,
2167                        )
2168                        .await?;
2169                    budget.restrict(prepared.authority_deadline())?;
2170                    let delivered = self
2171                        .client
2172                        .deliver_cancellation_scope_on_claim(&task, &prepared, &budget)
2173                        .await?;
2174                    task.history_events = delivered.history().to_vec();
2175                    task.total_history_events = None;
2176                    task.history_size_bytes = None;
2177                    continue;
2178                }
2179                let Some(opening) = decision.cancellation_scope_opening.as_ref() else {
2180                    return Ok(Some(decision));
2181                };
2182                if !decision.commands.is_empty() {
2183                    decision.cancellation_scope_opening = None;
2184                    return Ok(Some(decision));
2185                }
2186                let receipt = self
2187                    .client
2188                    .open_cancellation_scope_on_claim(
2189                        &task,
2190                        opening.sequence,
2191                        &opening.parent_scope_id,
2192                        opening.shield_parent,
2193                    )
2194                    .await?;
2195                task.history_events = receipt.history().to_vec();
2196                task.total_history_events = None;
2197                task.history_size_bytes = None;
2198            }
2199            return Err(invalid(
2200                "workflow exceeded the canonical scope opening replay limit",
2201            ));
2202        };
2203        task.history_events = self
2204            .client
2205            .refresh_workflow_cancellation_history_with_cache(
2206                &claim.task,
2207                observation,
2208                &mut verified_payloads,
2209            )
2210            .await?;
2211        for _ in 0..1000 {
2212            // Count the actual refreshed snapshot. Its byte budget was not
2213            // remeasured, so do not expose the old snapshot's size as current.
2214            task.total_history_events = None;
2215            task.history_size_bytes = None;
2216            let mut decision = claimed_worker.execute_workflow_task_decision_with_cancellation(
2217                task.clone(),
2218                Some(observation),
2219            )?;
2220            if let Some(intent) = decision.cancellation_scope_delivery.as_ref() {
2221                if !decision.commands.is_empty() {
2222                    decision.cancellation_scope_delivery = None;
2223                    return Ok(Some(decision));
2224                }
2225                let mut budget = CancellationScopeDeliveryBudget::new();
2226                budget.restrict(intent.context.deadline())?;
2227                let prepared = self
2228                    .client
2229                    .prepare_cancellation_scope_on_claim(
2230                        &task,
2231                        &intent.context,
2232                        &intent.boundary,
2233                        &budget,
2234                    )
2235                    .await?;
2236                budget.restrict(prepared.authority_deadline())?;
2237                let delivered = self
2238                    .client
2239                    .deliver_cancellation_scope_on_claim(&task, &prepared, &budget)
2240                    .await?;
2241                task.history_events = delivered.history().to_vec();
2242                continue;
2243            }
2244            let Some(intent) = decision.cancellation_delivery.as_ref() else {
2245                return Ok(Some(decision));
2246            };
2247            if !decision.commands.is_empty() {
2248                // Native permits delivery only at/before its next durable call.
2249                // Commit earlier commands first. Completion releases this claim
2250                // and its successor replays their durable results before delivery.
2251                decision.cancellation_delivery = None;
2252                return Ok(Some(decision));
2253            }
2254            if intent.call_kind == CancellationCallKind::ServiceOperation
2255                && !self.nexus_registration_confirmed.load(Ordering::SeqCst)
2256            {
2257                return Err(Error::CooperativeCancellationUnavailable(
2258                    "nexus_cooperative_cancellation_not_supported: new delivery requires confirmed Nexus registration".into(),
2259                ));
2260            }
2261            let delivery_error = match self
2262                .client
2263                .deliver_workflow_cancellation(&claim.task, intent)
2264                .await
2265            {
2266                Ok(CancellationDeliveryReply::ClaimReleased { .. }) => return Ok(None),
2267                Ok(CancellationDeliveryReply::Delivered(_)) => None,
2268                Err(error) => Some(error),
2269            };
2270            task.history_events = self
2271                .client
2272                .refresh_workflow_cancellation_history_with_cache(
2273                    &claim.task,
2274                    observation,
2275                    &mut verified_payloads,
2276                )
2277                .await?;
2278            let canonical =
2279                CancellationHistory::from_events(&task.history_events, run_id, Some(observation))?;
2280            if canonical.delivery.as_ref() != Some(intent) {
2281                return Err(delivery_error.unwrap_or_else(|| {
2282                    invalid(
2283                        "canonical history did not prove the exact intended cancellation delivery",
2284                    )
2285                }));
2286            }
2287        }
2288        Err(invalid(
2289            "workflow replay did not converge on its canonical cancellation delivery",
2290        ))
2291    }
2292}
2293
2294#[derive(Clone, Debug)]
2295pub(super) struct ActivityClaimGuard {
2296    client: Client,
2297    task_id: String,
2298    attempt_id: String,
2299    owner: String,
2300    active: Arc<AtomicBool>,
2301    cancellation_receipt: Arc<Mutex<Option<Value>>>,
2302    stop: Option<Arc<AtomicBool>>,
2303}
2304
2305struct AbandonActivityOnDrop(ActivityClaimGuard);
2306
2307impl Drop for AbandonActivityOnDrop {
2308    fn drop(&mut self) {
2309        self.0.abandon();
2310    }
2311}
2312
2313impl ActivityClaimGuard {
2314    pub(super) fn new(client: &Client, task: &ActivityTask, worker_id: &str) -> Result<Self> {
2315        let owner = task.lease_owner.as_deref().unwrap_or_default();
2316        let attempt = task
2317            .activity_attempt_id
2318            .as_deref()
2319            .or(task.attempt_id.as_deref())
2320            .unwrap_or_default();
2321        if task.task_id.trim().is_empty()
2322            || attempt.trim().is_empty()
2323            || owner.trim().is_empty()
2324            || owner != worker_id
2325            || matches!((&task.activity_attempt_id, &task.attempt_id), (Some(left), Some(right)) if left != right)
2326        {
2327            return Err(invalid(
2328                "activity execution requires the worker's actual immutable claim",
2329            ));
2330        }
2331        Ok(Self {
2332            client: client.clone(),
2333            task_id: task.task_id.clone(),
2334            attempt_id: attempt.to_owned(),
2335            owner: owner.to_owned(),
2336            active: Arc::new(AtomicBool::new(true)),
2337            cancellation_receipt: Arc::new(Mutex::new(None)),
2338            stop: client
2339                .worker_storage_admission
2340                .as_ref()
2341                .map(|admission| Arc::clone(&admission.stop)),
2342        })
2343    }
2344
2345    fn abandon(&self) {
2346        self.active.store(false, Ordering::SeqCst);
2347    }
2348
2349    /// Caller has already dropped the callback future. Never restores authority.
2350    async fn acknowledge_stopped(&self) -> Result<()> {
2351        self.abandon();
2352        let receipt = self
2353            .cancellation_receipt
2354            .lock()
2355            .map_err(|_| invalid("activity cancellation receipt lock was poisoned"))?
2356            .clone();
2357        if let Some(receipt) = receipt {
2358            self.client
2359                .acknowledge_activity_cancellation(
2360                    &self.task_id,
2361                    &self.attempt_id,
2362                    &self.owner,
2363                    text(&receipt, "request_id")?,
2364                )
2365                .await?;
2366        }
2367        Ok(())
2368    }
2369
2370    fn retain_cancellation_receipt(&self, value: &Value) -> Result<()> {
2371        if value["can_continue"].as_bool() != Some(false)
2372            || value["cancel_requested"].as_bool() != Some(true)
2373        {
2374            return Ok(());
2375        }
2376        let Some(receipt) = value
2377            .get("cancellation_acknowledgement")
2378            .filter(|receipt| receipt.is_object())
2379        else {
2380            return Ok(());
2381        };
2382        if !matches!(
2383            receipt["callback_state"].as_str(),
2384            Some("unknown" | "stopped")
2385        ) || [
2386            "request_id",
2387            "root_request_id",
2388            "cleanup_deadline_at",
2389            "cancellation_history_event_id",
2390        ]
2391        .iter()
2392        .any(|field| text(receipt, field).is_err())
2393            || DateTime::parse_from_rfc3339(text(receipt, "cleanup_deadline_at")?).is_err()
2394        {
2395            return Ok(());
2396        }
2397        let mut retained = self
2398            .cancellation_receipt
2399            .lock()
2400            .map_err(|_| invalid("activity cancellation receipt lock was poisoned"))?;
2401        if let Some(original) = retained.as_ref() {
2402            if [
2403                "request_id",
2404                "root_request_id",
2405                "cleanup_deadline_at",
2406                "cancellation_history_event_id",
2407            ]
2408            .iter()
2409            .any(|field| original[*field] != receipt[*field])
2410            {
2411                return Err(invalid(
2412                    "activity cancellation observation changed its original identity or deadline",
2413                ));
2414            }
2415        } else {
2416            *retained = Some(receipt.clone());
2417        }
2418        Ok(())
2419    }
2420
2421    fn boundary(&self) -> Result<()> {
2422        if !self.active.load(Ordering::SeqCst)
2423            || self
2424                .stop
2425                .as_ref()
2426                .is_some_and(|stop| stop.load(Ordering::SeqCst))
2427        {
2428            self.abandon();
2429            return Err(Error::ActivityExecutionAbandoned(
2430                "callback completed, was abandoned, or its worker is stopping".into(),
2431            ));
2432        }
2433        Ok(())
2434    }
2435
2436    async fn wait_for_shutdown(&self) {
2437        if let Some(stop) = &self.stop {
2438            wait_for_worker_stop(stop).await;
2439        } else {
2440            std::future::pending::<()>().await;
2441        }
2442    }
2443
2444    pub(super) async fn observe(&self) -> Result<()> {
2445        self.boundary()?;
2446        let result = self
2447            .client
2448            .activity_task_status(&self.task_id, &self.attempt_id, &self.owner)
2449            .await
2450            .and_then(|value| {
2451                self.retain_cancellation_receipt(&value)?;
2452                if value["can_continue"].as_bool() != Some(true)
2453                    || value["cancel_requested"].as_bool() != Some(false)
2454                    || value.get("reason") != Some(&Value::Null)
2455                    || value["task_status"].as_str() != Some("leased")
2456                    || value["attempt_status"].as_str() != Some("running")
2457                    || value["activity_status"].as_str() != Some("running")
2458                {
2459                    return Err(invalid("activity observation refused continuation"));
2460                }
2461                let mut bounds = vec![text(&value, "lease_expires_at")?];
2462                if let Some(deadlines) = value.get("deadlines").filter(|v| !v.is_null()) {
2463                    if !deadlines.is_object() {
2464                        return Err(invalid("activity execution deadlines must be an object"));
2465                    }
2466                    for kind in ["heartbeat", "start_to_close", "schedule_to_close"] {
2467                        if let Some(deadline) = deadlines.get(kind).filter(|v| !v.is_null()) {
2468                            bounds.push(
2469                                deadline
2470                                    .as_str()
2471                                    .ok_or_else(|| invalid("invalid activity deadline"))?,
2472                            );
2473                        }
2474                    }
2475                }
2476                if let Some(session) = value.get("worker_session").filter(|v| !v.is_null()) {
2477                    if session["status"].as_str() != Some("active")
2478                        || session["lease_owner"].as_str() != Some(self.owner.as_str())
2479                    {
2480                        return Err(invalid(
2481                            "activity no longer owns its required worker session",
2482                        ));
2483                    }
2484                    bounds.push(text(session, "lease_expires_at")?);
2485                    bounds.push(text(session, "ttl_expires_at")?);
2486                }
2487                for bound in bounds {
2488                    let deadline = DateTime::parse_from_rfc3339(bound)
2489                        .map_err(|_| invalid("activity deadline must include a timezone"))?;
2490                    let now = SystemTime::now()
2491                        .duration_since(UNIX_EPOCH)
2492                        .map_err(|_| invalid("activity observation clock precedes the epoch"))?;
2493                    if !u128::try_from(deadline.timestamp_millis())
2494                        .is_ok_and(|millis| millis > now.as_millis())
2495                    {
2496                        return Err(invalid("activity ownership or execution deadline elapsed"));
2497                    }
2498                }
2499                self.boundary()
2500            });
2501        result.map_err(|error| {
2502            self.abandon();
2503            Error::ActivityExecutionAbandoned(error.to_string())
2504        })
2505    }
2506
2507    pub(super) async fn heartbeat<T: Serialize>(
2508        &self,
2509        context: &ActivityContext,
2510        details: T,
2511    ) -> Result<ActivityHeartbeatResponse> {
2512        if context.task_id != self.task_id
2513            || context.activity_attempt_id != self.attempt_id
2514            || context.lease_owner != self.owner
2515            || context.worker_id != self.owner
2516        {
2517            self.abandon();
2518            return Err(Error::ActivityExecutionAbandoned(
2519                "activity context changed its original claim".into(),
2520            ));
2521        }
2522        self.observe().await?;
2523        let result = tokio::time::timeout(CONTROL_BUDGET, async {
2524            let details = AvroValue::from_serialize(&details)?.into_json()?;
2525            self.boundary()?;
2526            let value: Value = self.client.request_json(
2527                reqwest::Method::POST,
2528                &format!("/worker/activity-tasks/{}/heartbeat", percent_encode_path_segment(&self.task_id)),
2529                RequestProtocol::Worker("1.20"),
2530                Some(&json!({"activity_attempt_id":self.attempt_id,"lease_owner":self.owner,"details":details})),
2531            ).await?;
2532            if value["task_id"].as_str() != Some(self.task_id.as_str())
2533                || value["activity_attempt_id"].as_str() != Some(self.attempt_id.as_str())
2534                || value["lease_owner"].as_str() != Some(self.owner.as_str())
2535                || value["can_continue"].as_bool() != Some(true)
2536                || value["cancel_requested"].as_bool() != Some(false)
2537                || value["heartbeat_recorded"].as_bool() != Some(true)
2538            {
2539                return Err(invalid("activity heartbeat lost its original claim"));
2540            }
2541            if let Some(session) = context.worker_session() {
2542                session.track(&value["worker_session"])?;
2543            }
2544            serde_json::from_value(value).map_err(Error::from)
2545        }).await.map_err(|_| Error::Timeout).and_then(|result| result);
2546        let response = result.map_err(|error| {
2547            self.abandon();
2548            Error::ActivityExecutionAbandoned(error.to_string())
2549        })?;
2550        self.observe().await?;
2551        Ok(response)
2552    }
2553}
2554
2555pub(super) fn cancellation_claim(task: &WorkflowTask) -> Result<(&str, &str)> {
2556    let owner = task
2557        .lease_owner
2558        .as_deref()
2559        .filter(|owner| !owner.trim().is_empty());
2560    let run = task.run_id.as_deref().filter(|run| !run.trim().is_empty());
2561    if task.task_id.trim().is_empty()
2562        || task.workflow_task_attempt == 0
2563        || task.workflow_task_attempt > MAX_SEQUENCE
2564    {
2565        return Err(invalid(
2566            "cancellation transport requires a valid task and attempt",
2567        ));
2568    }
2569    Ok((
2570        owner.ok_or_else(|| invalid("cancellation transport requires the actual lease owner"))?,
2571        run.ok_or_else(|| invalid("cancellation transport requires the selected durable run"))?,
2572    ))
2573}
2574
2575impl WorkflowHandle {
2576    /// Request bounded cleanup for whichever run is current.
2577    pub async fn request_cancellation(
2578        &self,
2579        options: CooperativeCancellationOptions,
2580    ) -> Result<WorkflowCancellationRequest> {
2581        self.client
2582            .request_workflow_cancellation(&self.workflow_id, options)
2583            .await
2584    }
2585
2586    /// Request bounded cleanup only while this handle's selected run is current.
2587    pub async fn request_selected_run_cancellation(
2588        &self,
2589        options: CooperativeCancellationOptions,
2590    ) -> Result<WorkflowCancellationRequest> {
2591        let run_id = self
2592            .run_id
2593            .as_deref()
2594            .ok_or_else(|| invalid("selected run_id is required"))?;
2595        self.client
2596            .request_workflow_run_cancellation(&self.workflow_id, run_id, options)
2597            .await
2598    }
2599}
2600
2601#[cfg(test)]
2602mod reopen_order_tests {
2603    use super::*;
2604
2605    // #193 review: the next authored sequence follows the highest recorded
2606    // sequence even when grouped reopens are consumed out of sequence order.
2607    #[test]
2608    fn next_sequence_follows_the_highest_recorded_sequence() {
2609        let mut state = WorkflowState::new(
2610            crate::one_sided_grouped_reopen_history(Vec::new()),
2611            "rust-workers".to_string(),
2612            crate::DEFAULT_CODEC.to_string(),
2613            None,
2614        )
2615        .expect("one-sided grouped reopen history");
2616        let consumed = state
2617            .recorded_commands
2618            .iter()
2619            .map(RecordedCommand::sequence)
2620            .collect::<Vec<_>>();
2621        assert_eq!(consumed, vec![1, 3, 2]);
2622        state.command_cursor = state.recorded_commands.len();
2623        assert_eq!(
2624            state.next_cancellation_sequence().expect("next sequence"),
2625            4
2626        );
2627    }
2628}