byteflow-actors 0.9.27

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(test)]
use std::sync::atomic::{AtomicU32, AtomicU64};
use std::sync::{Arc, Condvar, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use crate::bytecode::{RestartPolicy, Value};

use super::error::{report_fault, SpawnError};
use super::handle::FlowHandle;
use super::monitor::FlowExitReason;
use super::process::{FlowId, FlowOutcome};
use super::runtime::RuntimeSpawner;
use super::sync_lock;

/// How many **restart waves** OTP-style supervisors allow inside a sliding
/// window before giving up (design notes §15). Three-in-five-seconds is the
/// classic default: enough to absorb a flaky child, tight enough that a
/// crash loop cannot spin the runtime forever.
///
/// A wave is one decision to restart after an unexpected exit — not the
/// number of individual `spawn_child` calls. `OneForAll` that rebuilds
/// three children still counts as **one** wave.
const DEFAULT_MAX_RESTARTS: u32 = 3;
const DEFAULT_MAX_PERIOD: Duration = Duration::from_secs(5);

/// A child the supervisor should start (and possibly restart).
///
/// `function` is an index into the runtime's chunk — the same number
/// [`super::runtime::Runtime::spawn`] takes. Args are cloned on every
/// restart so a child always comes back with the original call.
///
/// Non-empty [`Self::name`] is registered as `register_name` → an addressing
/// Cap ([`crate::CapRights::ADDRESSING`]) for that incarnation (swept on exit,
/// re-bound on restart).
#[derive(Clone, Debug)]
pub struct ChildSpec {
    pub name: String,
    pub function: u32,
    pub args: Vec<Value>,
    pub restart: RestartPolicy,
}

impl ChildSpec {
    pub fn new(name: impl Into<String>, function: u32) -> Self {
        ChildSpec {
            name: name.into(),
            function,
            args: Vec::new(),
            restart: RestartPolicy::OnFailure,
        }
    }

    pub fn args(mut self, args: Vec<Value>) -> Self {
        self.args = args;
        self
    }

    pub fn restart(mut self, restart: RestartPolicy) -> Self {
        self.restart = restart;
        self
    }
}

/// Which siblings die (and later come back) when one child exits.
///
/// Sibling abort is **cooperative**: parked children are taken out of the
/// mailbox immediately; a child mid-quantum dies at the next budget edge
/// (same contract as [`super::runtime::Runtime::kill`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RestartStrategy {
    /// Only the child that exited is considered for restart.
    OneForOne,
    /// Every sibling is shut down, then the whole set is started again
    /// in original start order.
    OneForAll,
    /// Children started *after* the failed one are shut down, then that
    /// suffix (failed + later) is started again in start order.
    RestForOne,
}

/// Tunables for [`Supervisor::with_config`].
#[derive(Clone, Debug)]
pub struct SupervisorConfig {
    /// Restart **waves** allowed inside [`Self::max_period`]. The initial
    /// start does not count. Hitting this cap sets
    /// [`Supervisor::intensity_exceeded`] and further waves are refused.
    ///
    /// One unexpected exit → one wave, even if the strategy respawns several
    /// siblings (`OneForAll` / `RestForOne`). This matches OTP intensity
    /// (restart decisions), not a raw spawn counter.
    pub max_restarts: u32,
    pub max_period: Duration,
    pub strategy: RestartStrategy,
}

impl Default for SupervisorConfig {
    fn default() -> Self {
        SupervisorConfig {
            max_restarts: DEFAULT_MAX_RESTARTS,
            max_period: DEFAULT_MAX_PERIOD,
            strategy: RestartStrategy::OneForOne,
        }
    }
}

struct ChildExit {
    id: FlowId,
    outcome: FlowOutcome,
    /// Policy from the dying flow (`SetRestartPolicy` / spawn default).
    restart: RestartPolicy,
}

struct LiveChild {
    spec: ChildSpec,
    /// Set when this incarnation is being torn down by a cascade so its
    /// exit does not start another strategy wave.
    expected_shutdown: bool,
}

struct ChildTable {
    by_id: HashMap<FlowId, LiveChild>,
    order: Vec<FlowId>,
}

impl ChildTable {
    fn new() -> Self {
        Self {
            by_id: HashMap::new(),
            order: Vec::new(),
        }
    }

    fn insert(&mut self, id: FlowId, child: LiveChild) {
        self.order.push(id);
        self.by_id.insert(id, child);
    }

    fn remove(&mut self, id: FlowId) -> Option<LiveChild> {
        self.order.retain(|x| *x != id);
        self.by_id.remove(&id)
    }

    fn len(&self) -> usize {
        self.by_id.len()
    }
}

/// In-flight one-for-all / rest-for-one: wait for sibling kills, then respawn.
struct Cascade {
    waiting: HashSet<FlowId>,
    specs: Vec<ChildSpec>,
}

