Skip to main content

durable_workflow/
cooperative_cancellation.rs

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