Skip to main content

byteflow/scheduler/
supervisor.rs

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