struct Inner {
    spawner: RuntimeSpawner,
    config: SupervisorConfig,
    events: Mutex<VecDeque<ChildExit>>,
    cvar: Condvar,
    children: Mutex<ChildTable>,
    cascade: Mutex<Option<Cascade>>,
    restart_times: Mutex<VecDeque<Instant>>,
    intensity_exceeded: AtomicBool,
    shutdown: AtomicBool,
    /// Test-only: next N `spawn_child` calls fail before OS spawn.
    #[cfg(test)]
    fail_next_spawns: AtomicU32,
    #[cfg(test)]
    respawn_fail_count: AtomicU64,
}

/// Cheap, `Clone` handle the worker uses to hand a terminal outcome back
/// without taking a lock on the supervisor's child table (the drive loop
/// is the only writer of that table).
#[derive(Clone)]
pub(crate) struct SupervisorLink {
    inner: Arc<Inner>,
}

impl SupervisorLink {
    /// Enqueue a terminal outcome for the drive loop.
    ///
    /// If the event mutex is poisoned the exit is **dropped** after
    /// [`report_fault`] — the child is already dead; supervision of that
    /// incarnation is abandoned (fail-stop). Prefer restarting the host
    /// process over continuing with a corrupted event queue.
    pub(crate) fn notify(&self, id: FlowId, outcome: FlowOutcome, restart: RestartPolicy) {
        match sync_lock::lock(&self.inner.events, "SupervisorLink::notify") {
            Ok(mut events) => {
                events.push_back(ChildExit {
                    id,
                    outcome,
                    restart,
                });
                self.inner.cvar.notify_one();
            }
            Err(e) => report_fault(e),
        }
    }

    /// Spawn another child on the same supervisor (bytecode `StartChild`).
    pub(crate) fn start_child(&self, spec: ChildSpec) -> Result<FlowHandle, SpawnError> {
        spawn_child(&self.inner, spec)
    }
}

/// Host-side child restarter (design notes §15-16).
///
/// A `Supervisor` is **not** a bytecode Flow. It is a dedicated OS
/// thread plus a table of [`ChildSpec`]s. When a supervised flow
/// becomes [`FlowOutcome::Failed`] (or completes, under
/// [`RestartPolicy::Always`]), the worker delivers the
/// [`FlowOutcome`] here instead of letting the fault take anything
/// else down. The supervisor then consults the child's
/// [`RestartPolicy`] and, if intensity allows, respawns it under a
/// fresh [`FlowId`] — Pids are never reused (see
/// [`super::process::FlowId`]).
///
/// Constructed from a [`RuntimeSpawner`] so it does not have to own the
/// runtime's worker `JoinHandle`s.
pub struct Supervisor {
    inner: Arc<Inner>,
    thread: Option<JoinHandle<()>>,
}

impl Supervisor {
    /// Handle a worker uses for [`SupervisorLink::start_child`].
    pub(crate) fn link(&self) -> SupervisorLink {
        SupervisorLink {
            inner: Arc::clone(&self.inner),
        }
    }

    pub fn new(spawner: RuntimeSpawner) -> Result<Self, SpawnError> {
        Self::with_config(spawner, SupervisorConfig::default())
    }

    /// Start the dedicated supervisor OS thread. Thread-spawn failure is
    /// [`SpawnError::ThreadSpawnFailed`] — same category-A surface as
    /// [`super::runtime::Runtime::new`], not a panic.
    pub fn with_config(
        spawner: RuntimeSpawner,
        config: SupervisorConfig,
    ) -> Result<Self, SpawnError> {
        let inner = Arc::new(Inner {
            spawner,
            config,
            events: Mutex::new(VecDeque::new()),
            cvar: Condvar::new(),
            children: Mutex::new(ChildTable::new()),
            cascade: Mutex::new(None),
            restart_times: Mutex::new(VecDeque::new()),
            intensity_exceeded: AtomicBool::new(false),
            shutdown: AtomicBool::new(false),
            #[cfg(test)]
            fail_next_spawns: AtomicU32::new(0),
            #[cfg(test)]
            respawn_fail_count: AtomicU64::new(0),
        });
        let drive_inner = inner.clone();
        let thread = std::thread::Builder::new()
            .name("byteflow-supervisor".into())
            .spawn(move || drive(drive_inner))
            .map_err(|e| SpawnError::ThreadSpawnFailed(e.to_string()))?;
        Ok(Supervisor {
            inner,
            thread: Some(thread),
        })
    }

    /// Spawn `spec` and start supervising it. The returned handle is for
    /// this incarnation only — a restart allocates a new Pid and a new
    /// completion channel.
    pub fn start_child(&self, spec: ChildSpec) -> Result<FlowHandle, SpawnError> {
        spawn_child(&self.inner, spec)
    }

