taskvisor 0.5.0

Task supervisor for Tokio: restarts background tasks on failure with exponential backoff and jitter, graceful shutdown, and lifecycle events
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//! # TaskActor: single-task supervisor.
//!
//! Supervises one [`Task`] in a restart loop.
//!
//! The actor owns the policy loop:
//! - starts attempts,
//! - applies [`RestartPolicy`],
//! - schedules [`BackoffPolicy`] delays after retryable failures,
//! - delays successful repeats for [`RestartPolicy::Always`],
//! - returns the final actor exit reason to the registry.
//!
//! A single attempt is executed by [`run_once`](super::runner::run_once).
//! `run_once` owns per-attempt timeout, panic capture, and attempt-level events.
//!
//! ## Flow
//!
//! ```text
//! Registry -> TaskActor::run()
//!
//! loop:
//!   wait for runtime permit, if configured
//!   publish TaskStarting
//!   run_once()
//!     - Ok(())          -> TaskStopped
//!     - Err(Canceled)   -> TaskCanceled
//!     - Err(Timeout)    -> TimeoutHit, then TaskFailed
//!     - Err(Fail/Fatal) -> TaskFailed
//!
//!   release runtime permit
//!
//!   success:
//!     Never / OnFailure    -> ActorExhausted, exit
//!     Always { Some(dur) } -> BackoffScheduled(Success), sleep effective delay
//!     Always { None }      -> small safety delay/yield
//!
//!   retryable failure:
//!     retry budget left    -> BackoffScheduled(Failure), sleep retry delay
//!     retry budget used    -> ActorExhausted, exit
//!
//!   fatal failure:
//!     ActorDead, exit
//!
//!   cancellation:
//!     cancelled while waiting or sleeping
//!       -> exit without an actor-level terminal event
//!     task returned Canceled during runtime shutdown
//!       -> TaskCanceled, then exit without ActorExhausted
//!     task returned Canceled while runtime is active
//!       -> TaskCanceled, then ActorExhausted(reason="task_returned_canceled")
//! ```
//!
//! ## Attempt Events vs Actor Exit
//!
//! `run_once` publishes the result of one attempt:
//! - `TaskStopped`
//! - `TaskCanceled`
//! - `TaskFailed`
//! - `TimeoutHit` before `TaskFailed` on timeout
//!
//! `TaskActor` publishes the actor decision:
//! - `BackoffScheduled` when a delay is scheduled before another attempt
//! - `ActorExhausted` when the actor stops without a fatal error
//! - `ActorDead` when a fatal error stops the actor
//!
//! `TaskFailed` does not mean the task is finished. It may be followed by
//! `BackoffScheduled` and another `TaskStarting`.
//!
//! ## Rules
//!
//! - Attempts are sequential inside one actor.
//! - The attempt counter starts at 1 and increments before each `run_once` call.
//! - `max_retries` counts retries after the first failed attempt.
//!   For example, `Some(1)` allows the first attempt plus one retry.
//! - A runtime permit is held only while the attempt is running.
//!   Backoff and success-delay sleeps do not hold it.
//! - `run_once` derives a child cancellation token for each attempt.
//! - The actor uses the runtime token while waiting for permits and sleeping between attempts.
//! - Successful `Always` restarts are rate-limited for instant tasks.
//! - Task panics are converted by `run_once` into retryable `TaskError::Fail`.
//! - Event sequence numbers are useful for sorting, but are not a cross-task causal ordering guarantee.

use std::{
    num::NonZeroU32,
    sync::Arc,
    time::{Duration, Instant},
};
use tokio::sync::Semaphore;
use tokio_util::sync::CancellationToken;

use crate::{
    TaskError,
    core::runner::run_once,
    error::SharedError,
    events::{Bus, Event, EventKind},
    identity::TaskId,
    policies::{BackoffPolicy, RestartPolicy},
    reasons,
    tasks::Task,
};

/// Small delay used to prevent hot restart loops.
///
/// This applies to `RestartPolicy::Always` when a task finishes very quickly.
/// Without this delay, a task that returns `Ok(())` immediately could restart as fast as the scheduler allows and flood the event bus.
///
/// The delay is only added when the task ran for less than this value.
/// If the task already spent enough time doing work, no extra delay is added.
const IMMEDIATE_RESTART_FLOOR: Duration = Duration::from_millis(1);

