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
18const DEFAULT_MAX_RESTARTS: u32 = 3;
27const DEFAULT_MAX_PERIOD: Duration = Duration::from_secs(5);
28
29#[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub enum RestartStrategy {
74 OneForOne,
76 OneForAll,
79 RestForOne,
82}
83
84#[derive(Clone, Debug)]
86pub struct SupervisorConfig {
87 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 restart: RestartPolicy,
114}
115
116struct LiveChild {
117 spec: ChildSpec,
118 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
151struct 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 #[cfg(test)]
169 fail_next_spawns: AtomicU32,
170 #[cfg(test)]
171 respawn_fail_count: AtomicU64,
172}
173
174#[derive(Clone)]
178pub(crate) struct SupervisorLink {
179 inner: Arc<Inner>,
180}
181
182impl SupervisorLink {
183 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 pub(crate) fn start_child(&self, spec: ChildSpec) -> Result<FlowHandle, SpawnError> {
205 spawn_child(&self.inner, spec)
206 }
207}
208
209pub struct Supervisor {
224 inner: Arc<Inner>,
225 thread: Option<JoinHandle<()>>,
226}
227
228impl Supervisor {
229 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 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 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 pub fn intensity_exceeded(&self) -> bool {
295 self.inner.intensity_exceeded.load(Ordering::Acquire)
296 }
297
298 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#[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 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 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
445fn 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 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 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 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 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 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 #[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 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 {
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 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 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)?; let b = registry_spawn(&sup, "b", 0)?; 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 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}