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