Skip to main content

saluki_core/runtime/
resumable.rs

1//! Workers that keep the state of their work across restarts.
2
3use std::{
4    any::Any,
5    fmt,
6    future::{poll_fn, Future},
7    panic::{catch_unwind, resume_unwind, AssertUnwindSafe},
8    pin::pin,
9    sync::{Arc, Mutex as SyncMutex},
10    task::Poll,
11    time::Duration,
12};
13
14use async_trait::async_trait;
15use saluki_common::{
16    sync::shutdown::{ShutdownCoordinator, ShutdownHandle, ShutdownView},
17    task::spawn_traced_named,
18};
19use saluki_error::{generic_error, GenericError};
20use tokio::{
21    sync::{Mutex, OwnedMutexGuard},
22    task::JoinHandle,
23};
24use tracing::{error, warn};
25
26use super::supervisable::{InitializationError, ShutdownStrategy, Supervisable, SupervisorFuture};
27
28const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
29
30/// Work whose state outlives the worker that runs it.
31///
32/// The state is `self`. A [`ResumableWorker`] calls [`run`][Self::run] each time it starts, and each call continues from
33/// whatever the previous call left in `self`.
34pub trait Resumable: Send + 'static {
35    /// Returns the shutdown strategy of the worker that runs this work.
36    ///
37    /// [`ResumableWorker`] calls this once, when it is created. Defaults to a graceful shutdown with a five-second
38    /// timeout.
39    fn shutdown_strategy(&self) -> ShutdownStrategy {
40        ShutdownStrategy::Graceful(DEFAULT_SHUTDOWN_TIMEOUT)
41    }
42
43    /// Runs the work until `stop` resolves.
44    ///
45    /// Once `stop` resolves, return at the next point where stopping loses no work. A call can also be dropped at any
46    /// await point, when its owner halts it or it is cancelled before supervision, so every await point must leave
47    /// `self` able to continue. Record work in flight that can't be repeated, and don't race it against `stop` if
48    /// stopping must lose nothing.
49    ///
50    /// The worker ends when this returns, and its owner then applies its restart policy. Work that can run out of
51    /// things to do waits for `stop`, returns an error, or runs in a worker that is added as a hosted child.
52    ///
53    /// # Errors
54    ///
55    /// An error ends the worker that runs this call, and its owner restarts it or fails, according to its restart
56    /// policy.
57    fn run(&mut self, stop: ShutdownHandle) -> impl Future<Output = Result<(), GenericError>> + Send + '_;
58}
59
60/// A worker that keeps the state of its work across restarts.
61///
62/// Most workers build their work again each time they start. A `ResumableWorker` keeps its [`Resumable`] state instead,
63/// so that each start continues from where the previous one stopped: a restart resumes rather than resets. This holds
64/// even after a panic, so a state that a panic left inconsistent can fail again until the restart limit of the owner
65/// passes the failure up the supervision tree.
66///
67/// Create one with [`new`][Self::new], or with [`start_early`][Self::start_early] for work that has to start before any
68/// supervisor runs. The worker isn't `Clone`: add it to one owner only.
69///
70/// # Starting early
71///
72/// [`start_early`][Self::start_early] runs the work at once in a plain task. The task isn't a process: it has no
73/// process identifier, scope, or dataspace, so the work can't spawn children or assert anything, and it isn't part of
74/// any supervision tree. It runs in the span and resource group of the caller.
75///
76/// When the worker first starts under supervision, it signals the early task to stop, waits for `run` to return at a
77/// point that loses no work, and then continues with the same state as a supervised process. If `run` ended before
78/// that, the first start ends with its result. If it panicked, the first start panics again. The shutdown strategy of
79/// the worker bounds the wait.
80///
81/// Dropping the worker before it first starts cancels the task.
82///
83/// # State
84///
85/// The same state is used before supervision and by each instance of the worker, so it **MUST NOT** hold anything
86/// bound to a process, such as a [`Scope`][crate::runtime::Scope], a [`ScopeGuard`][crate::runtime::ScopeGuard], or a
87/// [`SupervisorHandle`][crate::runtime::SupervisorHandle]. Set those up in each call to `run` instead.
88///
89/// Timers and connections stay bound to the Tokio runtime that created them. Don't run the worker on a runtime that is
90/// replaced when its owner restarts, such as the runtime of a supervisor with a
91/// [dedicated runtime][crate::runtime::RuntimeMode::Dedicated], unless `run` builds them again.
92pub struct ResumableWorker<L> {
93    name: String,
94    shutdown_strategy: ShutdownStrategy,
95    state: Arc<Mutex<L>>,
96    early: SyncMutex<Option<EarlyStart>>,
97}
98
99impl<L: Resumable> ResumableWorker<L> {
100    /// Creates a worker named `name` that runs `state` each time it starts.
101    #[must_use]
102    pub fn new<N: Into<String>>(name: N, state: L) -> Self {
103        Self {
104            name: name.into(),
105            shutdown_strategy: state.shutdown_strategy(),
106            state: Arc::new(Mutex::new(state)),
107            early: SyncMutex::new(None),
108        }
109    }
110
111    /// Starts running `state` now, in a task named `name`, and returns the worker that takes it over when it first
112    /// starts.
113    ///
114    /// See [Starting early](Self#starting-early).
115    ///
116    /// # Panics
117    ///
118    /// Panics if called outside of a Tokio runtime.
119    #[must_use = "dropping the worker before it starts cancels the work"]
120    pub fn start_early<N: Into<String>>(name: N, state: L) -> Self {
121        let mut worker = Self::new(name, state);
122
123        // Take an initial lock on the state, and spawn a task to do our early start run.
124        //
125        // We capture our shutdown handle to allow the worker to trigger handoff when it is added to a supervision tree
126        // and spawned.
127        let guard = Arc::clone(&worker.state)
128            .try_lock_owned()
129            .expect("a new mutex should be unlocked");
130        let (handoff, stop) = ShutdownHandle::paired();
131        let handed_off = stop.view();
132        let worker_name = worker.name.clone();
133        let task = spawn_traced_named(
134            worker_name.clone(),
135            run_resumable_early(worker_name, stop, handed_off, guard),
136        );
137
138        *worker.early.get_mut().unwrap_or_else(|e| e.into_inner()) = Some(EarlyStart {
139            handoff: Some(handoff),
140            task,
141        });
142        worker
143    }
144}
145
146#[async_trait]
147impl<L: Resumable> Supervisable for ResumableWorker<L> {
148    fn name(&self) -> &str {
149        &self.name
150    }
151
152    fn shutdown_strategy(&self) -> ShutdownStrategy {
153        self.shutdown_strategy
154    }
155
156    async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
157        let early = self.early.lock().unwrap_or_else(|e| e.into_inner()).take();
158        let state = Arc::clone(&self.state);
159
160        Ok(Box::pin(async move {
161            // If this is the first time the worker is running after an early start, signal the task to handoff to us
162            // and wait until the early task returns.
163            if let Some(early) = early {
164                if let Some(result) = early.hand_off().await {
165                    return result;
166                }
167            }
168
169            // Lock the worker state and run like normal.
170            let mut state = state.lock_owned().await;
171            state.run(process_shutdown).await
172        }))
173    }
174}
175
176impl<L> fmt::Debug for ResumableWorker<L> {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        f.debug_struct("ResumableWorker")
179            .field("name", &self.name)
180            .finish_non_exhaustive()
181    }
182}
183
184/// Early start task state.
185struct EarlyStart {
186    handoff: Option<ShutdownCoordinator>,
187    task: JoinHandle<HandoffOutcome>,
188}
189
190/// Outcome of the early start task handoff.
191enum HandoffOutcome {
192    /// Task successfully stopped and the state can be handed off to the worker.
193    Ready,
194
195    /// Task completed prematurely before handoff was requested.
196    EndedPrematurely(Result<(), GenericError>),
197
198    /// Task panicked before handoff was requested.
199    Panicked(Box<dyn Any + Send>),
200}
201
202impl EarlyStart {
203    /// Tells the task to stop and waits for it, returning the result of the work if it ended by itself.
204    async fn hand_off(mut self) -> Option<Result<(), GenericError>> {
205        if let Some(handoff) = self.handoff.take() {
206            handoff.shutdown();
207        }
208
209        match (&mut self.task).await {
210            Ok(HandoffOutcome::Ready) => None,
211            Ok(HandoffOutcome::EndedPrematurely(result)) => Some(result),
212            Ok(HandoffOutcome::Panicked(panic)) => resume_unwind(panic),
213            Err(e) => Some(Err(generic_error!(
214                "Work was cancelled before its worker started: {}",
215                e
216            ))),
217        }
218    }
219}
220
221impl Drop for EarlyStart {
222    fn drop(&mut self) {
223        // Does nothing if the task already finished.
224        self.task.abort();
225    }
226}
227
228async fn run_resumable_early<L: Resumable>(
229    worker_name: String, stop: ShutdownHandle, handed_off: ShutdownView, mut guard: OwnedMutexGuard<L>,
230) -> HandoffOutcome {
231    // Run our resumable worker directly until we're instructed to stop, taking care to
232    // capture any panics that occur.
233    let mut run = pin!(guard.run(stop));
234    let outcome = poll_fn(|cx| match catch_unwind(AssertUnwindSafe(|| run.as_mut().poll(cx))) {
235        Ok(Poll::Ready(result)) => Poll::Ready(Ok(result)),
236        Ok(Poll::Pending) => Poll::Pending,
237        Err(e) => Poll::Ready(Err(e)),
238    })
239    .await;
240
241    match outcome {
242        Err(e) => {
243            error!(%worker_name, "Task panicked before supervised worker started.");
244            HandoffOutcome::Panicked(e)
245        }
246        Ok(Ok(())) if handed_off.is_triggered() => HandoffOutcome::Ready,
247        Ok(result) => {
248            if !handed_off.is_triggered() {
249                match &result {
250                    Ok(()) => warn!(%worker_name, "Task ended before supervised worker started."),
251                    Err(e) => {
252                        warn!(%worker_name, error = %e, "Task failed before supervised worker started.")
253                    }
254                }
255            }
256            HandoffOutcome::EndedPrematurely(result)
257        }
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use std::sync::atomic::{AtomicBool, Ordering};
264
265    use saluki_common::sync::shutdown::ShutdownView;
266    use tokio::{
267        select,
268        sync::{Notify, Semaphore},
269    };
270
271    use super::*;
272    use crate::{
273        runtime::{
274            state::DataspaceRegistry, test_util::TestSupervisor, NodeSnapshot, ProcessId, RestartStrategy, Supervisor,
275        },
276        test_support::wait_until,
277    };
278
279    /// What the probe recorded for one completed step, or for a stop.
280    #[derive(Clone, Copy, Debug, PartialEq)]
281    enum Entry {
282        Step {
283            n: u64,
284            in_process: bool,
285            has_dataspace: bool,
286        },
287        Stopped {
288            in_process: bool,
289        },
290    }
291
292    #[derive(Clone, Copy, Debug, PartialEq)]
293    enum Knob {
294        Panic,
295        Fail,
296        End,
297    }
298
299    /// The parts of a probe that the test keeps.
300    #[derive(Clone)]
301    struct Controls {
302        journal: Arc<SyncMutex<Vec<Entry>>>,
303        begin: Arc<Semaphore>,
304        finish: Arc<Semaphore>,
305        stepping: Arc<AtomicBool>,
306        stops: Arc<SyncMutex<Vec<ShutdownView>>>,
307    }
308
309    impl Controls {
310        /// Lets `n` more steps begin and finish.
311        fn release(&self, n: usize) {
312            self.begin.add_permits(n);
313            self.finish.add_permits(n);
314        }
315
316        fn journal(&self) -> Vec<Entry> {
317            self.journal.lock().unwrap().clone()
318        }
319
320        fn steps(&self) -> Vec<(u64, bool)> {
321            self.journal()
322                .into_iter()
323                .filter_map(|entry| match entry {
324                    Entry::Step { n, in_process, .. } => Some((n, in_process)),
325                    Entry::Stopped { .. } => None,
326                })
327                .collect()
328        }
329
330        fn is_stepping(&self) -> bool {
331            self.stepping.load(Ordering::SeqCst)
332        }
333
334        /// Returns `true` once the stop signal of the first call to `run` fired.
335        fn handoff_fired(&self) -> bool {
336            self.stops
337                .lock()
338                .unwrap()
339                .first()
340                .is_some_and(ShutdownView::is_triggered)
341        }
342
343        async fn wait_for_steps(&self, count: usize) {
344            wait_until(&format!("{count} steps finished"), || self.steps().len() == count).await;
345        }
346
347        async fn wait_for_handoff(&self) {
348            wait_until("the handoff fired", || self.handoff_fired()).await;
349        }
350    }
351
352    /// Clears the flag that marks a step in progress when the step finishes, or when the call is dropped.
353    struct SteppingGuard(Arc<AtomicBool>);
354
355    impl SteppingGuard {
356        fn new(flag: &Arc<AtomicBool>) -> Self {
357            flag.store(true, Ordering::SeqCst);
358            Self(Arc::clone(flag))
359        }
360    }
361
362    impl Drop for SteppingGuard {
363        fn drop(&mut self) {
364            self.0.store(false, Ordering::SeqCst);
365        }
366    }
367
368    /// Work that runs numbered steps.
369    ///
370    /// A step begins once `begin` gives a permit, racing `stop`, and finishes once `finish` gives one, without racing
371    /// `stop`. A step that began is retried if a call is dropped before it finishes.
372    struct Probe {
373        controls: Controls,
374        strategy: ShutdownStrategy,
375        done: u64,
376        in_flight: bool,
377        knob: Option<(u64, Knob)>,
378    }
379
380    impl Probe {
381        fn new(strategy: ShutdownStrategy) -> (Self, Controls) {
382            let controls = Controls {
383                journal: Arc::default(),
384                begin: Arc::new(Semaphore::new(0)),
385                finish: Arc::new(Semaphore::new(0)),
386                stepping: Arc::default(),
387                stops: Arc::default(),
388            };
389            let probe = Self {
390                controls: controls.clone(),
391                strategy,
392                done: 0,
393                in_flight: false,
394                knob: None,
395            };
396            (probe, controls)
397        }
398
399        fn graceful() -> (Self, Controls) {
400            Self::new(ShutdownStrategy::Graceful(DEFAULT_SHUTDOWN_TIMEOUT))
401        }
402
403        fn brutal() -> (Self, Controls) {
404            Self::new(ShutdownStrategy::Brutal)
405        }
406
407        /// Acts on `knob` once, right after step `n` finishes.
408        fn with_knob(mut self, n: u64, knob: Knob) -> Self {
409            self.knob = Some((n, knob));
410            self
411        }
412
413        fn record(&self, entry: Entry) {
414            self.controls.journal.lock().unwrap().push(entry);
415        }
416    }
417
418    fn in_process() -> bool {
419        ProcessId::current() != ProcessId::ROOT
420    }
421
422    impl Resumable for Probe {
423        fn shutdown_strategy(&self) -> ShutdownStrategy {
424            self.strategy
425        }
426
427        async fn run(&mut self, stop: ShutdownHandle) -> Result<(), GenericError> {
428            self.controls.stops.lock().unwrap().push(stop.view());
429            let mut stop = pin!(stop);
430
431            loop {
432                if !self.in_flight {
433                    select! {
434                        biased;
435                        _ = &mut stop => {
436                            self.record(Entry::Stopped { in_process: in_process() });
437                            return Ok(());
438                        }
439                        permit = self.controls.begin.acquire() => permit.expect("gate stays open").forget(),
440                    }
441                    self.in_flight = true;
442                }
443
444                let stepping = SteppingGuard::new(&self.controls.stepping);
445                self.controls.finish.acquire().await.expect("gate stays open").forget();
446                drop(stepping);
447
448                self.done += 1;
449                self.in_flight = false;
450                self.record(Entry::Step {
451                    n: self.done,
452                    in_process: in_process(),
453                    has_dataspace: DataspaceRegistry::try_current().is_some(),
454                });
455
456                match self.knob {
457                    Some((n, knob)) if n == self.done => {
458                        self.knob = None;
459                        match knob {
460                            Knob::Panic => panic!("probe panicked after step {n}"),
461                            Knob::Fail => return Err(generic_error!("probe failed after step {}", n)),
462                            Knob::End => return Ok(()),
463                        }
464                    }
465                    _ => {}
466                }
467            }
468        }
469    }
470
471    /// A restartable sibling that fails each time it is tripped.
472    struct Tripwire(Arc<Notify>);
473
474    #[async_trait]
475    impl Supervisable for Tripwire {
476        fn name(&self) -> &str {
477            "tripwire"
478        }
479
480        async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
481            let trip = Arc::clone(&self.0);
482            Ok(Box::pin(async move {
483                select! {
484                    _ = process_shutdown => Ok(()),
485                    _ = trip.notified() => Err(generic_error!("tripped")),
486                }
487            }))
488        }
489    }
490
491    fn find<'a>(node: &'a NodeSnapshot, name: &str) -> Option<&'a NodeSnapshot> {
492        if node.name == name {
493            return Some(node);
494        }
495        node.children.iter().find_map(|child| find(child, name))
496    }
497
498    fn restart_count(supervisor: &TestSupervisor, name: &str) -> u32 {
499        let snapshot = supervisor.tree_handle().snapshot();
500        find(&snapshot.root, name).expect("node should exist").restart_count
501    }
502
503    async fn start(worker: ResumableWorker<Probe>) -> TestSupervisor {
504        TestSupervisor::start_with("test", |supervisor| supervisor.add_worker(worker)).await
505    }
506
507    async fn wait_for_release(state: &Arc<Mutex<Probe>>) {
508        wait_until("the state is released", || state.try_lock().is_ok()).await;
509    }
510
511    #[tokio::test]
512    async fn work_started_early_runs_outside_any_process() {
513        let (probe, controls) = Probe::graceful();
514        let _worker = ResumableWorker::start_early("probe", probe);
515
516        controls.release(2);
517        controls.wait_for_steps(2).await;
518
519        assert_eq!(
520            controls.journal(),
521            vec![
522                Entry::Step {
523                    n: 1,
524                    in_process: false,
525                    has_dataspace: false
526                },
527                Entry::Step {
528                    n: 2,
529                    in_process: false,
530                    has_dataspace: false
531                },
532            ]
533        );
534    }
535
536    #[tokio::test]
537    async fn the_worker_continues_the_work_from_the_state_the_task_left() {
538        let (probe, controls) = Probe::graceful();
539        let worker = ResumableWorker::start_early("probe", probe);
540        controls.release(2);
541        controls.wait_for_steps(2).await;
542
543        let supervisor = start(worker).await;
544        controls.wait_for_handoff().await;
545        controls.release(1);
546        controls.wait_for_steps(3).await;
547
548        assert_eq!(
549            controls.journal()[2..],
550            [
551                Entry::Stopped { in_process: false },
552                Entry::Step {
553                    n: 3,
554                    in_process: true,
555                    has_dataspace: true
556                },
557            ]
558        );
559        supervisor.shutdown().await.expect("shutdown should be clean");
560    }
561
562    #[tokio::test]
563    async fn the_handoff_waits_for_a_step_in_flight_and_does_not_repeat_it() {
564        let (probe, controls) = Probe::graceful();
565        let worker = ResumableWorker::start_early("probe", probe);
566        controls.begin.add_permits(1);
567        wait_until("step 1 began", || controls.is_stepping()).await;
568
569        let supervisor = start(worker).await;
570        controls.wait_for_handoff().await;
571        controls.finish.add_permits(1);
572        controls.wait_for_steps(1).await;
573        controls.release(1);
574        controls.wait_for_steps(2).await;
575
576        assert_eq!(controls.steps(), vec![(1, false), (2, true)]);
577        supervisor.shutdown().await.expect("shutdown should be clean");
578    }
579
580    #[tokio::test]
581    async fn a_restart_resumes_the_work_and_retries_an_interrupted_step() {
582        let (probe, controls) = Probe::brutal();
583        let worker = ResumableWorker::new("probe", probe);
584        let trip = Arc::new(Notify::new());
585        let mut inner = Supervisor::new("inner")
586            .unwrap()
587            .with_restart_strategy(RestartStrategy::one_for_all());
588        inner.add_worker(worker);
589        inner.add_worker(Tripwire(Arc::clone(&trip)));
590        let supervisor = TestSupervisor::start_with("test", |supervisor| supervisor.add_worker(inner)).await;
591
592        controls.release(1);
593        controls.wait_for_steps(1).await;
594
595        // Step 2 is halted while it is in flight, when the failing sibling restarts the probe.
596        controls.begin.add_permits(1);
597        wait_until("step 2 began", || controls.is_stepping()).await;
598        trip.notify_one();
599        wait_until("the probe was restarted", || controls.stops.lock().unwrap().len() == 2).await;
600        controls.finish.add_permits(1);
601        controls.wait_for_steps(2).await;
602
603        assert_eq!(controls.steps(), vec![(1, true), (2, true)]);
604        supervisor.shutdown().await.expect("shutdown should be clean");
605    }
606
607    #[tokio::test]
608    async fn halting_the_first_instance_during_the_handoff_cancels_the_task() {
609        let (probe, controls) = Probe::brutal();
610        let worker = ResumableWorker::start_early("probe", probe);
611        let state = Arc::clone(&worker.state);
612        controls.begin.add_permits(1);
613        wait_until("step 1 began", || controls.is_stepping()).await;
614
615        let supervisor = start(worker).await;
616        controls.wait_for_handoff().await;
617        supervisor.shutdown().await.expect("a brutal halt is a clean shutdown");
618
619        wait_until("the step is cancelled", || !controls.is_stepping()).await;
620        wait_for_release(&state).await;
621        assert!(controls.steps().is_empty());
622    }
623
624    #[tokio::test]
625    async fn dropping_the_first_instance_during_the_handoff_cancels_the_task() {
626        let (probe, controls) = Probe::graceful();
627        let worker = ResumableWorker::start_early("probe", probe);
628        let state = Arc::clone(&worker.state);
629        controls.begin.add_permits(1);
630        wait_until("step 1 began", || controls.is_stepping()).await;
631
632        let (_coordinator, shutdown) = ShutdownHandle::paired();
633        let run = worker.initialize(shutdown).await.expect("initialize never fails");
634        let instance = tokio::spawn(run);
635        controls.wait_for_handoff().await;
636        instance.abort();
637
638        wait_until("the step is cancelled", || !controls.is_stepping()).await;
639        wait_for_release(&state).await;
640        assert!(controls.steps().is_empty());
641    }
642
643    #[tokio::test]
644    async fn dropping_a_worker_that_never_started_cancels_the_task() {
645        let (probe, controls) = Probe::graceful();
646        let worker = ResumableWorker::start_early("probe", probe);
647        let state = Arc::clone(&worker.state);
648        controls.begin.add_permits(1);
649        wait_until("step 1 began", || controls.is_stepping()).await;
650
651        drop(worker);
652
653        // A task that was only signalled would still wait for `finish`.
654        wait_until("the step is cancelled", || !controls.is_stepping()).await;
655        wait_for_release(&state).await;
656        assert!(controls.steps().is_empty());
657    }
658
659    #[tokio::test]
660    async fn a_panic_before_the_handoff_fails_the_first_instance_and_the_restart_resumes() {
661        let (probe, controls) = Probe::graceful();
662        let worker = ResumableWorker::start_early("probe", probe.with_knob(1, Knob::Panic));
663        controls.release(1);
664        controls.wait_for_steps(1).await;
665
666        let supervisor = start(worker).await;
667        wait_until("the probe was restarted", || restart_count(&supervisor, "probe") == 1).await;
668        controls.release(1);
669        controls.wait_for_steps(2).await;
670
671        assert_eq!(controls.steps(), vec![(1, false), (2, true)]);
672        supervisor.shutdown().await.expect("shutdown should be clean");
673    }
674
675    async fn assert_early_end_becomes_the_first_result(knob: Knob) {
676        let (probe, controls) = Probe::graceful();
677        let worker = ResumableWorker::start_early("probe", probe.with_knob(1, knob));
678        controls.release(1);
679        controls.wait_for_steps(1).await;
680
681        let supervisor = start(worker).await;
682        wait_until("the probe was restarted", || restart_count(&supervisor, "probe") == 1).await;
683        controls.release(1);
684        controls.wait_for_steps(2).await;
685
686        // The first instance ended with the early result without running the work, so only the restart called `run`.
687        assert_eq!(controls.steps(), vec![(1, false), (2, true)]);
688        assert_eq!(controls.stops.lock().unwrap().len(), 2);
689        supervisor.shutdown().await.expect("shutdown should be clean");
690    }
691
692    #[tokio::test]
693    async fn work_that_ends_before_the_handoff_ends_the_first_instance() {
694        assert_early_end_becomes_the_first_result(Knob::End).await;
695    }
696
697    #[tokio::test]
698    async fn work_that_fails_before_the_handoff_fails_the_first_instance() {
699        assert_early_end_becomes_the_first_result(Knob::Fail).await;
700    }
701
702    #[tokio::test]
703    async fn a_stop_during_the_handoff_waits_for_the_step_then_stops() {
704        let (probe, controls) = Probe::graceful();
705        let worker = ResumableWorker::start_early("probe", probe);
706        let state = Arc::clone(&worker.state);
707        controls.begin.add_permits(1);
708        wait_until("step 1 began", || controls.is_stepping()).await;
709
710        let mut supervisor = start(worker).await;
711        controls.wait_for_handoff().await;
712        supervisor.signal_shutdown();
713        controls.finish.add_permits(1);
714        supervisor.wait().await.expect("shutdown should be clean");
715
716        // The instance returned only after the task ended, so the state is already free.
717        assert!(state.try_lock().is_ok());
718        assert_eq!(
719            controls.journal(),
720            vec![
721                Entry::Step {
722                    n: 1,
723                    in_process: false,
724                    has_dataspace: false
725                },
726                Entry::Stopped { in_process: false },
727                Entry::Stopped { in_process: true },
728            ]
729        );
730    }
731
732    #[tokio::test]
733    async fn a_graceful_worker_gives_the_work_its_stop_signal() {
734        let (probe, controls) = Probe::graceful();
735        let supervisor = start(ResumableWorker::new("probe", probe)).await;
736        controls.release(1);
737        controls.wait_for_steps(1).await;
738
739        supervisor.shutdown().await.expect("shutdown should be clean");
740
741        assert_eq!(controls.journal()[1], Entry::Stopped { in_process: true });
742    }
743
744    #[tokio::test]
745    async fn the_worker_declares_the_strategy_of_its_work() {
746        let (probe, controls) = Probe::brutal();
747        let worker = ResumableWorker::start_early("probe", probe);
748        controls.begin.add_permits(1);
749        wait_until("step 1 began", || controls.is_stepping()).await;
750
751        // The task holds the state while the step is in flight.
752        assert!(matches!(worker.shutdown_strategy(), ShutdownStrategy::Brutal));
753        assert!(matches!(
754            ResumableWorker::new("probe", Probe::graceful().0).shutdown_strategy(),
755            ShutdownStrategy::Graceful(timeout) if timeout == DEFAULT_SHUTDOWN_TIMEOUT
756        ));
757
758        controls.finish.add_permits(1);
759        let supervisor = start(worker).await;
760        controls.wait_for_handoff().await;
761        controls.release(1);
762        controls.wait_for_steps(2).await;
763        supervisor.shutdown().await.expect("a brutal halt is a clean shutdown");
764
765        // Only the task saw a stop signal: the worker was halted without one.
766        assert_eq!(
767            controls
768                .journal()
769                .into_iter()
770                .filter(|entry| matches!(entry, Entry::Stopped { .. }))
771                .collect::<Vec<_>>(),
772            vec![Entry::Stopped { in_process: false }]
773        );
774    }
775
776    #[tokio::test]
777    async fn shutdown_under_a_supervisor_releases_the_state() {
778        let (probe, controls) = Probe::graceful();
779        let worker = ResumableWorker::start_early("probe", probe);
780        let state = Arc::clone(&worker.state);
781        let supervisor = start(worker).await;
782        controls.wait_for_handoff().await;
783        controls.release(1);
784        controls.wait_for_steps(1).await;
785
786        supervisor.shutdown().await.expect("shutdown should be clean");
787
788        assert!(state.try_lock().is_ok());
789    }
790
791    #[tokio::test]
792    async fn a_failed_instance_is_restarted_and_resumes() {
793        let (probe, controls) = Probe::graceful();
794        let supervisor = start(ResumableWorker::new("probe", probe.with_knob(1, Knob::Fail))).await;
795        controls.release(1);
796        wait_until("the probe was restarted", || restart_count(&supervisor, "probe") == 1).await;
797        controls.release(1);
798        controls.wait_for_steps(2).await;
799
800        assert_eq!(controls.steps(), vec![(1, true), (2, true)]);
801        supervisor.shutdown().await.expect("shutdown should be clean");
802    }
803
804    #[tokio::test]
805    async fn an_instance_that_returns_is_restarted_and_resumes() {
806        let (probe, controls) = Probe::graceful();
807        let supervisor = start(ResumableWorker::new("probe", probe.with_knob(1, Knob::End))).await;
808        controls.release(1);
809        wait_until("the probe was restarted", || restart_count(&supervisor, "probe") == 1).await;
810        controls.release(1);
811        controls.wait_for_steps(2).await;
812
813        assert_eq!(controls.steps(), vec![(1, true), (2, true)]);
814        supervisor.shutdown().await.expect("shutdown should be clean");
815    }
816}