    pub fn live_children(&self) -> usize {
        match sync_lock::lock(&self.inner.children, "Supervisor::live_children") {
            Ok(g) => g.len(),
            Err(e) => {
                report_fault(e);
                0
            }
        }
    }

    /// `true` once more than [`SupervisorConfig::max_restarts`] **waves**
    /// landed inside the intensity window. Remaining children keep
    /// running; we just stop bringing them back (no safe abort of a
    /// mid-quantum flow).
    pub fn intensity_exceeded(&self) -> bool {
        self.inner.intensity_exceeded.load(Ordering::Acquire)
    }

    /// Stop the drive thread. Does not terminate live children — they
    /// belong to the runtime, not to us.
    pub fn shutdown(mut self) {
        self.stop_drive();
        if let Some(t) = self.thread.take() {
            let _ = t.join();
        }
    }

    fn stop_drive(&self) {
        self.inner.shutdown.store(true, Ordering::Release);
        self.inner.cvar.notify_all();
    }

    #[cfg(test)]
    fn fail_next_spawns(&self, n: u32) {
        self.inner.fail_next_spawns.store(n, Ordering::SeqCst);
    }

    #[cfg(test)]
    fn respawn_fail_count(&self) -> u64 {
        self.inner.respawn_fail_count.load(Ordering::Relaxed)
    }
}

impl Drop for Supervisor {
    fn drop(&mut self) {
        self.stop_drive();
        if let Some(t) = self.thread.take() {
            let _ = t.join();
        }
    }
}

/// Decrement `n` if it is positive; `true` when it did.
#[cfg(test)]
fn take_one(n: &std::sync::atomic::AtomicU32) -> bool {
    let mut cur = n.load(Ordering::SeqCst);
    while cur > 0 {
        match n.compare_exchange_weak(cur, cur - 1, Ordering::SeqCst, Ordering::SeqCst) {
            Ok(_) => return true,
            Err(actual) => cur = actual,
        }
    }
    false
}

fn spawn_child(inner: &Arc<Inner>, spec: ChildSpec) -> Result<FlowHandle, SpawnError> {
    #[cfg(test)]
    if take_one(&inner.fail_next_spawns) {
        return Err(SpawnError::VmInit("test: forced spawn failure".into()));
    }

    let link = SupervisorLink {
        inner: inner.clone(),
    };
    // Hold the table across spawn so a child that faults in its first
    // quantum cannot notify us before its row exists (the drive loop
    // takes this same lock in `handle_exit`, so the event waits).
    let mut children = match sync_lock::lock(&inner.children, "spawn_child") {
        Ok(c) => c,
        Err(e) => {
            report_fault(e);
            return Err(SpawnError::VmInit("supervisor child table poisoned".into()));
        }
    };
    let handle = inner
        .spawner
        .spawn_linked(spec.function, &spec.args, spec.restart, link)?;
    let id = handle.id();
    // Insert *before* name registration so a failed register still leaves a
    // row for the kill exit (expected_shutdown → no restart wave).
    children.insert(
        id,
        LiveChild {
            spec: spec.clone(),
            expected_shutdown: false,
        },
    );
    if !spec.name.is_empty() {
        if let Err(e) = register_child_name(inner, id, &spec.name) {
            if let Some(live) = children.by_id.get_mut(&id) {
                live.expected_shutdown = true;
            }
            inner.spawner.request_kill(id, FlowExitReason::Supervisor);
            return Err(e);
        }
    }
    Ok(handle)
}

fn note_respawn_failed(inner: &Inner, err: &SpawnError) {
    #[cfg(test)]
    {
        inner.respawn_fail_count.fetch_add(1, Ordering::Relaxed);
    }
    #[cfg(not(test))]
    {
        let _ = inner;
    }
    eprintln!("byteflow: supervisor respawn failed: {err} — child slot abandoned");
}

fn respawn_child(inner: &Arc<Inner>, spec: ChildSpec) {
    if let Err(e) = spawn_child(inner, spec) {
        note_respawn_failed(inner, &e);
    }
}

fn register_child_name(inner: &Inner, id: FlowId, name: &str) -> Result<(), SpawnError> {
    let cap = inner
        .spawner
        .shared
        .caps
        .mint(id, id, super::capability::CapRights::ADDRESSING)
        .map_err(|e| {
            report_fault(e);
            SpawnError::VmInit("cap mint failed (poisoned lock)".into())
        })?;
    match inner
        .spawner
        .shared
        .registry
        .register(super::registry::RegistryName::from(name), cap, id)
    {
        Ok(Ok(())) => Ok(()),
        Ok(Err(super::error::LifecycleError::AlreadyRegistered)) => Err(SpawnError::NameTaken {
            name: name.to_string(),
        }),
        Ok(Err(e)) => Err(SpawnError::VmInit(e.to_string())),
        Err(e) => {
            report_fault(e);
            Err(SpawnError::VmInit(
                "registry register failed (poisoned lock)".into(),
            ))
        }
    }
}

