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