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            match slot.as_ref() {
606                Some(c) => c.waiting.is_empty(),
607                None => true,
608            }
609        }
610        Err(e) => {
611            report_fault(e);
612            return;
613        }
614    };
615    if remaining || waiting.is_empty() {
616        finish_cascade(inner);
617    }
618}
619
620fn on_cascade_progress(inner: &Arc<Inner>, id: FlowId) {
621    let ready = match sync_lock::lock(&inner.cascade, "on_cascade_progress") {
622        Ok(mut slot) => {
623            let Some(c) = slot.as_mut() else {
624                return;
625            };
626            c.waiting.remove(&id);
627            c.waiting.is_empty()
628        }
629        Err(e) => {
630            report_fault(e);
631            return;
632        }
633    };
634    if ready {
635        finish_cascade(inner);
636    }
637}
638
639fn finish_cascade(inner: &Arc<Inner>) {
640    let specs = match sync_lock::lock(&inner.cascade, "finish_cascade") {
641        Ok(mut slot) => match slot.take() {
642            Some(c) => c.specs,
643            None => return,
644        },
645        Err(e) => {
646            report_fault(e);
647            return;
648        }
649    };
650    for spec in specs {
651        if inner.intensity_exceeded.load(Ordering::Acquire) {
652            return;
653        }
654        respawn_child(inner, spec);
655    }
656}
657
658#[cfg(test)]
659mod tests {
660    use super::*;
661    use std::time::{Duration, Instant};
662
663    use crate::bytecode::{builder::ChunkBuilder, Chunk, Value};
664    use crate::scheduler::runtime::{Runtime, RuntimeConfig};
665
666    fn trap_chunk() -> Chunk {
667        let mut b = ChunkBuilder::new("trap");
668        b.begin_function("boom", 0, 1);
669        b.emit_trap(1);
670        b.finish()
671    }
672
673    /// Sets `RestartPolicy::Never` then traps — must not be restarted.
674    fn never_then_trap_chunk() -> Chunk {
675        let mut b = ChunkBuilder::new("never-trap");
676        b.begin_function("boom", 0, 1);
677        b.emit_set_restart_policy(RestartPolicy::Never.as_u8());
678        b.emit_trap(1);
679        b.finish()
680    }
681
682    fn ok_chunk() -> Chunk {
683        let mut b = ChunkBuilder::new("ok");
684        b.begin_function("main", 0, 1);
685        b.emit_load_imm(0, 7);
686        b.emit_return(0);
687        b.finish()
688    }
689
690    fn tiny_runtime(chunk: Chunk) -> Result<Runtime, crate::scheduler::SpawnError> {
691        Runtime::with_config(
692            chunk,
693            RuntimeConfig {
694                workers: 1,
695                quantum: 1_000,
696                mailbox: super::super::mailbox::MailboxConfig::DEFAULT,
697                ..Default::default()
698            },
699        )
700    }
701
702    fn wait_until(mut pred: impl FnMut() -> bool) {
703        let start = Instant::now();
704        while !pred() {
705            assert!(
706                start.elapsed() < Duration::from_secs(2),
707                "supervisor test timed out"
708            );
709            std::thread::sleep(Duration::from_millis(5));
710        }
711    }
712
713    #[test]
714    fn on_failure_does_not_restart_a_clean_exit() -> Result<(), Box<dyn std::error::Error>> {
715        let rt = tiny_runtime(ok_chunk())?;
716        let sup = Supervisor::new(rt.spawner())?;
717        let outcome = sup
718            .start_child(ChildSpec::new("main", 0).restart(RestartPolicy::OnFailure))?
719            .join();
720        wait_until(|| sup.live_children() == 0);
721        let spawned = rt.metrics().processes_spawned;
722        sup.shutdown();
723        rt.shutdown();
724        assert!(matches!(outcome, FlowOutcome::Completed(_)));
725        assert_eq!(spawned, 1);
726        Ok(())
727    }
728
729    #[test]
730    fn on_failure_restarts_until_intensity() -> Result<(), Box<dyn std::error::Error>> {
731        let rt = tiny_runtime(trap_chunk())?;
732        let sup = Supervisor::with_config(
733            rt.spawner(),
734            SupervisorConfig {
735                max_restarts: 2,
736                max_period: Duration::from_secs(5),
737                strategy: RestartStrategy::OneForOne,
738            },
739        )?;
740        let _first =
741            sup.start_child(ChildSpec::new("boom", 0).restart(RestartPolicy::OnFailure))?;
742        wait_until(|| sup.intensity_exceeded() && rt.metrics().processes_failed >= 3);
743        let spawned = rt.metrics().processes_spawned;
744        let failed = rt.metrics().processes_failed;
745        sup.shutdown();
746        rt.shutdown();
747        // initial start + 2 restarts, then intensity refuses the 3rd restart
748        assert_eq!(spawned, 3);
749        assert_eq!(failed, 3);
750        Ok(())
751    }
752
753    #[test]
754    fn set_restart_policy_never_skips_restart() -> Result<(), Box<dyn std::error::Error>> {
755        let rt = tiny_runtime(never_then_trap_chunk())?;
756        let sup = Supervisor::with_config(
757            rt.spawner(),
758            SupervisorConfig {
759                max_restarts: 5,
760                max_period: Duration::from_secs(5),
761                strategy: RestartStrategy::OneForOne,
762            },
763        )?;
764        // ChildSpec says OnFailure, but bytecode SetRestartPolicy(Never)
765        // must win at exit.
766        let _ = sup.start_child(ChildSpec::new("boom", 0).restart(RestartPolicy::OnFailure))?;
767        wait_until(|| rt.metrics().processes_failed >= 1 && sup.live_children() == 0);
768        let spawned = rt.metrics().processes_spawned;
769        let failed = rt.metrics().processes_failed;
770        std::thread::sleep(Duration::from_millis(50));
771        let spawned_after = rt.metrics().processes_spawned;
772        sup.shutdown();
773        rt.shutdown();
774        assert_eq!(failed, 1);
775        assert_eq!(spawned, 1);
776        assert_eq!(spawned_after, 1, "Never must not restart");
777        Ok(())
778    }
779
780    #[test]
781    fn always_restarts_a_clean_exit_until_intensity() -> Result<(), Box<dyn std::error::Error>> {
782        let rt = tiny_runtime(ok_chunk())?;
783        let sup = Supervisor::with_config(
784            rt.spawner(),
785            SupervisorConfig {
786                max_restarts: 2,
787                max_period: Duration::from_secs(5),
788                strategy: RestartStrategy::OneForOne,
789            },
790        )?;
791        let _ = sup.start_child(ChildSpec::new("main", 0).restart(RestartPolicy::Always))?;
792        wait_until(|| sup.intensity_exceeded() && rt.metrics().processes_completed >= 3);
793        let spawned = rt.metrics().processes_spawned;
794        sup.shutdown();
795        rt.shutdown();
796        assert_eq!(spawned, 3);
797        Ok(())
798    }
799
800    fn wait_and_trap_chunk() -> Chunk {
801        let mut b = ChunkBuilder::new("sup-mix");
802        b.begin_function("wait", 0, 1);
803        b.emit_receive(0);
804        b.emit_return(0);
805        b.begin_function("boom", 0, 1);
806        b.emit_trap(1);
807        b.begin_function("delayed", 0, 1);
808        b.emit_load_imm(0, 80);
809        b.emit_sleep(0);
810        b.emit_trap(1);
811        b.finish()
812    }
813
814    #[test]
815    fn one_for_one_does_not_kill_sibling() -> Result<(), Box<dyn std::error::Error>> {
816        let rt = tiny_runtime(wait_and_trap_chunk())?;
817        let sup = Supervisor::new(rt.spawner())?;
818        let parked = sup.start_child(ChildSpec::new("wait", 0))?;
819        let _boom = sup.start_child(ChildSpec::new("boom", 1).restart(RestartPolicy::OnFailure))?;
820        wait_until(|| rt.metrics().processes_failed >= 1);
821        assert!(
822            parked.try_join().is_none(),
823            "one-for-one must leave the parked sibling"
824        );
825        sup.shutdown();
826        rt.shutdown();
827        Ok(())
828    }
829
830    #[test]
831    fn one_for_all_kills_parked_sibling() -> Result<(), Box<dyn std::error::Error>> {
832        let rt = tiny_runtime(wait_and_trap_chunk())?;
833        let sup = Supervisor::with_config(
834            rt.spawner(),
835            SupervisorConfig {
836                max_restarts: 8,
837                max_period: Duration::from_secs(5),
838                strategy: RestartStrategy::OneForAll,
839            },
840        )?;
841        let parked = sup.start_child(ChildSpec::new("wait", 0))?;
842        let _boom = sup.start_child(ChildSpec::new("boom", 1).restart(RestartPolicy::OnFailure))?;
843        wait_until(|| parked.try_join().is_some());
844        let outcome = parked.join();
845        sup.shutdown();
846        rt.shutdown();
847        assert!(
848            matches!(outcome, FlowOutcome::Failed(_)),
849            "one-for-all must kill the parked sibling, got {outcome:?}"
850        );
851        Ok(())
852    }
853
854    #[test]
855    fn rest_for_one_kills_only_later_children() -> Result<(), Box<dyn std::error::Error>> {
856        let rt = tiny_runtime(wait_and_trap_chunk())?;
857        let sup = Supervisor::with_config(
858            rt.spawner(),
859            SupervisorConfig {
860                max_restarts: 8,
861                max_period: Duration::from_secs(5),
862                strategy: RestartStrategy::RestForOne,
863            },
864        )?;
865        let earlier = sup.start_child(ChildSpec::new("keep", 0))?;
866        let _boom =
867            sup.start_child(ChildSpec::new("delayed", 2).restart(RestartPolicy::OnFailure))?;
868        let later = sup.start_child(ChildSpec::new("tail", 0))?;
869        wait_until(|| later.try_join().is_some());
870        assert!(
871            earlier.try_join().is_none(),
872            "rest-for-one must not kill children started before the failure"
873        );
874        let later_outcome = later.join();
875        sup.shutdown();
876        rt.shutdown();
877        assert!(
878            matches!(later_outcome, FlowOutcome::Failed(_)),
879            "rest-for-one must kill children started after the failure, got {later_outcome:?}"
880        );
881        Ok(())
882    }
883
884    #[test]
885    fn child_name_registers_and_rejects_duplicate() -> Result<(), Box<dyn std::error::Error>> {
886        let rt = tiny_runtime(wait_and_trap_chunk())?;
887        let sup = Supervisor::new(rt.spawner())?;
888        let parked = sup.start_child(ChildSpec::new("svc", 0))?;
889        wait_until(|| matches!(rt.whereis("svc"), Ok(Some(_))));
890        assert!(rt.whereis("svc")?.is_some());
891        let failed_before = rt.metrics().processes_failed;
892        let dup = sup.start_child(ChildSpec::new("svc", 1));
893        match &dup {
894            Err(SpawnError::NameTaken { name }) if name == "svc" => {}
895            Ok(_) => return Err("expected NameTaken, got Ok(handle)".into()),
896            Err(e) => return Err(format!("expected NameTaken, got Err({e})").into()),
897        }
898        // Failed register must kill the orphan spawn and leave only `parked`.
899        wait_until(|| {
900            rt.metrics().processes_failed > failed_before && sup.live_children() == 1
901        });
902        assert_eq!(sup.live_children(), 1);
903        assert_eq!(
904            registry_target(&rt, "svc")?,
905            parked.id(),
906            "svc must still address the original child"
907        );
908        sup.shutdown();
909        rt.shutdown();
910        Ok(())
911    }
912
913    fn registry_target(
914        rt: &Runtime,
915        name: &str,
916    ) -> Result<FlowId, Box<dyn std::error::Error>> {
917        rt.spawner()
918            .shared
919            .registry
920            .target(name)?
921            .ok_or_else(|| format!("whereis({name}) empty").into())
922    }
923
924    #[test]
925    fn restart_rebinds_registry_name() -> Result<(), Box<dyn std::error::Error>> {
926        let rt = tiny_runtime(wait_and_trap_chunk())?;
927        let sup = Supervisor::with_config(
928            rt.spawner(),
929            SupervisorConfig {
930                max_restarts: 8,
931                max_period: Duration::from_secs(5),
932                strategy: RestartStrategy::OneForOne,
933            },
934        )?;
935        // Delayed trap so we can observe the first binding before restart.
936        let first = sup.start_child(
937            ChildSpec::new("svc", 2).restart(RestartPolicy::OnFailure),
938        )?;
939        let first_id = first.id();
940        wait_until(|| registry_target(&rt, "svc").ok() == Some(first_id));
941        wait_until(|| match registry_target(&rt, "svc") {
942            Ok(id) => id != first_id,
943            Err(_) => false,
944        });
945        let rebound = registry_target(&rt, "svc")?;
946        assert_ne!(rebound, first_id);
947        assert_eq!(sup.live_children(), 1);
948        sup.shutdown();
949        rt.shutdown();
950        Ok(())
951    }
952
953    #[test]
954    fn one_for_all_rebinds_all_registry_names() -> Result<(), Box<dyn std::error::Error>> {
955        let rt = tiny_runtime(wait_and_trap_chunk())?;
956        let sup = Supervisor::with_config(
957            rt.spawner(),
958            SupervisorConfig {
959                max_restarts: 8,
960                max_period: Duration::from_secs(5),
961                strategy: RestartStrategy::OneForAll,
962            },
963        )?;
964        let a = registry_spawn(&sup, "a", 0)?; // wait
965        let b = registry_spawn(&sup, "b", 0)?; // wait
966        // Delayed trap so the post-cascade registry rebind is observable.
967        let boom = sup.start_child(
968            ChildSpec::new("c", 2).restart(RestartPolicy::OnFailure),
969        )?;
970        let old_a = a;
971        let old_b = b;
972        let old_c = boom.id();
973        wait_until(|| {
974            let ok_a = match registry_target(&rt, "a") {
975                Ok(id) => id != old_a,
976                Err(_) => false,
977            };
978            let ok_b = match registry_target(&rt, "b") {
979                Ok(id) => id != old_b,
980                Err(_) => false,
981            };
982            let ok_c = match registry_target(&rt, "c") {
983                Ok(id) => id != old_c,
984                Err(_) => false,
985            };
986            ok_a && ok_b && ok_c && sup.live_children() == 3
987        });
988        assert_ne!(registry_target(&rt, "a")?, old_a);
989        assert_ne!(registry_target(&rt, "b")?, old_b);
990        assert_ne!(registry_target(&rt, "c")?, old_c);
991        sup.shutdown();
992        rt.shutdown();
993        Ok(())
994    }
995
996    fn registry_spawn(
997        sup: &Supervisor,
998        name: &str,
999        function: u32,
1000    ) -> Result<FlowId, Box<dyn std::error::Error>> {
1001        Ok(sup.start_child(ChildSpec::new(name, function))?.id())
1002    }
1003
1004    #[test]
1005    fn respawn_failure_is_reported_and_abandons_slot() -> Result<(), Box<dyn std::error::Error>> {
1006        let rt = tiny_runtime(wait_and_trap_chunk())?;
1007        let sup = Supervisor::with_config(
1008            rt.spawner(),
1009            SupervisorConfig {
1010                max_restarts: 8,
1011                max_period: Duration::from_secs(5),
1012                strategy: RestartStrategy::OneForOne,
1013            },
1014        )?;
1015        // Delayed trap: arm the failpoint before the first exit is handled.
1016        let _ = sup.start_child(ChildSpec::new("boom", 2).restart(RestartPolicy::OnFailure))?;
1017        assert_eq!(sup.live_children(), 1);
1018        sup.fail_next_spawns(1);
1019        wait_until(|| sup.respawn_fail_count() >= 1 && sup.live_children() == 0);
1020        assert_eq!(sup.respawn_fail_count(), 1);
1021        assert_eq!(sup.live_children(), 0);
1022        std::thread::sleep(Duration::from_millis(40));
1023        assert_eq!(sup.respawn_fail_count(), 1);
1024        assert_eq!(sup.live_children(), 0);
1025        sup.shutdown();
1026        rt.shutdown();
1027        Ok(())
1028    }
1029
1030    #[test]
1031    fn policy_table() {
1032        let ok = FlowOutcome::Completed(Value::Unit);
1033        let fail = FlowOutcome::Failed("boom".into());
1034        assert!(should_restart(RestartPolicy::Always, &ok));
1035        assert!(should_restart(RestartPolicy::Always, &fail));
1036        assert!(!should_restart(RestartPolicy::OnFailure, &ok));
1037        assert!(should_restart(RestartPolicy::OnFailure, &fail));
1038        assert!(!should_restart(RestartPolicy::Never, &ok));
1039        assert!(!should_restart(RestartPolicy::Never, &fail));
1040    }
1041}