fn should_restart(policy: RestartPolicy, outcome: &FlowOutcome) -> bool {
    match policy {
        RestartPolicy::Always => true,
        RestartPolicy::OnFailure => matches!(outcome, FlowOutcome::Failed(_)),
        RestartPolicy::Never => false,
    }
}

/// Drop restart marks older than `period`.
///
/// `checked_sub` fails when `period` reaches past the start of the `Instant`
/// clock. That means every recorded mark is still inside the window. Treating
/// the start as `now` dropped the whole history and intensity never tripped.
fn prune_restart_window(times: &mut VecDeque<Instant>, now: Instant, period: Duration) {
    let Some(start) = now.checked_sub(period) else {
        return;
    };
    while times.front().is_some_and(|t| *t < start) {
        times.pop_front();
    }
}

fn intensity_hit(inner: &Inner) -> bool {
    let now = Instant::now();
    let mut times = match sync_lock::lock(&inner.restart_times, "intensity_hit") {
        Ok(t) => t,
        Err(e) => {
            report_fault(e);
            return true;
        }
    };
    times.push_back(now);
    prune_restart_window(&mut times, now, inner.config.max_period);
    if times.len() as u32 > inner.config.max_restarts {
        inner.intensity_exceeded.store(true, Ordering::Release);
        true
    } else {
        false
    }
}

fn drive(inner: Arc<Inner>) {
    loop {
        if inner.shutdown.load(Ordering::Acquire) {
            return;
        }
        let exit = {
            let mut events = match sync_lock::lock(&inner.events, "supervisor::drive") {
                Ok(e) => e,
                Err(e) => {
                    report_fault(e);
                    return;
                }
            };
            loop {
                if inner.shutdown.load(Ordering::Acquire) {
                    return;
                }
                if let Some(exit) = events.pop_front() {
                    break exit;
                }
                match sync_lock::wait(&inner.cvar, events, "supervisor::wait") {
                    Ok(guard) => events = guard,
                    Err(e) => {
                        report_fault(e);
                        return;
                    }
                }
            }
        };
        handle_exit(&inner, exit);
    }
}

fn handle_exit(inner: &Arc<Inner>, exit: ChildExit) {
    let (spec, expected, failed_idx, later) = {
        let mut children = match sync_lock::lock(&inner.children, "handle_exit") {
            Ok(c) => c,
            Err(e) => {
                report_fault(e);
                return;
            }
        };
        let failed_idx = children.order.iter().position(|id| *id == exit.id);
        let live = match children.remove(exit.id) {
            Some(live) => live,
            None => return,
        };
        let later = match (inner.config.strategy, failed_idx) {
            (RestartStrategy::OneForAll, _) => children.order.clone(),
            (RestartStrategy::RestForOne, Some(i)) => children.order[i..].to_vec(),
            _ => Vec::new(),
        };
        (live.spec, live.expected_shutdown, failed_idx, later)
    };

    if expected {
        on_cascade_progress(inner, exit.id);
        return;
    }

    if !should_restart(exit.restart, &exit.outcome) {
        return;
    }
    if inner.intensity_exceeded.load(Ordering::Acquire) || intensity_hit(inner) {
        return;
    }
    // One restart wave at a time. A second unexpected exit (e.g. RestForOne
    // earlier sibling) must not overwrite the in-flight cascade's specs.
    if cascade_active(inner) {
        eprintln!(
            "byteflow: supervisor restart abandoned — cascade already in progress (exit {})",
            exit.id
        );
        return;
    }

    match inner.config.strategy {
        RestartStrategy::OneForOne => {
            respawn_child(inner, spec);
        }
        RestartStrategy::OneForAll | RestartStrategy::RestForOne => {
            let Some(failed_idx) = failed_idx else {
                // Row was in by_id but missing from order — refuse to guess
                // a start position (OneForAll order is part of the contract).
                eprintln!(
                    "byteflow: supervisor cascade abort — exit {} missing from child order",
                    exit.id
                );
                return;
            };
            start_cascade(inner, spec, failed_idx, later);
        }
    }
}

fn cascade_active(inner: &Inner) -> bool {
    match sync_lock::lock(&inner.cascade, "cascade_active") {
        Ok(slot) => slot.is_some(),
        Err(e) => {
            report_fault(e);
            true
        }
    }
}

