Skip to main content

byteflow/scheduler/
supervisor.rs

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