/// Returns the effective delay after a successful `Always { interval: Some(d) }` attempt.
///
/// The configured interval is used unless the restart safety delay requires a longer delay for an instant task.
fn floored_interval(interval: Duration, elapsed: Duration) -> Duration {
    interval.max(IMMEDIATE_RESTART_FLOOR.saturating_sub(elapsed))
}

/// Final reason returned by [`TaskActor::run`].
///
/// The registry uses this value after joining the actor to clean up the task and resolve the matching [`TaskOutcome`](crate::TaskOutcome).
#[derive(Debug, Clone)]
pub(crate) enum ActorExitReason {
    /// Final attempt succeeded and the restart policy stopped the actor.
    ///
    /// Occurs when:
    /// - `RestartPolicy::Never` and the task completed successfully
    /// - `RestartPolicy::OnFailure` and the task completed successfully
    Completed,

    /// Final attempt failed and the actor stopped without a fatal error.
    ///
    /// Occurs when:
    /// - `RestartPolicy::Never` does not allow a retry
    /// - the error is not retryable
    /// - the retry budget (`max_retries`) is used up
    Exhausted {
        /// Final failure message. Same text as the `ActorExhausted` event reason.
        reason: Arc<str>,
        /// Numeric exit code from a process-like task, if any.
        exit_code: Option<i32>,
        /// Original error source from the final [`TaskError`], if any.
        source: Option<SharedError>,
    },

    /// Actor stopped because of runtime shutdown, explicit removal, or `TaskError::Canceled`.
    ///
    /// This maps to [`TaskOutcome::Canceled`](crate::TaskOutcome).
    /// Depending on where cancellation happened, there may be no actor-level terminal event.
    Canceled,

    /// Actor stopped because the task returned a fatal error.
    ///
    /// Fatal errors are not retried.
    Fatal {
        /// Fatal error message. Same text as the `ActorDead` event reason.
        reason: Arc<str>,
        /// Numeric exit code from a process-like task, if any.
        exit_code: Option<i32>,
        /// Original error source from the fatal [`TaskError`], if any.
        source: Option<SharedError>,
    },
}

/// Runtime parameters used by one task actor.
#[derive(Clone)]
pub(crate) struct TaskActorParams {
    /// Policy that decides whether another attempt is allowed.
    pub(crate) restart: RestartPolicy,
    /// Delay policy for retryable failures.
    pub(crate) backoff: BackoffPolicy,
    /// Optional timeout for one attempt (`None` = no timeout).
    pub(crate) timeout: Option<Duration>,
    /// Maximum retries after the first failed attempt (`None` = unlimited).
    pub(crate) max_retries: Option<NonZeroU32>,
}

/// Internal supervisor for one registered task.
///
/// The registry spawns one actor per accepted task.
/// The actor runs attempts sequentially and returns one [`ActorExitReason`] when the retry loop ends.
pub(crate) struct TaskActor {
    /// Runtime identity stamped on lifecycle events for this task run.
    id: TaskId,
    /// Task label.
    name: Arc<str>,
    /// Task to execute.
    task: Arc<dyn Task>,
    /// Restart, backoff, timeout, and retry settings.
    params: TaskActorParams,
    /// Internal event bus used for lifecycle events.
    bus: Bus,
    /// Optional global limiter for concurrently running attempts.
    ///
    /// Held only while `run_once` is executing. Retry/backoff sleeps do not hold it.
    semaphore: Option<Arc<Semaphore>>,
}

impl TaskActor {
    /// Creates an actor for one accepted task registration.
    pub(crate) fn new(
        bus: Bus,
        name: Arc<str>,
        task: Arc<dyn Task>,
        params: TaskActorParams,
        semaphore: Option<Arc<Semaphore>>,
        id: TaskId,
    ) -> Self {
        Self {
            id,
            name,
            task,
            params,
            bus,
            semaphore,
        }
    }