fn start_cascade(inner: &Arc<Inner>, failed: ChildSpec, failed_idx: usize, later: Vec<FlowId>) {
    if cascade_active(inner) {
        eprintln!("byteflow: supervisor cascade abort — another wave is already in progress");
        return;
    }

    let specs = {
        let mut children = match sync_lock::lock(&inner.children, "start_cascade") {
            Ok(c) => c,
            Err(e) => {
                report_fault(e);
                return;
            }
        };
        let later_specs: Vec<ChildSpec> = later
            .iter()
            .filter_map(|id| {
                children.by_id.get_mut(id).map(|c| {
                    c.expected_shutdown = true;
                    c.spec.clone()
                })
            })
            .collect();
        match inner.config.strategy {
            RestartStrategy::OneForAll => {
                let mut specs = later_specs;
                if failed_idx > specs.len() {
                    eprintln!(
                        "byteflow: supervisor OneForAll abort — failed_idx {failed_idx} > {}",
                        specs.len()
                    );
                    return;
                }
                specs.insert(failed_idx, failed);
                specs
            }
            RestartStrategy::RestForOne => {
                let mut specs = vec![failed];
                specs.extend(later_specs);
                specs
            }
            RestartStrategy::OneForOne => vec![failed],
        }
    };

    let waiting: HashSet<FlowId> = later.iter().copied().collect();
    match sync_lock::lock(&inner.cascade, "start_cascade.cascade") {
        Ok(mut slot) => {
            if slot.is_some() {
                eprintln!(
                    "byteflow: supervisor cascade abort — another wave is already in progress"
                );
                return;
            }
            *slot = Some(Cascade {
                waiting: waiting.clone(),
                specs,
            });
        }
        Err(e) => {
            report_fault(e);
            return;
        }
    }

    for id in &later {
        inner.spawner.request_kill(*id, FlowExitReason::Supervisor);
    }

    let remaining = match sync_lock::lock(&inner.cascade, "start_cascade.prune") {
        Ok(mut slot) => {
            if let Some(c) = slot.as_mut() {
                c.waiting
                    .retain(|id| matches!(inner.spawner.shared.directory.lookup(*id), Ok(Some(_))));
            }
            match slot.as_ref() {
                Some(c) => c.waiting.is_empty(),
                None => true,
            }
        }
        Err(e) => {
            report_fault(e);
            return;
        }
    };
    if remaining || waiting.is_empty() {
        finish_cascade(inner);
    }
}

fn on_cascade_progress(inner: &Arc<Inner>, id: FlowId) {
    let ready = match sync_lock::lock(&inner.cascade, "on_cascade_progress") {
        Ok(mut slot) => {
            let Some(c) = slot.as_mut() else {
                return;
            };
            c.waiting.remove(&id);
            c.waiting.is_empty()
        }
        Err(e) => {
            report_fault(e);
            return;
        }
    };
    if ready {
        finish_cascade(inner);
    }
}

