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