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