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.max_recorded_sequence()
761                    .checked_add(self.commands.len() as u64)
762                    .and_then(|sequence| sequence.checked_add(1))
763                    .filter(|sequence| *sequence < MAX_SEQUENCE)
764                    .ok_or_else(|| invalid("authored cancellation sequence overflowed"))
765            },
766            |command| Ok(command.sequence()),
767        )
768    }
769
770    fn prepare_cancellation_delivery(&mut self, delivery: CancellationDelivery) -> Result<bool> {
771        if !self.cancellation_delivery_enabled || self.cancellation_shield_depth > 0 {
772            return Ok(false);
773        }
774        self.assert_root_cancellation_membership()?;
775        if self.cancellation_delivery_intent.is_some() {
776            self.matched_recorded_pending = true;
777            return Ok(true);
778        }
779        let (base, span) = delivery.range();
780        if !self.cancellation_history.eligible(base, span) {
781            return Ok(false);
782        }
783        let payload = json!({
784            "workflow_command_id":delivery.request_id, "sequence":delivery.sequence,
785            "call_kind":delivery.call_kind, "sequence_span":delivery.sequence_span,
786            "operation_sequence":delivery.operation_sequence,
787            "operation_sequence_span":delivery.operation_sequence_span,
788        });
789        CancellationDelivery::from_payload(&payload)?;
790        self.cancellation_delivery_command_count = self.commands.len();
791        self.cancellation_delivery_intent = Some(delivery);
792        self.matched_recorded_pending = true;
793        Ok(true)
794    }
795
796    fn assert_root_cancellation_membership(&self) -> Result<()> {
797        if self
798            .scope_delivery
799            .as_ref()
800            .is_some_and(|replay| replay.active_scope != "root")
801        {
802            return Err(Error::CancellationScopeExecutionUnavailable);
803        }
804        Ok(())
805    }
806
807    pub(super) fn prepare_scalar_cancellation(
808        &mut self,
809        index: usize,
810        kind: CancellationCallKind,
811        group_path: &[ParallelGroupMetadata],
812    ) -> Result<bool> {
813        if self.prepare_scalar_scope_cancellation(index, kind, group_path)? {
814            return Ok(true);
815        }
816        if !self.cancellation_delivery_enabled || self.cancellation_shield_depth > 0 {
817            return Ok(false);
818        }
819        // Group leaves validate their recorded calls before the enclosing
820        // parallel/select future suspends. They never choose scalar delivery.
821        if !group_path.is_empty() && self.cancellation_delivery_intent.is_none() {
822            return Ok(false);
823        }
824        let Some(request) = self.cancellation_history.request.as_ref() else {
825            return Ok(false);
826        };
827        let sequence = self.recorded_commands.get(index).map_or_else(
828            || self.next_cancellation_sequence(),
829            |command| Ok(command.sequence()),
830        )?;
831        let pending = self.prepare_cancellation_delivery(CancellationDelivery {
832            request_id: request.request_id.clone(),
833            sequence,
834            call_kind: kind,
835            sequence_span: 1,
836            operation_sequence: None,
837            operation_sequence_span: 1,
838        })?;
839        if pending && index < self.recorded_commands.len() {
840            self.command_cursor = index + 1;
841        }
842        Ok(pending)
843    }
844
845    pub(super) fn prepare_group_cancellation(
846        &mut self,
847        descriptors: &[ParallelDescriptor],
848    ) -> Result<()> {
849        let Some(request) = self.cancellation_history.request.as_ref() else {
850            return Ok(());
851        };
852        let Some(group) = descriptors.first().and_then(|leaf| leaf.group_path.first()) else {
853            return Ok(());
854        };
855        self.prepare_cancellation_delivery(CancellationDelivery {
856            request_id: request.request_id.clone(),
857            sequence: group.parallel_group_base_sequence,
858            call_kind: CancellationCallKind::Parallel,
859            sequence_span: descriptors.len() as u64,
860            operation_sequence: None,
861            operation_sequence_span: 1,
862        })?;
863        Ok(())
864    }
865
866    pub(super) fn prepare_selection_handle_cancellation(
867        &mut self,
868        handle: &DurableOperationHandle,
869    ) -> Result<bool> {
870        if !self.cancellation_delivery_enabled || self.cancellation_shield_depth > 0 {
871            return Ok(false);
872        }
873        validate_selection_delivery_handle(self, handle)?;
874        if !self
875            .cancellation_history
876            .eligible(handle.base_sequence, handle.size as u64)
877        {
878            return Ok(false);
879        }
880        let request_id = self
881            .cancellation_history
882            .request
883            .as_ref()
884            .expect("eligible request")
885            .request_id
886            .clone();
887        self.prepare_cancellation_delivery(CancellationDelivery {
888            request_id,
889            sequence: self.next_cancellation_sequence()?,
890            call_kind: CancellationCallKind::SelectionHandle,
891            sequence_span: 1,
892            operation_sequence: Some(handle.base_sequence),
893            operation_sequence_span: handle.size as u64,
894        })
895    }
896
897    pub(super) fn expand_cancellation_group(
898        &mut self,
899        descriptors: &[ParallelDescriptor],
900    ) -> Result<()> {
901        let Some(RecordedCommand::CancellationGroup {
902            sequence,
903            span,
904            original,
905        }) = self.recorded_commands.get(self.command_cursor).cloned()
906        else {
907            return Ok(());
908        };
909        self.validate_cancellation_call(
910            sequence,
911            CancellationCallKind::Parallel,
912            CancellationCallKind::Parallel,
913        )?;
914        if descriptors.len() as u64 != span {
915            return Err(invalid_recorded_history(
916                "cooperative_cancellation_call_mismatch",
917                sequence,
918                &format!("parallel group with {span} durable leaves"),
919                &format!("{} durable leaves", descriptors.len()),
920                "authored parallel group span differs from its committed cancellation",
921            ));
922        }
923        let mut original = original.into_iter().peekable();
924        let mut leaves = Vec::with_capacity(descriptors.len());
925        for descriptor in descriptors {
926            let leaf_sequence = sequence + descriptor.offset as u64;
927            let command = if original.peek().map(RecordedCommand::sequence) == Some(leaf_sequence) {
928                original.next()
929            } else {
930                None
931            };
932            if self
933                .cancellation_history
934                .resolved_before_request
935                .contains(&leaf_sequence)
936            {
937                let command = command.ok_or_else(|| {
938                    invalid_recorded_history(
939                        "cooperative_cancellation_call_mismatch",
940                        leaf_sequence,
941                        "recorded earlier result",
942                        "missing durable call",
943                        "parallel cancellation cannot discard an earlier committed result",
944                    )
945                })?;
946                leaves.push(command);
947                continue;
948            }
949            let kind = match &descriptor.operation {
950                ParallelOperation::Activity { .. } => CancellationCallKind::Activity,
951                ParallelOperation::ChildWorkflow { .. } => CancellationCallKind::Child,
952                ParallelOperation::Timer(_) => CancellationCallKind::Timer,
953                ParallelOperation::Signal(_) => CancellationCallKind::Signal,
954                ParallelOperation::Condition { .. } => CancellationCallKind::Condition,
955                ParallelOperation::Group(_) => unreachable!("descriptor is a durable leaf"),
956            };
957            leaves.push(RecordedCommand::CancellationBoundary {
958                sequence: leaf_sequence,
959                call_kind: kind,
960                original: command.map(Box::new),
961            });
962        }
963        self.recorded_commands
964            .splice(self.command_cursor..=self.command_cursor, leaves);
965        Ok(())
966    }
967
968    pub(super) fn cancellation_error(&mut self) -> Error {
969        if self.cancellation_consumed {
970            self.start_cancellation_clock();
971        }
972        match (
973            &self.cancellation_history.request,
974            &self.cancellation_history.delivery,
975        ) {
976            (Some(request), Some(delivery)) => {
977                let mut request = request.clone();
978                request.context = request.context.map(|context| {
979                    context.with_replay(cancellation_replay_clock::active_binding())
980                });
981                Error::CooperativeCancellationRequested(CooperativeCancellationRequested {
982                    request,
983                    delivery: delivery.clone(),
984                })
985            }
986            _ => Error::WorkflowCancellationRequested(WorkflowCancellationRequested),
987        }
988    }
989
990    fn validate_cancellation_call(
991        &self,
992        sequence: u64,
993        kind: CancellationCallKind,
994        recorded_kind: CancellationCallKind,
995    ) -> Result<()> {
996        if kind != recorded_kind || self.cancellation_shield_depth > 0 {
997            return Err(invalid_recorded_history(
998                "cooperative_cancellation_call_mismatch",
999                sequence,
1000                "matching unshielded authored call",
1001                &format!("{kind:?}"),
1002                "committed cancellation call kind or cleanup scope changed",
1003            ));
1004        }
1005        Ok(())
1006    }
1007
1008    pub(super) fn cancellation_replay_command(
1009        &mut self,
1010        index: usize,
1011        kind: CancellationCallKind,
1012    ) -> Result<Option<RecordedCommand>> {
1013        match self.recorded_commands.get(index).cloned() {
1014            Some(RecordedCommand::CancellationBoundary {
1015                sequence,
1016                call_kind,
1017                original,
1018            }) => {
1019                if let Some(original) = original {
1020                    return Ok(Some(*original));
1021                }
1022                self.replay_scope_cancellation_at(index, kind)?;
1023                self.assert_root_cancellation_membership()?;
1024                self.validate_cancellation_call(sequence, kind, call_kind)?;
1025                self.cancellation_consumed = true;
1026                self.cancel_requested = true;
1027                self.command_cursor = index + 1;
1028                Err(self.cancellation_error())
1029            }
1030            command => Ok(command),
1031        }
1032    }
1033
1034    pub(super) fn replay_cancellation_at(
1035        &mut self,
1036        index: usize,
1037        kind: CancellationCallKind,
1038    ) -> Result<()> {
1039        self.replay_scope_cancellation_at(index, kind)?;
1040        if let Some(RecordedCommand::CancellationBoundary {
1041            sequence,
1042            call_kind,
1043            ..
1044        }) = self.recorded_commands.get(index)
1045        {
1046            self.assert_root_cancellation_membership()?;
1047            self.validate_cancellation_call(*sequence, kind, *call_kind)?;
1048            self.cancellation_consumed = true;
1049            self.cancel_requested = true;
1050            self.command_cursor = index + 1;
1051            return Err(self.cancellation_error());
1052        }
1053        Ok(())
1054    }
1055
1056    pub(super) fn replay_selection_handle_cancellation(
1057        &mut self,
1058        handle: &DurableOperationHandle,
1059    ) -> Result<()> {
1060        let Some(RecordedCommand::CancellationBoundary {
1061            sequence,
1062            call_kind,
1063            original,
1064        }) = self.recorded_commands.get(self.command_cursor)
1065        else {
1066            return Ok(());
1067        };
1068        self.validate_cancellation_call(
1069            *sequence,
1070            CancellationCallKind::SelectionHandle,
1071            *call_kind,
1072        )?;
1073        let delivery = self
1074            .cancellation_history
1075            .delivery
1076            .as_ref()
1077            .expect("bound canonical delivery");
1078        if original.is_some()
1079            || delivery.operation_sequence != Some(handle.base_sequence)
1080            || delivery.operation_sequence_span != handle.size as u64
1081        {
1082            return Err(invalid_recorded_history(
1083                "cooperative_cancellation_call_mismatch",
1084                *sequence,
1085                "selection handle for the committed operation range",
1086                &format!("{}:{}", handle.base_sequence, handle.size),
1087                "cancellation delivery targets a different authored selection member",
1088            ));
1089        }
1090        validate_selection_delivery_handle(self, handle)?;
1091        self.replay_cancellation_at(self.command_cursor, CancellationCallKind::SelectionHandle)
1092    }
1093}
1094
1095impl WorkflowContext {
1096    /// Original immutable metadata, visible only at committed delivery.
1097    pub fn cancellation_context(&self) -> Result<Option<CancellationContext>> {
1098        let state = self
1099            .state
1100            .lock()
1101            .map_err(|_| Error::WorkflowStatePoisoned)?;
1102        Ok(
1103            if state.cancellation_consumed && self.cancellation_scope_id == "root" {
1104                state
1105                    .cancellation_history
1106                    .request
1107                    .as_ref()
1108                    .and_then(|request| request.context.clone())
1109                    .map(|context| context.with_replay(Some(Arc::downgrade(&self.state))))
1110            } else {
1111                None
1112            },
1113        )
1114    }
1115
1116    /// Shield explicit cleanup from repeated cancellation checks.
1117    ///
1118    /// Keep the returned guard alive across cleanup awaits. Scopes can nest.
1119    /// The Server retains and enforces the original immutable cleanup deadline.
1120    pub fn cancellation_shield(&self) -> Result<CancellationShield> {
1121        let mut state = self
1122            .state
1123            .lock()
1124            .map_err(|_| Error::WorkflowStatePoisoned)?;
1125        state.cancellation_shield_depth = state
1126            .cancellation_shield_depth
1127            .checked_add(1)
1128            .ok_or_else(|| invalid("cancellation shield nesting overflowed"))?;
1129        Ok(CancellationShield {
1130            state: Arc::clone(&self.state),
1131        })
1132    }
1133}
1134
1135pub(super) fn supports_protocol(version: &str) -> bool {
1136    let Some((major, minor)) = version.split_once('.') else {
1137        return false;
1138    };
1139    major == "1"
1140        && !minor.is_empty()
1141        && minor.bytes().all(|byte| byte.is_ascii_digit())
1142        && minor.parse::<u64>().is_ok_and(|minor| minor >= 20)
1143}
1144
1145fn require_discovery(info: &Value) -> Result<()> {
1146    let protocol = &info["worker_protocol"];
1147    if protocol["server_capabilities"]["cooperative_cancellation"].as_bool() != Some(true)
1148        || !protocol["version"].as_str().is_some_and(supports_protocol)
1149    {
1150        return Err(Error::CooperativeCancellationUnavailable(
1151            "runtime discovery must explicitly advertise support and compatible protocol 1.20"
1152                .to_string(),
1153        ));
1154    }
1155    Ok(())
1156}
1157
1158fn acknowledgment(
1159    value: &Value,
1160    workflow_id: &str,
1161    selected_run: Option<&str>,
1162) -> Result<WorkflowCancellationRequest> {
1163    if value["accepted"].as_bool() != Some(true)
1164        || text(value, "workflow_id")? != workflow_id
1165        || selected_run.is_some_and(|run| value["run_id"].as_str() != Some(run))
1166    {
1167        return Err(invalid(
1168            "acknowledgment does not match the accepted workflow/run request",
1169        ));
1170    }
1171    Ok(WorkflowCancellationRequest {
1172        workflow_id: workflow_id.to_owned(),
1173        run_id: text(value, "run_id")?.to_owned(),
1174        duplicate: value["duplicate"]
1175            .as_bool()
1176            .ok_or_else(|| invalid("duplicate must be a boolean"))?,
1177        cancellation_request: CancellationRequest::from_observation(
1178            &value["cancellation_request"],
1179        )?,
1180    })
1181}
1182
1183impl Client {
1184    /// Report a stopped and dropped remote callback under its original claim.
1185    ///
1186    /// Call only after callback execution has ended. This explicit protocol 1.20
1187    /// operation preserves the original cancellation request and grants no lease
1188    /// or result publication authority. The request has one five-second budget.
1189    pub async fn acknowledge_activity_cancellation(
1190        &self,
1191        task_id: &str,
1192        activity_attempt_id: &str,
1193        lease_owner: &str,
1194        request_id: &str,
1195    ) -> Result<Value> {
1196        if [task_id, activity_attempt_id, lease_owner, request_id]
1197            .iter()
1198            .any(|value| value.trim().is_empty() || value.len() > 255)
1199        {
1200            return Err(invalid(
1201                "activity stop receipt requires bounded original claim and request identities",
1202            ));
1203        }
1204        tokio::time::timeout(CONTROL_BUDGET, async {
1205            let value: Value = activity_task_response(
1206                self.request_json(
1207                    reqwest::Method::POST,
1208                    &format!("/worker/activity-tasks/{}/acknowledge-cancellation", percent_encode_path_segment(task_id)),
1209                    RequestProtocol::Worker("1.20"),
1210                    Some(&json!({"activity_attempt_id":activity_attempt_id,"lease_owner":lease_owner,"request_id":request_id})),
1211                ).await,
1212                "acknowledge-cancellation", task_id, activity_attempt_id,
1213            )?;
1214            if value["task_id"].as_str() != Some(task_id)
1215                || value["activity_attempt_id"].as_str() != Some(activity_attempt_id)
1216                || value["lease_owner"].as_str() != Some(lease_owner)
1217                || value["request_id"].as_str() != Some(request_id)
1218                || value["acknowledged"].as_bool() != Some(true)
1219                || value["duplicate"].as_bool().is_none()
1220                || value.get("reason") != Some(&Value::Null)
1221                || value["heartbeat_recorded"].as_bool() != Some(false)
1222                || text(&value, "history_event_id").is_err()
1223            {
1224                return Err(invalid("activity callback-stop acknowledgment did not prove the original claim and receipt"));
1225            }
1226            Ok(value)
1227        }).await.map_err(|_| Error::Timeout)?
1228    }
1229
1230    /// Observe an exact activity attempt without renewing its lease or progress.
1231    ///
1232    /// This explicit worker-protocol 1.20 operation has one five-second budget.
1233    /// A pending workflow request alone does not cancel an activity. Its reply
1234    /// reports the runtime's current continuation authority after delivery.
1235    pub async fn activity_task_status(
1236        &self,
1237        task_id: &str,
1238        activity_attempt_id: &str,
1239        lease_owner: &str,
1240    ) -> Result<Value> {
1241        if [task_id, activity_attempt_id, lease_owner]
1242            .iter()
1243            .any(|value| value.trim().is_empty())
1244        {
1245            return Err(invalid("activity observation requires the actual claim"));
1246        }
1247        tokio::time::timeout(CONTROL_BUDGET, async {
1248            let value: Value = activity_task_response(
1249                self.request_json(
1250                    reqwest::Method::POST,
1251                    &format!(
1252                        "/worker/activity-tasks/{}/status",
1253                        percent_encode_path_segment(task_id)
1254                    ),
1255                    RequestProtocol::Worker("1.20"),
1256                    Some(&json!({
1257                        "activity_attempt_id":activity_attempt_id,"lease_owner":lease_owner
1258                    })),
1259                )
1260                .await,
1261                "status",
1262                task_id,
1263                activity_attempt_id,
1264            )?;
1265            if value["task_id"].as_str() != Some(task_id)
1266                || value["activity_attempt_id"].as_str() != Some(activity_attempt_id)
1267                || value["lease_owner"].as_str() != Some(lease_owner)
1268                || value["can_continue"].as_bool().is_none()
1269                || value["cancel_requested"].as_bool().is_none()
1270                || value["heartbeat_recorded"].as_bool() != Some(false)
1271            {
1272                return Err(invalid(
1273                    "activity observation did not acknowledge the exact claim",
1274                ));
1275            }
1276            Ok(value)
1277        })
1278        .await
1279        .map_err(|_| Error::Timeout)?
1280    }
1281
1282    /// Acquire a claim with protocol 1.20 and retain its pending observation.
1283    ///
1284    /// The Server must have admitted a capable worker registration. This method
1285    /// registers no capability and does not change ordinary [`Worker`] polling.
1286    /// It never substitutes a worker ID for a missing lease owner or invents a
1287    /// task attempt. Poll retries reuse one request ID. Poll and history loading
1288    /// share one long-poll budget plus five seconds, with at most 128 pages.
1289    /// Managed Workers separately budget claimed hydration using the Client
1290    /// timeout while maintaining task authority.
1291    pub async fn poll_cooperative_workflow_task(
1292        &self,
1293        worker_id: &str,
1294        task_queue: &str,
1295        timeout: Duration,
1296    ) -> Result<CooperativeWorkflowTaskPoll> {
1297        self.poll_cooperative_workflow_task_with_request_id(
1298            worker_id,
1299            task_queue,
1300            timeout,
1301            &unique_request_id("rust-workflow-poll"),
1302            1,
1303            false,
1304        )
1305        .await
1306    }
1307
1308    async fn poll_cooperative_workflow_task_with_request_id(
1309        &self,
1310        worker_id: &str,
1311        task_queue: &str,
1312        timeout: Duration,
1313        poll_request_id: &str,
1314        transport_retries: usize,
1315        managed: bool,
1316    ) -> Result<CooperativeWorkflowTaskPoll> {
1317        if worker_id.trim().is_empty()
1318            || task_queue.trim().is_empty()
1319            || poll_request_id.trim().is_empty()
1320        {
1321            return Err(invalid(
1322                "cooperative polling requires a worker and task queue",
1323            ));
1324        }
1325        let budget = timeout
1326            .checked_add(CONTROL_BUDGET)
1327            .ok_or_else(|| invalid("cooperative poll timeout exceeds its supported budget"))?;
1328        let body = json!({
1329            "worker_id":worker_id, "task_queue":task_queue,
1330            "poll_request_id":poll_request_id,
1331            "timeout_seconds":long_poll_timeout_seconds(timeout),
1332            "history_page_size":WORKFLOW_HISTORY_PAGE_SIZE,
1333            "build_id":self.worker_build_id,
1334        });
1335        let deadline = tokio::time::Instant::now() + budget;
1336        let mut value: Value = tokio::time::timeout(
1337            budget,
1338            self.poll_request_json_unresolved(
1339                "/worker/workflow-tasks/poll",
1340                RequestProtocol::Worker("1.20"),
1341                &body,
1342                budget,
1343                transport_retries,
1344            ),
1345        )
1346        .await
1347        .map_err(|_| Error::Timeout)??;
1348        let hydration =
1349            workflow_hydration::HydrationClaim::from_poll(&value, worker_id, &self.namespace)?
1350                .map(workflow_hydration::HydrationClaim::cooperative);
1351        let loading = workflow_hydration::HydrationClaim::protect(hydration, self, async {
1352            let mut verified_payloads = runtime_payloads::VerifiedPayloads::new();
1353            self.resolve_runtime_payloads_with_cache(
1354                &mut value,
1355                "/worker/workflow-tasks/poll",
1356                RequestProtocol::Worker("1.20"),
1357                &mut verified_payloads,
1358            )
1359            .await?;
1360            let mut response: PollWorkflowTaskResponse = serde_json::from_value(value.clone())
1361                .map_err(|_| invalid("cooperative poll returned a malformed envelope or task"))?;
1362            let outcome = response.outcome();
1363            let task = if let Some(task) = response.task.take() {
1364                let (owner, _) = cancellation_claim(&task)?;
1365                if owner != worker_id
1366                    || value["task"]["workflow_task_attempt"].as_u64()
1367                        != Some(task.workflow_task_attempt)
1368                {
1369                    return Err(invalid(
1370                        "cooperative poll did not return the caller's actual owner and attempt",
1371                    ));
1372                }
1373                let cancellation_request = match value["task"].get("cancellation_request") {
1374                    None | Some(Value::Null) => None,
1375                    Some(observation) => Some(CancellationRequest::from_observation(observation)?),
1376                };
1377                let mut claim = CooperativeWorkflowTask {
1378                    task,
1379                    cancellation_request,
1380                    sticky_snapshot: None,
1381                    verified_payloads,
1382                };
1383                if self.sticky_cache.is_some() {
1384                    claim.sticky_snapshot = Some(
1385                        self.load_sticky_history(&mut claim.task, &value["task"], worker_id)
1386                            .await?,
1387                    );
1388                } else {
1389                    self.load_cooperative_claim_history(&mut claim).await?;
1390                }
1391                Some(claim)
1392            } else {
1393                None
1394            };
1395            Ok(CooperativeWorkflowTaskPoll {
1396                task,
1397                outcome,
1398                protocol_version: response.protocol_version,
1399                server_capabilities: response.server_capabilities,
1400            })
1401        });
1402        let (mut loaded, pending) = if managed {
1403            loading.await?
1404        } else {
1405            tokio::time::timeout_at(deadline, loading)
1406                .await
1407                .map_err(|_| Error::Timeout)??
1408        };
1409        if let (Some(claim), Some(pending)) = (loaded.task.as_mut(), pending) {
1410            claim.cancellation_request = Some(pending);
1411        }
1412        Ok(loaded)
1413    }
1414
1415    async fn load_cooperative_claim_history(
1416        &self,
1417        claim: &mut CooperativeWorkflowTask,
1418    ) -> Result<()> {
1419        let (owner, _) = cancellation_claim(&claim.task)?;
1420        let owner = owner.to_owned();
1421        let mut token = claim.task.next_history_page_token.clone();
1422        let mut seen = BTreeSet::new();
1423        while let Some(current) = token.take() {
1424            if current.trim().is_empty()
1425                || seen.len() >= MAX_REFRESH_PAGES
1426                || !seen.insert(current.clone())
1427            {
1428                return Err(invalid(
1429                    "claim history exceeded its page bound or returned an invalid/repeated token",
1430                ));
1431            }
1432            let body = json!({
1433                "lease_owner":owner,"workflow_task_attempt":claim.task.workflow_task_attempt,
1434                "next_history_page_token":current,"history_page_size":WORKFLOW_HISTORY_PAGE_SIZE,
1435            });
1436            let value: Value = self
1437                .request_json(
1438                    reqwest::Method::POST,
1439                    &format!(
1440                        "/worker/workflow-tasks/{}/history",
1441                        percent_encode_path_segment(&claim.task.task_id)
1442                    ),
1443                    RequestProtocol::Worker("1.20"),
1444                    Some(&body),
1445                )
1446                .await?;
1447            if value["task_id"].as_str() != Some(claim.task.task_id.as_str())
1448                || value["workflow_task_attempt"].as_u64() != Some(claim.task.workflow_task_attempt)
1449            {
1450                return Err(invalid(
1451                    "claim history changed the selected task or attempt",
1452                ));
1453            }
1454            let events = value["history_events"]
1455                .as_array()
1456                .ok_or_else(|| invalid("claim history page must contain an event array"))?;
1457            if events.len() > WORKFLOW_HISTORY_PAGE_SIZE as usize {
1458                return Err(invalid(
1459                    "claim history page exceeds its requested event limit",
1460                ));
1461            }
1462            token = match value.get("next_history_page_token") {
1463                Some(Value::Null) => None,
1464                Some(Value::String(next)) if !next.trim().is_empty() && !events.is_empty() => {
1465                    Some(next.clone())
1466                }
1467                _ => return Err(invalid("claim history page token or progress is invalid")),
1468            };
1469            let page: WorkflowTaskHistoryPage = serde_json::from_value(value)
1470                .map_err(|_| invalid("claim history page contains malformed fields or events"))?;
1471            if page
1472                .history_events
1473                .iter()
1474                .any(|event| event.event_type.trim().is_empty())
1475            {
1476                return Err(invalid("claim history event type must be non-empty"));
1477            }
1478            claim.task.append_history_page(page);
1479        }
1480        Ok(())
1481    }
1482
1483    /// Renew the exact selected workflow-task lease using worker protocol 1.20.
1484    ///
1485    /// The reply must acknowledge the actual task, owner and attempt. Renewal
1486    /// neither commits cancellation delivery nor extends its cleanup deadline.
1487    pub async fn heartbeat_workflow_task(
1488        &self,
1489        task: &WorkflowTask,
1490        original: Option<&CancellationRequest>,
1491    ) -> Result<WorkflowTaskHeartbeat> {
1492        self.heartbeat_workflow_task_with_protocol(task, original, "1.20")
1493            .await
1494    }
1495
1496    pub(super) async fn heartbeat_workflow_task_with_protocol(
1497        &self,
1498        task: &WorkflowTask,
1499        original: Option<&CancellationRequest>,
1500        protocol: &'static str,
1501    ) -> Result<WorkflowTaskHeartbeat> {
1502        let (owner, _) = cancellation_claim(task)?;
1503        if let Some(original) = original {
1504            original.validate_observation()?;
1505        }
1506        tokio::time::timeout(CONTROL_BUDGET, async {
1507            let response: Value = self.request_json(
1508                reqwest::Method::POST,
1509                &format!("/worker/workflow-tasks/{}/heartbeat", percent_encode_path_segment(&task.task_id)),
1510                RequestProtocol::Worker(protocol),
1511                Some(&json!({"lease_owner":owner,"workflow_task_attempt":task.workflow_task_attempt})),
1512            ).await?;
1513            if response["task_id"].as_str() != Some(task.task_id.as_str())
1514                || response["workflow_task_attempt"].as_u64() != Some(task.workflow_task_attempt)
1515                || response["lease_owner"].as_str() != Some(owner)
1516                || response["renewed"].as_bool() != Some(true)
1517                || response.get("reason") != Some(&Value::Null)
1518                || response["task_status"].as_str() != Some("leased")
1519            {
1520                return Err(invalid("workflow heartbeat did not acknowledge the exact leased claim"));
1521            }
1522            let expires = text(&response, "lease_expires_at")?;
1523            DateTime::parse_from_rfc3339(expires).map_err(|_| invalid("workflow heartbeat lease expiry must include a timezone"))?;
1524            let run_status = text(&response, "run_status")?;
1525            if !matches!(run_status, "pending" | "running" | "waiting") {
1526                return Err(invalid("workflow heartbeat did not acknowledge an active run"));
1527            }
1528            let cancellation_request = match response.get("cancellation_request") {
1529                None | Some(Value::Null) if original.is_none() => None,
1530                None | Some(Value::Null) => return Err(invalid("workflow heartbeat omitted its original pending request")),
1531                Some(observation) => {
1532                    let current = CancellationRequest::from_observation(observation)?;
1533                    Some(match original {
1534                        Some(original) => original.preserve_observation(&current)?,
1535                        None => current,
1536                    })
1537                },
1538            };
1539            Ok(WorkflowTaskHeartbeat {
1540                task_id:task.task_id.clone(), workflow_task_attempt:task.workflow_task_attempt,
1541                lease_owner:owner.to_owned(), lease_expires_at:expires.to_owned(),
1542                run_status:run_status.to_owned(), cancellation_request,
1543            })
1544        }).await.map_err(|_| Error::Timeout)?
1545    }
1546
1547    /// Commit cooperative delivery on the exact selected workflow-task claim.
1548    ///
1549    /// This explicit worker-protocol 1.20 operation renews no lease and advertises
1550    /// no worker capability. The Server requires a previously admitted capable
1551    /// claim. Reload canonical history before exposing cancellation to workflow
1552    /// code, including when an acknowledgment is lost. A cancellation wait explicitly
1553    /// releases the claim and must return the worker to polling.
1554    pub async fn deliver_workflow_cancellation(
1555        &self,
1556        task: &WorkflowTask,
1557        delivery: &CancellationDelivery,
1558    ) -> Result<CancellationDeliveryReply> {
1559        let (owner, run_id) = cancellation_claim(task)?;
1560        let body = json!({
1561            "lease_owner":owner, "workflow_task_attempt":task.workflow_task_attempt,
1562            "request_id":delivery.request_id, "sequence":delivery.sequence,
1563            "call_kind":delivery.call_kind, "sequence_span":delivery.sequence_span,
1564            "operation_sequence":delivery.operation_sequence,
1565            "operation_sequence_span":delivery.operation_sequence_span
1566        });
1567        let mut payload = body.clone();
1568        payload["workflow_command_id"] = json!(delivery.request_id);
1569        if CancellationDelivery::from_payload(&payload)? != *delivery {
1570            return Err(invalid(
1571                "delivery must name a valid authored operation range",
1572            ));
1573        }
1574        tokio::time::timeout(CONTROL_BUDGET, async {
1575            let path = format!(
1576                "/worker/workflow-tasks/{}/deliver-cancellation",
1577                percent_encode_path_segment(&task.task_id)
1578            );
1579            let response: Value = self
1580                .request_json(
1581                    reqwest::Method::POST,
1582                    &path,
1583                    RequestProtocol::Worker("1.20"),
1584                    Some(&body),
1585                )
1586                .await?;
1587            if response["delivered"].as_bool() == Some(false)
1588                && match response["reason"].as_str() {
1589                    Some("cancellation_waiting_for_service_operation") => {
1590                        delivery.call_kind == CancellationCallKind::ServiceOperation
1591                    }
1592                    Some("cancellation_waiting_for_child") => matches!(
1593                        delivery.call_kind,
1594                        CancellationCallKind::Child
1595                            | CancellationCallKind::Parallel
1596                            | CancellationCallKind::SelectionHandle
1597                    ),
1598                    Some("cancellation_waiting_for_activity") => matches!(
1599                        delivery.call_kind,
1600                        CancellationCallKind::Activity
1601                            | CancellationCallKind::LocalActivity
1602                            | CancellationCallKind::Parallel
1603                            | CancellationCallKind::SelectionHandle
1604                    ),
1605                    _ => false,
1606                }
1607                && response["claim_released"].as_bool() == Some(true)
1608                && response["task_id"].as_str() == Some(task.task_id.as_str())
1609                && response["workflow_run_id"].as_str() == Some(run_id)
1610                && [
1611                    "request_id",
1612                    "sequence",
1613                    "call_kind",
1614                    "sequence_span",
1615                    "operation_sequence",
1616                    "operation_sequence_span",
1617                ]
1618                .iter()
1619                .all(|field| response.get(*field).is_none_or(Value::is_null))
1620            {
1621                return Ok(CancellationDeliveryReply::ClaimReleased {
1622                    task_id: task.task_id.clone(),
1623                    run_id: run_id.to_owned(),
1624                });
1625            }
1626            if response["delivered"].as_bool() != Some(true)
1627                || response["task_id"].as_str() != Some(task.task_id.as_str())
1628                || response["workflow_run_id"].as_str() != Some(run_id)
1629                || response.get("reason") != Some(&Value::Null)
1630                || [
1631                    "sequence_span",
1632                    "operation_sequence",
1633                    "operation_sequence_span",
1634                ]
1635                .iter()
1636                .any(|field| response.get(*field).is_none())
1637            {
1638                return Err(invalid(
1639                    "delivery acknowledgment does not match the selected task/run",
1640                ));
1641            }
1642            let mut recorded = response.clone();
1643            recorded["workflow_command_id"] = response["request_id"].clone();
1644            if CancellationDelivery::from_payload(&recorded)? != *delivery {
1645                return Err(invalid(
1646                    "delivery acknowledgment changed its authored operation range",
1647                ));
1648            }
1649            Ok(CancellationDeliveryReply::Delivered(
1650                CancellationDeliveryReceipt {
1651                    task_id: task.task_id.clone(),
1652                    run_id: run_id.to_owned(),
1653                    delivery: delivery.clone(),
1654                },
1655            ))
1656        })
1657        .await
1658        .map_err(|_| Error::Timeout)?
1659    }
1660
1661    /// Reload canonical history with the Server-issued token and exact claim.
1662    ///
1663    /// The refresh has one five-second budget, at most 128 pages, and the existing
1664    /// SDK page-size limit. Invalid, repeated or non-progressing tokens and pages
1665    /// fail closed. This returns fresh history without modifying the caller's
1666    /// previous task snapshot or its original request identity.
1667    pub async fn refresh_workflow_cancellation_history(
1668        &self,
1669        task: &WorkflowTask,
1670        observation: &CancellationRequest,
1671    ) -> Result<Vec<HistoryEvent>> {
1672        self.refresh_workflow_cancellation_history_with_cache(
1673            task,
1674            observation,
1675            &mut runtime_payloads::VerifiedPayloads::new(),
1676        )
1677        .await
1678    }
1679
1680    async fn refresh_workflow_cancellation_history_with_cache(
1681        &self,
1682        task: &WorkflowTask,
1683        observation: &CancellationRequest,
1684        verified_payloads: &mut runtime_payloads::VerifiedPayloads,
1685    ) -> Result<Vec<HistoryEvent>> {
1686        let (owner, run_id) = cancellation_claim(task)?;
1687        observation.validate_observation()?;
1688        let first_token = observation
1689            .history_refresh_page_token
1690            .clone()
1691            .expect("validated history token");
1692        tokio::time::timeout(CONTROL_BUDGET, async {
1693            let path = format!("/worker/workflow-tasks/{}/history", percent_encode_path_segment(&task.task_id));
1694            let mut token = Some(first_token);
1695            let mut seen = BTreeSet::new();
1696            let mut history = Vec::new();
1697            while let Some(current) = token.take() {
1698                if seen.len() >= MAX_REFRESH_PAGES || !seen.insert(current.clone()) {
1699                    return Err(invalid("canonical history refresh exceeded its page bound or repeated a token"));
1700                }
1701                let body = json!({
1702                    "lease_owner":owner, "workflow_task_attempt":task.workflow_task_attempt,
1703                    "next_history_page_token":current, "history_page_size":WORKFLOW_HISTORY_PAGE_SIZE,
1704                });
1705                let mut page: Value = self.request_json_unresolved_with_timeout(
1706                    reqwest::Method::POST, &path, RequestProtocol::Worker("1.20"), Some(&body),
1707                    CONTROL_BUDGET,
1708                ).await?;
1709                self.resolve_runtime_payloads_with_cache(&mut page, &path, RequestProtocol::Worker("1.20"), verified_payloads).await?;
1710                if page["task_id"].as_str() != Some(task.task_id.as_str())
1711                    || page["workflow_task_attempt"].as_u64() != Some(task.workflow_task_attempt)
1712                {
1713                    return Err(invalid("canonical history page changed the selected task/attempt"));
1714                }
1715                let events = page["history_events"].as_array().ok_or_else(|| invalid("canonical history page must contain an event array"))?;
1716                if events.len() > WORKFLOW_HISTORY_PAGE_SIZE as usize {
1717                    return Err(invalid("canonical history page exceeds its requested event limit"));
1718                }
1719                token = match page.get("next_history_page_token") {
1720                    Some(Value::Null) => None,
1721                    Some(Value::String(next)) if !next.is_empty() && !events.is_empty() => Some(next.clone()),
1722                    _ => return Err(invalid("canonical history page token or progress is invalid")),
1723                };
1724                for event in events {
1725                    let event: HistoryEvent = serde_json::from_value(event.clone()).map_err(|_| invalid("canonical history page contains a malformed event"))?;
1726                    if event.event_type.trim().is_empty() {
1727                        return Err(invalid("canonical history event type must be non-empty"));
1728                    }
1729                    history.push(event);
1730                }
1731            }
1732            let canonical = CancellationHistory::from_events(&history, run_id, Some(observation))?;
1733            if canonical.request_index >= history.len() {
1734                return Err(invalid("canonical refresh omitted the original request event"));
1735            }
1736            Ok(history)
1737        }).await.map_err(|_| Error::Timeout)?
1738    }
1739
1740    /// Request bounded workflow-authored cleanup on a capable runtime.
1741    ///
1742    /// This is separate from terminal cancellation. Discovery must advertise
1743    /// cooperative support and compatible protocol 1.20. The Server also
1744    /// refuses an active workflow claim that cannot deliver cooperation.
1745    /// Repeated requests retain its original request identity and deadline.
1746    pub async fn request_workflow_cancellation(
1747        &self,
1748        workflow_id: &str,
1749        options: CooperativeCancellationOptions,
1750    ) -> Result<WorkflowCancellationRequest> {
1751        self.request_workflow_cancellation_target(workflow_id, None, options)
1752            .await
1753    }
1754
1755    /// Request cleanup only if the selected run remains current.
1756    pub async fn request_workflow_run_cancellation(
1757        &self,
1758        workflow_id: &str,
1759        run_id: &str,
1760        options: CooperativeCancellationOptions,
1761    ) -> Result<WorkflowCancellationRequest> {
1762        self.request_workflow_cancellation_target(workflow_id, Some(run_id), options)
1763            .await
1764    }
1765
1766    async fn request_workflow_cancellation_target(
1767        &self,
1768        workflow_id: &str,
1769        run_id: Option<&str>,
1770        options: CooperativeCancellationOptions,
1771    ) -> Result<WorkflowCancellationRequest> {
1772        if workflow_id.trim().is_empty() || run_id.is_some_and(|id| id.trim().is_empty()) {
1773            return Err(invalid(
1774                "workflow and selected run identities must be non-empty",
1775            ));
1776        }
1777        if options
1778            .cleanup_timeout_seconds
1779            .is_some_and(|seconds| !(1..=3600).contains(&seconds))
1780            || options
1781                .reason
1782                .as_ref()
1783                .is_some_and(|reason| reason.chars().count() > 1000)
1784        {
1785            return Err(invalid(
1786                "cleanup timeout must be 1..3600 seconds and reason at most 1000 characters",
1787            ));
1788        }
1789
1790        // Bound discovery, mutation and any storage retry by one total budget.
1791        tokio::time::timeout(CONTROL_BUDGET, async {
1792            let info: Value = self
1793                .request_json(
1794                    reqwest::Method::GET,
1795                    "/cluster/info",
1796                    RequestProtocol::ControlPlane,
1797                    Option::<&Value>::None,
1798                )
1799                .await?;
1800            require_discovery(&info)?;
1801            let mut path = format!("/workflows/{}", percent_encode_path_segment(workflow_id));
1802            if let Some(run_id) = run_id {
1803                path.push_str(&format!("/runs/{}", percent_encode_path_segment(run_id)));
1804            }
1805            path.push_str("/request-cancellation");
1806            let response: Value = self
1807                .request_json(
1808                    reqwest::Method::POST,
1809                    &path,
1810                    RequestProtocol::ControlPlane,
1811                    Some(&options),
1812                )
1813                .await?;
1814            acknowledgment(&response, workflow_id, run_id)
1815        })
1816        .await
1817        .map_err(|_| Error::Timeout)?
1818    }
1819}
1820
1821impl Worker {
1822    pub(super) async fn settle_cooperative_activity(
1823        &self,
1824        task: worker_session::SessionActivityTask,
1825        task_metrics: &mut crate::metrics::WorkerObservation,
1826    ) -> Result<ManagedPollOutcome> {
1827        let session = self.track_session_task(task.worker_session.as_ref())?;
1828        let metadata = task.invocation(session);
1829        let task = task.task;
1830        let guard = ActivityClaimGuard::new(&self.client, &task, &self.worker_id)?;
1831        let _abandon_on_drop = AbandonActivityOnDrop(guard.clone());
1832        if guard.observe().await.is_err() {
1833            return Ok(ManagedPollOutcome::Handled);
1834        }
1835        let mut callback_started = false;
1836        let result = {
1837            let invocation = self.execute_cooperative_activity_task(
1838                &task,
1839                &guard,
1840                &mut callback_started,
1841                metadata,
1842            );
1843            tokio::pin!(invocation);
1844            loop {
1845                tokio::select! {
1846                    biased;
1847                    _ = guard.wait_for_shutdown() => {
1848                        guard.abandon();
1849                        break None;
1850                    }
1851                    result = &mut invocation => break Some(result),
1852                    _ = tokio::time::sleep(Duration::from_secs(1)) => {
1853                        if guard.observe().await.is_err() {
1854                            break None;
1855                        }
1856                    }
1857                }
1858            }
1859        };
1860        // The invocation and its callback future are dropped before any receipt.
1861        let Some(result) = result else {
1862            if callback_started {
1863                guard.acknowledge_stopped().await?;
1864            }
1865            return Ok(ManagedPollOutcome::Handled);
1866        };
1867        // Both genuine application failures and successful results need current
1868        // authority before result upload or completion/failure publication.
1869        if matches!(result, Err(Error::ActivityExecutionAbandoned(_)))
1870            || guard.observe().await.is_err()
1871        {
1872            if callback_started {
1873                guard.acknowledge_stopped().await?;
1874            }
1875            return Ok(ManagedPollOutcome::Handled);
1876        }
1877        let task_outcome = if result.is_ok() {
1878            "completed"
1879        } else {
1880            "failed"
1881        };
1882        let settlement = match result {
1883            Ok(value) => {
1884                self.client
1885                    .complete_activity_task(
1886                        &guard.task_id,
1887                        &guard.attempt_id,
1888                        &guard.owner,
1889                        value,
1890                        &task.payload_codec,
1891                    )
1892                    .await
1893            }
1894            Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
1895            Err(error) => {
1896                self.client
1897                    .fail_activity_task_with_error(
1898                        &guard.task_id,
1899                        &guard.attempt_id,
1900                        &guard.owner,
1901                        &crate::ActivityError::from_error(&error, "RustActivityFailure"),
1902                    )
1903                    .await
1904            }
1905        };
1906        if let Err(error) = settlement {
1907            if !activity_task_rejection_is_final(&error) {
1908                return Err(error);
1909            }
1910        }
1911        task_metrics.outcome(task_outcome);
1912        Ok(ManagedPollOutcome::Handled)
1913    }
1914
1915    async fn execute_cooperative_activity_task(
1916        &self,
1917        task: &ActivityTask,
1918        guard: &ActivityClaimGuard,
1919        callback_started: &mut bool,
1920        invocation: worker_session::ActivityInvocation,
1921    ) -> Result<AvroValue> {
1922        #[cfg(feature = "telemetry")]
1923        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
1924            !self
1925                .client
1926                .observability_context_supported
1927                .load(Ordering::SeqCst)
1928        }) {
1929            return telemetry
1930                .run(
1931                    "durable.activity.task",
1932                    self.activity_telemetry_fields(task),
1933                    false,
1934                    self.execute_cooperative_activity_task_inner(
1935                        task,
1936                        guard,
1937                        callback_started,
1938                        invocation,
1939                    ),
1940                )
1941                .await;
1942        }
1943        self.execute_cooperative_activity_task_inner(task, guard, callback_started, invocation)
1944            .await
1945    }
1946
1947    async fn execute_cooperative_activity_task_inner(
1948        &self,
1949        task: &ActivityTask,
1950        guard: &ActivityClaimGuard,
1951        callback_started: &mut bool,
1952        invocation: worker_session::ActivityInvocation,
1953    ) -> Result<AvroValue> {
1954        let worker_session::ActivityInvocation {
1955            worker_session,
1956            hydration_claim,
1957            retry_info,
1958        } = invocation;
1959        validate_activity_task_payloads(task)?;
1960        let handler = self
1961            .activities
1962            .get(&task.activity_type)
1963            .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
1964        let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
1965        let context = ActivityContext {
1966            client: self.client.clone(),
1967            task_id: guard.task_id.clone(),
1968            activity_attempt_id: guard.attempt_id.clone(),
1969            lease_owner: guard.owner.clone(),
1970            activity_type: task.activity_type.clone(),
1971            attempt_number: task.attempt_number,
1972            retry_info,
1973            activity_execution_id: task.activity_execution_id.clone(),
1974            workflow_id: task.workflow_id.clone(),
1975            run_id: task.run_id.clone(),
1976            task_queue: self.task_queue.clone(),
1977            worker_id: self.worker_id.clone(),
1978            claim_guard: Some(guard.clone()),
1979            local_heartbeats: None,
1980            worker_session,
1981        };
1982        if let Some(claim) = &hydration_claim {
1983            claim.confirm(&self.client).await?;
1984        }
1985        guard.boundary()?;
1986        *callback_started = true;
1987        #[cfg(feature = "telemetry")]
1988        if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
1989            self.client
1990                .observability_context_supported
1991                .load(Ordering::SeqCst)
1992        }) {
1993            return telemetry
1994                .run_observed(
1995                    "durable.activity.task",
1996                    self.activity_telemetry_fields(task),
1997                    false,
1998                    self.activity_observations(task),
1999                    async { self.activity_callback(handler, context, args, false).await },
2000                )
2001                .await;
2002        }
2003        self.activity_callback(handler, context, args, false).await
2004    }
2005
2006    pub(super) async fn poll_cooperative_workflow_once(&self) -> Result<ManagedPollOutcome> {
2007        let mut poll_metrics = self.metrics.worker(false, "workflow", &self.task_queue);
2008        let poll_request_id = unique_request_id("rust-workflow-poll");
2009        let response = self
2010            .retry_worker_operation(|| {
2011                self.client.poll_cooperative_workflow_task_with_request_id(
2012                    &self.worker_id,
2013                    &self.task_queue,
2014                    self.poll_timeout,
2015                    &poll_request_id,
2016                    0,
2017                    true,
2018                )
2019            })
2020            .await;
2021        poll_metrics.poll(&response, |value| value.outcome.clone());
2022        drop(poll_metrics);
2023        let Some(response) = self.settle_worker_poll_response(response).await? else {
2024            return Ok(ManagedPollOutcome::Idle);
2025        };
2026        if response.outcome.should_stop() {
2027            return Ok(ManagedPollOutcome::Stop);
2028        }
2029        let memo_updates_supported =
2030            runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
2031        let Some(claim) = response.task else {
2032            return Ok(ManagedPollOutcome::Idle);
2033        };
2034        self.client.release_worker_poll();
2035        let mut task_metrics = self.metrics.worker(true, "workflow", &self.task_queue);
2036        task_metrics.outcome("failed");
2037        // Anchor the immutable cleanup deadline once, before replay. Deferring
2038        // completion must not grant another cleanup budget on each retry.
2039        let mut completion_worker = None;
2040        if let (Some(request), Some(_)) = (
2041            claim.cancellation_request.as_ref(),
2042            self.client.worker_storage_admission.as_ref(),
2043        ) {
2044            let mut worker = self.clone();
2045            let admission = worker.client.worker_storage_admission.as_mut().unwrap();
2046            let deadline = DateTime::parse_from_rfc3339(&request.cleanup_deadline_at)
2047                .map_err(|_| invalid("invalid original cleanup deadline"))?;
2048            let monotonic_now = tokio::time::Instant::now();
2049            let unix = SystemTime::now()
2050                .duration_since(UNIX_EPOCH)
2051                .map_err(|_| Error::Timeout)?;
2052            let now = DateTime::<chrono::Utc>::from_timestamp(
2053                i64::try_from(unix.as_secs()).map_err(|_| Error::Timeout)?,
2054                unix.subsec_nanos(),
2055            )
2056            .ok_or(Error::Timeout)?;
2057            let remaining = (deadline.with_timezone(&chrono::Utc) - now)
2058                .to_std()
2059                .unwrap_or(Duration::ZERO);
2060            admission.workflow_completion_retry_deadline = Some(monotonic_now + remaining);
2061            completion_worker = Some(worker);
2062        }
2063        // An uncertain observation, delivery or canonical refresh cannot become
2064        // an application failure or be published as a workflow-task decision.
2065        let Some(decision) = self.replay_cooperative_workflow_claim(&claim).await? else {
2066            return Ok(ManagedPollOutcome::Handled);
2067        };
2068        let (owner, _) = cancellation_claim(&claim.task)?;
2069        let task_outcome = crate::metrics::workflow_task_outcome(Some(&decision));
2070        let settled = completion_worker
2071            .as_ref()
2072            .unwrap_or(self)
2073            .settle_workflow_task_decision(
2074                &claim.task.task_id,
2075                owner,
2076                claim.task.workflow_task_attempt,
2077                claim.task.run_id.as_deref(),
2078                Ok(decision),
2079                memo_updates_supported,
2080                claim.sticky_snapshot.clone(),
2081            )
2082            .await;
2083        if settled.is_ok() {
2084            task_metrics.outcome(task_outcome);
2085        }
2086        settled
2087    }
2088
2089    async fn replay_cooperative_workflow_claim(
2090        &self,
2091        claim: &CooperativeWorkflowTask,
2092    ) -> Result<Option<WorkflowTaskDecision>> {
2093        let mut verified_payloads = claim.verified_payloads.clone();
2094        let (owner, run_id) = cancellation_claim(&claim.task)?;
2095        if owner != self.worker_id {
2096            return Err(invalid(
2097                "cooperative replay requires this worker's actual claim",
2098            ));
2099        }
2100        let mut task = claim.task.clone();
2101        let Some(observation) = claim.cancellation_request.as_ref() else {
2102            let canonical = CancellationHistory::from_events(&task.history_events, run_id, None)?;
2103            if canonical.request.is_some() {
2104                return Err(invalid(
2105                    "cooperative replay omitted its original pending observation",
2106                ));
2107            }
2108            for _ in 0..1000 {
2109                let mut decision = self.execute_workflow_task_decision(task.clone())?;
2110                if let Some(intent) = decision.cancellation_scope_delivery.as_ref() {
2111                    if !decision.commands.is_empty() {
2112                        decision.cancellation_scope_delivery = None;
2113                        return Ok(Some(decision));
2114                    }
2115                    let mut budget = CancellationScopeDeliveryBudget::new();
2116                    budget.restrict(intent.context.deadline())?;
2117                    let prepared = self
2118                        .client
2119                        .prepare_cancellation_scope_on_claim(
2120                            &task,
2121                            &intent.context,
2122                            &intent.boundary,
2123                            &budget,
2124                        )
2125                        .await?;
2126                    budget.restrict(prepared.authority_deadline())?;
2127                    let delivered = self
2128                        .client
2129                        .deliver_cancellation_scope_on_claim(&task, &prepared, &budget)
2130                        .await?;
2131                    task.history_events = delivered.history().to_vec();
2132                    task.total_history_events = None;
2133                    task.history_size_bytes = None;
2134                    continue;
2135                }
2136                let Some(opening) = decision.cancellation_scope_opening.as_ref() else {
2137                    return Ok(Some(decision));
2138                };
2139                if !decision.commands.is_empty() {
2140                    decision.cancellation_scope_opening = None;
2141                    return Ok(Some(decision));
2142                }
2143                let receipt = self
2144                    .client
2145                    .open_cancellation_scope_on_claim(
2146                        &task,
2147                        opening.sequence,
2148                        &opening.parent_scope_id,
2149                        opening.shield_parent,
2150                    )
2151                    .await?;
2152                task.history_events = receipt.history().to_vec();
2153                task.total_history_events = None;
2154                task.history_size_bytes = None;
2155            }
2156            return Err(invalid(
2157                "workflow exceeded the canonical scope opening replay limit",
2158            ));
2159        };
2160        task.history_events = self
2161            .client
2162            .refresh_workflow_cancellation_history_with_cache(
2163                &claim.task,
2164                observation,
2165                &mut verified_payloads,
2166            )
2167            .await?;
2168        for _ in 0..1000 {
2169            // Count the actual refreshed snapshot. Its byte budget was not
2170            // remeasured, so do not expose the old snapshot's size as current.
2171            task.total_history_events = None;
2172            task.history_size_bytes = None;
2173            let mut decision = self.execute_workflow_task_decision_with_cancellation(
2174                task.clone(),
2175                Some(observation),
2176            )?;
2177            if let Some(intent) = decision.cancellation_scope_delivery.as_ref() {
2178                if !decision.commands.is_empty() {
2179                    decision.cancellation_scope_delivery = None;
2180                    return Ok(Some(decision));
2181                }
2182                let mut budget = CancellationScopeDeliveryBudget::new();
2183                budget.restrict(intent.context.deadline())?;
2184                let prepared = self
2185                    .client
2186                    .prepare_cancellation_scope_on_claim(
2187                        &task,
2188                        &intent.context,
2189                        &intent.boundary,
2190                        &budget,
2191                    )
2192                    .await?;
2193                budget.restrict(prepared.authority_deadline())?;
2194                let delivered = self
2195                    .client
2196                    .deliver_cancellation_scope_on_claim(&task, &prepared, &budget)
2197                    .await?;
2198                task.history_events = delivered.history().to_vec();
2199                continue;
2200            }
2201            let Some(intent) = decision.cancellation_delivery.as_ref() else {
2202                return Ok(Some(decision));
2203            };
2204            if !decision.commands.is_empty() {
2205                // Native permits delivery only at/before its next durable call.
2206                // Commit earlier commands first. Completion releases this claim
2207                // and its successor replays their durable results before delivery.
2208                decision.cancellation_delivery = None;
2209                return Ok(Some(decision));
2210            }
2211            if intent.call_kind == CancellationCallKind::ServiceOperation
2212                && !self.nexus_registration_confirmed.load(Ordering::SeqCst)
2213            {
2214                return Err(Error::CooperativeCancellationUnavailable(
2215                    "nexus_cooperative_cancellation_not_supported: new delivery requires confirmed Nexus registration".into(),
2216                ));
2217            }
2218            let delivery_error = match self
2219                .client
2220                .deliver_workflow_cancellation(&claim.task, intent)
2221                .await
2222            {
2223                Ok(CancellationDeliveryReply::ClaimReleased { .. }) => return Ok(None),
2224                Ok(CancellationDeliveryReply::Delivered(_)) => None,
2225                Err(error) => Some(error),
2226            };
2227            task.history_events = self
2228                .client
2229                .refresh_workflow_cancellation_history_with_cache(
2230                    &claim.task,
2231                    observation,
2232                    &mut verified_payloads,
2233                )
2234                .await?;
2235            let canonical =
2236                CancellationHistory::from_events(&task.history_events, run_id, Some(observation))?;
2237            if canonical.delivery.as_ref() != Some(intent) {
2238                return Err(delivery_error.unwrap_or_else(|| {
2239                    invalid(
2240                        "canonical history did not prove the exact intended cancellation delivery",
2241                    )
2242                }));
2243            }
2244        }
2245        Err(invalid(
2246            "workflow replay did not converge on its canonical cancellation delivery",
2247        ))
2248    }
2249}
2250
2251#[derive(Clone, Debug)]
2252pub(super) struct ActivityClaimGuard {
2253    client: Client,
2254    task_id: String,
2255    attempt_id: String,
2256    owner: String,
2257    active: Arc<AtomicBool>,
2258    cancellation_receipt: Arc<Mutex<Option<Value>>>,
2259    stop: Option<Arc<AtomicBool>>,
2260}
2261
2262struct AbandonActivityOnDrop(ActivityClaimGuard);
2263
2264impl Drop for AbandonActivityOnDrop {
2265    fn drop(&mut self) {
2266        self.0.abandon();
2267    }
2268}
2269
2270impl ActivityClaimGuard {
2271    pub(super) fn new(client: &Client, task: &ActivityTask, worker_id: &str) -> Result<Self> {
2272        let owner = task.lease_owner.as_deref().unwrap_or_default();
2273        let attempt = task
2274            .activity_attempt_id
2275            .as_deref()
2276            .or(task.attempt_id.as_deref())
2277            .unwrap_or_default();
2278        if task.task_id.trim().is_empty()
2279            || attempt.trim().is_empty()
2280            || owner.trim().is_empty()
2281            || owner != worker_id
2282            || matches!((&task.activity_attempt_id, &task.attempt_id), (Some(left), Some(right)) if left != right)
2283        {
2284            return Err(invalid(
2285                "activity execution requires the worker's actual immutable claim",
2286            ));
2287        }
2288        Ok(Self {
2289            client: client.clone(),
2290            task_id: task.task_id.clone(),
2291            attempt_id: attempt.to_owned(),
2292            owner: owner.to_owned(),
2293            active: Arc::new(AtomicBool::new(true)),
2294            cancellation_receipt: Arc::new(Mutex::new(None)),
2295            stop: client
2296                .worker_storage_admission
2297                .as_ref()
2298                .map(|admission| Arc::clone(&admission.stop)),
2299        })
2300    }
2301
2302    fn abandon(&self) {
2303        self.active.store(false, Ordering::SeqCst);
2304    }
2305
2306    /// Caller has already dropped the callback future. Never restores authority.
2307    async fn acknowledge_stopped(&self) -> Result<()> {
2308        self.abandon();
2309        let receipt = self
2310            .cancellation_receipt
2311            .lock()
2312            .map_err(|_| invalid("activity cancellation receipt lock was poisoned"))?
2313            .clone();
2314        if let Some(receipt) = receipt {
2315            self.client
2316                .acknowledge_activity_cancellation(
2317                    &self.task_id,
2318                    &self.attempt_id,
2319                    &self.owner,
2320                    text(&receipt, "request_id")?,
2321                )
2322                .await?;
2323        }
2324        Ok(())
2325    }
2326
2327    fn retain_cancellation_receipt(&self, value: &Value) -> Result<()> {
2328        if value["can_continue"].as_bool() != Some(false)
2329            || value["cancel_requested"].as_bool() != Some(true)
2330        {
2331            return Ok(());
2332        }
2333        let Some(receipt) = value
2334            .get("cancellation_acknowledgement")
2335            .filter(|receipt| receipt.is_object())
2336        else {
2337            return Ok(());
2338        };
2339        if !matches!(
2340            receipt["callback_state"].as_str(),
2341            Some("unknown" | "stopped")
2342        ) || [
2343            "request_id",
2344            "root_request_id",
2345            "cleanup_deadline_at",
2346            "cancellation_history_event_id",
2347        ]
2348        .iter()
2349        .any(|field| text(receipt, field).is_err())
2350            || DateTime::parse_from_rfc3339(text(receipt, "cleanup_deadline_at")?).is_err()
2351        {
2352            return Ok(());
2353        }
2354        let mut retained = self
2355            .cancellation_receipt
2356            .lock()
2357            .map_err(|_| invalid("activity cancellation receipt lock was poisoned"))?;
2358        if let Some(original) = retained.as_ref() {
2359            if [
2360                "request_id",
2361                "root_request_id",
2362                "cleanup_deadline_at",
2363                "cancellation_history_event_id",
2364            ]
2365            .iter()
2366            .any(|field| original[*field] != receipt[*field])
2367            {
2368                return Err(invalid(
2369                    "activity cancellation observation changed its original identity or deadline",
2370                ));
2371            }
2372        } else {
2373            *retained = Some(receipt.clone());
2374        }
2375        Ok(())
2376    }
2377
2378    fn boundary(&self) -> Result<()> {
2379        if !self.active.load(Ordering::SeqCst)
2380            || self
2381                .stop
2382                .as_ref()
2383                .is_some_and(|stop| stop.load(Ordering::SeqCst))
2384        {
2385            self.abandon();
2386            return Err(Error::ActivityExecutionAbandoned(
2387                "callback completed, was abandoned, or its worker is stopping".into(),
2388            ));
2389        }
2390        Ok(())
2391    }
2392
2393    async fn wait_for_shutdown(&self) {
2394        if let Some(stop) = &self.stop {
2395            wait_for_worker_stop(stop).await;
2396        } else {
2397            std::future::pending::<()>().await;
2398        }
2399    }
2400
2401    pub(super) async fn observe(&self) -> Result<()> {
2402        self.boundary()?;
2403        let result = self
2404            .client
2405            .activity_task_status(&self.task_id, &self.attempt_id, &self.owner)
2406            .await
2407            .and_then(|value| {
2408                self.retain_cancellation_receipt(&value)?;
2409                if value["can_continue"].as_bool() != Some(true)
2410                    || value["cancel_requested"].as_bool() != Some(false)
2411                    || value.get("reason") != Some(&Value::Null)
2412                    || value["task_status"].as_str() != Some("leased")
2413                    || value["attempt_status"].as_str() != Some("running")
2414                    || value["activity_status"].as_str() != Some("running")
2415                {
2416                    return Err(invalid("activity observation refused continuation"));
2417                }
2418                let mut bounds = vec![text(&value, "lease_expires_at")?];
2419                if let Some(deadlines) = value.get("deadlines").filter(|v| !v.is_null()) {
2420                    if !deadlines.is_object() {
2421                        return Err(invalid("activity execution deadlines must be an object"));
2422                    }
2423                    for kind in ["heartbeat", "start_to_close", "schedule_to_close"] {
2424                        if let Some(deadline) = deadlines.get(kind).filter(|v| !v.is_null()) {
2425                            bounds.push(
2426                                deadline
2427                                    .as_str()
2428                                    .ok_or_else(|| invalid("invalid activity deadline"))?,
2429                            );
2430                        }
2431                    }
2432                }
2433                if let Some(session) = value.get("worker_session").filter(|v| !v.is_null()) {
2434                    if session["status"].as_str() != Some("active")
2435                        || session["lease_owner"].as_str() != Some(self.owner.as_str())
2436                    {
2437                        return Err(invalid(
2438                            "activity no longer owns its required worker session",
2439                        ));
2440                    }
2441                    bounds.push(text(session, "lease_expires_at")?);
2442                    bounds.push(text(session, "ttl_expires_at")?);
2443                }
2444                for bound in bounds {
2445                    let deadline = DateTime::parse_from_rfc3339(bound)
2446                        .map_err(|_| invalid("activity deadline must include a timezone"))?;
2447                    let now = SystemTime::now()
2448                        .duration_since(UNIX_EPOCH)
2449                        .map_err(|_| invalid("activity observation clock precedes the epoch"))?;
2450                    if !u128::try_from(deadline.timestamp_millis())
2451                        .is_ok_and(|millis| millis > now.as_millis())
2452                    {
2453                        return Err(invalid("activity ownership or execution deadline elapsed"));
2454                    }
2455                }
2456                self.boundary()
2457            });
2458        result.map_err(|error| {
2459            self.abandon();
2460            Error::ActivityExecutionAbandoned(error.to_string())
2461        })
2462    }
2463
2464    pub(super) async fn heartbeat<T: Serialize>(
2465        &self,
2466        context: &ActivityContext,
2467        details: T,
2468    ) -> Result<ActivityHeartbeatResponse> {
2469        if context.task_id != self.task_id
2470            || context.activity_attempt_id != self.attempt_id
2471            || context.lease_owner != self.owner
2472            || context.worker_id != self.owner
2473        {
2474            self.abandon();
2475            return Err(Error::ActivityExecutionAbandoned(
2476                "activity context changed its original claim".into(),
2477            ));
2478        }
2479        self.observe().await?;
2480        let result = tokio::time::timeout(CONTROL_BUDGET, async {
2481            let details = AvroValue::from_serialize(&details)?.into_json()?;
2482            self.boundary()?;
2483            let value: Value = self.client.request_json(
2484                reqwest::Method::POST,
2485                &format!("/worker/activity-tasks/{}/heartbeat", percent_encode_path_segment(&self.task_id)),
2486                RequestProtocol::Worker("1.20"),
2487                Some(&json!({"activity_attempt_id":self.attempt_id,"lease_owner":self.owner,"details":details})),
2488            ).await?;
2489            if value["task_id"].as_str() != Some(self.task_id.as_str())
2490                || value["activity_attempt_id"].as_str() != Some(self.attempt_id.as_str())
2491                || value["lease_owner"].as_str() != Some(self.owner.as_str())
2492                || value["can_continue"].as_bool() != Some(true)
2493                || value["cancel_requested"].as_bool() != Some(false)
2494                || value["heartbeat_recorded"].as_bool() != Some(true)
2495            {
2496                return Err(invalid("activity heartbeat lost its original claim"));
2497            }
2498            if let Some(session) = context.worker_session() {
2499                session.track(&value["worker_session"])?;
2500            }
2501            serde_json::from_value(value).map_err(Error::from)
2502        }).await.map_err(|_| Error::Timeout).and_then(|result| result);
2503        let response = result.map_err(|error| {
2504            self.abandon();
2505            Error::ActivityExecutionAbandoned(error.to_string())
2506        })?;
2507        self.observe().await?;
2508        Ok(response)
2509    }
2510}
2511
2512pub(super) fn cancellation_claim(task: &WorkflowTask) -> Result<(&str, &str)> {
2513    let owner = task
2514        .lease_owner
2515        .as_deref()
2516        .filter(|owner| !owner.trim().is_empty());
2517    let run = task.run_id.as_deref().filter(|run| !run.trim().is_empty());
2518    if task.task_id.trim().is_empty()
2519        || task.workflow_task_attempt == 0
2520        || task.workflow_task_attempt > MAX_SEQUENCE
2521    {
2522        return Err(invalid(
2523            "cancellation transport requires a valid task and attempt",
2524        ));
2525    }
2526    Ok((
2527        owner.ok_or_else(|| invalid("cancellation transport requires the actual lease owner"))?,
2528        run.ok_or_else(|| invalid("cancellation transport requires the selected durable run"))?,
2529    ))
2530}
2531
2532impl WorkflowHandle {
2533    /// Request bounded cleanup for whichever run is current.
2534    pub async fn request_cancellation(
2535        &self,
2536        options: CooperativeCancellationOptions,
2537    ) -> Result<WorkflowCancellationRequest> {
2538        self.client
2539            .request_workflow_cancellation(&self.workflow_id, options)
2540            .await
2541    }
2542
2543    /// Request bounded cleanup only while this handle's selected run is current.
2544    pub async fn request_selected_run_cancellation(
2545        &self,
2546        options: CooperativeCancellationOptions,
2547    ) -> Result<WorkflowCancellationRequest> {
2548        let run_id = self
2549            .run_id
2550            .as_deref()
2551            .ok_or_else(|| invalid("selected run_id is required"))?;
2552        self.client
2553            .request_workflow_run_cancellation(&self.workflow_id, run_id, options)
2554            .await
2555    }
2556}
2557
2558#[cfg(test)]
2559mod reopen_order_tests {
2560    use super::*;
2561
2562    // #193 review: the next authored sequence follows the highest recorded
2563    // sequence even when grouped reopens are consumed out of sequence order.
2564    #[test]
2565    fn next_sequence_follows_the_highest_recorded_sequence() {
2566        let mut state = WorkflowState::new(
2567            crate::one_sided_grouped_reopen_history(Vec::new()),
2568            "rust-workers".to_string(),
2569            crate::DEFAULT_CODEC.to_string(),
2570            None,
2571        )
2572        .expect("one-sided grouped reopen history");
2573        let consumed = state
2574            .recorded_commands
2575            .iter()
2576            .map(RecordedCommand::sequence)
2577            .collect::<Vec<_>>();
2578        assert_eq!(consumed, vec![1, 3, 2]);
2579        state.command_cursor = state.recorded_commands.len();
2580        assert_eq!(
2581            state.next_cancellation_sequence().expect("next sequence"),
2582            4
2583        );
2584    }
2585}