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 if loaded.task.is_some() {
1423 self.worker_dispatch_metrics.ready_age(
1424 "workflow",
1425 task_queue,
1426 metrics::ready_age_from_poll(&value),
1427 );
1428 }
1429 Ok(loaded)
1430 }
1431
1432 async fn load_cooperative_claim_history(
1433 &self,
1434 claim: &mut CooperativeWorkflowTask,
1435 ) -> Result<()> {
1436 let (owner, _) = cancellation_claim(&claim.task)?;
1437 let owner = owner.to_owned();
1438 let mut token = claim.task.next_history_page_token.clone();
1439 let mut seen = BTreeSet::new();
1440 while let Some(current) = token.take() {
1441 if current.trim().is_empty()
1442 || seen.len() >= MAX_REFRESH_PAGES
1443 || !seen.insert(current.clone())
1444 {
1445 return Err(invalid(
1446 "claim history exceeded its page bound or returned an invalid/repeated token",
1447 ));
1448 }
1449 let body = json!({
1450 "lease_owner":owner,"workflow_task_attempt":claim.task.workflow_task_attempt,
1451 "next_history_page_token":current,"history_page_size":WORKFLOW_HISTORY_PAGE_SIZE,
1452 });
1453 let value: Value = self
1454 .request_json(
1455 reqwest::Method::POST,
1456 &format!(
1457 "/worker/workflow-tasks/{}/history",
1458 percent_encode_path_segment(&claim.task.task_id)
1459 ),
1460 RequestProtocol::Worker("1.20"),
1461 Some(&body),
1462 )
1463 .await?;
1464 if value["task_id"].as_str() != Some(claim.task.task_id.as_str())
1465 || value["workflow_task_attempt"].as_u64() != Some(claim.task.workflow_task_attempt)
1466 {
1467 return Err(invalid(
1468 "claim history changed the selected task or attempt",
1469 ));
1470 }
1471 let events = value["history_events"]
1472 .as_array()
1473 .ok_or_else(|| invalid("claim history page must contain an event array"))?;
1474 if events.len() > WORKFLOW_HISTORY_PAGE_SIZE as usize {
1475 return Err(invalid(
1476 "claim history page exceeds its requested event limit",
1477 ));
1478 }
1479 token = match value.get("next_history_page_token") {
1480 Some(Value::Null) => None,
1481 Some(Value::String(next)) if !next.trim().is_empty() && !events.is_empty() => {
1482 Some(next.clone())
1483 }
1484 _ => return Err(invalid("claim history page token or progress is invalid")),
1485 };
1486 let page: WorkflowTaskHistoryPage = serde_json::from_value(value)
1487 .map_err(|_| invalid("claim history page contains malformed fields or events"))?;
1488 if page
1489 .history_events
1490 .iter()
1491 .any(|event| event.event_type.trim().is_empty())
1492 {
1493 return Err(invalid("claim history event type must be non-empty"));
1494 }
1495 claim.task.append_history_page(page);
1496 }
1497 Ok(())
1498 }
1499
1500 pub async fn heartbeat_workflow_task(
1505 &self,
1506 task: &WorkflowTask,
1507 original: Option<&CancellationRequest>,
1508 ) -> Result<WorkflowTaskHeartbeat> {
1509 self.heartbeat_workflow_task_with_protocol(task, original, "1.20")
1510 .await
1511 }
1512
1513 pub(super) async fn heartbeat_workflow_task_with_protocol(
1514 &self,
1515 task: &WorkflowTask,
1516 original: Option<&CancellationRequest>,
1517 protocol: &'static str,
1518 ) -> Result<WorkflowTaskHeartbeat> {
1519 let (owner, _) = cancellation_claim(task)?;
1520 if let Some(original) = original {
1521 original.validate_observation()?;
1522 }
1523 tokio::time::timeout(CONTROL_BUDGET, async {
1524 let response: Value = self.request_json(
1525 reqwest::Method::POST,
1526 &format!("/worker/workflow-tasks/{}/heartbeat", percent_encode_path_segment(&task.task_id)),
1527 RequestProtocol::Worker(protocol),
1528 Some(&json!({"lease_owner":owner,"workflow_task_attempt":task.workflow_task_attempt})),
1529 ).await?;
1530 if response["task_id"].as_str() != Some(task.task_id.as_str())
1531 || response["workflow_task_attempt"].as_u64() != Some(task.workflow_task_attempt)
1532 || response["lease_owner"].as_str() != Some(owner)
1533 || response["renewed"].as_bool() != Some(true)
1534 || response.get("reason") != Some(&Value::Null)
1535 || response["task_status"].as_str() != Some("leased")
1536 {
1537 return Err(invalid("workflow heartbeat did not acknowledge the exact leased claim"));
1538 }
1539 let expires = text(&response, "lease_expires_at")?;
1540 DateTime::parse_from_rfc3339(expires).map_err(|_| invalid("workflow heartbeat lease expiry must include a timezone"))?;
1541 let run_status = text(&response, "run_status")?;
1542 if !matches!(run_status, "pending" | "running" | "waiting") {
1543 return Err(invalid("workflow heartbeat did not acknowledge an active run"));
1544 }
1545 let cancellation_request = match response.get("cancellation_request") {
1546 None | Some(Value::Null) if original.is_none() => None,
1547 None | Some(Value::Null) => return Err(invalid("workflow heartbeat omitted its original pending request")),
1548 Some(observation) => {
1549 let current = CancellationRequest::from_observation(observation)?;
1550 Some(match original {
1551 Some(original) => original.preserve_observation(¤t)?,
1552 None => current,
1553 })
1554 },
1555 };
1556 Ok(WorkflowTaskHeartbeat {
1557 task_id:task.task_id.clone(), workflow_task_attempt:task.workflow_task_attempt,
1558 lease_owner:owner.to_owned(), lease_expires_at:expires.to_owned(),
1559 run_status:run_status.to_owned(), cancellation_request,
1560 })
1561 }).await.map_err(|_| Error::Timeout)?
1562 }
1563
1564 pub async fn deliver_workflow_cancellation(
1572 &self,
1573 task: &WorkflowTask,
1574 delivery: &CancellationDelivery,
1575 ) -> Result<CancellationDeliveryReply> {
1576 let (owner, run_id) = cancellation_claim(task)?;
1577 let body = json!({
1578 "lease_owner":owner, "workflow_task_attempt":task.workflow_task_attempt,
1579 "request_id":delivery.request_id, "sequence":delivery.sequence,
1580 "call_kind":delivery.call_kind, "sequence_span":delivery.sequence_span,
1581 "operation_sequence":delivery.operation_sequence,
1582 "operation_sequence_span":delivery.operation_sequence_span
1583 });
1584 let mut payload = body.clone();
1585 payload["workflow_command_id"] = json!(delivery.request_id);
1586 if CancellationDelivery::from_payload(&payload)? != *delivery {
1587 return Err(invalid(
1588 "delivery must name a valid authored operation range",
1589 ));
1590 }
1591 tokio::time::timeout(CONTROL_BUDGET, async {
1592 let path = format!(
1593 "/worker/workflow-tasks/{}/deliver-cancellation",
1594 percent_encode_path_segment(&task.task_id)
1595 );
1596 let response: Value = self
1597 .request_json(
1598 reqwest::Method::POST,
1599 &path,
1600 RequestProtocol::Worker("1.20"),
1601 Some(&body),
1602 )
1603 .await?;
1604 if response["delivered"].as_bool() == Some(false)
1605 && match response["reason"].as_str() {
1606 Some("cancellation_waiting_for_service_operation") => {
1607 delivery.call_kind == CancellationCallKind::ServiceOperation
1608 }
1609 Some("cancellation_waiting_for_child") => matches!(
1610 delivery.call_kind,
1611 CancellationCallKind::Child
1612 | CancellationCallKind::Parallel
1613 | CancellationCallKind::SelectionHandle
1614 ),
1615 Some("cancellation_waiting_for_activity") => matches!(
1616 delivery.call_kind,
1617 CancellationCallKind::Activity
1618 | CancellationCallKind::LocalActivity
1619 | CancellationCallKind::Parallel
1620 | CancellationCallKind::SelectionHandle
1621 ),
1622 _ => false,
1623 }
1624 && response["claim_released"].as_bool() == Some(true)
1625 && response["task_id"].as_str() == Some(task.task_id.as_str())
1626 && response["workflow_run_id"].as_str() == Some(run_id)
1627 && [
1628 "request_id",
1629 "sequence",
1630 "call_kind",
1631 "sequence_span",
1632 "operation_sequence",
1633 "operation_sequence_span",
1634 ]
1635 .iter()
1636 .all(|field| response.get(*field).is_none_or(Value::is_null))
1637 {
1638 return Ok(CancellationDeliveryReply::ClaimReleased {
1639 task_id: task.task_id.clone(),
1640 run_id: run_id.to_owned(),
1641 });
1642 }
1643 if response["delivered"].as_bool() != Some(true)
1644 || response["task_id"].as_str() != Some(task.task_id.as_str())
1645 || response["workflow_run_id"].as_str() != Some(run_id)
1646 || response.get("reason") != Some(&Value::Null)
1647 || [
1648 "sequence_span",
1649 "operation_sequence",
1650 "operation_sequence_span",
1651 ]
1652 .iter()
1653 .any(|field| response.get(*field).is_none())
1654 {
1655 return Err(invalid(
1656 "delivery acknowledgment does not match the selected task/run",
1657 ));
1658 }
1659 let mut recorded = response.clone();
1660 recorded["workflow_command_id"] = response["request_id"].clone();
1661 if CancellationDelivery::from_payload(&recorded)? != *delivery {
1662 return Err(invalid(
1663 "delivery acknowledgment changed its authored operation range",
1664 ));
1665 }
1666 Ok(CancellationDeliveryReply::Delivered(
1667 CancellationDeliveryReceipt {
1668 task_id: task.task_id.clone(),
1669 run_id: run_id.to_owned(),
1670 delivery: delivery.clone(),
1671 },
1672 ))
1673 })
1674 .await
1675 .map_err(|_| Error::Timeout)?
1676 }
1677
1678 pub async fn refresh_workflow_cancellation_history(
1685 &self,
1686 task: &WorkflowTask,
1687 observation: &CancellationRequest,
1688 ) -> Result<Vec<HistoryEvent>> {
1689 self.refresh_workflow_cancellation_history_with_cache(
1690 task,
1691 observation,
1692 &mut runtime_payloads::VerifiedPayloads::new(),
1693 )
1694 .await
1695 }
1696
1697 async fn refresh_workflow_cancellation_history_with_cache(
1698 &self,
1699 task: &WorkflowTask,
1700 observation: &CancellationRequest,
1701 verified_payloads: &mut runtime_payloads::VerifiedPayloads,
1702 ) -> Result<Vec<HistoryEvent>> {
1703 let (owner, run_id) = cancellation_claim(task)?;
1704 observation.validate_observation()?;
1705 let first_token = observation
1706 .history_refresh_page_token
1707 .clone()
1708 .expect("validated history token");
1709 tokio::time::timeout(CONTROL_BUDGET, async {
1710 let path = format!("/worker/workflow-tasks/{}/history", percent_encode_path_segment(&task.task_id));
1711 let mut token = Some(first_token);
1712 let mut seen = BTreeSet::new();
1713 let mut history = Vec::new();
1714 while let Some(current) = token.take() {
1715 if seen.len() >= MAX_REFRESH_PAGES || !seen.insert(current.clone()) {
1716 return Err(invalid("canonical history refresh exceeded its page bound or repeated a token"));
1717 }
1718 let body = json!({
1719 "lease_owner":owner, "workflow_task_attempt":task.workflow_task_attempt,
1720 "next_history_page_token":current, "history_page_size":WORKFLOW_HISTORY_PAGE_SIZE,
1721 });
1722 let mut page: Value = self.request_json_unresolved_with_timeout(
1723 reqwest::Method::POST, &path, RequestProtocol::Worker("1.20"), Some(&body),
1724 CONTROL_BUDGET,
1725 ).await?;
1726 self.resolve_runtime_payloads_with_cache(&mut page, &path, RequestProtocol::Worker("1.20"), verified_payloads).await?;
1727 if page["task_id"].as_str() != Some(task.task_id.as_str())
1728 || page["workflow_task_attempt"].as_u64() != Some(task.workflow_task_attempt)
1729 {
1730 return Err(invalid("canonical history page changed the selected task/attempt"));
1731 }
1732 let events = page["history_events"].as_array().ok_or_else(|| invalid("canonical history page must contain an event array"))?;
1733 if events.len() > WORKFLOW_HISTORY_PAGE_SIZE as usize {
1734 return Err(invalid("canonical history page exceeds its requested event limit"));
1735 }
1736 token = match page.get("next_history_page_token") {
1737 Some(Value::Null) => None,
1738 Some(Value::String(next)) if !next.is_empty() && !events.is_empty() => Some(next.clone()),
1739 _ => return Err(invalid("canonical history page token or progress is invalid")),
1740 };
1741 for event in events {
1742 let event: HistoryEvent = serde_json::from_value(event.clone()).map_err(|_| invalid("canonical history page contains a malformed event"))?;
1743 if event.event_type.trim().is_empty() {
1744 return Err(invalid("canonical history event type must be non-empty"));
1745 }
1746 history.push(event);
1747 }
1748 }
1749 let canonical = CancellationHistory::from_events(&history, run_id, Some(observation))?;
1750 if canonical.request_index >= history.len() {
1751 return Err(invalid("canonical refresh omitted the original request event"));
1752 }
1753 Ok(history)
1754 }).await.map_err(|_| Error::Timeout)?
1755 }
1756
1757 pub async fn request_workflow_cancellation(
1764 &self,
1765 workflow_id: &str,
1766 options: CooperativeCancellationOptions,
1767 ) -> Result<WorkflowCancellationRequest> {
1768 self.request_workflow_cancellation_target(workflow_id, None, options)
1769 .await
1770 }
1771
1772 pub async fn request_workflow_run_cancellation(
1774 &self,
1775 workflow_id: &str,
1776 run_id: &str,
1777 options: CooperativeCancellationOptions,
1778 ) -> Result<WorkflowCancellationRequest> {
1779 self.request_workflow_cancellation_target(workflow_id, Some(run_id), options)
1780 .await
1781 }
1782
1783 async fn request_workflow_cancellation_target(
1784 &self,
1785 workflow_id: &str,
1786 run_id: Option<&str>,
1787 options: CooperativeCancellationOptions,
1788 ) -> Result<WorkflowCancellationRequest> {
1789 let mut path = format!("/workflows/{}", path_segment("workflow_id", workflow_id)?);
1790 if let Some(run_id) = run_id {
1791 path.push_str(&format!("/runs/{}", path_segment("run_id", run_id)?));
1792 }
1793 path.push_str("/request-cancellation");
1794 if workflow_id.trim().is_empty() || run_id.is_some_and(|id| id.trim().is_empty()) {
1795 return Err(invalid(
1796 "workflow and selected run identities must be non-empty",
1797 ));
1798 }
1799 if options
1800 .cleanup_timeout_seconds
1801 .is_some_and(|seconds| !(1..=3600).contains(&seconds))
1802 || options
1803 .reason
1804 .as_ref()
1805 .is_some_and(|reason| reason.chars().count() > 1000)
1806 {
1807 return Err(invalid(
1808 "cleanup timeout must be 1..3600 seconds and reason at most 1000 characters",
1809 ));
1810 }
1811
1812 tokio::time::timeout(CONTROL_BUDGET, async {
1814 let info: Value = self
1815 .request_json(
1816 reqwest::Method::GET,
1817 "/cluster/info",
1818 RequestProtocol::ControlPlane,
1819 Option::<&Value>::None,
1820 )
1821 .await?;
1822 require_discovery(&info)?;
1823 let response: Value = self
1824 .request_json(
1825 reqwest::Method::POST,
1826 &path,
1827 RequestProtocol::ControlPlane,
1828 Some(&options),
1829 )
1830 .await?;
1831 acknowledgment(&response, workflow_id, run_id)
1832 })
1833 .await
1834 .map_err(|_| Error::Timeout)?
1835 }
1836}
1837
1838impl Worker {
1839 pub(super) async fn settle_cooperative_activity(
1840 &self,
1841 task: worker_session::SessionActivityTask,
1842 task_metrics: &mut crate::metrics::WorkerObservation,
1843 ) -> Result<ManagedPollOutcome> {
1844 let session = self.track_session_task(task.worker_session.as_ref())?;
1845 let metadata = task.invocation(session);
1846 let task = task.task;
1847 let guard = ActivityClaimGuard::new(&self.client, &task, &self.worker_id)?;
1848 let _abandon_on_drop = AbandonActivityOnDrop(guard.clone());
1849 if guard.observe().await.is_err() {
1850 return Ok(ManagedPollOutcome::Handled);
1851 }
1852 let mut callback_started = false;
1853 let result = {
1854 let invocation = self.execute_cooperative_activity_task(
1855 &task,
1856 &guard,
1857 &mut callback_started,
1858 metadata,
1859 );
1860 tokio::pin!(invocation);
1861 loop {
1862 tokio::select! {
1863 biased;
1864 _ = guard.wait_for_shutdown() => {
1865 guard.abandon();
1866 break None;
1867 }
1868 result = &mut invocation => break Some(result),
1869 _ = tokio::time::sleep(Duration::from_secs(1)) => {
1870 if guard.observe().await.is_err() {
1871 break None;
1872 }
1873 }
1874 }
1875 }
1876 };
1877 let Some(result) = result else {
1879 if callback_started {
1880 guard.acknowledge_stopped().await?;
1881 }
1882 return Ok(ManagedPollOutcome::Handled);
1883 };
1884 if matches!(result, Err(Error::ActivityExecutionAbandoned(_)))
1887 || guard.observe().await.is_err()
1888 {
1889 if callback_started {
1890 guard.acknowledge_stopped().await?;
1891 }
1892 return Ok(ManagedPollOutcome::Handled);
1893 }
1894 let task_outcome = if result.is_ok() {
1895 "completed"
1896 } else {
1897 "failed"
1898 };
1899 let settlement = match result {
1900 Ok(value) => {
1901 self.client
1902 .complete_activity_task(
1903 &guard.task_id,
1904 &guard.attempt_id,
1905 &guard.owner,
1906 value,
1907 &task.payload_codec,
1908 )
1909 .await
1910 }
1911 Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
1912 Err(error) => {
1913 self.client
1914 .fail_activity_task_with_error(
1915 &guard.task_id,
1916 &guard.attempt_id,
1917 &guard.owner,
1918 &crate::ActivityError::from_error(&error, "RustActivityFailure"),
1919 )
1920 .await
1921 }
1922 };
1923 if let Err(error) = settlement {
1924 if !activity_task_rejection_is_final(&error) {
1925 return Err(error);
1926 }
1927 }
1928 task_metrics.outcome(task_outcome);
1929 Ok(ManagedPollOutcome::Handled)
1930 }
1931
1932 async fn execute_cooperative_activity_task(
1933 &self,
1934 task: &ActivityTask,
1935 guard: &ActivityClaimGuard,
1936 callback_started: &mut bool,
1937 invocation: worker_session::ActivityInvocation,
1938 ) -> Result<AvroValue> {
1939 #[cfg(feature = "telemetry")]
1940 if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
1941 !self
1942 .client
1943 .observability_context_supported
1944 .load(Ordering::SeqCst)
1945 }) {
1946 return telemetry
1947 .run(
1948 "durable.activity.task",
1949 self.activity_telemetry_fields(task),
1950 false,
1951 self.execute_cooperative_activity_task_inner(
1952 task,
1953 guard,
1954 callback_started,
1955 invocation,
1956 ),
1957 )
1958 .await;
1959 }
1960 self.execute_cooperative_activity_task_inner(task, guard, callback_started, invocation)
1961 .await
1962 }
1963
1964 async fn execute_cooperative_activity_task_inner(
1965 &self,
1966 task: &ActivityTask,
1967 guard: &ActivityClaimGuard,
1968 callback_started: &mut bool,
1969 invocation: worker_session::ActivityInvocation,
1970 ) -> Result<AvroValue> {
1971 let worker_session::ActivityInvocation {
1972 worker_session,
1973 hydration_claim,
1974 retry_info,
1975 } = invocation;
1976 validate_activity_task_payloads(task)?;
1977 let handler = self
1978 .activities
1979 .get(&task.activity_type)
1980 .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
1981 let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
1982 let context = ActivityContext {
1983 client: self.client.clone(),
1984 task_id: guard.task_id.clone(),
1985 activity_attempt_id: guard.attempt_id.clone(),
1986 lease_owner: guard.owner.clone(),
1987 activity_type: task.activity_type.clone(),
1988 attempt_number: task.attempt_number,
1989 retry_info,
1990 activity_execution_id: task.activity_execution_id.clone(),
1991 workflow_id: task.workflow_id.clone(),
1992 run_id: task.run_id.clone(),
1993 task_queue: self.task_queue.clone(),
1994 worker_id: self.worker_id.clone(),
1995 claim_guard: Some(guard.clone()),
1996 local_heartbeats: None,
1997 worker_session,
1998 };
1999 if let Some(claim) = &hydration_claim {
2000 claim.confirm(&self.client).await?;
2001 }
2002 guard.boundary()?;
2003 *callback_started = true;
2004 #[cfg(feature = "telemetry")]
2005 if let Some(telemetry) = self.telemetry.as_ref().filter(|_| {
2006 self.client
2007 .observability_context_supported
2008 .load(Ordering::SeqCst)
2009 }) {
2010 return telemetry
2011 .run_observed(
2012 "durable.activity.task",
2013 self.activity_telemetry_fields(task),
2014 false,
2015 self.activity_observations(task),
2016 async { self.activity_callback(handler, context, args, false).await },
2017 )
2018 .await;
2019 }
2020 self.activity_callback(handler, context, args, false).await
2021 }
2022
2023 pub(super) async fn poll_cooperative_workflow_once(&self) -> Result<ManagedPollOutcome> {
2024 let mut poll_metrics = self.metrics.worker(false, "workflow", &self.task_queue);
2025 let poll_request_id = unique_request_id("rust-workflow-poll");
2026 let response = self
2027 .retry_worker_operation(|| {
2028 self.client.poll_cooperative_workflow_task_with_request_id(
2029 &self.worker_id,
2030 &self.task_queue,
2031 self.poll_timeout,
2032 &poll_request_id,
2033 0,
2034 true,
2035 )
2036 })
2037 .await;
2038 poll_metrics.poll(&response, |value| value.outcome.clone());
2039 drop(poll_metrics);
2040 let Some(response) = self.settle_worker_poll_response(response).await? else {
2041 return Ok(ManagedPollOutcome::Idle);
2042 };
2043 if response.outcome.should_stop() {
2044 return Ok(ManagedPollOutcome::Stop);
2045 }
2046 let memo_updates_supported =
2047 runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
2048 let Some(claim) = response.task else {
2049 return Ok(ManagedPollOutcome::Idle);
2050 };
2051 self.client.release_worker_poll();
2052 let mut task_metrics = self.metrics.worker(true, "workflow", &self.task_queue);
2053 task_metrics.outcome("failed");
2054 let mut completion_worker = None;
2057 if let (Some(request), Some(_)) = (
2058 claim.cancellation_request.as_ref(),
2059 self.client.worker_storage_admission.as_ref(),
2060 ) {
2061 let mut worker = self.clone();
2062 let admission = worker.client.worker_storage_admission.as_mut().unwrap();
2063 let deadline = DateTime::parse_from_rfc3339(&request.cleanup_deadline_at)
2064 .map_err(|_| invalid("invalid original cleanup deadline"))?;
2065 let monotonic_now = tokio::time::Instant::now();
2066 let unix = SystemTime::now()
2067 .duration_since(UNIX_EPOCH)
2068 .map_err(|_| Error::Timeout)?;
2069 let now = DateTime::<chrono::Utc>::from_timestamp(
2070 i64::try_from(unix.as_secs()).map_err(|_| Error::Timeout)?,
2071 unix.subsec_nanos(),
2072 )
2073 .ok_or(Error::Timeout)?;
2074 let remaining = (deadline.with_timezone(&chrono::Utc) - now)
2075 .to_std()
2076 .unwrap_or(Duration::ZERO);
2077 admission.workflow_completion_retry_deadline = Some(monotonic_now + remaining);
2078 completion_worker = Some(worker);
2079 }
2080 let Some(decision) = self.replay_cooperative_workflow_claim(&claim).await? else {
2083 return Ok(ManagedPollOutcome::Handled);
2084 };
2085 let (owner, _) = cancellation_claim(&claim.task)?;
2086 let task_outcome = crate::metrics::workflow_task_outcome(Some(&decision));
2087 let settled = completion_worker
2088 .as_ref()
2089 .unwrap_or(self)
2090 .settle_workflow_task_decision(
2091 &claim.task.task_id,
2092 owner,
2093 claim.task.workflow_task_attempt,
2094 claim.task.run_id.as_deref(),
2095 Ok(decision),
2096 memo_updates_supported,
2097 claim.sticky_snapshot.clone(),
2098 )
2099 .await;
2100 if settled.is_ok() {
2101 task_metrics.outcome(task_outcome);
2102 }
2103 settled
2104 }
2105
2106 async fn replay_cooperative_workflow_claim(
2107 &self,
2108 claim: &CooperativeWorkflowTask,
2109 ) -> Result<Option<WorkflowTaskDecision>> {
2110 let mut verified_payloads = claim.verified_payloads.clone();
2111 let (owner, run_id) = cancellation_claim(&claim.task)?;
2112 if owner != self.worker_id {
2113 return Err(invalid(
2114 "cooperative replay requires this worker's actual claim",
2115 ));
2116 }
2117 let mut task = claim.task.clone();
2118 let Some(observation) = claim.cancellation_request.as_ref() else {
2119 let canonical = CancellationHistory::from_events(&task.history_events, run_id, None)?;
2120 if canonical.request.is_some() {
2121 return Err(invalid(
2122 "cooperative replay omitted its original pending observation",
2123 ));
2124 }
2125 for _ in 0..1000 {
2126 let mut decision = self.execute_workflow_task_decision(task.clone())?;
2127 if let Some(intent) = decision.cancellation_scope_delivery.as_ref() {
2128 if !decision.commands.is_empty() {
2129 decision.cancellation_scope_delivery = None;
2130 return Ok(Some(decision));
2131 }
2132 let mut budget = CancellationScopeDeliveryBudget::new();
2133 budget.restrict(intent.context.deadline())?;
2134 let prepared = self
2135 .client
2136 .prepare_cancellation_scope_on_claim(
2137 &task,
2138 &intent.context,
2139 &intent.boundary,
2140 &budget,
2141 )
2142 .await?;
2143 budget.restrict(prepared.authority_deadline())?;
2144 let delivered = self
2145 .client
2146 .deliver_cancellation_scope_on_claim(&task, &prepared, &budget)
2147 .await?;
2148 task.history_events = delivered.history().to_vec();
2149 task.total_history_events = None;
2150 task.history_size_bytes = None;
2151 continue;
2152 }
2153 let Some(opening) = decision.cancellation_scope_opening.as_ref() else {
2154 return Ok(Some(decision));
2155 };
2156 if !decision.commands.is_empty() {
2157 decision.cancellation_scope_opening = None;
2158 return Ok(Some(decision));
2159 }
2160 let receipt = self
2161 .client
2162 .open_cancellation_scope_on_claim(
2163 &task,
2164 opening.sequence,
2165 &opening.parent_scope_id,
2166 opening.shield_parent,
2167 )
2168 .await?;
2169 task.history_events = receipt.history().to_vec();
2170 task.total_history_events = None;
2171 task.history_size_bytes = None;
2172 }
2173 return Err(invalid(
2174 "workflow exceeded the canonical scope opening replay limit",
2175 ));
2176 };
2177 task.history_events = self
2178 .client
2179 .refresh_workflow_cancellation_history_with_cache(
2180 &claim.task,
2181 observation,
2182 &mut verified_payloads,
2183 )
2184 .await?;
2185 for _ in 0..1000 {
2186 task.total_history_events = None;
2189 task.history_size_bytes = None;
2190 let mut decision = self.execute_workflow_task_decision_with_cancellation(
2191 task.clone(),
2192 Some(observation),
2193 )?;
2194 if let Some(intent) = decision.cancellation_scope_delivery.as_ref() {
2195 if !decision.commands.is_empty() {
2196 decision.cancellation_scope_delivery = None;
2197 return Ok(Some(decision));
2198 }
2199 let mut budget = CancellationScopeDeliveryBudget::new();
2200 budget.restrict(intent.context.deadline())?;
2201 let prepared = self
2202 .client
2203 .prepare_cancellation_scope_on_claim(
2204 &task,
2205 &intent.context,
2206 &intent.boundary,
2207 &budget,
2208 )
2209 .await?;
2210 budget.restrict(prepared.authority_deadline())?;
2211 let delivered = self
2212 .client
2213 .deliver_cancellation_scope_on_claim(&task, &prepared, &budget)
2214 .await?;
2215 task.history_events = delivered.history().to_vec();
2216 continue;
2217 }
2218 let Some(intent) = decision.cancellation_delivery.as_ref() else {
2219 return Ok(Some(decision));
2220 };
2221 if !decision.commands.is_empty() {
2222 decision.cancellation_delivery = None;
2226 return Ok(Some(decision));
2227 }
2228 if intent.call_kind == CancellationCallKind::ServiceOperation
2229 && !self.nexus_registration_confirmed.load(Ordering::SeqCst)
2230 {
2231 return Err(Error::CooperativeCancellationUnavailable(
2232 "nexus_cooperative_cancellation_not_supported: new delivery requires confirmed Nexus registration".into(),
2233 ));
2234 }
2235 let delivery_error = match self
2236 .client
2237 .deliver_workflow_cancellation(&claim.task, intent)
2238 .await
2239 {
2240 Ok(CancellationDeliveryReply::ClaimReleased { .. }) => return Ok(None),
2241 Ok(CancellationDeliveryReply::Delivered(_)) => None,
2242 Err(error) => Some(error),
2243 };
2244 task.history_events = self
2245 .client
2246 .refresh_workflow_cancellation_history_with_cache(
2247 &claim.task,
2248 observation,
2249 &mut verified_payloads,
2250 )
2251 .await?;
2252 let canonical =
2253 CancellationHistory::from_events(&task.history_events, run_id, Some(observation))?;
2254 if canonical.delivery.as_ref() != Some(intent) {
2255 return Err(delivery_error.unwrap_or_else(|| {
2256 invalid(
2257 "canonical history did not prove the exact intended cancellation delivery",
2258 )
2259 }));
2260 }
2261 }
2262 Err(invalid(
2263 "workflow replay did not converge on its canonical cancellation delivery",
2264 ))
2265 }
2266}
2267
2268#[derive(Clone, Debug)]
2269pub(super) struct ActivityClaimGuard {
2270 client: Client,
2271 task_id: String,
2272 attempt_id: String,
2273 owner: String,
2274 active: Arc<AtomicBool>,
2275 cancellation_receipt: Arc<Mutex<Option<Value>>>,
2276 stop: Option<Arc<AtomicBool>>,
2277}
2278
2279struct AbandonActivityOnDrop(ActivityClaimGuard);
2280
2281impl Drop for AbandonActivityOnDrop {
2282 fn drop(&mut self) {
2283 self.0.abandon();
2284 }
2285}
2286
2287impl ActivityClaimGuard {
2288 pub(super) fn new(client: &Client, task: &ActivityTask, worker_id: &str) -> Result<Self> {
2289 let owner = task.lease_owner.as_deref().unwrap_or_default();
2290 let attempt = task
2291 .activity_attempt_id
2292 .as_deref()
2293 .or(task.attempt_id.as_deref())
2294 .unwrap_or_default();
2295 if task.task_id.trim().is_empty()
2296 || attempt.trim().is_empty()
2297 || owner.trim().is_empty()
2298 || owner != worker_id
2299 || matches!((&task.activity_attempt_id, &task.attempt_id), (Some(left), Some(right)) if left != right)
2300 {
2301 return Err(invalid(
2302 "activity execution requires the worker's actual immutable claim",
2303 ));
2304 }
2305 Ok(Self {
2306 client: client.clone(),
2307 task_id: task.task_id.clone(),
2308 attempt_id: attempt.to_owned(),
2309 owner: owner.to_owned(),
2310 active: Arc::new(AtomicBool::new(true)),
2311 cancellation_receipt: Arc::new(Mutex::new(None)),
2312 stop: client
2313 .worker_storage_admission
2314 .as_ref()
2315 .map(|admission| Arc::clone(&admission.stop)),
2316 })
2317 }
2318
2319 fn abandon(&self) {
2320 self.active.store(false, Ordering::SeqCst);
2321 }
2322
2323 async fn acknowledge_stopped(&self) -> Result<()> {
2325 self.abandon();
2326 let receipt = self
2327 .cancellation_receipt
2328 .lock()
2329 .map_err(|_| invalid("activity cancellation receipt lock was poisoned"))?
2330 .clone();
2331 if let Some(receipt) = receipt {
2332 self.client
2333 .acknowledge_activity_cancellation(
2334 &self.task_id,
2335 &self.attempt_id,
2336 &self.owner,
2337 text(&receipt, "request_id")?,
2338 )
2339 .await?;
2340 }
2341 Ok(())
2342 }
2343
2344 fn retain_cancellation_receipt(&self, value: &Value) -> Result<()> {
2345 if value["can_continue"].as_bool() != Some(false)
2346 || value["cancel_requested"].as_bool() != Some(true)
2347 {
2348 return Ok(());
2349 }
2350 let Some(receipt) = value
2351 .get("cancellation_acknowledgement")
2352 .filter(|receipt| receipt.is_object())
2353 else {
2354 return Ok(());
2355 };
2356 if !matches!(
2357 receipt["callback_state"].as_str(),
2358 Some("unknown" | "stopped")
2359 ) || [
2360 "request_id",
2361 "root_request_id",
2362 "cleanup_deadline_at",
2363 "cancellation_history_event_id",
2364 ]
2365 .iter()
2366 .any(|field| text(receipt, field).is_err())
2367 || DateTime::parse_from_rfc3339(text(receipt, "cleanup_deadline_at")?).is_err()
2368 {
2369 return Ok(());
2370 }
2371 let mut retained = self
2372 .cancellation_receipt
2373 .lock()
2374 .map_err(|_| invalid("activity cancellation receipt lock was poisoned"))?;
2375 if let Some(original) = retained.as_ref() {
2376 if [
2377 "request_id",
2378 "root_request_id",
2379 "cleanup_deadline_at",
2380 "cancellation_history_event_id",
2381 ]
2382 .iter()
2383 .any(|field| original[*field] != receipt[*field])
2384 {
2385 return Err(invalid(
2386 "activity cancellation observation changed its original identity or deadline",
2387 ));
2388 }
2389 } else {
2390 *retained = Some(receipt.clone());
2391 }
2392 Ok(())
2393 }
2394
2395 fn boundary(&self) -> Result<()> {
2396 if !self.active.load(Ordering::SeqCst)
2397 || self
2398 .stop
2399 .as_ref()
2400 .is_some_and(|stop| stop.load(Ordering::SeqCst))
2401 {
2402 self.abandon();
2403 return Err(Error::ActivityExecutionAbandoned(
2404 "callback completed, was abandoned, or its worker is stopping".into(),
2405 ));
2406 }
2407 Ok(())
2408 }
2409
2410 async fn wait_for_shutdown(&self) {
2411 if let Some(stop) = &self.stop {
2412 wait_for_worker_stop(stop).await;
2413 } else {
2414 std::future::pending::<()>().await;
2415 }
2416 }
2417
2418 pub(super) async fn observe(&self) -> Result<()> {
2419 self.boundary()?;
2420 let result = self
2421 .client
2422 .activity_task_status(&self.task_id, &self.attempt_id, &self.owner)
2423 .await
2424 .and_then(|value| {
2425 self.retain_cancellation_receipt(&value)?;
2426 if value["can_continue"].as_bool() != Some(true)
2427 || value["cancel_requested"].as_bool() != Some(false)
2428 || value.get("reason") != Some(&Value::Null)
2429 || value["task_status"].as_str() != Some("leased")
2430 || value["attempt_status"].as_str() != Some("running")
2431 || value["activity_status"].as_str() != Some("running")
2432 {
2433 return Err(invalid("activity observation refused continuation"));
2434 }
2435 let mut bounds = vec![text(&value, "lease_expires_at")?];
2436 if let Some(deadlines) = value.get("deadlines").filter(|v| !v.is_null()) {
2437 if !deadlines.is_object() {
2438 return Err(invalid("activity execution deadlines must be an object"));
2439 }
2440 for kind in ["heartbeat", "start_to_close", "schedule_to_close"] {
2441 if let Some(deadline) = deadlines.get(kind).filter(|v| !v.is_null()) {
2442 bounds.push(
2443 deadline
2444 .as_str()
2445 .ok_or_else(|| invalid("invalid activity deadline"))?,
2446 );
2447 }
2448 }
2449 }
2450 if let Some(session) = value.get("worker_session").filter(|v| !v.is_null()) {
2451 if session["status"].as_str() != Some("active")
2452 || session["lease_owner"].as_str() != Some(self.owner.as_str())
2453 {
2454 return Err(invalid(
2455 "activity no longer owns its required worker session",
2456 ));
2457 }
2458 bounds.push(text(session, "lease_expires_at")?);
2459 bounds.push(text(session, "ttl_expires_at")?);
2460 }
2461 for bound in bounds {
2462 let deadline = DateTime::parse_from_rfc3339(bound)
2463 .map_err(|_| invalid("activity deadline must include a timezone"))?;
2464 let now = SystemTime::now()
2465 .duration_since(UNIX_EPOCH)
2466 .map_err(|_| invalid("activity observation clock precedes the epoch"))?;
2467 if !u128::try_from(deadline.timestamp_millis())
2468 .is_ok_and(|millis| millis > now.as_millis())
2469 {
2470 return Err(invalid("activity ownership or execution deadline elapsed"));
2471 }
2472 }
2473 self.boundary()
2474 });
2475 result.map_err(|error| {
2476 self.abandon();
2477 Error::ActivityExecutionAbandoned(error.to_string())
2478 })
2479 }
2480
2481 pub(super) async fn heartbeat<T: Serialize>(
2482 &self,
2483 context: &ActivityContext,
2484 details: T,
2485 ) -> Result<ActivityHeartbeatResponse> {
2486 if context.task_id != self.task_id
2487 || context.activity_attempt_id != self.attempt_id
2488 || context.lease_owner != self.owner
2489 || context.worker_id != self.owner
2490 {
2491 self.abandon();
2492 return Err(Error::ActivityExecutionAbandoned(
2493 "activity context changed its original claim".into(),
2494 ));
2495 }
2496 self.observe().await?;
2497 let result = tokio::time::timeout(CONTROL_BUDGET, async {
2498 let details = AvroValue::from_serialize(&details)?.into_json()?;
2499 self.boundary()?;
2500 let value: Value = self.client.request_json(
2501 reqwest::Method::POST,
2502 &format!("/worker/activity-tasks/{}/heartbeat", percent_encode_path_segment(&self.task_id)),
2503 RequestProtocol::Worker("1.20"),
2504 Some(&json!({"activity_attempt_id":self.attempt_id,"lease_owner":self.owner,"details":details})),
2505 ).await?;
2506 if value["task_id"].as_str() != Some(self.task_id.as_str())
2507 || value["activity_attempt_id"].as_str() != Some(self.attempt_id.as_str())
2508 || value["lease_owner"].as_str() != Some(self.owner.as_str())
2509 || value["can_continue"].as_bool() != Some(true)
2510 || value["cancel_requested"].as_bool() != Some(false)
2511 || value["heartbeat_recorded"].as_bool() != Some(true)
2512 {
2513 return Err(invalid("activity heartbeat lost its original claim"));
2514 }
2515 if let Some(session) = context.worker_session() {
2516 session.track(&value["worker_session"])?;
2517 }
2518 serde_json::from_value(value).map_err(Error::from)
2519 }).await.map_err(|_| Error::Timeout).and_then(|result| result);
2520 let response = result.map_err(|error| {
2521 self.abandon();
2522 Error::ActivityExecutionAbandoned(error.to_string())
2523 })?;
2524 self.observe().await?;
2525 Ok(response)
2526 }
2527}
2528
2529pub(super) fn cancellation_claim(task: &WorkflowTask) -> Result<(&str, &str)> {
2530 let owner = task
2531 .lease_owner
2532 .as_deref()
2533 .filter(|owner| !owner.trim().is_empty());
2534 let run = task.run_id.as_deref().filter(|run| !run.trim().is_empty());
2535 if task.task_id.trim().is_empty()
2536 || task.workflow_task_attempt == 0
2537 || task.workflow_task_attempt > MAX_SEQUENCE
2538 {
2539 return Err(invalid(
2540 "cancellation transport requires a valid task and attempt",
2541 ));
2542 }
2543 Ok((
2544 owner.ok_or_else(|| invalid("cancellation transport requires the actual lease owner"))?,
2545 run.ok_or_else(|| invalid("cancellation transport requires the selected durable run"))?,
2546 ))
2547}
2548
2549impl WorkflowHandle {
2550 pub async fn request_cancellation(
2552 &self,
2553 options: CooperativeCancellationOptions,
2554 ) -> Result<WorkflowCancellationRequest> {
2555 self.client
2556 .request_workflow_cancellation(&self.workflow_id, options)
2557 .await
2558 }
2559
2560 pub async fn request_selected_run_cancellation(
2562 &self,
2563 options: CooperativeCancellationOptions,
2564 ) -> Result<WorkflowCancellationRequest> {
2565 let run_id = self
2566 .run_id
2567 .as_deref()
2568 .ok_or_else(|| invalid("selected run_id is required"))?;
2569 self.client
2570 .request_workflow_run_cancellation(&self.workflow_id, run_id, options)
2571 .await
2572 }
2573}
2574
2575#[cfg(test)]
2576mod reopen_order_tests {
2577 use super::*;
2578
2579 #[test]
2582 fn next_sequence_follows_the_highest_recorded_sequence() {
2583 let mut state = WorkflowState::new(
2584 crate::one_sided_grouped_reopen_history(Vec::new()),
2585 "rust-workers".to_string(),
2586 crate::DEFAULT_CODEC.to_string(),
2587 None,
2588 )
2589 .expect("one-sided grouped reopen history");
2590 let consumed = state
2591 .recorded_commands
2592 .iter()
2593 .map(RecordedCommand::sequence)
2594 .collect::<Vec<_>>();
2595 assert_eq!(consumed, vec![1, 3, 2]);
2596 state.command_cursor = state.recorded_commands.len();
2597 assert_eq!(
2598 state.next_cancellation_sequence().expect("next sequence"),
2599 4
2600 );
2601 }
2602}