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    /// Spawn another child on the same supervisor (bytecode `StartChild`).
204    pub(crate) fn start_child(
205        &self,
206        spec: ChildSpec,
207    ) -> Result<FlowHandle, SpawnError> {
208        spawn_child(&self.inner, spec)
209    }
210}
211
212/// Host-side child restarter (design notes §15-16).
213///
214/// A `Supervisor` is **not** a bytecode Flow. It is a dedicated OS
215/// thread plus a table of [`ChildSpec`]s. When a supervised flow
216/// becomes [`FlowOutcome::Failed`] (or completes, under
217/// [`RestartPolicy::Always`]), the worker delivers the
218/// [`FlowOutcome`] here instead of letting the fault take anything
219/// else down. The supervisor then consults the child's
220/// [`RestartPolicy`] and, if intensity allows, respawns it under a
221/// fresh [`FlowId`] — Pids are never reused (see
222/// [`super::process::FlowId`]).
223///
224/// Constructed from a [`RuntimeSpawner`] so it does not have to own the
225/// runtime's worker `JoinHandle`s.
226pub struct Supervisor {
227    inner: Arc<Inner>,
228    thread: Option<JoinHandle<()>>,
229}
230
231impl Supervisor {
232    pub fn new(spawner: RuntimeSpawner) -> Result<Self, SpawnError> {
233        Self::with_config(spawner, SupervisorConfig::default())
234    }
235
236    /// Start the dedicated supervisor OS thread. Thread-spawn failure is
237    /// [`SpawnError::ThreadSpawnFailed`] — same category-A surface as
238    /// [`super::runtime::Runtime::new`], not a panic.
239    pub fn with_config(
240        spawner: RuntimeSpawner,
241        config: SupervisorConfig,
242    ) -> Result<Self, SpawnError> {
243        let inner = Arc::new(Inner {
244            spawner,
245            config,
246            events: Mutex::new(VecDeque::new()),
247            cvar: Condvar::new(),
248            children: Mutex::new(ChildTable::new()),
249            cascade: Mutex::new(None),
250            restart_times: Mutex::new(VecDeque::new()),
251            intensity_exceeded: AtomicBool::new(false),
252            shutdown: AtomicBool::new(false),
253            #[cfg(test)]
254            fail_next_spawns: AtomicU32::new(0),
255            #[cfg(test)]
256            respawn_fail_count: AtomicU64::new(0),
257        });
258        let drive_inner = inner.clone();
259        let thread = std::thread::Builder::new()
260            .name("byteflow-supervisor".into())
261            .spawn(move || drive(drive_inner))
262            .map_err(|e| SpawnError::ThreadSpawnFailed(e.to_string()))?;
263        Ok(Supervisor {
264            inner,
265            thread: Some(thread),
266        })
267    }
268
269    /// Spawn `spec` and start supervising it. The returned handle is for
270    /// this incarnation only — a restart allocates a new Pid and a new
271    /// completion channel.
272    pub fn start_child(&self, spec: ChildSpec) -> Result<FlowHandle, SpawnError> {
273        spawn_child(&self.inner, spec)
274    }
275
276    pub fn live_children(&self) -> usize {
277        match sync_lock::lock(&self.inner.children, "Supervisor::live_children") {
278            Ok(g) => g.len(),
279            Err(e) => {
280                report_fault(e);
281                0
282            }
283        }
284    }
285
286    /// `true` once more than [`SupervisorConfig::max_restarts`] **waves**
287    /// landed inside the intensity window. Remaining children keep
288    /// running; we just stop bringing them back (no safe abort of a
289    /// mid-quantum flow).
290    pub fn intensity_exceeded(&self) -> bool {
291        self.inner.intensity_exceeded.load(Ordering::Acquire)
292    }
293
294    /// Stop the drive thread. Does not terminate live children — they
295    /// belong to the runtime, not to us.
296    pub fn shutdown(mut self) {
297        self.inner.shutdown.store(true, Ordering::Release);
298        self.inner.cvar.notify_all();
299        if let Some(t) = self.thread.take() {
300            let _ = t.join();
301        }
302    }
303
304    #[cfg(test)]
305    fn fail_next_spawns(&self, n: u32) {
306        self.inner.fail_next_spawns.store(n, Ordering::SeqCst);
307    }
308
309    #[cfg(test)]
310    fn respawn_fail_count(&self) -> u64 {
311        self.inner.respawn_fail_count.load(Ordering::Relaxed)
312    }
313}
314
315fn spawn_child(inner: &Arc<Inner>, spec: ChildSpec) -> Result<FlowHandle, SpawnError> {
316    #[cfg(test)]
317    if inner
318        .fail_next_spawns
319        .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
320        .is_ok()
321    {
322        return Err(SpawnError::VmInit("test: forced spawn failure".into()));
323    }
324
325    let link = SupervisorLink {
326        inner: inner.clone(),
327    };
328    // Hold the table across spawn so a child that faults in its first
329    // quantum cannot notify us before its row exists (the drive loop
330    // takes this same lock in `handle_exit`, so the event waits).
331    let mut children = match sync_lock::lock(&inner.children, "spawn_child") {
332        Ok(c) => c,
333        Err(e) => {
334            report_fault(e);
335            return Err(SpawnError::VmInit("supervisor child table poisoned".into()));
336        }
337    };
338    let handle = inner
339        .spawner
340        .spawn_linked(spec.function, &spec.args, spec.restart, link)?;
341    let id = handle.id();
342    // Insert *before* name registration so a failed register still leaves a
343    // row for the kill exit (expected_shutdown → no restart wave).
344    children.insert(
345        id,
346        LiveChild {
347            spec: spec.clone(),
348            expected_shutdown: false,
349        },
350    );
351    if !spec.name.is_empty() {
352        if let Err(e) = register_child_name(inner, id, &spec.name) {
353            if let Some(live) = children.by_id.get_mut(&id) {
354                live.expected_shutdown = true;
355            }
356            inner
357                .spawner
358                .request_kill(id, FlowExitReason::Supervisor);
359            return Err(e);
360        }
361    }
362    Ok(handle)
363}
364
365fn note_respawn_failed(inner: &Inner, err: &SpawnError) {
366    #[cfg(test)]
367    {
368        inner.respawn_fail_count.fetch_add(1, Ordering::Relaxed);
369    }
370    #[cfg(not(test))]
371    {
372        let _ = inner;
373    }
374    eprintln!("byteflow: supervisor respawn failed: {err} — child slot abandoned");
375}
376
377fn respawn_child(inner: &Arc<Inner>, spec: ChildSpec) {
378    if let Err(e) = spawn_child(inner, spec) {
379        note_respawn_failed(inner, &e);
380    }
381}
382
383fn register_child_name(inner: &Inner, id: FlowId, name: &str) -> Result<(), SpawnError> {
384    let cap = inner
385        .spawner
386        .shared
387        .caps
388        .mint(id, id, super::capability::CapRights::ADDRESSING)
389        .map_err(|e| {
390            report_fault(e);
391            SpawnError::VmInit("cap mint failed (poisoned lock)".into())
392        })?;
393    match inner
394        .spawner
395        .shared
396        .registry
397        .register(super::registry::RegistryName::from(name), cap, id)
398    {
399        Ok(Ok(())) => Ok(()),
400        Ok(Err(super::error::LifecycleError::AlreadyRegistered)) => Err(SpawnError::NameTaken {
401            name: name.to_string(),
402        }),
403        Ok(Err(e)) => Err(SpawnError::VmInit(e.to_string())),
404        Err(e) => {
405            report_fault(e);
406            Err(SpawnError::VmInit(
407                "registry register failed (poisoned lock)".into(),
408            ))
409        }
410    }
411}
412
413fn should_restart(policy: RestartPolicy, outcome: &FlowOutcome) -> bool {
414    match policy {
415        RestartPolicy::Always => true,
416        RestartPolicy::OnFailure => matches!(outcome, FlowOutcome::Failed(_)),
417        RestartPolicy::Never => false,
418    }
419}
420
421fn intensity_hit(inner: &Inner) -> bool {
422    let now = Instant::now();
423    let mut times = match sync_lock::lock(&inner.restart_times, "intensity_hit") {
424        Ok(t) => t,
425        Err(e) => {
426            report_fault(e);
427            return true;
428        }
429    };
430    times.push_back(now);
431    let window_start = match now.checked_sub(inner.config.max_period) {
432        Some(t) => t,
433        None => now,
434    };
435    loop {
436        match times.front() {
437            Some(t) if *t < window_start => {
438                times.pop_front();
439            }
440            _ => break,
441        }
442    }
443    if times.len() as u32 > inner.config.max_restarts {
444        inner.intensity_exceeded.store(true, Ordering::Release);
445        true
446    } else {
447        false
448    }
449}
450
451fn drive(inner: Arc<Inner>) {
452    loop {
453        if inner.shutdown.load(Ordering::Acquire) {
454            return;
455        }
456        let exit = {
457            let mut events = match sync_lock::lock(&inner.events, "supervisor::drive") {
458                Ok(e) => e,
459                Err(e) => {
460                    report_fault(e);
461                    return;
462                }
463            };
464            loop {
465                if inner.shutdown.load(Ordering::Acquire) {
466                    return;
467                }
468                if let Some(exit) = events.pop_front() {
469                    break exit;
470                }
471                match sync_lock::wait(
472                    &inner.cvar,
473                    events,
474                    "supervisor::wait",
475                ) {
476                    Ok(guard) => events = guard,
477                    Err(e) => {
478                        report_fault(e);
479                        return;
480                    }
481                }
482            }
483        };
484        handle_exit(&inner, exit);
485    }
486}
487
488fn handle_exit(inner: &Arc<Inner>, exit: ChildExit) {
489    let (spec, expected, failed_idx, later) = {
490        let mut children = match sync_lock::lock(&inner.children, "handle_exit") {
491            Ok(c) => c,
492            Err(e) => {
493                report_fault(e);
494                return;
495            }
496        };
497        let failed_idx = children.order.iter().position(|id| *id == exit.id);
498        let live = match children.remove(exit.id) {
499            Some(live) => live,
500            None => return,
501        };
502        let later = match (inner.config.strategy, failed_idx) {
503            (RestartStrategy::OneForAll, _) => children.order.clone(),
504            (RestartStrategy::RestForOne, Some(i)) => children.order[i..].to_vec(),
505            _ => Vec::new(),
506        };
507        (live.spec, live.expected_shutdown, failed_idx, later)
508    };
509
510    if expected {
511        on_cascade_progress(inner, exit.id);
512        return;
513    }
514
515    if !should_restart(exit.restart, &exit.outcome) {
516        return;
517    }
518    if inner.intensity_exceeded.load(Ordering::Acquire) || intensity_hit(inner) {
519        return;
520    }
521
522    match inner.config.strategy {
523        RestartStrategy::OneForOne => {
524            respawn_child(inner, spec);
525        }
526        RestartStrategy::OneForAll | RestartStrategy::RestForOne => {
527            let Some(failed_idx) = failed_idx else {
528                // Row was in by_id but missing from order — refuse to guess
529                // a start position (OneForAll order is part of the contract).
530                eprintln!(
531                    "byteflow: supervisor cascade abort — exit {} missing from child order",
532                    exit.id
533                );
534                return;
535            };
536            start_cascade(inner, spec, failed_idx, later);
537        }
538    }
539}
540
541fn start_cascade(inner: &Arc<Inner>, failed: ChildSpec, failed_idx: usize, later: Vec<FlowId>) {
542    let specs = {
543        let mut children = match sync_lock::lock(&inner.children, "start_cascade") {
544            Ok(c) => c,
545            Err(e) => {
546                report_fault(e);
547                return;
548            }
549        };
550        let later_specs: Vec<ChildSpec> = later
551            .iter()
552            .filter_map(|id| {
553                children.by_id.get_mut(id).map(|c| {
554                    c.expected_shutdown = true;
555                    c.spec.clone()
556                })
557            })
558            .collect();
559        match inner.config.strategy {
560            RestartStrategy::OneForAll => {
561                let mut specs = later_specs;
562                if failed_idx > specs.len() {
563                    eprintln!(
564                        "byteflow: supervisor OneForAll abort — failed_idx {failed_idx} > {}",
565                        specs.len()
566                    );
567                    return;
568                }
569                specs.insert(failed_idx, failed);
570                specs
571            }
572            RestartStrategy::RestForOne => {
573                let mut specs = vec![failed];
574                specs.extend(later_specs);
575                specs
576            }
577            RestartStrategy::OneForOne => vec![failed],
578        }
579    };
580
581    let waiting: HashSet<FlowId> = later.iter().copied().collect();
582    match sync_lock::lock(&inner.cascade, "start_cascade.cascade") {
583        Ok(mut slot) => {
584            *slot = Some(Cascade {
585                waiting: waiting.clone(),
586                specs,
587            })
588        }
589        Err(e) => {
590            report_fault(e);
591            return;
592        }
593    }
594
595    for id in &later {
596        inner.spawner.request_kill(*id, FlowExitReason::Supervisor);
597    }
598
599    let remaining = match sync_lock::lock(&inner.cascade, "start_cascade.prune") {
600        Ok(mut slot) => {
601            if let Some(c) = slot.as_mut() {
602                c.waiting
603                    .retain(|id| matches!(inner.spawner.shared.directory.lookup(*id), Ok(Some(_))));
604            }
605            slot.as_ref().map(|c| c.waiting.is_empty()).unwrap_or(true)
606        }
607        Err(e) => {
608            report_fault(e);
609            return;
610        }
611    };
612    if remaining || waiting.is_empty() {
613        finish_cascade(inner);
614    }
615}
616
617fn on_cascade_progress(inner: &Arc<Inner>, id: FlowId) {
618    let ready = match sync_lock::lock(&inner.cascade, "on_cascade_progress") {
619        Ok(mut slot) => {
620            let Some(c) = slot.as_mut() else {
621                return;
622            };
623            c.waiting.remove(&id);
624            c.waiting.is_empty()
625        }
626        Err(e) => {
627            report_fault(e);
628            return;
629        }
630    };
631    if ready {
632        finish_cascade(inner);
633    }
634}
635
636fn finish_cascade(inner: &Arc<Inner>) {
637    let specs = match sync_lock::lock(&inner.cascade, "finish_cascade") {
638        Ok(mut slot) => match slot.take() {
639            Some(c) => c.specs,
640            None => return,
641        },
642        Err(e) => {
643            report_fault(e);
644            return;
645        }
646    };
647    for spec in specs {
648        if inner.intensity_exceeded.load(Ordering::Acquire) {
649            return;
650        }
651        respawn_child(inner, spec);
652    }
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658    use std::time::{Duration, Instant};
659
660    use crate::bytecode::{builder::ChunkBuilder, Chunk, Value};
661    use crate::scheduler::runtime::{Runtime, RuntimeConfig};
662
663    fn trap_chunk() -> Chunk {
664        let mut b = ChunkBuilder::new("trap");
665        b.begin_function("boom", 0, 1);
666        b.emit_trap(1);
667        b.finish()
668    }
669
670    /// Sets `RestartPolicy::Never` then traps — must not be restarted.
671    fn never_then_trap_chunk() -> Chunk {
672        let mut b = ChunkBuilder::new("never-trap");
673        b.begin_function("boom", 0, 1);
674        b.emit_set_restart_policy(RestartPolicy::Never.as_u8());
675        b.emit_trap(1);
676        b.finish()
677    }
678
679    fn ok_chunk() -> Chunk {
680        let mut b = ChunkBuilder::new("ok");
681        b.begin_function("main", 0, 1);
682        b.emit_load_imm(0, 7);
683        b.emit_return(0);
684        b.finish()
685    }
686
687    fn tiny_runtime(chunk: Chunk) -> Result<Runtime, crate::scheduler::SpawnError> {
688        Runtime::with_config(
689            chunk,
690            RuntimeConfig {
691                workers: 1,
692                quantum: 1_000,
693                mailbox: super::super::mailbox::MailboxConfig::DEFAULT,
694                ..Default::default()
695            },
696        )
697    }
698
699    fn wait_until(mut pred: impl FnMut() -> bool) {
700        let start = Instant::now();
701        while !pred() {
702            assert!(
703                start.elapsed() < Duration::from_secs(2),
704                "supervisor test timed out"
705            );
706            std::thread::sleep(Duration::from_millis(5));
707        }
708    }
709
710    #[test]
711    fn on_failure_does_not_restart_a_clean_exit() -> Result<(), Box<dyn std::error::Error>> {
712        let rt = tiny_runtime(ok_chunk())?;
713        let sup = Supervisor::new(rt.spawner())?;
714        let outcome = sup
715            .start_child(ChildSpec::new("main", 0).restart(RestartPolicy::OnFailure))?
716            .join();
717        wait_until(|| sup.live_children() == 0);
718        let spawned = rt.metrics().processes_spawned;
719        sup.shutdown();
720        rt.shutdown();
721        assert!(matches!(outcome, FlowOutcome::Completed(_)));
722        assert_eq!(spawned, 1);
723        Ok(())
724    }
725
726    #[test]
727    fn on_failure_restarts_until_intensity() -> Result<(), Box<dyn std::error::Error>> {
728        let rt = tiny_runtime(trap_chunk())?;
729        let sup = Supervisor::with_config(
730            rt.spawner(),
731            SupervisorConfig {
732                max_restarts: 2,
733                max_period: Duration::from_secs(5),
734                strategy: RestartStrategy::OneForOne,
735            },
736        )?;
737        let _first =
738            sup.start_child(ChildSpec::new("boom", 0).restart(RestartPolicy::OnFailure))?;
739        wait_until(|| sup.intensity_exceeded() && rt.metrics().processes_failed >= 3);
740        let spawned = rt.metrics().processes_spawned;
741        let failed = rt.metrics().processes_failed;
742        sup.shutdown();
743        rt.shutdown();
744        // initial start + 2 restarts, then intensity refuses the 3rd restart
745        assert_eq!(spawned, 3);
746        assert_eq!(failed, 3);
747        Ok(())
748    }
749
750    #[test]
751    fn set_restart_policy_never_skips_restart() -> Result<(), Box<dyn std::error::Error>> {
752        let rt = tiny_runtime(never_then_trap_chunk())?;
753        let sup = Supervisor::with_config(
754            rt.spawner(),
755            SupervisorConfig {
756                max_restarts: 5,
757                max_period: Duration::from_secs(5),
758                strategy: RestartStrategy::OneForOne,
759            },
760        )?;
761        // ChildSpec says OnFailure, but bytecode SetRestartPolicy(Never)
762        // must win at exit.
763        let _ = sup.start_child(ChildSpec::new("boom", 0).restart(RestartPolicy::OnFailure))?;
764        wait_until(|| rt.metrics().processes_failed >= 1 && sup.live_children() == 0);
765        let spawned = rt.metrics().processes_spawned;
766        let failed = rt.metrics().processes_failed;
767        std::thread::sleep(Duration::from_millis(50));
768        let spawned_after = rt.metrics().processes_spawned;
769        sup.shutdown();
770        rt.shutdown();
771        assert_eq!(failed, 1);
772        assert_eq!(spawned, 1);
773        assert_eq!(spawned_after, 1, "Never must not restart");
774        Ok(())
775    }
776
777    #[test]
778    fn always_restarts_a_clean_exit_until_intensity() -> Result<(), Box<dyn std::error::Error>> {
779        let rt = tiny_runtime(ok_chunk())?;
780        let sup = Supervisor::with_config(
781            rt.spawner(),
782            SupervisorConfig {
783                max_restarts: 2,
784                max_period: Duration::from_secs(5),
785                strategy: RestartStrategy::OneForOne,
786            },
787        )?;
788        let _ = sup.start_child(ChildSpec::new("main", 0).restart(RestartPolicy::Always))?;
789        wait_until(|| sup.intensity_exceeded() && rt.metrics().processes_completed >= 3);
790        let spawned = rt.metrics().processes_spawned;
791        sup.shutdown();
792        rt.shutdown();
793        assert_eq!(spawned, 3);
794        Ok(())
795    }
796
797    fn wait_and_trap_chunk() -> Chunk {
798        let mut b = ChunkBuilder::new("sup-mix");
799        b.begin_function("wait", 0, 1);
800        b.emit_receive(0);
801        b.emit_return(0);
802        b.begin_function("boom", 0, 1);
803        b.emit_trap(1);
804        b.begin_function("delayed", 0, 1);
805        b.emit_load_imm(0, 80);
806        b.emit_sleep(0);
807        b.emit_trap(1);
808        b.finish()
809    }
810
811    #[test]
812    fn one_for_one_does_not_kill_sibling() -> Result<(), Box<dyn std::error::Error>> {
813        let rt = tiny_runtime(wait_and_trap_chunk())?;
814        let sup = Supervisor::new(rt.spawner())?;
815        let parked = sup.start_child(ChildSpec::new("wait", 0))?;
816        let _boom = sup.start_child(ChildSpec::new("boom", 1).restart(RestartPolicy::OnFailure))?;
817        wait_until(|| rt.metrics().processes_failed >= 1);
818        assert!(
819            parked.try_join().is_none(),
820            "one-for-one must leave the parked sibling"
821        );
822        sup.shutdown();
823        rt.shutdown();
824        Ok(())
825    }
826
827    #[test]
828    fn one_for_all_kills_parked_sibling() -> Result<(), Box<dyn std::error::Error>> {
829        let rt = tiny_runtime(wait_and_trap_chunk())?;
830        let sup = Supervisor::with_config(
831            rt.spawner(),
832            SupervisorConfig {
833                max_restarts: 8,
834                max_period: Duration::from_secs(5),
835                strategy: RestartStrategy::OneForAll,
836            },
837        )?;
838        let parked = sup.start_child(ChildSpec::new("wait", 0))?;
839        let _boom = sup.start_child(ChildSpec::new("boom", 1).restart(RestartPolicy::OnFailure))?;
840        wait_until(|| parked.try_join().is_some());
841        let outcome = parked.join();
842        sup.shutdown();
843        rt.shutdown();
844        assert!(
845            matches!(outcome, FlowOutcome::Failed(_)),
846            "one-for-all must kill the parked sibling, got {outcome:?}"
847        );
848        Ok(())
849    }
850
851    #[test]
852    fn rest_for_one_kills_only_later_children() -> Result<(), Box<dyn std::error::Error>> {
853        let rt = tiny_runtime(wait_and_trap_chunk())?;
854        let sup = Supervisor::with_config(
855            rt.spawner(),
856            SupervisorConfig {
857                max_restarts: 8,
858                max_period: Duration::from_secs(5),
859                strategy: RestartStrategy::RestForOne,
860            },
861        )?;
862        let earlier = sup.start_child(ChildSpec::new("keep", 0))?;
863        let _boom =
864            sup.start_child(ChildSpec::new("delayed", 2).restart(RestartPolicy::OnFailure))?;
865        let later = sup.start_child(ChildSpec::new("tail", 0))?;
866        wait_until(|| later.try_join().is_some());
867        assert!(
868            earlier.try_join().is_none(),
869            "rest-for-one must not kill children started before the failure"
870        );
871        let later_outcome = later.join();
872        sup.shutdown();
873        rt.shutdown();
874        assert!(
875            matches!(later_outcome, FlowOutcome::Failed(_)),
876            "rest-for-one must kill children started after the failure, got {later_outcome:?}"
877        );
878        Ok(())
879    }
880
881    #[test]
882    fn child_name_registers_and_rejects_duplicate() -> Result<(), Box<dyn std::error::Error>> {
883        let rt = tiny_runtime(wait_and_trap_chunk())?;
884        let sup = Supervisor::new(rt.spawner())?;
885        let parked = sup.start_child(ChildSpec::new("svc", 0))?;
886        wait_until(|| matches!(rt.whereis("svc"), Ok(Some(_))));
887        assert!(rt.whereis("svc")?.is_some());
888        let failed_before = rt.metrics().processes_failed;
889        let dup = sup.start_child(ChildSpec::new("svc", 1));
890        match &dup {
891            Err(SpawnError::NameTaken { name }) if name == "svc" => {}
892            Ok(_) => return Err("expected NameTaken, got Ok(handle)".into()),
893            Err(e) => return Err(format!("expected NameTaken, got Err({e})").into()),
894        }
895        // Failed register must kill the orphan spawn and leave only `parked`.
896        wait_until(|| {
897            rt.metrics().processes_failed > failed_before && sup.live_children() == 1
898        });
899        assert_eq!(sup.live_children(), 1);
900        assert_eq!(
901            registry_target(&rt, "svc")?,
902            parked.id(),
903            "svc must still address the original child"
904        );
905        sup.shutdown();
906        rt.shutdown();
907        Ok(())
908    }
909
910    fn registry_target(
911        rt: &Runtime,
912        name: &str,
913    ) -> Result<FlowId, Box<dyn std::error::Error>> {
914        rt.spawner()
915            .shared
916            .registry
917            .target(name)?
918            .ok_or_else(|| format!("whereis({name}) empty").into())
919    }
920
921    #[test]
922    fn restart_rebinds_registry_name() -> Result<(), Box<dyn std::error::Error>> {
923        let rt = tiny_runtime(wait_and_trap_chunk())?;
924        let sup = Supervisor::with_config(
925            rt.spawner(),
926            SupervisorConfig {
927                max_restarts: 8,
928                max_period: Duration::from_secs(5),
929                strategy: RestartStrategy::OneForOne,
930            },
931        )?;
932        // Delayed trap so we can observe the first binding before restart.
933        let first = sup.start_child(
934            ChildSpec::new("svc", 2).restart(RestartPolicy::OnFailure),
935        )?;
936        let first_id = first.id();
937        wait_until(|| registry_target(&rt, "svc").ok() == Some(first_id));
938        wait_until(|| {
939            registry_target(&rt, "svc")
940                .map(|id| id != first_id)
941                .unwrap_or(false)
942        });
943        let rebound = registry_target(&rt, "svc")?;
944        assert_ne!(rebound, first_id);
945        assert_eq!(sup.live_children(), 1);
946        sup.shutdown();
947        rt.shutdown();
948        Ok(())
949    }
950
951    #[test]
952    fn one_for_all_rebinds_all_registry_names() -> Result<(), Box<dyn std::error::Error>> {
953        let rt = tiny_runtime(wait_and_trap_chunk())?;
954        let sup = Supervisor::with_config(
955            rt.spawner(),
956            SupervisorConfig {
957                max_restarts: 8,
958                max_period: Duration::from_secs(5),
959                strategy: RestartStrategy::OneForAll,
960            },
961        )?;
962        let a = registry_spawn(&sup, "a", 0)?; // wait
963        let b = registry_spawn(&sup, "b", 0)?; // wait
964        // Delayed trap so the post-cascade registry rebind is observable.
965        let boom = sup.start_child(
966            ChildSpec::new("c", 2).restart(RestartPolicy::OnFailure),
967        )?;
968        let old_a = a;
969        let old_b = b;
970        let old_c = boom.id();
971        wait_until(|| {
972            let ok_a = registry_target(&rt, "a").map(|id| id != old_a).unwrap_or(false);
973            let ok_b = registry_target(&rt, "b").map(|id| id != old_b).unwrap_or(false);
974            let ok_c = registry_target(&rt, "c").map(|id| id != old_c).unwrap_or(false);
975            ok_a && ok_b && ok_c && sup.live_children() == 3
976        });
977        assert_ne!(registry_target(&rt, "a")?, old_a);
978        assert_ne!(registry_target(&rt, "b")?, old_b);
979        assert_ne!(registry_target(&rt, "c")?, old_c);
980        sup.shutdown();
981        rt.shutdown();
982        Ok(())
983    }
984
985    fn registry_spawn(
986        sup: &Supervisor,
987        name: &str,
988        function: u32,
989    ) -> Result<FlowId, Box<dyn std::error::Error>> {
990        Ok(sup.start_child(ChildSpec::new(name, function))?.id())
991    }
992
993    #[test]
994    fn respawn_failure_is_reported_and_abandons_slot() -> Result<(), Box<dyn std::error::Error>> {
995        let rt = tiny_runtime(wait_and_trap_chunk())?;
996        let sup = Supervisor::with_config(
997            rt.spawner(),
998            SupervisorConfig {
999                max_restarts: 8,
1000                max_period: Duration::from_secs(5),
1001                strategy: RestartStrategy::OneForOne,
1002            },
1003        )?;
1004        // Delayed trap: arm the failpoint before the first exit is handled.
1005        let _ = sup.start_child(ChildSpec::new("boom", 2).restart(RestartPolicy::OnFailure))?;
1006        assert_eq!(sup.live_children(), 1);
1007        sup.fail_next_spawns(1);
1008        wait_until(|| sup.respawn_fail_count() >= 1 && sup.live_children() == 0);
1009        assert_eq!(sup.respawn_fail_count(), 1);
1010        assert_eq!(sup.live_children(), 0);
1011        std::thread::sleep(Duration::from_millis(40));
1012        assert_eq!(sup.respawn_fail_count(), 1);
1013        assert_eq!(sup.live_children(), 0);
1014        sup.shutdown();
1015        rt.shutdown();
1016        Ok(())
1017    }
1018
1019    #[test]
1020    fn policy_table() {
1021        let ok = FlowOutcome::Completed(Value::Unit);
1022        let fail = FlowOutcome::Failed("boom".into());
1023        assert!(should_restart(RestartPolicy::Always, &ok));
1024        assert!(should_restart(RestartPolicy::Always, &fail));
1025        assert!(!should_restart(RestartPolicy::OnFailure, &ok));
1026        assert!(should_restart(RestartPolicy::OnFailure, &fail));
1027        assert!(!should_restart(RestartPolicy::Never, &ok));
1028        assert!(!should_restart(RestartPolicy::Never, &fail));
1029    }
1030}