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