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