Skip to content
Durable Workflowrust

durable_workflow/
local_activity.rs

1use super::*;
2
3const MAX_ATTEMPTS: u64 = 100;
4const MAX_HEARTBEATS: usize = 1000;
5const LEASE_RENEWAL_INTERVAL: Duration = Duration::from_secs(1);
6
7/// Retry and timeout settings for an activity executed by the workflow worker.
8///
9/// Local activities bypass the activity queue. They do not accept routing,
10/// schedule-to-start timeouts, or remote activity cancellation policies.
11#[derive(Clone, Debug, Default, PartialEq, Eq)]
12pub struct LocalActivityOptions {
13    pub retry_policy: Option<ActivityRetryPolicy>,
14    pub start_to_close_timeout: Option<Duration>,
15    pub schedule_to_close_timeout: Option<Duration>,
16    pub heartbeat_timeout: Option<Duration>,
17}
18
19impl LocalActivityOptions {
20    pub fn new() -> Self {
21        Self::default()
22    }
23    pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
24        self.retry_policy = Some(policy);
25        self
26    }
27    pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
28        self.start_to_close_timeout = Some(timeout);
29        self
30    }
31    pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
32        self.schedule_to_close_timeout = Some(timeout);
33        self
34    }
35    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
36        self.heartbeat_timeout = Some(timeout);
37        self
38    }
39    fn into_activity_options(self) -> ActivityOptions {
40        ActivityOptions {
41            retry_policy: self.retry_policy,
42            start_to_close_timeout: self.start_to_close_timeout,
43            schedule_to_close_timeout: self.schedule_to_close_timeout,
44            heartbeat_timeout: self.heartbeat_timeout,
45            ..ActivityOptions::default()
46        }
47    }
48}
49
50pub(super) fn validate(options: &ValidatedActivityOptions) -> Result<()> {
51    let max_attempts = options
52        .retry_policy
53        .as_ref()
54        .and_then(|policy| policy["max_attempts"].as_u64())
55        .unwrap_or(1);
56    if max_attempts > MAX_ATTEMPTS {
57        return Err(Error::InvalidActivityOptions(ActivityOptionsError::new(
58            ActivityOptionsErrorKind::InvalidMaxAttempts,
59            Some("max_attempts"),
60            "local activities support at most 100 attempts",
61        )));
62    }
63    for seconds in [
64        options.start_to_close_timeout,
65        options.schedule_to_close_timeout,
66        options.heartbeat_timeout,
67    ]
68    .into_iter()
69    .flatten()
70    .chain(options.retry_policy.iter().flat_map(|p| {
71        p["backoff_seconds"]
72            .as_array()
73            .into_iter()
74            .flatten()
75            .filter_map(Value::as_u64)
76    })) {
77        if Instant::now()
78            .checked_add(Duration::from_secs(seconds))
79            .is_none()
80        {
81            return Err(Error::InvalidActivityOptions(ActivityOptionsError::new(
82                ActivityOptionsErrorKind::TimeoutOverflow,
83                Some("local_activity"),
84                "local timing exceeds the monotonic clock range",
85            )));
86        }
87    }
88    Ok(())
89}
90
91impl WorkflowContext {
92    /// Execute a registered activity in this workflow worker and record its outcome.
93    ///
94    /// Committed results are replayed without executing the callback. A worker
95    /// lost before acknowledgment can execute the callback again, so side effects
96    /// must be idempotent. Callbacks must yield to Tokio and avoid blocking work.
97    #[track_caller]
98    pub fn local_activity<T: Serialize>(
99        &self,
100        activity_type: impl Into<String>,
101        args: T,
102    ) -> ActivityCall {
103        self.local_activity_with_options(activity_type, LocalActivityOptions::new(), args)
104    }
105
106    #[track_caller]
107    pub fn local_activity_with_options<T: Serialize>(
108        &self,
109        activity_type: impl Into<String>,
110        options: LocalActivityOptions,
111        args: T,
112    ) -> ActivityCall {
113        let mut call =
114            self.activity_with_options(activity_type, options.into_activity_options(), args);
115        call.local = true;
116        call
117    }
118
119    /// Lossless Avro result, including bytes and large integers.
120    pub async fn local_activity_avro_value<T: Serialize>(
121        &self,
122        activity_type: impl Into<String>,
123        args: T,
124    ) -> Result<AvroValue> {
125        self.local_activity_avro_value_with_options(
126            activity_type,
127            LocalActivityOptions::new(),
128            args,
129        )
130        .await
131    }
132
133    pub async fn local_activity_avro_value_with_options<T: Serialize>(
134        &self,
135        activity_type: impl Into<String>,
136        options: LocalActivityOptions,
137        args: T,
138    ) -> Result<AvroValue> {
139        let mut call = self.local_activity_with_options(activity_type, options, args);
140        call.source = None;
141        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
142    }
143
144    pub async fn local_activity_typed<I: Serialize, O: DeserializeOwned>(
145        &self,
146        activity_type: impl Into<String>,
147        args: I,
148    ) -> Result<O> {
149        self.local_activity_typed_with_options(activity_type, LocalActivityOptions::new(), args)
150            .await
151    }
152
153    pub async fn local_activity_typed_with_options<I: Serialize, O: DeserializeOwned>(
154        &self,
155        activity_type: impl Into<String>,
156        options: LocalActivityOptions,
157        args: I,
158    ) -> Result<O> {
159        let activity_type = activity_type.into();
160        let result = self
161            .local_activity_avro_value_with_options(activity_type.clone(), options, args)
162            .await?;
163        decode_handler_result(result, HandlerKind::Activity, &activity_type)
164    }
165}
166
167#[derive(Debug)]
168pub(super) struct Request {
169    pub command_index: usize,
170    pub options: ValidatedActivityOptions,
171    pub arguments: AvroValue,
172    pub result: Arc<Mutex<Option<ActivityOutcome>>>,
173}
174
175#[derive(Debug)]
176pub(super) struct Heartbeats {
177    active: bool,
178    started: Instant,
179    last: Instant,
180    reports: Vec<Value>,
181    capacity: usize,
182    overflowed: bool,
183}
184
185impl Heartbeats {
186    pub(super) fn captured_attempt() -> (Arc<Mutex<Self>>, impl Drop) {
187        let now = Instant::now();
188        let reports = Arc::new(Mutex::new(Self {
189            active: true,
190            started: now,
191            last: now,
192            reports: Vec::new(),
193            capacity: MAX_HEARTBEATS,
194            overflowed: false,
195        }));
196        let close = CloseAttempt(reports.clone());
197        (reports, close)
198    }
199
200    pub fn record<T: Serialize>(&mut self, details: T) -> Result<ActivityHeartbeatResponse> {
201        if !self.active {
202            return Ok(heartbeat_response(false));
203        }
204        if self.reports.len() >= self.capacity {
205            self.overflowed = true;
206            return Err(Error::WorkerLoop(
207                "local_activity_heartbeat_limit_exceeded: at most 1000 reports per local command"
208                    .into(),
209            ));
210        }
211        let details = encode_typed_envelope(&AvroValue::from_serialize(&details)?, DEFAULT_CODEC)?;
212        let now = Instant::now();
213        self.reports.push(
214            json!({"elapsed_ms": millis(now.duration_since(self.started)), "details": details}),
215        );
216        self.last = now;
217        Ok(heartbeat_response(true))
218    }
219}
220
221fn heartbeat_response(active: bool) -> ActivityHeartbeatResponse {
222    ActivityHeartbeatResponse {
223        cancel_requested: false,
224        heartbeat_recorded: active,
225        can_continue: Some(active),
226        reason: (!active).then(|| "local_activity_attempt_closed".into()),
227        run_closed_reason: None,
228        run_closed_at: None,
229        lease_expires_at: None,
230        last_heartbeat_at: None,
231    }
232}
233
234struct CloseAttempt(Arc<Mutex<Heartbeats>>);
235impl Drop for CloseAttempt {
236    fn drop(&mut self) {
237        if let Ok(mut heartbeats) = self.0.lock() {
238            heartbeats.active = false;
239        }
240    }
241}
242
243fn millis(duration: Duration) -> u64 {
244    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
245}
246
247impl Worker {
248    pub(super) async fn execute_workflow_with_local_activities(
249        &self,
250        task: WorkflowTask,
251    ) -> Result<Option<WorkflowTaskDecision>> {
252        #[cfg(feature = "telemetry")]
253        if let Some(telemetry) = &self.telemetry {
254            return telemetry
255                .run_observed(
256                    "durable.workflow.task",
257                    self.workflow_telemetry_fields(&task),
258                    false,
259                    self.workflow_observations(&task),
260                    async {
261                        let mut decision = self
262                            .execute_workflow_with_local_activities_inner(task)
263                            .await?;
264                        if let Some(decision) = &mut decision {
265                            self.stamp_observability_commands(&mut decision.commands);
266                        }
267                        Ok(decision)
268                    },
269                )
270                .await;
271        }
272        self.execute_workflow_with_local_activities_inner(task)
273            .await
274    }
275
276    async fn execute_workflow_with_local_activities_inner(
277        &self,
278        task: WorkflowTask,
279    ) -> Result<Option<WorkflowTaskDecision>> {
280        let (task, context, mut future) = match self.prepare_workflow_task_execution(task, None)? {
281            PreparedWorkflowTask::Decision(decision) => return Ok(Some(decision)),
282            PreparedWorkflowTask::Execution {
283                task,
284                context,
285                future,
286            } => (task, context, future),
287        };
288        loop {
289            let outcome = Self::poll_workflow_future(&context, &mut future)?;
290            let requests = {
291                let mut state = context
292                    .state
293                    .lock()
294                    .map_err(|_| Error::WorkflowStatePoisoned)?;
295                std::mem::take(&mut state.local_activity_requests)
296            };
297            if requests.is_empty() {
298                return self
299                    .finish_workflow_task_execution(&task, &context, outcome)
300                    .map(Some);
301            }
302            if !self.client.local_activities_enabled {
303                return Err(Error::WorkerLoop("local_activities_not_enabled: opt in with Worker::local_activities(true) before executing inline local work".into()));
304            }
305            // A custom future cannot publish a terminal decision while ignoring
306            // an unresolved local call. Resolve only genuinely suspended work.
307            if !outcome.is_pending() {
308                return Err(Error::WorkflowYieldedWithoutCommand);
309            }
310            for request in requests {
311                let Some((wire, result)) = self
312                    .execute_local_activity(&task, &context, &request)
313                    .await?
314                else {
315                    // Do not fail, complete, or continue the workflow after a
316                    // refused or uncertain lease. Reclaim owns subsequent work.
317                    return Ok(None);
318                };
319                let mut state = context
320                    .state
321                    .lock()
322                    .map_err(|_| Error::WorkflowStatePoisoned)?;
323                state.commands[request.command_index] = wire;
324                *request
325                    .result
326                    .lock()
327                    .map_err(|_| Error::WorkflowStatePoisoned)? = Some(result);
328            }
329        }
330    }
331
332    async fn local_claim_is_active(&self, task: &WorkflowTask) -> bool {
333        tokio::select! {
334            biased;
335            _ = self.local_worker_stopped() => false,
336            receipt = self.client.heartbeat_workflow_task_with_protocol(task, None, MINIMUM_WORKER_PROTOCOL_VERSION) => {
337                receipt.is_ok_and(|receipt| receipt.cancellation_request.is_none())
338            }
339        }
340    }
341
342    async fn local_worker_stopped(&self) {
343        match &self.client.worker_storage_admission {
344            Some(admission) => wait_for_worker_stop(&admission.stop).await,
345            None => std::future::pending::<()>().await,
346        }
347    }
348
349    async fn externalize_local_command(
350        &self,
351        task: &WorkflowTask,
352        context: &WorkflowContext,
353        index: usize,
354        wire: &mut Value,
355        messages: &[(usize, crate::failure_reporting::LocalText)],
356    ) -> Result<()> {
357        let mut commands = context
358            .state
359            .lock()
360            .map_err(|_| Error::WorkflowStatePoisoned)?
361            .commands
362            .clone();
363        commands[index] = wire.clone();
364        let mut body = json!({"lease_owner": task.lease_owner, "workflow_task_attempt": task.workflow_task_attempt,
365            "commands": commands});
366        let path = format!("/worker/workflow-tasks/{}/complete", task.task_id);
367        let limit = self
368            .client
369            .known_failure_request_limit(RequestProtocol::DefaultWorker)?;
370        crate::failure_reporting::fit_local(&mut body, index, messages, limit)?;
371        self.client
372            .externalize_runtime_payloads(&mut body, &path, RequestProtocol::DefaultWorker)
373            .await?;
374        let limit = self
375            .client
376            .known_failure_request_limit(RequestProtocol::DefaultWorker)?;
377        crate::failure_reporting::fit_local(&mut body, index, messages, limit)?;
378        *wire = body["commands"][index].take();
379        Ok(())
380    }
381
382    async fn admit_local_command(
383        &self,
384        task: &WorkflowTask,
385        context: &WorkflowContext,
386        index: usize,
387        wire: &mut Value,
388        messages: &[(usize, crate::failure_reporting::LocalText)],
389    ) -> Result<bool> {
390        match self
391            .externalize_local_command(task, context, index, wire, messages)
392            .await
393        {
394            Ok(()) => Ok(true),
395            Err(error @ Error::FailureReporting(_)) => Err(error),
396            Err(_) => Ok(false),
397        }
398    }
399
400    async fn execute_local_activity(
401        &self,
402        task: &WorkflowTask,
403        context: &WorkflowContext,
404        request: &Request,
405    ) -> Result<Option<(Value, ActivityOutcome)>> {
406        let mut wire = context
407            .state
408            .lock()
409            .map_err(|_| Error::WorkflowStatePoisoned)?
410            .commands[request.command_index]
411            .clone();
412        // Serialize and admit input before the callback can produce side effects.
413        if !self
414            .admit_local_command(task, context, request.command_index, &mut wire, &[])
415            .await?
416        {
417            return Ok(None);
418        }
419        let activity_type = wire["activity_type"]
420            .as_str()
421            .unwrap_or_default()
422            .to_owned();
423        let policy = request.options.retry_policy.as_ref();
424        let max_attempts = policy
425            .and_then(|policy| policy["max_attempts"].as_u64())
426            .unwrap_or(1);
427        let started = Instant::now();
428        let total_deadline = request
429            .options
430            .schedule_to_close_timeout
431            .map(|seconds| started + Duration::from_secs(seconds));
432        let mut attempts = Vec::new();
433        let mut messages = Vec::new();
434        let mut heartbeat_count = 0;
435        for number in 1..=max_attempts {
436            if !self.local_claim_is_active(task).await {
437                return Ok(None);
438            }
439            let attempt_started = Instant::now();
440            let reports = Arc::new(Mutex::new(Heartbeats {
441                active: true,
442                started: attempt_started,
443                last: attempt_started,
444                reports: Vec::new(),
445                capacity: MAX_HEARTBEATS - heartbeat_count,
446                overflowed: false,
447            }));
448            let close = CloseAttempt(reports.clone());
449            let attempt_id = format!(
450                "{:x}",
451                Sha256::digest(
452                    format!(
453                        "{}\0{}\0{}\0{}",
454                        task.task_id, task.workflow_task_attempt, request.command_index, number
455                    )
456                    .as_bytes()
457                )
458            );
459            let ctx = ActivityContext {
460                client: self.client.clone(),
461                task_id: task.task_id.clone(),
462                activity_attempt_id: attempt_id.clone(),
463                lease_owner: task.lease_owner.clone().unwrap_or_default(),
464                activity_type: activity_type.clone(),
465                attempt_number: number,
466                retry_info: crate::ActivityRetryInfo::new(number, None),
467                heartbeat_resume: Default::default(),
468                activity_execution_id: None,
469                workflow_id: task.workflow_id.clone(),
470                run_id: task.run_id.clone(),
471                task_queue: self.task_queue.clone(),
472                worker_id: self.worker_id.clone(),
473                claim_guard: None,
474                local_heartbeats: Some(reports.clone()),
475                worker_session: None,
476            };
477            let callback = self
478                .activities
479                .get(&activity_type)
480                .filter(|_| total_deadline.is_none_or(|deadline| Instant::now() < deadline));
481            let mut future: ActivityFuture = match callback {
482                Some(callback) => {
483                    self.activity_callback(callback, ctx, request.arguments.clone(), true)
484                }
485                None if total_deadline.is_some_and(|deadline| Instant::now() >= deadline) => {
486                    Box::pin(std::future::pending())
487                }
488                None => {
489                    let unknown = activity_type.clone();
490                    Box::pin(async move { Err(Error::ActivityNotRegistered(unknown)) })
491                }
492            };
493            let attempt_deadline = request
494                .options
495                .start_to_close_timeout
496                .map(|seconds| attempt_started + Duration::from_secs(seconds));
497            let outcome = loop {
498                let heartbeat_deadline = request
499                    .options
500                    .heartbeat_timeout
501                    .map(|seconds| {
502                        reports
503                            .lock()
504                            .map(|reports| reports.last + Duration::from_secs(seconds))
505                    })
506                    .transpose()
507                    .map_err(|_| Error::WorkflowStatePoisoned)?;
508                let next_timeout = [
509                    (total_deadline, "schedule_to_close"),
510                    (attempt_deadline, "start_to_close"),
511                    (heartbeat_deadline, "heartbeat"),
512                ]
513                .into_iter()
514                .filter_map(|(deadline, kind)| deadline.map(|d| (d, kind)))
515                .min_by_key(|(deadline, _)| *deadline);
516                let timeout_kind = next_timeout
517                    .map(|(_, kind)| kind)
518                    .unwrap_or("start_to_close");
519                let timeout = async {
520                    match next_timeout {
521                        Some((deadline, _)) => tokio::time::sleep_until(deadline.into()).await,
522                        None => std::future::pending::<()>().await,
523                    }
524                };
525                tokio::pin!(timeout);
526                tokio::select! {
527                    biased;
528                    _ = self.local_worker_stopped() => return Ok(None),
529                    _ = &mut timeout => {
530                        if timeout_kind == "heartbeat" && heartbeat_extended(&reports, request.options.heartbeat_timeout)? { continue; }
531                        break Err((format!("local activity exceeded {timeout_kind} timeout"), "LocalActivityTimeout".to_owned(), false, Some(timeout_kind)));
532                    },
533                    result = &mut future => break result.map_err(local_error),
534                    _ = tokio::time::sleep(LEASE_RENEWAL_INTERVAL) => {
535                        tokio::select! {
536                            biased;
537                            _ = &mut timeout => {
538                                if timeout_kind == "heartbeat" && heartbeat_extended(&reports, request.options.heartbeat_timeout)? { continue; }
539                                break Err((format!("local activity exceeded {timeout_kind} timeout"), "LocalActivityTimeout".to_owned(), false, Some(timeout_kind)));
540                            },
541                            active = self.local_claim_is_active(task) => { if !active { return Ok(None); } }
542                        }
543                    }
544                }
545            };
546            drop(future);
547            drop(close);
548            let (heartbeats, overflowed) = {
549                let mut reports = reports.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
550                (std::mem::take(&mut reports.reports), reports.overflowed)
551            };
552            heartbeat_count += heartbeats.len();
553            let outcome = if overflowed {
554                Err((
555                    "local activity exceeded 1000 heartbeat reports".into(),
556                    "LocalActivityHeartbeatLimit".into(),
557                    true,
558                    None,
559                ))
560            } else {
561                outcome
562            };
563            let mut report = json!({"attempt_number": number, "attempt_id": attempt_id,
564                "duration_ms": millis(attempt_started.elapsed()), "heartbeats": heartbeats});
565            let (result, failure) = match outcome {
566                Ok(result) => match encode_typed_envelope(&result, &task.payload_codec) {
567                    Ok(envelope) => {
568                        wire["result"] = envelope;
569                        (Some(result), None)
570                    }
571                    Err(error) => (
572                        None,
573                        Some((
574                            error.to_string(),
575                            "LocalActivityResultCodecError".into(),
576                            true,
577                            None,
578                        )),
579                    ),
580                },
581                Err(failure) => (None, Some(failure)),
582            };
583            if let Some((message, exception_type, mut non_retryable, timeout_kind)) = failure {
584                non_retryable |= policy
585                    .and_then(|policy| policy["non_retryable_error_types"].as_array())
586                    .is_some_and(|types| {
587                        types
588                            .iter()
589                            .any(|t| t.as_str() == Some(exception_type.as_str()))
590                    });
591                let status = if timeout_kind.is_some() {
592                    "timed_out"
593                } else {
594                    "failed"
595                };
596                report["outcome"] = json!(status);
597                let original = crate::failure_reporting::LocalText::new(&message);
598                report["message"] = json!(original.render(crate::failure_reporting::MESSAGE_BYTES));
599                messages.push((attempts.len(), original));
600                report["exception_type"] = json!(exception_type);
601                report["non_retryable"] = json!(non_retryable);
602                if let Some(kind) = timeout_kind {
603                    report["timeout_kind"] = json!(kind);
604                }
605                let retry = number < max_attempts
606                    && !non_retryable
607                    && timeout_kind != Some("schedule_to_close");
608                if retry {
609                    let backoff = local_retry_backoff_seconds(policy, number);
610                    report["retry_reason"] = json!(if timeout_kind.is_some() {
611                        "timeout"
612                    } else {
613                        "failure"
614                    });
615                    report["backoff_seconds"] = json!(backoff);
616                    attempts.push(report);
617                    let wake = Instant::now() + Duration::from_secs(backoff);
618                    while Instant::now() < wake {
619                        // An elapsed total deadline is reported as the next
620                        // terminal attempt, with no further callback invocation.
621                        if total_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
622                            break;
623                        }
624                        if !self.local_claim_is_active(task).await {
625                            return Ok(None);
626                        }
627                        let deadline = total_deadline.map_or(wake, |d| d.min(wake));
628                        tokio::time::sleep(
629                            deadline
630                                .saturating_duration_since(Instant::now())
631                                .min(LEASE_RENEWAL_INTERVAL),
632                        )
633                        .await;
634                    }
635                    continue;
636                }
637                attempts.push(report);
638                for field in [
639                    "outcome",
640                    "message",
641                    "exception_type",
642                    "non_retryable",
643                    "timeout_kind",
644                ] {
645                    if let Some(value) = attempts.last().unwrap().get(field) {
646                        wire[field] = value.clone();
647                    }
648                }
649                wire["attempts"] = json!(attempts);
650                if !self
651                    .admit_local_command(task, context, request.command_index, &mut wire, &messages)
652                    .await?
653                    || !self.local_claim_is_active(task).await
654                {
655                    return Ok(None);
656                }
657                // Match the terminal fields Server persists. Database-generated
658                // execution/failure IDs are only available on committed replay.
659                let mut payload = wire.clone();
660                if let Some(message) = payload["message"].as_str() {
661                    payload["message"] =
662                        json!(crate::failure_reporting::committed_message(message));
663                }
664                payload["attempt_number"] = json!(number);
665                payload["failure_category"] = json!(if timeout_kind.is_some() {
666                    "timeout"
667                } else {
668                    "application"
669                });
670                if timeout_kind.is_some() {
671                    payload["exception_class"] = payload["exception_type"].take();
672                    payload.as_object_mut().unwrap().remove("exception_type");
673                    payload.as_object_mut().unwrap().remove("non_retryable");
674                }
675                let event = HistoryEvent {
676                    event_type: if timeout_kind.is_some() {
677                        "ActivityTimedOut"
678                    } else {
679                        "ActivityFailed"
680                    }
681                    .into(),
682                    payload,
683                    raw: HashMap::new(),
684                };
685                let result =
686                    activity_outcome(&event, &task.payload_codec, Some(activity_type.clone()))?;
687                return Ok(Some((wire, result)));
688            }
689            report["outcome"] = json!("completed");
690            attempts.push(report);
691            wire["outcome"] = json!("completed");
692            wire["attempts"] = json!(attempts);
693            if !self
694                .admit_local_command(task, context, request.command_index, &mut wire, &messages)
695                .await?
696                || !self.local_claim_is_active(task).await
697            {
698                return Ok(None);
699            }
700            return Ok(Some((wire, Ok(result.unwrap()))));
701        }
702        unreachable!("validated local retry budget includes at least one attempt")
703    }
704}
705
706fn local_error(error: Error) -> (String, String, bool, Option<&'static str>) {
707    let failure = crate::ActivityError::from_error(&error, "RustActivityError");
708    (
709        failure.message,
710        failure.exception_type,
711        failure.non_retryable,
712        None,
713    )
714}
715
716fn heartbeat_extended(reports: &Arc<Mutex<Heartbeats>>, timeout: Option<u64>) -> Result<bool> {
717    let reports = reports.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
718    Ok(timeout.is_some_and(|seconds| reports.last + Duration::from_secs(seconds) > Instant::now()))
719}
720
721/// The delay before retrying after attempt `number` (1-based). Once attempts
722/// outnumber the backoff list, the final entry repeats, as it does for
723/// Server-scheduled activities (durable-workflow/.github#219). No list means
724/// no delay.
725fn local_retry_backoff_seconds(policy: Option<&Value>, number: u64) -> u64 {
726    policy
727        .and_then(|p| p["backoff_seconds"].as_array())
728        .and_then(|list| {
729            let index = usize::try_from(number)
730                .ok()?
731                .min(list.len())
732                .checked_sub(1)?;
733            list.get(index)
734        })
735        .and_then(Value::as_u64)
736        .unwrap_or(0)
737}
738
739#[cfg(test)]
740mod local_retry_backoff_tests {
741    use super::{local_retry_backoff_seconds, LocalActivityOptions};
742    use crate::ActivityRetryPolicy;
743    use serde_json::json;
744    use std::time::Duration;
745
746    fn local_delays(policy: ActivityRetryPolicy) -> (serde_json::Value, Vec<u64>) {
747        let validated = LocalActivityOptions::new()
748            .retry_policy(policy)
749            .into_activity_options()
750            .validate()
751            .expect("valid local policy");
752        let policy = validated.retry_policy.expect("encoded retry policy");
753        let attempts = policy["max_attempts"].as_u64().unwrap();
754        let delays = (1..attempts)
755            .map(|number| local_retry_backoff_seconds(Some(&policy), number))
756            .collect();
757        (policy, delays)
758    }
759
760    #[test]
761    fn capped_exponential_local_policy_keeps_waiting_the_cap() {
762        // Generation stops at the cap; the repeat rule keeps every later
763        // local retry at the cap instead of retrying immediately.
764        let (policy, delays) = local_delays(ActivityRetryPolicy::new(7).exponential_backoff(
765            Duration::from_secs(1),
766            2,
767            Some(Duration::from_secs(4)),
768        ));
769        assert_eq!(policy["backoff_seconds"], json!([1, 2, 4]));
770        assert_eq!(delays, vec![1, 2, 4, 4, 4, 4]);
771    }
772
773    #[test]
774    fn explicit_short_and_empty_local_lists_follow_the_documented_rule() {
775        let (_, short) = local_delays(
776            ActivityRetryPolicy::new(5)
777                .backoff_intervals([Duration::from_secs(1), Duration::from_secs(2)]),
778        );
779        assert_eq!(short, vec![1, 2, 2, 2]);
780        let (policy, empty) = local_delays(ActivityRetryPolicy::new(5).backoff_intervals([]));
781        assert_eq!(policy["backoff_seconds"], json!([]));
782        assert_eq!(empty, vec![0, 0, 0, 0]);
783    }
784
785    #[test]
786    fn repeats_the_final_entry_once_the_list_runs_out() {
787        let policy = json!({"max_attempts": 5, "backoff_seconds": [1, 2]});
788        let delays: Vec<u64> = (1..=4)
789            .map(|number| local_retry_backoff_seconds(Some(&policy), number))
790            .collect();
791        assert_eq!(delays, vec![1, 2, 2, 2]);
792    }
793
794    #[test]
795    fn no_list_or_no_policy_means_no_delay() {
796        let empty = json!({"max_attempts": 3, "backoff_seconds": []});
797        let missing = json!({"max_attempts": 3});
798        assert_eq!(local_retry_backoff_seconds(Some(&empty), 2), 0);
799        assert_eq!(local_retry_backoff_seconds(Some(&missing), 2), 0);
800        assert_eq!(local_retry_backoff_seconds(None, 1), 0);
801    }
802}