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