    /// Runs the actor until completion, retry exhaustion, fatal failure, or cancellation.
    ///
    /// `run_once` derives a child token for the current attempt.
    /// The actor uses the runtime token while waiting for a permit and while sleeping between attempts, shutdown can interrupt both places.
    pub(crate) async fn run(self, runtime_token: CancellationToken) -> ActorExitReason {
        let task_name: Arc<str> = self.name.clone();
        let id = self.id;
        let mut attempt: u32 = 0;
        let mut backoff_attempt: u32 = 0;

        loop {
            if runtime_token.is_cancelled() {
                return ActorExitReason::Canceled;
            }
            let permit = match &self.semaphore {
                Some(sem) => {
                    let fut = sem.clone().acquire_owned();
                    tokio::pin!(fut);

                    tokio::select! {
                        res = &mut fut => match res {
                            Ok(p) => Some(p),
                            Err(_closed) => {
                                self.bus.publish(
                                    Event::new(EventKind::ActorExhausted)
                                        .with_task(task_name.clone())
                                        .with_id(id)
                                        .with_attempt(attempt)
                                        .with_reason("semaphore_closed"),
                                );
                                return ActorExitReason::Canceled;
                            }
                        },
                        _ = runtime_token.cancelled() => {
                            return ActorExitReason::Canceled;
                        }
                    }
                }
                None => None,
            };
            if runtime_token.is_cancelled() {
                drop(permit);
                return ActorExitReason::Canceled;
            }

            attempt = attempt.saturating_add(1);

            self.bus.publish(
                Event::new(EventKind::TaskStarting)
                    .with_task(task_name.clone())
                    .with_id(id)
                    .with_attempt(attempt),
            );
            let attempt_start = Instant::now();
            let res = run_once(
                self.task.as_ref(),
                &runtime_token,
                self.params.timeout,
                attempt,
                id,
                &self.bus,
            )
            .await;

            drop(permit);
            match res {
                Ok(()) => {
                    backoff_attempt = 0;

                    match self.params.restart {
                        RestartPolicy::Always { interval } => {
                            if let Some(d) = interval {
                                let delay = floored_interval(d, attempt_start.elapsed());
                                self.bus.publish(
                                    Event::new(EventKind::BackoffScheduled)
                                        .with_backoff_success()
                                        .with_task(task_name.clone())
                                        .with_id(id)
                                        .with_attempt(attempt)
                                        .with_delay(delay),
                                );
                                if !Self::sleep_cancellable(delay, &runtime_token).await {
                                    return ActorExitReason::Canceled;
                                }
                            } else {
                                let elapsed = attempt_start.elapsed();
                                if elapsed < IMMEDIATE_RESTART_FLOOR {
                                    if !Self::sleep_cancellable(
                                        IMMEDIATE_RESTART_FLOOR - elapsed,
                                        &runtime_token,
                                    )
                                    .await
                                    {
                                        return ActorExitReason::Canceled;
                                    }
                                } else {
                                    tokio::task::yield_now().await;
                                }
                            }
                            continue;
                        }
                        RestartPolicy::OnFailure | RestartPolicy::Never => {
                            if runtime_token.is_cancelled() {
                                return ActorExitReason::Canceled;
                            }
                            self.bus.publish(
                                Event::new(EventKind::ActorExhausted)
                                    .with_task(task_name.clone())
                                    .with_id(id)
                                    .with_attempt(attempt)
                                    .with_reason(reasons::POLICY_EXHAUSTED_SUCCESS),
                            );
                            return ActorExitReason::Completed;
                        }
                    }
                }
                Err(e) if e.is_fatal() => {
                    let reason: Arc<str> = Arc::from(e.to_string());
                    let exit_code = e.exit_code();
                    let source: Option<SharedError> = e.into_source().map(Arc::from);

                    let mut ev = Event::new(EventKind::ActorDead)
                        .with_task(task_name.clone())
                        .with_id(id)
                        .with_attempt(attempt)
                        .with_reason(Arc::clone(&reason));
                    if let Some(code) = exit_code {
                        ev = ev.with_exit_code(code);
                    }
                    self.bus.publish(ev);
                    return ActorExitReason::Fatal {
                        reason,
                        exit_code,
                        source,
                    };
                }
                Err(TaskError::Canceled) => {
                    if runtime_token.is_cancelled() {
                        return ActorExitReason::Canceled;
                    }
                    self.bus.publish(
                        Event::new(EventKind::ActorExhausted)
                            .with_task(task_name.clone())
                            .with_id(id)
                            .with_attempt(attempt)
                            .with_reason(reasons::TASK_RETURNED_CANCELED),
                    );
                    return ActorExitReason::Canceled;
                }
                Err(e) => {
                    let policy_allows_retry = matches!(
                        self.params.restart,
                        RestartPolicy::OnFailure | RestartPolicy::Always { .. }
                    );
                    let error_is_retryable = e.is_retryable();
                    let retries_exhausted = self
                        .params
                        .max_retries
                        .is_some_and(|max| backoff_attempt >= max.get());

                    if !(policy_allows_retry && error_is_retryable) || retries_exhausted {
                        let reason: Arc<str> = if let Some(limit) =
                            self.params.max_retries.filter(|_| retries_exhausted)
                        {
                            Arc::from(format!(
                                "{}({}/{}): {}",
                                reasons::MAX_RETRIES_EXCEEDED,
                                backoff_attempt,
                                limit.get(),
                                e
                            ))
                        } else {
                            Arc::from(e.to_string())
                        };
                        let exit_code = e.exit_code();
                        let source: Option<SharedError> = e.into_source().map(Arc::from);

                        let mut ev = Event::new(EventKind::ActorExhausted)
                            .with_task(task_name.clone())
                            .with_id(id)
                            .with_attempt(attempt)
                            .with_reason(Arc::clone(&reason));
                        if let Some(code) = exit_code {
                            ev = ev.with_exit_code(code);
                        }
                        self.bus.publish(ev);
                        return ActorExitReason::Exhausted {
                            reason,
                            exit_code,
                            source,
                        };
                    }

                    let delay = self.params.backoff.next(backoff_attempt);
                    backoff_attempt = backoff_attempt.saturating_add(1);

                    self.bus.publish(
                        Event::new(EventKind::BackoffScheduled)
                            .with_backoff_failure()
                            .with_task(task_name.clone())
                            .with_id(id)
                            .with_delay(delay)
                            .with_attempt(attempt)
                            .with_reason(e.to_string()),
                    );
                    if !Self::sleep_cancellable(delay, &runtime_token).await {
                        return ActorExitReason::Canceled;
                    }
                }
            }
        }
    }

