Skip to main content

byteflow/scheduler/
supervisor.rs

1use std::collections::{HashMap, HashSet, VecDeque};
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::sync::{Arc, Condvar, Mutex};
4use std::thread::JoinHandle;
5use std::time::{Duration, Instant};
6
7use crate::bytecode::{RestartPolicy, Value};
8
9use super::error::{report_fault, SpawnError};
10use super::handle::FlowHandle;
11use super::monitor::FlowExitReason;
12use super::process::{FlowId, FlowOutcome};
13use super::runtime::RuntimeSpawner;
14use super::sync_lock;
15
16/// How many restarts OTP-style supervisors allow inside a sliding window
17/// before giving up (design notes §15). Three-in-five-seconds is the
18/// classic default: enough to absorb a flaky child, tight enough that a
19/// crash loop cannot spin the runtime forever.
20const DEFAULT_MAX_RESTARTS: u32 = 3;
21const DEFAULT_MAX_PERIOD: Duration = Duration::from_secs(5);
22
23/// A child the supervisor should start (and possibly restart).
24///
25/// `function` is an index into the runtime's chunk — the same number
26/// [`super::runtime::Runtime::spawn`] takes. Args are cloned on every
27/// restart so a child always comes back with the original call.
28///
29/// Non-empty [`Self::name`] is registered as `register_name` → an addressing
30/// Cap ([`CapRights::ADDRESSING`]) for that incarnation (swept on exit,
31/// re-bound on restart).
32#[derive(Clone, Debug)]
33pub struct ChildSpec {
34    pub name: String,
35    pub function: u32,
36    pub args: Vec<Value>,
37    pub restart: RestartPolicy,
38}
39
40impl ChildSpec {
41    pub fn new(name: impl Into<String>, function: u32) -> Self {
42        ChildSpec {
43            name: name.into(),
44            function,
45            args: Vec::new(),
46            restart: RestartPolicy::OnFailure,
47        }
48    }
49
50    pub fn args(mut self, args: Vec<Value>) -> Self {
51        self.args = args;
52        self
53    }
54
55    pub fn restart(mut self, restart: RestartPolicy) -> Self {
56        self.restart = restart;
57        self
58    }
59}
60
61/// Which siblings die (and later come back) when one child exits.
62///
63/// Sibling abort is **cooperative**: parked children are taken out of the
64/// mailbox immediately; a child mid-quantum dies at the next budget edge
65/// (same contract as [`super::runtime::Runtime::kill`]).
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum RestartStrategy {
68    /// Only the child that exited is considered for restart.
69    OneForOne,
70    /// Every sibling is shut down, then the whole set is started again
71    /// in original start order.
72    OneForAll,
73    /// Children started *after* the failed one are shut down, then that
74    /// suffix (failed + later) is started again in start order.
75    RestForOne,
76}
77
78/// Tunables for [`Supervisor::with_config`].
79#[derive(Clone, Debug)]
80pub struct SupervisorConfig {
81    /// Restarts allowed inside [`Self::max_period`]. The initial start does
82    /// not count; only respawns do. Hitting this cap sets
83    /// [`Supervisor::intensity_exceeded`] and further restarts are refused.
84    pub max_restarts: u32,
85    pub max_period: Duration,
86    pub strategy: RestartStrategy,
87}
88
89impl Default for SupervisorConfig {
90    fn default() -> Self {
91        SupervisorConfig {
92            max_restarts: DEFAULT_MAX_RESTARTS,
93            max_period: DEFAULT_MAX_PERIOD,
94            strategy: RestartStrategy::OneForOne,
95        }
96    }
97}
98
99struct ChildExit {
100    id: FlowId,
101    outcome: FlowOutcome,
102    /// Policy from the dying flow (`SetRestartPolicy` / spawn default).
103    restart: RestartPolicy,
104}
105
106struct LiveChild {
107    spec: ChildSpec,
108    /// Set when this incarnation is being torn down by a cascade so its
109    /// exit does not start another strategy wave.
110    expected_shutdown: bool,
111}
112
113struct ChildTable {
114    by_id: HashMap<FlowId, LiveChild>,
115    order: Vec<FlowId>,
116}
117
118impl ChildTable {
119    fn new() -> Self {
120        Self {
121            by_id: HashMap::new(),
122            order: Vec::new(),
123        }
124    }
125
126    fn insert(&mut self, id: FlowId, child: LiveChild) {
127        self.order.push(id);
128        self.by_id.insert(id, child);
129    }
130
131    fn remove(&mut self, id: FlowId) -> Option<LiveChild> {
132        self.order.retain(|x| *x != id);
133        self.by_id.remove(&id)
134    }
135
136    fn len(&self) -> usize {
137        self.by_id.len()
138    }
139}
140
141/// In-flight one-for-all / rest-for-one: wait for sibling kills, then respawn.
142struct Cascade {
143    waiting: HashSet<FlowId>,
144    specs: Vec<ChildSpec>,
145}
146
147struct Inner {
148    spawner: RuntimeSpawner,
149    config: SupervisorConfig,
150    events: Mutex<VecDeque<ChildExit>>,
151    cvar: Condvar,
152    children: Mutex<ChildTable>,
153    cascade: Mutex<Option<Cascade>>,
154    restart_times: Mutex<VecDeque<Instant>>,
155    intensity_exceeded: AtomicBool,
156    shutdown: AtomicBool,
157}
158
159/// Cheap, `Clone` handle the worker uses to hand a terminal outcome back
160/// without taking a lock on the supervisor's child table (the drive loop
161/// is the only writer of that table).
162#[derive(Clone)]
163pub(crate) struct SupervisorLink {
164    inner: Arc<Inner>,
165}
166
167impl SupervisorLink {
168    pub(crate) fn notify(&self, id: FlowId, outcome: FlowOutcome, restart: RestartPolicy) {
169        match sync_lock::lock(&self.inner.events, "SupervisorLink::notify") {
170            Ok(mut events) => {
171                events.push_back(ChildExit {
172                    id,
173                    outcome,
174                    restart,
175                });
176                self.inner.cvar.notify_one();
177            }
178            Err(e) => report_fault(e),
179        }
180    }
181}
182
183/// Host-side child restarter (design notes §15-16).
184///
185/// A `Supervisor` is **not** a bytecode Flow. It is a dedicated OS
186/// thread plus a table of [`ChildSpec`]s. When a supervised flow
187/// becomes [`FlowOutcome::Failed`] (or completes, under
188/// [`RestartPolicy::Always`]), the worker delivers the
189/// [`FlowOutcome`] here instead of letting the fault take anything
190/// else down. The supervisor then consults the child's
191/// [`RestartPolicy`] and, if intensity allows, respawns it under a
192/// fresh [`FlowId`] — Pids are never reused (see
193/// [`super::process::FlowId`]).
194///
195/// Constructed from a [`RuntimeSpawner`] so it does not have to own the
196/// runtime's worker `JoinHandle`s.
197pub struct Supervisor {
198    inner: Arc<Inner>,
199    thread: Option<JoinHandle<()>>,
200}
201
202impl Supervisor {
203    pub fn new(spawner: RuntimeSpawner) -> Result<Self, SpawnError> {
204        Self::with_config(spawner, SupervisorConfig::default())
205    }
206
207    /// Start the dedicated supervisor OS thread. Thread-spawn failure is
208    /// [`SpawnError::ThreadSpawnFailed`] — same category-A surface as
209    /// [`super::runtime::Runtime::new`], not a panic.
210    pub fn with_config(
211        spawner: RuntimeSpawner,
212        config: SupervisorConfig,
213    ) -> Result<Self, SpawnError> {
214        let inner = Arc::new(Inner {
215            spawner,
216            config,
217            events: Mutex::new(VecDeque::new()),
218            cvar: Condvar::new(),
219            children: Mutex::new(ChildTable::new()),
220            cascade: Mutex::new(None),
221            restart_times: Mutex::new(VecDeque::new()),
222            intensity_exceeded: AtomicBool::new(false),
223            shutdown: AtomicBool::new(false),
224        });
225        let drive_inner = inner.clone();
226        let thread = std::thread::Builder::new()
227            .name("byteflow-supervisor".into())
228            .spawn(move || drive(drive_inner))
229            .map_err(|e| SpawnError::ThreadSpawnFailed(e.to_string()))?;
230        Ok(Supervisor {
231            inner,
232            thread: Some(thread),
233        })
234    }
235
236    /// Spawn `spec` and start supervising it. The returned handle is for
237    /// this incarnation only — a restart allocates a new Pid and a new
238    /// completion channel.
239    pub fn start_child(&self, spec: ChildSpec) -> Result<FlowHandle, SpawnError> {
240        spawn_child(&self.inner, spec)
241    }
242
243    pub fn live_children(&self) -> usize {
244        match sync_lock::lock(&self.inner.children, "Supervisor::live_children") {
245            Ok(g) => g.len(),
246            Err(e) => {
247                report_fault(e);
248                0
249            }
250        }
251    }
252
253    /// `true` once more than [`SupervisorConfig::max_restarts`] respawns
254    /// landed inside the intensity window. Remaining children keep
255    /// running; we just stop bringing them back (no safe abort of a
256    /// mid-quantum flow).
257    pub fn intensity_exceeded(&self) -> bool {
258        self.inner.intensity_exceeded.load(Ordering::Acquire)
259    }
260
261    /// Stop the drive thread. Does not terminate live children — they
262    /// belong to the runtime, not to us.
263    pub fn shutdown(mut self) {
264        self.inner.shutdown.store(true, Ordering::Release);
265        self.inner.cvar.notify_all();
266        if let Some(t) = self.thread.take() {
267            let _ = t.join();
268        }
269    }
270}
271
272fn spawn_child(inner: &Arc<Inner>, spec: ChildSpec) -> Result<FlowHandle, SpawnError> {
273    let link = SupervisorLink {
274        inner: inner.clone(),
275    };
276    // Hold the table across spawn so a child that faults in its first
277    // quantum cannot notify us before its row exists (the drive loop
278    // takes this same lock in `handle_exit`, so the event waits).
279    let mut children = match sync_lock::lock(&inner.children, "spawn_child") {
280        Ok(c) => c,
281        Err(e) => {
282            report_fault(e);
283            return Err(SpawnError::VmInit("supervisor child table poisoned".into()));
284        }
285    };
286    let handle = inner
287        .spawner
288        .spawn_linked(spec.function, &spec.args, spec.restart, link)?;
289    if !spec.name.is_empty() {
290        if let Err(e) = register_child_name(inner, handle.id(), &spec.name) {
291            inner
292                .spawner
293                .request_kill(handle.id(), FlowExitReason::Supervisor);
294            return Err(e);
295        }
296    }
297    children.insert(
298        handle.id(),
299        LiveChild {
300            spec,
301            expected_shutdown: false,
302        },
303    );
304    Ok(handle)
305}
306
307fn register_child_name(inner: &Inner, id: FlowId, name: &str) -> Result<(), SpawnError> {
308    let cap = inner
309        .spawner
310        .shared
311        .caps
312        .mint(id, id, super::capability::CapRights::ADDRESSING)
313        .map_err(|e| {
314            report_fault(e);
315            SpawnError::VmInit("cap mint failed (poisoned lock)".into())
316        })?;
317    match inner
318        .spawner
319        .shared
320        .registry
321        .register(super::registry::RegistryName::from(name), cap, id)
322    {
323        Ok(Ok(())) => Ok(()),
324        Ok(Err(super::error::LifecycleError::AlreadyRegistered)) => Err(SpawnError::NameTaken {
325            name: name.to_string(),
326        }),
327        Ok(Err(e)) => Err(SpawnError::VmInit(e.to_string())),
328        Err(e) => {
329            report_fault(e);
330            Err(SpawnError::VmInit(
331                "registry register failed (poisoned lock)".into(),
332            ))
333        }
334    }
335}
336
337fn should_restart(policy: RestartPolicy, outcome: &FlowOutcome) -> bool {
338    match policy {
339        RestartPolicy::Always => true,
340        RestartPolicy::OnFailure => matches!(outcome, FlowOutcome::Failed(_)),
341        RestartPolicy::Never => false,
342    }
343}
344
345fn intensity_hit(inner: &Inner) -> bool {
346    let now = Instant::now();
347    let mut times = match sync_lock::lock(&inner.restart_times, "intensity_hit") {
348        Ok(t) => t,
349        Err(e) => {
350            report_fault(e);
351            return true;
352        }
353    };
354    times.push_back(now);
355    let window_start = match now.checked_sub(inner.config.max_period) {
356        Some(t) => t,
357        None => now,
358    };
359    loop {
360        match times.front() {
361            Some(t) if *t < window_start => {
362                times.pop_front();
363            }
364            _ => break,
365        }
366    }
367    if times.len() as u32 > inner.config.max_restarts {
368        inner.intensity_exceeded.store(true, Ordering::Release);
369        true
370    } else {
371        false
372    }
373}
374
375fn drive(inner: Arc<Inner>) {
376    loop {
377        if inner.shutdown.load(Ordering::Acquire) {
378            return;
379        }
380        let exit = {
381            let mut events = match sync_lock::lock(&inner.events, "supervisor::drive") {
382                Ok(e) => e,
383                Err(e) => {
384                    report_fault(e);
385                    return;
386                }
387            };
388            loop {
389                if inner.shutdown.load(Ordering::Acquire) {
390                    return;
391                }
392                if let Some(exit) = events.pop_front() {
393                    break exit;
394                }
395                match sync_lock::wait_timeout(
396                    &inner.cvar,
397                    events,
398                    Duration::from_millis(100),
399                    "supervisor::wait",
400                ) {
401                    Ok((guard, _)) => events = guard,
402                    Err(e) => {
403                        report_fault(e);
404                        return;
405                    }
406                }
407            }
408        };
409        handle_exit(&inner, exit);
410    }
411}
412
413fn handle_exit(inner: &Arc<Inner>, exit: ChildExit) {
414    let (spec, expected, failed_idx, later) = {
415        let mut children = match sync_lock::lock(&inner.children, "handle_exit") {
416            Ok(c) => c,
417            Err(e) => {
418                report_fault(e);
419                return;
420            }
421        };
422        let failed_idx = children.order.iter().position(|id| *id == exit.id);
423        let live = match children.remove(exit.id) {
424            Some(live) => live,
425            None => return,
426        };
427        let later = match (inner.config.strategy, failed_idx) {
428            (RestartStrategy::OneForAll, _) => children.order.clone(),
429            (RestartStrategy::RestForOne, Some(i)) => children.order[i..].to_vec(),
430            _ => Vec::new(),
431        };
432        (live.spec, live.expected_shutdown, failed_idx, later)
433    };
434
435    if expected {
436        on_cascade_progress(inner, exit.id);
437        return;
438    }
439
440    if !should_restart(exit.restart, &exit.outcome) {
441        return;
442    }
443    if inner.intensity_exceeded.load(Ordering::Acquire) || intensity_hit(inner) {
444        return;
445    }
446
447    match inner.config.strategy {
448        RestartStrategy::OneForOne => {
449            let _ = spawn_child(inner, spec);
450        }
451        RestartStrategy::OneForAll | RestartStrategy::RestForOne => {
452            start_cascade(inner, spec, failed_idx, later);
453        }
454    }
455}
456
457fn start_cascade(
458    inner: &Arc<Inner>,
459    failed: ChildSpec,
460    failed_idx: Option<usize>,
461    later: Vec<FlowId>,
462) {
463    let specs = {
464        let mut children = match sync_lock::lock(&inner.children, "start_cascade") {
465            Ok(c) => c,
466            Err(e) => {
467                report_fault(e);
468                return;
469            }
470        };
471        let later_specs: Vec<ChildSpec> = later
472            .iter()
473            .filter_map(|id| {
474                children.by_id.get_mut(id).map(|c| {
475                    c.expected_shutdown = true;
476                    c.spec.clone()
477                })
478            })
479            .collect();
480        match inner.config.strategy {
481            RestartStrategy::OneForAll => {
482                let mut specs = later_specs;
483                specs.insert(failed_idx.unwrap_or(specs.len()), failed);
484                specs
485            }
486            RestartStrategy::RestForOne => {
487                let mut specs = vec![failed];
488                specs.extend(later_specs);
489                specs
490            }
491            RestartStrategy::OneForOne => vec![failed],
492        }
493    };
494
495    let waiting: HashSet<FlowId> = later.iter().copied().collect();
496    match sync_lock::lock(&inner.cascade, "start_cascade.cascade") {
497        Ok(mut slot) => {
498            *slot = Some(Cascade {
499                waiting: waiting.clone(),
500                specs,
501            })
502        }
503        Err(e) => {
504            report_fault(e);
505            return;
506        }
507    }
508
509    for id in &later {
510        inner.spawner.request_kill(*id, FlowExitReason::Supervisor);
511    }
512
513    let remaining = match sync_lock::lock(&inner.cascade, "start_cascade.prune") {
514        Ok(mut slot) => {
515            if let Some(c) = slot.as_mut() {
516                c.waiting
517                    .retain(|id| matches!(inner.spawner.shared.directory.lookup(*id), Ok(Some(_))));
518            }
519            slot.as_ref().map(|c| c.waiting.is_empty()).unwrap_or(true)
520        }
521        Err(e) => {
522            report_fault(e);
523            return;
524        }
525    };
526    if remaining || waiting.is_empty() {
527        finish_cascade(inner);
528    }
529}
530
531fn on_cascade_progress(inner: &Arc<Inner>, id: FlowId) {
532    let ready = match sync_lock::lock(&inner.cascade, "on_cascade_progress") {
533        Ok(mut slot) => {
534            let Some(c) = slot.as_mut() else {
535                return;
536            };
537            c.waiting.remove(&id);
538            c.waiting.is_empty()
539        }
540        Err(e) => {
541            report_fault(e);
542            return;
543        }
544    };
545    if ready {
546        finish_cascade(inner);
547    }
548}
549
550fn finish_cascade(inner: &Arc<Inner>) {
551    let specs = match sync_lock::lock(&inner.cascade, "finish_cascade") {
552        Ok(mut slot) => match slot.take() {
553            Some(c) => c.specs,
554            None => return,
555        },
556        Err(e) => {
557            report_fault(e);
558            return;
559        }
560    };
561    for spec in specs {
562        if inner.intensity_exceeded.load(Ordering::Acquire) {
563            return;
564        }
565        let _ = spawn_child(inner, spec);
566    }
567}
568
569#[cfg(test)]
570mod tests {
571    use super::*;
572    use std::time::{Duration, Instant};
573
574    use crate::bytecode::{builder::ChunkBuilder, Chunk, Value};
575    use crate::scheduler::runtime::{Runtime, RuntimeConfig};
576
577    fn trap_chunk() -> Chunk {
578        let mut b = ChunkBuilder::new("trap");
579        b.begin_function("boom", 0, 1);
580        b.emit_trap(1);
581        b.finish()
582    }
583
584    /// Sets `RestartPolicy::Never` then traps — must not be restarted.
585    fn never_then_trap_chunk() -> Chunk {
586        let mut b = ChunkBuilder::new("never-trap");
587        b.begin_function("boom", 0, 1);
588        b.emit_set_restart_policy(RestartPolicy::Never.as_u8());
589        b.emit_trap(1);
590        b.finish()
591    }
592
593    fn ok_chunk() -> Chunk {
594        let mut b = ChunkBuilder::new("ok");
595        b.begin_function("main", 0, 1);
596        b.emit_load_imm(0, 7);
597        b.emit_return(0);
598        b.finish()
599    }
600
601    fn tiny_runtime(chunk: Chunk) -> Result<Runtime, crate::scheduler::SpawnError> {
602        Runtime::with_config(
603            chunk,
604            RuntimeConfig {
605                workers: 1,
606                quantum: 1_000,
607                mailbox: super::super::mailbox::MailboxConfig::DEFAULT,
608                ..Default::default()
609            },
610        )
611    }
612
613    fn wait_until(mut pred: impl FnMut() -> bool) {
614        let start = Instant::now();
615        while !pred() {
616            assert!(
617                start.elapsed() < Duration::from_secs(2),
618                "supervisor test timed out"
619            );
620            std::thread::sleep(Duration::from_millis(5));
621        }
622    }
623
624    #[test]
625    fn on_failure_does_not_restart_a_clean_exit() -> Result<(), Box<dyn std::error::Error>> {
626        let rt = tiny_runtime(ok_chunk())?;
627        let sup = Supervisor::new(rt.spawner())?;
628        let outcome = sup
629            .start_child(ChildSpec::new("main", 0).restart(RestartPolicy::OnFailure))?
630            .join();
631        wait_until(|| sup.live_children() == 0);
632        let spawned = rt.metrics().processes_spawned;
633        sup.shutdown();
634        rt.shutdown();
635        assert!(matches!(outcome, FlowOutcome::Completed(_)));
636        assert_eq!(spawned, 1);
637        Ok(())
638    }
639
640    #[test]
641    fn on_failure_restarts_until_intensity() -> Result<(), Box<dyn std::error::Error>> {
642        let rt = tiny_runtime(trap_chunk())?;
643        let sup = Supervisor::with_config(
644            rt.spawner(),
645            SupervisorConfig {
646                max_restarts: 2,
647                max_period: Duration::from_secs(5),
648                strategy: RestartStrategy::OneForOne,
649            },
650        )?;
651        let _first =
652            sup.start_child(ChildSpec::new("boom", 0).restart(RestartPolicy::OnFailure))?;
653        wait_until(|| sup.intensity_exceeded() && rt.metrics().processes_failed >= 3);
654        let spawned = rt.metrics().processes_spawned;
655        let failed = rt.metrics().processes_failed;
656        sup.shutdown();
657        rt.shutdown();
658        // initial start + 2 restarts, then intensity refuses the 3rd restart
659        assert_eq!(spawned, 3);
660        assert_eq!(failed, 3);
661        Ok(())
662    }
663
664    #[test]
665    fn set_restart_policy_never_skips_restart() -> Result<(), Box<dyn std::error::Error>> {
666        let rt = tiny_runtime(never_then_trap_chunk())?;
667        let sup = Supervisor::with_config(
668            rt.spawner(),
669            SupervisorConfig {
670                max_restarts: 5,
671                max_period: Duration::from_secs(5),
672                strategy: RestartStrategy::OneForOne,
673            },
674        )?;
675        // ChildSpec says OnFailure, but bytecode SetRestartPolicy(Never)
676        // must win at exit.
677        let _ = sup.start_child(ChildSpec::new("boom", 0).restart(RestartPolicy::OnFailure))?;
678        wait_until(|| rt.metrics().processes_failed >= 1 && sup.live_children() == 0);
679        let spawned = rt.metrics().processes_spawned;
680        let failed = rt.metrics().processes_failed;
681        std::thread::sleep(Duration::from_millis(50));
682        let spawned_after = rt.metrics().processes_spawned;
683        sup.shutdown();
684        rt.shutdown();
685        assert_eq!(failed, 1);
686        assert_eq!(spawned, 1);
687        assert_eq!(spawned_after, 1, "Never must not restart");
688        Ok(())
689    }
690
691    #[test]
692    fn always_restarts_a_clean_exit_until_intensity() -> Result<(), Box<dyn std::error::Error>> {
693        let rt = tiny_runtime(ok_chunk())?;
694        let sup = Supervisor::with_config(
695            rt.spawner(),
696            SupervisorConfig {
697                max_restarts: 2,
698                max_period: Duration::from_secs(5),
699                strategy: RestartStrategy::OneForOne,
700            },
701        )?;
702        let _ = sup.start_child(ChildSpec::new("main", 0).restart(RestartPolicy::Always))?;
703        wait_until(|| sup.intensity_exceeded() && rt.metrics().processes_completed >= 3);
704        let spawned = rt.metrics().processes_spawned;
705        sup.shutdown();
706        rt.shutdown();
707        assert_eq!(spawned, 3);
708        Ok(())
709    }
710
711    fn wait_and_trap_chunk() -> Chunk {
712        let mut b = ChunkBuilder::new("sup-mix");
713        b.begin_function("wait", 0, 1);
714        b.emit_receive(0);
715        b.emit_return(0);
716        b.begin_function("boom", 0, 1);
717        b.emit_trap(1);
718        b.begin_function("delayed", 0, 1);
719        b.emit_load_imm(0, 80);
720        b.emit_sleep(0);
721        b.emit_trap(1);
722        b.finish()
723    }
724
725    #[test]
726    fn one_for_one_does_not_kill_sibling() -> Result<(), Box<dyn std::error::Error>> {
727        let rt = tiny_runtime(wait_and_trap_chunk())?;
728        let sup = Supervisor::new(rt.spawner())?;
729        let parked = sup.start_child(ChildSpec::new("wait", 0))?;
730        let _boom = sup.start_child(ChildSpec::new("boom", 1).restart(RestartPolicy::OnFailure))?;
731        wait_until(|| rt.metrics().processes_failed >= 1);
732        assert!(
733            parked.try_join().is_none(),
734            "one-for-one must leave the parked sibling"
735        );
736        sup.shutdown();
737        rt.shutdown();
738        Ok(())
739    }
740
741    #[test]
742    fn one_for_all_kills_parked_sibling() -> Result<(), Box<dyn std::error::Error>> {
743        let rt = tiny_runtime(wait_and_trap_chunk())?;
744        let sup = Supervisor::with_config(
745            rt.spawner(),
746            SupervisorConfig {
747                max_restarts: 8,
748                max_period: Duration::from_secs(5),
749                strategy: RestartStrategy::OneForAll,
750            },
751        )?;
752        let parked = sup.start_child(ChildSpec::new("wait", 0))?;
753        let _boom = sup.start_child(ChildSpec::new("boom", 1).restart(RestartPolicy::OnFailure))?;
754        wait_until(|| parked.try_join().is_some());
755        let outcome = parked.join();
756        sup.shutdown();
757        rt.shutdown();
758        assert!(
759            matches!(outcome, FlowOutcome::Failed(_)),
760            "one-for-all must kill the parked sibling, got {outcome:?}"
761        );
762        Ok(())
763    }
764
765    #[test]
766    fn rest_for_one_kills_only_later_children() -> Result<(), Box<dyn std::error::Error>> {
767        let rt = tiny_runtime(wait_and_trap_chunk())?;
768        let sup = Supervisor::with_config(
769            rt.spawner(),
770            SupervisorConfig {
771                max_restarts: 8,
772                max_period: Duration::from_secs(5),
773                strategy: RestartStrategy::RestForOne,
774            },
775        )?;
776        let earlier = sup.start_child(ChildSpec::new("keep", 0))?;
777        let _boom =
778            sup.start_child(ChildSpec::new("delayed", 2).restart(RestartPolicy::OnFailure))?;
779        let later = sup.start_child(ChildSpec::new("tail", 0))?;
780        wait_until(|| later.try_join().is_some());
781        assert!(
782            earlier.try_join().is_none(),
783            "rest-for-one must not kill children started before the failure"
784        );
785        let later_outcome = later.join();
786        sup.shutdown();
787        rt.shutdown();
788        assert!(
789            matches!(later_outcome, FlowOutcome::Failed(_)),
790            "rest-for-one must kill children started after the failure, got {later_outcome:?}"
791        );
792        Ok(())
793    }
794
795    #[test]
796    fn child_name_registers_and_rejects_duplicate() -> Result<(), Box<dyn std::error::Error>> {
797        let rt = tiny_runtime(wait_and_trap_chunk())?;
798        let sup = Supervisor::new(rt.spawner())?;
799        let _parked = sup.start_child(ChildSpec::new("svc", 0))?;
800        wait_until(|| matches!(rt.whereis("svc"), Ok(Some(_))));
801        assert!(rt.whereis("svc")?.is_some());
802        let dup = sup.start_child(ChildSpec::new("svc", 1));
803        sup.shutdown();
804        rt.shutdown();
805        match dup {
806            Err(SpawnError::NameTaken { name }) if name == "svc" => {}
807            Ok(_) => return Err("expected NameTaken, got Ok(handle)".into()),
808            Err(e) => return Err(format!("expected NameTaken, got Err({e})").into()),
809        }
810        Ok(())
811    }
812
813    #[test]
814    fn policy_table() {
815        let ok = FlowOutcome::Completed(Value::Unit);
816        let fail = FlowOutcome::Failed("boom".into());
817        assert!(should_restart(RestartPolicy::Always, &ok));
818        assert!(should_restart(RestartPolicy::Always, &fail));
819        assert!(!should_restart(RestartPolicy::OnFailure, &ok));
820        assert!(should_restart(RestartPolicy::OnFailure, &fail));
821        assert!(!should_restart(RestartPolicy::Never, &ok));
822        assert!(!should_restart(RestartPolicy::Never, &fail));
823    }
824}