fn finish_cascade(inner: &Arc<Inner>) {
    let specs = match sync_lock::lock(&inner.cascade, "finish_cascade") {
        Ok(mut slot) => match slot.take() {
            Some(c) => c.specs,
            None => return,
        },
        Err(e) => {
            report_fault(e);
            return;
        }
    };
    for spec in specs {
        if inner.intensity_exceeded.load(Ordering::Acquire) {
            return;
        }
        respawn_child(inner, spec);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::VecDeque;
    use std::time::{Duration, Instant};

    #[test]
    fn a_period_longer_than_the_clock_keeps_every_restart() {
        let now = Instant::now();
        let earlier = match now.checked_sub(Duration::from_secs(1)) {
            Some(t) => t,
            None => return,
        };
        let mut times = VecDeque::from([earlier, now]);
        super::prune_restart_window(&mut times, now, Duration::MAX);
        assert_eq!(times.len(), 2);
        super::prune_restart_window(&mut times, now, Duration::from_millis(100));
        assert_eq!(times.len(), 1);
        assert_eq!(times.front().copied(), Some(now));
    }

    use crate::bytecode::{builder::ChunkBuilder, Chunk, Value};
    use crate::scheduler::runtime::{Runtime, RuntimeConfig};

    fn trap_chunk() -> Chunk {
        let mut b = ChunkBuilder::new("trap");
        b.begin_function("boom", 0, 1);
        b.emit_trap(1);
        b.finish()
    }

    /// Sets `RestartPolicy::Never` then traps — must not be restarted.
    fn never_then_trap_chunk() -> Chunk {
        let mut b = ChunkBuilder::new("never-trap");
        b.begin_function("boom", 0, 1);
        b.emit_set_restart_policy(RestartPolicy::Never.as_u8());
        b.emit_trap(1);
        b.finish()
    }

    fn ok_chunk() -> Chunk {
        let mut b = ChunkBuilder::new("ok");
        b.begin_function("main", 0, 1);
        b.emit_load_imm(0, 7);
        b.emit_return(0);
        b.finish()
    }

    fn tiny_runtime(chunk: Chunk) -> Result<Runtime, crate::scheduler::SpawnError> {
        Runtime::with_config(
            chunk,
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: super::super::mailbox::MailboxConfig::DEFAULT,
                ..Default::default()
            },
        )
    }

    fn wait_until(mut pred: impl FnMut() -> bool) {
        let start = Instant::now();
        while !pred() {
            assert!(
                start.elapsed() < Duration::from_secs(2),
                "supervisor test timed out"
            );
            std::thread::sleep(Duration::from_millis(5));
        }
    }

    #[test]
    fn on_failure_does_not_restart_a_clean_exit() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny_runtime(ok_chunk())?;
        let sup = Supervisor::new(rt.spawner())?;
        let outcome = sup
            .start_child(ChildSpec::new("main", 0).restart(RestartPolicy::OnFailure))?
            .join();
        wait_until(|| sup.live_children() == 0);
        let spawned = rt.metrics().processes_spawned;
        sup.shutdown();
        rt.shutdown();
        assert!(matches!(outcome, FlowOutcome::Completed(_)));
        assert_eq!(spawned, 1);
        Ok(())
    }

    #[test]
    fn on_failure_restarts_until_intensity() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny_runtime(trap_chunk())?;
        let sup = Supervisor::with_config(
            rt.spawner(),
            SupervisorConfig {
                max_restarts: 2,
                max_period: Duration::from_secs(5),
                strategy: RestartStrategy::OneForOne,
            },
        )?;
        let _first =
            sup.start_child(ChildSpec::new("boom", 0).restart(RestartPolicy::OnFailure))?;
        wait_until(|| sup.intensity_exceeded() && rt.metrics().processes_failed >= 3);
        let spawned = rt.metrics().processes_spawned;
        let failed = rt.metrics().processes_failed;
        sup.shutdown();
        rt.shutdown();
        // initial start + 2 restarts, then intensity refuses the 3rd restart
        assert_eq!(spawned, 3);
        assert_eq!(failed, 3);
        Ok(())
    }

    #[test]
    fn set_restart_policy_never_skips_restart() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny_runtime(never_then_trap_chunk())?;
        let sup = Supervisor::with_config(
            rt.spawner(),
            SupervisorConfig {
                max_restarts: 5,
                max_period: Duration::from_secs(5),
                strategy: RestartStrategy::OneForOne,
            },
        )?;
        // ChildSpec says OnFailure, but bytecode SetRestartPolicy(Never)
        // must win at exit.
        let _ = sup.start_child(ChildSpec::new("boom", 0).restart(RestartPolicy::OnFailure))?;
        wait_until(|| rt.metrics().processes_failed >= 1 && sup.live_children() == 0);
        let spawned = rt.metrics().processes_spawned;
        let failed = rt.metrics().processes_failed;
        std::thread::sleep(Duration::from_millis(50));
        let spawned_after = rt.metrics().processes_spawned;
        sup.shutdown();
        rt.shutdown();
        assert_eq!(failed, 1);
        assert_eq!(spawned, 1);
        assert_eq!(spawned_after, 1, "Never must not restart");
        Ok(())
    }

    #[test]
    fn always_restarts_a_clean_exit_until_intensity() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny_runtime(ok_chunk())?;
        let sup = Supervisor::with_config(
            rt.spawner(),
            SupervisorConfig {
                max_restarts: 2,
                max_period: Duration::from_secs(5),
                strategy: RestartStrategy::OneForOne,
            },
        )?;
        let _ = sup.start_child(ChildSpec::new("main", 0).restart(RestartPolicy::Always))?;
        wait_until(|| sup.intensity_exceeded() && rt.metrics().processes_completed >= 3);
        let spawned = rt.metrics().processes_spawned;
        sup.shutdown();
        rt.shutdown();
        assert_eq!(spawned, 3);
        Ok(())
    }

    fn wait_and_trap_chunk() -> Chunk {
        let mut b = ChunkBuilder::new("sup-mix");
        b.begin_function("wait", 0, 1);
        b.emit_receive(0);
        b.emit_return(0);
        b.begin_function("boom", 0, 1);
        b.emit_trap(1);
        b.begin_function("delayed", 0, 1);
        b.emit_load_imm(0, 80);
        b.emit_sleep(0);
        b.emit_trap(1);
        b.finish()
    }

    #[test]
    fn one_for_one_does_not_kill_sibling() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny_runtime(wait_and_trap_chunk())?;
        let sup = Supervisor::new(rt.spawner())?;
        let parked = sup.start_child(ChildSpec::new("wait", 0))?;
        let _boom = sup.start_child(ChildSpec::new("boom", 1).restart(RestartPolicy::OnFailure))?;
        wait_until(|| rt.metrics().processes_failed >= 1);
        assert!(
            parked.try_join().is_none(),
            "one-for-one must leave the parked sibling"
        );
        sup.shutdown();
        rt.shutdown();
        Ok(())
    }

    #[test]
    fn one_for_all_kills_parked_sibling() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny_runtime(wait_and_trap_chunk())?;
        let sup = Supervisor::with_config(
            rt.spawner(),
            SupervisorConfig {
                max_restarts: 8,
                max_period: Duration::from_secs(5),
                strategy: RestartStrategy::OneForAll,
            },
        )?;
        let parked = sup.start_child(ChildSpec::new("wait", 0))?;
        let _boom = sup.start_child(ChildSpec::new("boom", 1).restart(RestartPolicy::OnFailure))?;
        wait_until(|| parked.try_join().is_some());
        let outcome = parked.join();
        sup.shutdown();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Failed(_)),
            "one-for-all must kill the parked sibling, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn rest_for_one_kills_only_later_children() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny_runtime(wait_and_trap_chunk())?;
        let sup = Supervisor::with_config(
            rt.spawner(),
            SupervisorConfig {
                max_restarts: 8,
                max_period: Duration::from_secs(5),
                strategy: RestartStrategy::RestForOne,
            },
        )?;
        let earlier = sup.start_child(ChildSpec::new("keep", 0))?;
        let _boom =
            sup.start_child(ChildSpec::new("delayed", 2).restart(RestartPolicy::OnFailure))?;
        let later = sup.start_child(ChildSpec::new("tail", 0))?;
        wait_until(|| later.try_join().is_some());
        assert!(
            earlier.try_join().is_none(),
            "rest-for-one must not kill children started before the failure"
        );
        let later_outcome = later.join();
        sup.shutdown();
        rt.shutdown();
        assert!(
            matches!(later_outcome, FlowOutcome::Failed(_)),
            "rest-for-one must kill children started after the failure, got {later_outcome:?}"
        );
        Ok(())
    }

    /// A second unexpected exit must not overwrite an in-flight cascade's specs.
    #[test]
    fn second_wave_does_not_clobber_cascade_specs() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny_runtime(wait_and_trap_chunk())?;
        let sup = Supervisor::with_config(
            rt.spawner(),
            SupervisorConfig {
                max_restarts: 8,
                max_period: Duration::from_secs(5),
                strategy: RestartStrategy::RestForOne,
            },
        )?;
        let kept = ChildSpec::new("kept-wave", 0).restart(RestartPolicy::OnFailure);
        {
            let mut slot = sync_lock::lock(&sup.inner.cascade, "cascade-test-seed")?;
            *slot = Some(Cascade {
                waiting: HashSet::new(),
                specs: vec![kept.clone()],
            });
        }
        // Simulate an earlier sibling failing while the first wave still owns
        // the slot — same path RestForOne hits in production.
        let earlier = FlowId(0xCA5C_ADE0);
        {
            let mut children = sync_lock::lock(&sup.inner.children, "cascade-test-child")?;
            children.insert(
                earlier,
                LiveChild {
                    spec: ChildSpec::new("earlier", 1).restart(RestartPolicy::OnFailure),
                    expected_shutdown: false,
                },
            );
        }
        handle_exit(
            &sup.inner,
            ChildExit {
                id: earlier,
                outcome: FlowOutcome::Failed("mid-cascade".into()),
                restart: RestartPolicy::OnFailure,
            },
        );
        {
            let slot = sync_lock::lock(&sup.inner.cascade, "cascade-test-check")?;
            let cascade = slot.as_ref().ok_or("cascade slot cleared")?;
            assert_eq!(cascade.specs.len(), 1);
            assert_eq!(cascade.specs[0].name, "kept-wave");
        }
        assert_eq!(sup.live_children(), 0);
        assert_eq!(rt.metrics().processes_spawned, 0);
        // Clear the seeded slot without respawning into the real runtime.
        {
            let mut slot = sync_lock::lock(&sup.inner.cascade, "cascade-test-clear")?;
            *slot = None;
        }
        sup.shutdown();
        rt.shutdown();
        let _ = kept;
        Ok(())
    }

    #[test]
    fn child_name_registers_and_rejects_duplicate() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny_runtime(wait_and_trap_chunk())?;
        let sup = Supervisor::new(rt.spawner())?;
        let parked = sup.start_child(ChildSpec::new("svc", 0))?;
        wait_until(|| matches!(rt.whereis("svc"), Ok(Some(_))));
        assert!(rt.whereis("svc")?.is_some());
        let failed_before = rt.metrics().processes_failed;
        let dup = sup.start_child(ChildSpec::new("svc", 1));
        match &dup {
            Err(SpawnError::NameTaken { name }) if name == "svc" => {}
            Ok(_) => return Err("expected NameTaken, got Ok(handle)".into()),
            Err(e) => return Err(format!("expected NameTaken, got Err({e})").into()),
        }
        // Failed register must kill the orphan spawn and leave only `parked`.
        wait_until(|| rt.metrics().processes_failed > failed_before && sup.live_children() == 1);
        assert_eq!(sup.live_children(), 1);
        assert_eq!(
            registry_target(&rt, "svc")?,
            parked.id(),
            "svc must still address the original child"
        );
        sup.shutdown();
        rt.shutdown();
        Ok(())
    }

    fn registry_target(rt: &Runtime, name: &str) -> Result<FlowId, Box<dyn std::error::Error>> {
        rt.spawner()
            .shared
            .registry
            .target(name)?
            .ok_or_else(|| format!("whereis({name}) empty").into())
    }

    #[test]
    fn restart_rebinds_registry_name() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny_runtime(wait_and_trap_chunk())?;
        let sup = Supervisor::with_config(
            rt.spawner(),
            SupervisorConfig {
                max_restarts: 8,
                max_period: Duration::from_secs(5),
                strategy: RestartStrategy::OneForOne,
            },
        )?;
        // Delayed trap so we can observe the first binding before restart.
        let first = sup.start_child(ChildSpec::new("svc", 2).restart(RestartPolicy::OnFailure))?;
        let first_id = first.id();
        wait_until(|| registry_target(&rt, "svc").ok() == Some(first_id));
        wait_until(|| match registry_target(&rt, "svc") {
            Ok(id) => id != first_id,
            Err(_) => false,
        });
        let rebound = registry_target(&rt, "svc")?;
        assert_ne!(rebound, first_id);
        assert_eq!(sup.live_children(), 1);
        sup.shutdown();
        rt.shutdown();
        Ok(())
    }

    #[test]
    fn one_for_all_rebinds_all_registry_names() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny_runtime(wait_and_trap_chunk())?;
        let sup = Supervisor::with_config(
            rt.spawner(),
            SupervisorConfig {
                max_restarts: 8,
                max_period: Duration::from_secs(5),
                strategy: RestartStrategy::OneForAll,
            },
        )?;
        let a = registry_spawn(&sup, "a", 0)?; // wait
        let b = registry_spawn(&sup, "b", 0)?; // wait
                                               // Delayed trap so the post-cascade registry rebind is observable.
        let boom = sup.start_child(ChildSpec::new("c", 2).restart(RestartPolicy::OnFailure))?;
        let old_a = a;
        let old_b = b;
        let old_c = boom.id();
        wait_until(|| {
            let ok_a = match registry_target(&rt, "a") {
                Ok(id) => id != old_a,
                Err(_) => false,
            };
            let ok_b = match registry_target(&rt, "b") {
                Ok(id) => id != old_b,
                Err(_) => false,
            };
            let ok_c = match registry_target(&rt, "c") {
                Ok(id) => id != old_c,
                Err(_) => false,
            };
            ok_a && ok_b && ok_c && sup.live_children() == 3
        });
        assert_ne!(registry_target(&rt, "a")?, old_a);
        assert_ne!(registry_target(&rt, "b")?, old_b);
        assert_ne!(registry_target(&rt, "c")?, old_c);
        sup.shutdown();
        rt.shutdown();
        Ok(())
    }

    fn registry_spawn(
        sup: &Supervisor,
        name: &str,
        function: u32,
    ) -> Result<FlowId, Box<dyn std::error::Error>> {
        Ok(sup.start_child(ChildSpec::new(name, function))?.id())
    }

    #[test]
    fn respawn_failure_is_reported_and_abandons_slot() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny_runtime(wait_and_trap_chunk())?;
        let sup = Supervisor::with_config(
            rt.spawner(),
            SupervisorConfig {
                max_restarts: 8,
                max_period: Duration::from_secs(5),
                strategy: RestartStrategy::OneForOne,
            },
        )?;
        // Delayed trap: arm the failpoint before the first exit is handled.
        let _ = sup.start_child(ChildSpec::new("boom", 2).restart(RestartPolicy::OnFailure))?;
        assert_eq!(sup.live_children(), 1);
        sup.fail_next_spawns(1);
        wait_until(|| sup.respawn_fail_count() >= 1 && sup.live_children() == 0);
        assert_eq!(sup.respawn_fail_count(), 1);
        assert_eq!(sup.live_children(), 0);
        std::thread::sleep(Duration::from_millis(40));
        assert_eq!(sup.respawn_fail_count(), 1);
        assert_eq!(sup.live_children(), 0);
        sup.shutdown();
        rt.shutdown();
        Ok(())
    }

    #[test]
    fn policy_table() {
        let ok = FlowOutcome::Completed(Value::Unit);
        let fail = FlowOutcome::Failed("boom".into());
        assert!(should_restart(RestartPolicy::Always, &ok));
        assert!(should_restart(RestartPolicy::Always, &fail));
        assert!(!should_restart(RestartPolicy::OnFailure, &ok));
        assert!(should_restart(RestartPolicy::OnFailure, &fail));
        assert!(!should_restart(RestartPolicy::Never, &ok));
        assert!(!should_restart(RestartPolicy::Never, &fail));
    }
}