    /// Sleeps until `duration` elapses or `token` is cancelled.
    ///
    /// Returns `true` if the sleep finished, or `false` if it was cancelled.
    #[inline]
    async fn sleep_cancellable(duration: Duration, token: &CancellationToken) -> bool {
        let sleep = tokio::time::sleep(duration);
        tokio::pin!(sleep);

        tokio::select! {
            _ = &mut sleep => true,
            _ = token.cancelled() => false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::TaskContext;
    use std::future::Future;
    use std::pin::Pin;
    use std::sync::atomic::{AtomicU32, Ordering};

    type BoxFut = Pin<Box<dyn Future<Output = Result<(), TaskError>> + Send + 'static>>;

    fn fast_backoff() -> BackoffPolicy {
        BackoffPolicy::new(
            Duration::from_millis(1),
            Duration::from_millis(1),
            1.0,
            crate::JitterPolicy::None,
        )
        .expect("valid backoff")
    }

    fn params(restart: RestartPolicy, max_retries: u32) -> TaskActorParams {
        TaskActorParams {
            restart,
            backoff: fast_backoff(),
            timeout: None,
            max_retries: NonZeroU32::new(max_retries),
        }
    }

    fn actor(task: Arc<dyn Task>, restart: RestartPolicy, max_retries: u32) -> TaskActor {
        let name: Arc<str> = Arc::from(task.name());
        TaskActor::new(
            Bus::new(16),
            name,
            Arc::clone(&task),
            params(restart, max_retries),
            None,
            TaskId::next(),
        )
    }

    struct OkTask;
    impl Task for OkTask {
        fn name(&self) -> &str {
            "ok"
        }
        fn spawn(&self, _ctx: TaskContext) -> BoxFut {
            Box::pin(async { Ok(()) })
        }
    }

    struct FailTask;
    impl Task for FailTask {
        fn name(&self) -> &str {
            "fail"
        }
        fn spawn(&self, _ctx: TaskContext) -> BoxFut {
            Box::pin(async { Err(TaskError::fail("boom")) })
        }
    }

    struct FatalTask;
    impl Task for FatalTask {
        fn name(&self) -> &str {
            "fatal"
        }
        fn spawn(&self, _ctx: TaskContext) -> BoxFut {
            Box::pin(async { Err(TaskError::fatal("fatal")) })
        }
    }

    struct CountedTask {
        remaining: AtomicU32,
    }
    impl CountedTask {
        fn new(fail_count: u32) -> Self {
            Self {
                remaining: AtomicU32::new(fail_count),
            }
        }
    }
    impl Task for CountedTask {
        fn name(&self) -> &str {
            "counted"
        }
        fn spawn(&self, _ctx: TaskContext) -> BoxFut {
            let prev = self.remaining.fetch_sub(1, Ordering::SeqCst);
            if prev > 0 {
                Box::pin(async { Err(TaskError::fail("transient")) })
            } else {
                Box::pin(async { Ok(()) })
            }
        }
    }

    #[tokio::test]
    async fn ok_task_returns_completed_under_non_restarting_policies() {
        for restart in [RestartPolicy::Never, RestartPolicy::OnFailure] {
            let a = actor(Arc::new(OkTask), restart, 0);
            let reason = a.run(CancellationToken::new()).await;
            assert!(
                matches!(reason, ActorExitReason::Completed),
                "{restart:?} + Ok task must exit Completed, got {reason:?}"
            );
        }
    }

    #[tokio::test]
    async fn fatal_error_returns_fatal_with_reason() {
        let a = actor(Arc::new(FatalTask), RestartPolicy::OnFailure, 0);
        let reason = a.run(CancellationToken::new()).await;
        match reason {
            ActorExitReason::Fatal {
                reason, exit_code, ..
            } => {
                assert!(
                    reason.contains("fatal"),
                    "reason must carry the error: {reason}"
                );
                assert_eq!(exit_code, None);
            }
            other => panic!("expected Fatal, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn max_retries_exhausted_returns_exhausted_with_reason() {
        let a = actor(Arc::new(FailTask), RestartPolicy::OnFailure, 3);
        let reason = a.run(CancellationToken::new()).await;
        match reason {
            ActorExitReason::Exhausted { reason, .. } => {
                assert!(
                    reason.contains("max_retries_exceeded"),
                    "reason must mention exhausted budget: {reason}"
                );
            }
            other => panic!("expected Exhausted, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn cancellation_returns_cancelled() {
        let token = CancellationToken::new();
        token.cancel();
        let a = actor(
            Arc::new(OkTask),
            RestartPolicy::Always { interval: None },
            0,
        );
        let reason = a.run(token).await;
        assert!(matches!(reason, ActorExitReason::Canceled));
    }

    #[tokio::test]
    async fn on_failure_retries_then_succeeds() {
        let task = Arc::new(CountedTask::new(2));
        let a = actor(task, RestartPolicy::OnFailure, 0);
        let reason = a.run(CancellationToken::new()).await;
        assert!(matches!(reason, ActorExitReason::Completed));
    }

    #[tokio::test]
    async fn always_none_instant_ok_is_rate_limited() {
        use std::sync::atomic::{AtomicU32, Ordering};

        struct Counting(Arc<AtomicU32>);
        impl Task for Counting {
            fn name(&self) -> &str {
                "spin"
            }
            fn spawn(&self, _ctx: TaskContext) -> BoxFut {
                self.0.fetch_add(1, Ordering::Relaxed);
                Box::pin(async { Ok(()) })
            }
        }

        let counter = Arc::new(AtomicU32::new(0));
        let task = Arc::new(Counting(Arc::clone(&counter)));
        let a = actor(task, RestartPolicy::Always { interval: None }, 0);

        let token = CancellationToken::new();
        let child = token.clone();
        let handle = tokio::spawn(async move { a.run(child).await });

        tokio::time::sleep(Duration::from_millis(25)).await;
        token.cancel();
        let _ = handle.await;
        let n = counter.load(Ordering::Relaxed);
        assert!(
            (1..=200).contains(&n),
            "Always {{ interval: None }} with an instant-Ok task must be floored, got {n} restarts in 25ms"
        );
    }

    #[test]
    fn floored_interval_floors_only_the_idle_portion() {
        let floor = IMMEDIATE_RESTART_FLOOR;

        assert_eq!(floored_interval(Duration::ZERO, Duration::ZERO), floor);
        assert_eq!(floored_interval(floor / 2, Duration::ZERO), floor);
        assert_eq!(
            floored_interval(Duration::ZERO, floor * 2),
            Duration::ZERO,
            "a slow attempt must not be additionally delayed"
        );
        assert_eq!(floored_interval(floor * 10, Duration::ZERO), floor * 10);
        assert_eq!(floored_interval(floor * 10, floor * 3), floor * 10);
    }
}