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