flynnel 0.6.0

K-aware NUMA-aware work-stealing scheduler with extended-Flynn-taxonomy dispatch (MIMD / SIMC / MIMC / MISD / SIMT / MIMT): a rayon-shaped pool reshaped around per-call execution-class plans with first-class CPU+GPU hybrid (join_hybrid, hybrid_pipeline) and per-call dispatch profiles.
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
//! Cooperative N-way fork-join with adaptive dispatch.
//!
//! [`cooperative_join_n`] picks a shape from N: tree (balanced
//! binary `sched::join` recursion, depth log2(N)) below N = 12,
//! flat fan-out (one StackJob per closure, critical-path depth 1)
//! at N >= 12. Tree amortizes per-StackJob overhead for short
//! closures; flat wins once log2(N) nesting extends the wait for
//! the slowest closure. The N = 12 crossover gave the same routing
//! decision on every workload measured across Zen+ R7 2700, Xeon
//! Cascade Lake, and Genoa EPYC 9B14; a timed probe was rejected
//! because it adds one closure of serial latency (~2ms on a 4.7ms
//! large-N total). [`cooperative_join_n_tree`] and
//! [`cooperative_join_n_flat`] bypass the heuristic.
//!
//! The returned `Vec<R>` is in caller-supplied order regardless of
//! which worker ran which closure; bit-exact reductions rely on
//! this. Both variants forward the [`crate::sched::JobPlan`] to
//! every nested dispatch. The flat variant's external entry lands
//! one injected StackJob on the local NUMA node and pushes all N
//! children onto that worker's deque, so the cooperative cluster
//! stays intra-node unless peer steal pulls work across.

use std::panic;

use crate::sched::arena::{global_local_arena, join};
use crate::sched::arena_local::{WorkerCtx, current_worker_ctx};
use crate::sched::job::{NUMA_HINT_ANY, StackJob};
use crate::sched::latch::{CountLatch, LockLatch};
use crate::sched::plan::JobPlan;

/// Adaptive cooperative fork-join over an arbitrary-N closure
/// list. Returns a `Vec` of results in caller-supplied order.
///
/// N = 0 returns an empty `Vec`; N = 1 runs inline; N = 2 is
/// [`crate::sched::join`]. At N >= 3 the shape resolves per the
/// [`crate::sched::adaptive_cooperative`] precedence: per-plan
/// `cooperative_routing` (non-`Auto`) wins, else the process-global
/// tag, else the population heuristic - `N < n_workers` routes to
/// [`cooperative_join_n_tree`] and `N >= n_workers` to
/// [`cooperative_join_n_flat_mailbox`]. The explicit variants and
/// [`crate::sched::JobPlan::with_cooperative_routing`] bypass the
/// heuristic.
///
/// Being routed to `cooperative_join_n_flat_mailbox` is not the same
/// as taking the mailbox shape. That function applies its own gate at
/// 32 times the worker count: below it every closure goes onto the
/// calling worker's own deque for random peer-steal to distribute, and
/// at or above it each closure is pushed to one specific peer's
/// mailbox, drained mailbox-first with no shared-deque CAS contention.
/// A fan-out at or a little above the pool width therefore takes the
/// deque shape, which is the common case and is measured 2 to 22
/// percent faster than the mailbox shape across that band.
///
/// No shape places a closure on a worker the caller can name, so a
/// closure must not depend on which worker runs it.
///
/// A plan capped at one worker ([`JobPlan::with_workers`]`(1)`) runs
/// every closure on the calling thread in caller order, here and in
/// [`cooperative_join_n_tree`], [`cooperative_join_n_flat`] and
/// [`cooperative_join_n_flat_mailbox`], without reading or starting the
/// pool.
///
/// # Determinism contract
///
/// The returned `Vec<R>` is in caller-supplied order, invariant
/// regardless of which thread executed which closure.
///
/// # Example
///
/// ```
/// use flynnel::sched::{JobPlan, cooperative_join_n};
///
/// let plan = JobPlan::new(8, 1);
/// let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> = vec![
///     Box::new(|| 1),
///     Box::new(|| 2),
///     Box::new(|| 3),
/// ];
/// let results = cooperative_join_n(&plan, closures);
/// assert_eq!(results, vec![1, 2, 3]);
/// ```
pub fn cooperative_join_n<R>(
    plan: &JobPlan,
    closures: Vec<Box<dyn FnOnce() -> R + Send>>,
) -> Vec<R>
where
    R: Send + 'static,
{
    if plan.capped_to_caller() {
        return run_on_caller(closures);
    }
    let n = closures.len();
    if n < 3 {
        // Inline / 2-way fast paths live inside the tree variant.
        return cooperative_join_n_tree(plan, closures);
    }
    // N >= 3: resolve the dispatch shape through the precedence chain.
    // Per-plan override wins outright; Auto defers to the population
    // heuristic. The plan field was resolved from the process-global
    // active tag at JobPlan::new construction time, so the global flip
    // via migrate_cooperative_routing propagates here without an
    // additional atomic load on the cooperative hot path.
    use crate::sched::adaptive_cooperative::CooperativeRouting;
    match plan.cooperative_routing {
        CooperativeRouting::ForceTree => cooperative_join_n_tree(plan, closures),
        CooperativeRouting::ForceMailbox => {
            cooperative_join_n_flat_mailbox(plan, closures)
        }
        CooperativeRouting::ForceDeque => cooperative_join_n_flat(plan, closures),
        CooperativeRouting::Auto => {
            // Population heuristic: a fan-out narrower than the pool
            // routes to tree, a wider one to the flat path.
            //
            // The flat path is not the mailbox shape. It applies
            // `mailbox_gate` itself and runs the deque shape below it,
            // which is every width from the pool count to 32 times it -
            // the band where the deque fan-out is 2 to 22 percent
            // faster. Raising this comparison instead would send that
            // band to the tree, which is slower than either.
            //
            // The count is the calling thread's own node, which is the
            // population the gate inside cooperative_join_n_flat_mailbox
            // compares against: a worker's `ctx.sleep` covers the
            // workers of the node it belongs to. Both read the same
            // number, so a fan-out this arm routes onward is one that
            // path can populate.
            let n_workers = global_local_arena().local_worker_count();
            if n < n_workers {
                cooperative_join_n_tree(plan, closures)
            } else {
                cooperative_join_n_flat_mailbox(plan, closures)
            }
        }
    }
}

/// How many jobs a deque fan-out buffers before it publishes, wakes,
/// and switches to the refusing push.
///
/// One slot's worth, so the first publication carries a full
/// cache-line batch rather than a single job.
///
/// Everything before this point sits in the owner's accumulator, so a
/// fan-out that never reaches it is published by the flush below the
/// push loop exactly as before. Everything after is pushed with a
/// bounded push whose refusal the caller runs inline, because the ring
/// holds `ADAPTIVE_SLOT_CAPACITY * 3` jobs and a wider fan-out than
/// that would otherwise spin in `publish` waiting for a consumer that
/// this loop has not yet woken - and cannot wake, because the wake is
/// below it. At 256 slots that bound is 768 jobs, which a 1024-way
/// fan-out exceeds by 255.
const DEQUE_FIRST_BURST: usize = crate::sched::arena_local::JOBS_PER_SLOT;

/// How many times the worker count a fan-out must reach before
/// owner-directed mailbox distribution beats random peer-steal.
///
/// Measured on a 24-worker Zen 4, every width run in both registration
/// orders, comparing the deque fan-out against the routed entry point a
/// caller actually reaches:
///
/// ```text
///    N   xpool   deque    routed   faster
///  512     21   197.77   202.81   deque   by  2.5%
///  640     27   233.15   261.77   deque   by 12.3%
///  768     32   270.85   262.27   routed  by  3.2%
///  896     37   313.77   295.30   routed  by  5.9%
/// 1024     43   384.93   322.43   routed  by 19.4%
/// ```
///
/// Microseconds, mean of both orders. The crossing lies between 640 and
/// 768, so the gate is the first measured width past it. Below it the
/// mailbox path costs 10 to 22 percent at every width from the pool
/// count through 256.
///
/// A multiple of the pool rather than a constant: the crossing is a
/// property of how many workers have to be reached before directed
/// placement repays its cost, so it moves with the pool. The multiple
/// itself is measured on one host and one workload shape, and a host
/// whose sync costs differ will put it elsewhere.
const MAILBOX_GATE_POOL_MULTIPLE: usize = 32;

/// The fan-out width at or above which mailbox mode is chosen.
///
/// Saturating, so a pool count large enough to overflow the multiply
/// yields a gate no fan-out can reach - which selects the deque path,
/// the one that is faster everywhere below the crossing.
#[inline]
fn mailbox_gate(n_workers: usize) -> usize {
    n_workers.saturating_mul(MAILBOX_GATE_POOL_MULTIPLE)
}

/// Every closure run on the calling thread, in caller order: the shape
/// a plan capped at one worker takes in each variant.
fn run_on_caller<R>(closures: Vec<Box<dyn FnOnce() -> R + Send>>) -> Vec<R> {
    closures.into_iter().map(|c| c()).collect()
}

/// Tree-shape cooperative fork-join: balanced binary bisect of
/// `sched::join` calls, depth `log2(N)`. Pick this directly when
/// you know per-closure work is short (sub-100us) and want to
/// skip the probe cost.
///
/// # Determinism contract
///
/// Same as [`cooperative_join_n`]: caller-supplied result order.
///
/// # Algebraic balancing
///
/// The split point is `len / 2` (left-biased on odd N). For
/// `N = 5` this produces the tree `((c0, c1), ((c2, c3), c4))`.
/// The shape is deterministic given N; it does not depend on
/// available worker count.
pub fn cooperative_join_n_tree<R>(
    plan: &JobPlan,
    closures: Vec<Box<dyn FnOnce() -> R + Send>>,
) -> Vec<R>
where
    R: Send + 'static,
{
    if plan.capped_to_caller() {
        return run_on_caller(closures);
    }
    let n = closures.len();
    if n == 0 {
        return Vec::new();
    }
    if n == 1 {
        let mut iter = closures.into_iter();
        let c = iter.next().expect("len == 1 checked");
        return vec![c()];
    }
    if n == 2 {
        let mut iter = closures.into_iter();
        let a = iter.next().expect("len == 2 checked");
        let b = iter.next().expect("len == 2 checked");
        let (ra, rb) = join(plan, a, b);
        return vec![ra, rb];
    }

    let mid = n / 2;
    let mut closures = closures;
    let right = closures.split_off(mid);
    let left = closures;

    let plan_left = *plan;
    let plan_right = *plan;

    let (left_results, right_results) = join(
        plan,
        move || cooperative_join_n_tree::<R>(&plan_left, left),
        move || cooperative_join_n_tree::<R>(&plan_right, right),
    );

    let mut out = left_results;
    out.extend(right_results);
    out
}

/// Flat-shape fork-join over an arbitrary-N closure list. Pushes
/// every closure as one StackJob onto the dispatching worker's
/// local Chase-Lev deque in a single fan-out (critical-path depth
/// 1), then waits on all N latches while participating in
/// work-stealing.
///
/// # When to use
///
/// Pick this when closures are uniformly long (>= 100us each) and
/// N is large enough that the tree's `log2(N)` depth measurably
/// adds to the critical path (typically N >= 12). For short
/// per-closure work or small N, the per-StackJob overhead (one
/// Box alloc + one latch wait per closure) outweighs the saved
/// tree depth; use [`cooperative_join_n`] instead.
///
/// # Determinism contract
///
/// Same as [`cooperative_join_n`]: results returned in caller
/// order regardless of which thread executed which closure.
///
/// # Example
///
/// ```
/// use flynnel::sched::{JobPlan, cooperative_join_n_flat};
///
/// let plan = JobPlan::new(8, 1);
/// let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> =
///     (0..12u32).map(|i| Box::new(move || i * 10) as _).collect();
/// let results = cooperative_join_n_flat(&plan, closures);
/// assert_eq!(results.len(), 12);
/// ```
pub fn cooperative_join_n_flat<R>(
    plan: &JobPlan,
    closures: Vec<Box<dyn FnOnce() -> R + Send>>,
) -> Vec<R>
where
    R: Send + 'static,
{
    if plan.capped_to_caller() {
        return run_on_caller(closures);
    }
    let n = closures.len();
    if n == 0 {
        return Vec::new();
    }
    if n == 1 {
        let mut iter = closures.into_iter();
        let c = iter.next().expect("len == 1 checked");
        return vec![c()];
    }
    if n == 2 {
        let mut iter = closures.into_iter();
        let a = iter.next().expect("len == 2 checked");
        let b = iter.next().expect("len == 2 checked");
        let (ra, rb) = join(plan, a, b);
        return vec![ra, rb];
    }

    // N >= 3: flat fan-out. Pick the in-worker fast path when
    // already on a Flynnel worker; otherwise wrap in a single
    // injected StackJob (mirrors `sched::arena::external_dispatch`)
    // that runs the fan-out from a worker.
    let ctx_ptr = current_worker_ctx();
    if !ctx_ptr.is_null() {
        // SAFETY: `current_worker_ctx` returns a pointer set by
        // `worker_loop` on this same thread; it is valid until
        // `worker_loop` returns.
        let ctx = unsafe { &*ctx_ptr };
        return fan_out_in_worker(ctx, plan, closures, FanOutMode::Deque);
    }
    fan_out_external(plan, closures, FanOutMode::Deque)
}

/// Mailbox-distribute variant of [`cooperative_join_n_flat`]. Each
/// child closure routes directly to a SPECIFIC peer's mailbox via
/// owner-directed distribution (URD-style); the target worker
/// drains its mailbox at the head of `find_work`, so each closure starts
/// on its assigned core with zero shared-deque CAS contention.
///
/// **Use when:** the workload is N uniform-cost independent
/// closures (canonical SIMC pattern) and N >= 3. The mailbox path
/// is the SIMC primitive's structural fit per the Flynn-axis
/// taxonomy (`SIMC = cooperative_join_n + owner-directed
/// distribution`).
///
/// **Use the regular [`cooperative_join_n_flat`] instead when:**
/// closures are heterogeneous (some take longer than others) - the
/// mailbox round-robin doesn't observe per-peer load and can
/// concentrate slow closures on one worker while others idle. The
/// deque variant uses random peer-steal which naturally rebalances.
///
/// # Determinism contract
///
/// Same as [`cooperative_join_n_flat`]: results returned in
/// caller-supplied order regardless of execution order.
pub fn cooperative_join_n_flat_mailbox<R>(
    plan: &JobPlan,
    closures: Vec<Box<dyn FnOnce() -> R + Send>>,
) -> Vec<R>
where
    R: Send + 'static,
{
    if plan.capped_to_caller() {
        return run_on_caller(closures);
    }
    let n = closures.len();
    if n == 0 {
        return Vec::new();
    }
    if n == 1 {
        let mut iter = closures.into_iter();
        let c = iter.next().expect("len == 1 checked");
        return vec![c()];
    }
    if n == 2 {
        let mut iter = closures.into_iter();
        let a = iter.next().expect("len == 2 checked");
        let b = iter.next().expect("len == 2 checked");
        let (ra, rb) = join(plan, a, b);
        return vec![ra, rb];
    }
    let ctx_ptr = current_worker_ctx();
    if !ctx_ptr.is_null() {
        // SAFETY: same as cooperative_join_n_flat.
        let ctx = unsafe { &*ctx_ptr };
        // Mailbox-distribute reaches only the workers it targets, and
        // peer-steal reads deques rather than mailboxes, so a fan-out
        // that does not clear the gate leaves the parent and the
        // untargeted workers idle for the wait. Deque mode keeps them
        // fed, and is faster well past the pool width.
        //
        // The base is the worker count, which is what
        // `fan_out_in_worker` also gates and round-robins on. The
        // stealer table is longer by `EXTERNAL_SLOT_COUNT`.
        let n_workers = ctx.sleep.worker_count();
        let mode = if n >= mailbox_gate(n_workers) {
            FanOutMode::Mailbox
        } else {
            FanOutMode::Deque
        };
        return fan_out_in_worker(ctx, plan, closures, mode);
    }
    // External path: no worker context yet, so the worker count is not
    // reachable here. `fan_out_in_worker` applies `mailbox_gate` when
    // the wrapper lands on a worker and demotes this to Deque itself
    // below it, which is why asking for Mailbox unconditionally here is
    // a request rather than a decision.
    fan_out_external(plan, closures, FanOutMode::Mailbox)
}

/// Cooperative fan-out distribution mode. Selects how the N-1
/// child closures are routed to peer workers in the in-worker
/// fast path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FanOutMode {
    /// All N-1 closures pushed to the calling worker's local
    /// deque (default Public tier). Peer workers pull via random
    /// peer-steal. Matches the historical behavior of
    /// [`cooperative_join_n_flat`] before the mailbox variant
    /// shipped.
    Deque,
    /// Each closure pushed directly to a SPECIFIC peer worker's
    /// mailbox via `WorkerCtx::push_to_mailbox`. Target rotates
    /// starting at `caller.index + 1` (the SMT sibling on the
    /// standard enumeration), skipping self, wrapping around.
    /// The target worker drains its mailbox at the head of `find_work`,
    /// so each closure starts on its assigned core with zero
    /// shared-deque CAS contention. URD-style owner-directed
    /// distribution back-ported in-process.
    ///
    /// Fallback: if a target mailbox is full (bounded at
    /// `MAILBOX_CAPACITY = 16`), the JobRef falls through to
    /// `ctx.push_burst()` so peer-steal still catches it. With
    /// MAILBOX_CAPACITY=16, N up to `n_workers * 16` per call
    /// fits without spilling.
    Mailbox,
}

/// Convenience alias for the boxed-closure shape stored in each
/// `StackJob` for the cooperative fan-out path.
type WrappedClosure<R> = Box<dyn FnOnce(bool) -> R + Send>;

/// Type alias for one StackJobShared in the flat fan-out path. All
/// N-1 share the same `Arc<CountLatch>` so the parent waits on ONE
/// atomic count reaching zero rather than walking N-1 latches.
type FanOutStackJob<R> =
    crate::sched::job::StackJobShared<CountLatch, WrappedClosure<R>, R>;

/// In-worker flat fan-out: build N-1 StackJobs, push them onto
/// the calling worker's local deque (or distribute via mailbox
/// per `mode`), run the last closure inline, then wait on all
/// N-1 latches while participating in stealing.
fn fan_out_in_worker<R>(
    ctx: &WorkerCtx,
    plan: &JobPlan,
    mut closures: Vec<Box<dyn FnOnce() -> R + Send>>,
    mode: FanOutMode,
) -> Vec<R>
where
    R: Send + 'static,
{
    let n = closures.len();
    debug_assert!(n >= 2, "fan_out_in_worker should not see n < 2 (caller branches early)");

    // Pop the last closure for inline execution on this worker
    // while siblings drain the deque. The inline closure keeps
    // the calling worker productively busy and avoids paying a
    // StackJob+latch round-trip for it.
    let last_closure = closures.pop().expect("n >= 2 checked");

    // Build ONE shared CountLatch with count == N-1 (the inline
    // last_closure does NOT decrement; only the dispatched N-1
    // siblings do). The parent waits on the calling worker's own
    // Parker via this latch.
    //
    // CountLatch is the canonical wake-capable N-participant latch
    // at `sched::latch::CountLatch`, and this fan-out is its
    // production consumer: one atomic count gives the parent a
    // single-poll wait surface instead of walking N-1 separate
    // CoreLatches in `is_set` order.
    let n_to_dispatch = closures.len();
    let my_parker: std::sync::Arc<crate::sched::sleep::Parker> = ctx
        .parkers[ctx.index]
        .get()
        .expect("worker parker initialized by worker_loop before any fan_out_in_worker call")
        .clone();
    let shared_latch: std::sync::Arc<CountLatch> =
        std::sync::Arc::new(CountLatch::new(n_to_dispatch, my_parker));
    // Build N-1 StackJobShared in `Box`es so the StackJob memory
    // has a stable heap address. Each StackJob holds an Arc clone
    // of the shared CountLatch.
    let stack_jobs: Vec<Box<FanOutStackJob<R>>> = closures
        .into_iter()
        .map(|c| {
            let wrapped: WrappedClosure<R> = Box::new(move |_stolen| c());
            Box::new(crate::sched::job::StackJobShared::new(
                wrapped,
                shared_latch.clone(),
            ))
        })
        .collect();

    let numa_hint_byte = plan.numa_hint.unwrap_or(NUMA_HINT_ANY as u32) as u8;
    // The count of threads that drain a mailbox, which is the worker
    // count and not `ctx.stealers.len()`. The stealer table carries
    // `EXTERNAL_SLOT_COUNT` further entries for external submitters;
    // a mailbox at one of those indices is popped only by a thread
    // that has claimed that slot, and `find_work` pops `self.mailbox`
    // alone, so a job routed there is not reachable by peer-steal.
    //
    // Both uses below depend on this being the worker count. The
    // round-robin takes its modulus from it, so a larger value spreads
    // targets past the last worker; the gate compares against it, so a
    // larger value also delays the mode that would expose that.
    let n_workers = ctx.sleep.worker_count();
    // Mailbox-distribute gate: mailbox mode leaves the parent and any
    // worker without a target idle for the wait, because peer-steal
    // reads deques rather than mailboxes. Deque mode keeps them fed,
    // so it is the mode below the gate. Mailbox at 8 closures on a
    // 16-worker Ryzen 7 2700 runs 4.4x the deque variant.
    //
    // This is the backstop for the external path, which cannot read a
    // worker count before landing on a worker and so arrives asking for
    // Mailbox at every width.
    let effective_mode = match mode {
        FanOutMode::Mailbox if n < mailbox_gate(n_workers) => FanOutMode::Deque,
        other => other,
    };
    // Wake protocol per mode. Both end in exactly one broadcast and
    // they differ in which call issues it.
    //
    // - Deque mode: no scope. `push_burst` never wakes - it buffers
    //   into the owner accumulator and counts - so `ctx.flush_all()`
    //   below issues the one broadcast, covering every burst push
    //   since the last flush. A deque fan-out's entire wake is that
    //   call, and it is guarded by `DISPATCH_USE_JEC_WAKE`.
    //
    // - Mailbox mode: the scope holds `DISPATCH_USE_JEC_WAKE` false
    //   across the pushes and the flush, so `push_to_mailbox` stays
    //   silent and `flush_all` does not broadcast either; the one
    //   broadcast is issued explicitly after the scope drops. Each
    //   push targets a different mailbox and only the targeted worker
    //   can pop it, so per-push wakes would be n-1 broadcasts each
    //   cascading through every parker. Measured 1.5x -> ~1.0x at
    //   N=16.
    //
    // The scope covers the flush and not the wait loop: it drops
    // before the loop at the bottom so a job executed there pushes
    // under the restored flag.
    let _wake_scope = match effective_mode {
        FanOutMode::Mailbox => {
            // Use new_if_change so we skip the TLS write+drop when
            // the cell already holds `false` (e.g., nested mailbox
            // scopes). Wraps the Option in another Option but the
            // outer Option carries None when the inner is None too.
            crate::sched::arena_local::DispatchScope::new_if_change(false)
        }
        FanOutMode::Deque => None,
    };
    let n_to_push = stack_jobs.len();
    // SAFETY: each StackJob lives in a Box on the heap; the Box
    // is owned by `stack_jobs` which outlives the latch-wait loop
    // below. Each `as_job_ref` returns a JobRef pointing at the
    // StackJob's stable heap address.
    // Producer-fast fan-out: the first `DEQUE_FIRST_BURST` pushes are
    // burst pushes, so they pack into one cache-line slot (K_inner=3
    // amortization), and the flush at that boundary publishes them and
    // broadcasts. Past it the deque arm pushes with the refusing call
    // and runs what it refuses inline, because the burst path spins
    // when the ring is full and the ring holds fewer jobs than a wide
    // fan-out pushes. Mailbox mode bursts throughout; its pushes go to
    // n different mailboxes rather than one ring, so no single buffer
    // fills.
    unsafe {
        for (i, sj) in stack_jobs.iter().enumerate() {
            let r = sj.as_job_ref(plan.k_outer, numa_hint_byte, plan.variant);
            match effective_mode {
                FanOutMode::Deque if i < DEQUE_FIRST_BURST => {
                    ctx.push_burst(r);
                }
                FanOutMode::Deque => {
                    if i == DEQUE_FIRST_BURST {
                        // Publish and broadcast before the ring can
                        // fill. Everything above is still buffered in
                        // the accumulator, so without this the first
                        // job a peer could see is the one flushed
                        // after the whole loop.
                        ctx.flush_all();
                    }
                    if let Err(refused) = ctx.try_push(r) {
                        // The ring is full. Running it here is bounded;
                        // waiting for a slot is not, because every
                        // thief may be a producer in the same state and
                        // the wake that would free one is below this
                        // loop.
                        refused.execute();
                    }
                }
                FanOutMode::Mailbox => {
                    // Round-robin starting at (ctx.index + 1) so
                    // closure[0] goes to the SMT sibling first
                    // (under the standard adjacent-sibling x86
                    // enumeration).
                    let target = if n_workers > 1 {
                        let mut t = (ctx.index + 1 + i) % n_workers;
                        if t == ctx.index {
                            t = (t + 1) % n_workers;
                        }
                        t
                    } else {
                        ctx.index
                    };
                    if target == ctx.index {
                        // Self-push: still burst (the same worker
                        // will pop these immediately after the
                        // wait-loop starts).
                        ctx.push_burst(r);
                    } else if let Err(returned) =
                        ctx.push_to_mailbox(target, r)
                    {
                        // Mailbox full: fall back to burst on our
                        // own deque.
                        ctx.push_burst(returned);
                    }
                }
            }
        }
    }
    // Publishes accumulated bursts so thieves see them as 3-per-slot
    // batches, and in Deque mode issues the fan-out's only wake.
    // Mailbox mode reaches here inside the scope, so this publishes its
    // self-push bursts (the target == ctx.index case) without waking;
    // its mailbox pushes are direct and need no flush.
    ctx.flush_all();
    crate::sched::trace::emit(crate::sched::trace::TraceEvent::JoinPush, n as u32);
    // Drop the wake_scope (if any) so DISPATCH_USE_JEC_WAKE
    // returns to true for subsequent in-wait-loop pushes.
    let needs_batched_broadcast = _wake_scope.is_some();
    drop(_wake_scope);
    // Mailbox mode only: the one broadcast, covering every item pushed
    // silently under the scope. Deque mode has already had its wake
    // from `flush_all` above, whose broadcast was not suppressed
    // because that mode holds no scope.
    if needs_batched_broadcast && n_to_push > 0 {
        ctx.sleep.new_internal_jobs(n_to_push as u32, true);
    }

    // Run the last closure inline. Capture any panic so we still
    // wait on the sibling StackJobs (a panic that escapes here
    // would leave workers reading freed StackJob memory).
    let last_result = panic::catch_unwind(panic::AssertUnwindSafe(last_closure));

    crate::sched::trace::emit(crate::sched::trace::TraceEvent::JoinWaitBegin, n as u32);

    // Wait for the shared CountLatch (count drops to 0 when all
    // N-1 siblings have called Latch::set). Single atomic poll
    // per wait-loop iteration instead of walking N-1 separate
    // latches; same behavior because the original loop exited
    // only when the slowest child finished regardless.
    while !shared_latch.is_set() {
        if let Some(job) = ctx.find_work() {
            // SAFETY: `JobRef::execute` contract: execute exactly
            // once. We just popped this JobRef from the local
            // deque / injector / a peer's deque so we hold the
            // only outstanding reference to it.
            unsafe { job.execute() };
        } else {
            std::thread::yield_now();
        }
    }
    crate::sched::trace::emit(crate::sched::trace::TraceEvent::JoinWaitEnd, n as u32);

    // Collect results in caller order: results from stack_jobs[0..n-1]
    // first, then the inline `last_result`.
    let mut out: Vec<R> = Vec::with_capacity(n);
    for sj in stack_jobs {
        // SAFETY: `latch.is_set()` returned true above, which
        // means `StackJob::execute` already wrote into the
        // result slot. `into_result` consumes the Box's interior.
        out.push(unsafe { (*sj).into_result() });
    }
    match last_result {
        Ok(r) => out.push(r),
        Err(payload) => {
            // Drop the sibling results so their destructors run
            // before we resume the panic.
            drop(out);
            panic::resume_unwind(payload);
        }
    }
    out
}

/// External-entry flat fan-out: wrap the in-worker fan-out in a
/// single StackJob, inject it into the NumaArena, and park the
/// caller until the latch fires. Mirrors the wrapper pattern from
/// [`crate::sched::arena::external_dispatch`].
fn fan_out_external<R>(
    plan: &JobPlan,
    closures: Vec<Box<dyn FnOnce() -> R + Send>>,
    mode: FanOutMode,
) -> Vec<R>
where
    R: Send + 'static,
{
    let arena = global_local_arena();
    // Acquire SMT-sibling guards for the lifetime of the dispatch
    // when the plan asks for SMT participation, the same as
    // `external_dispatch` does for the 2-way join.
    let _smt_guards: Vec<crate::sched::arena_local::SmtGuard> = if plan.effective_use_smt() {
        arena.acquire_smt()
    } else {
        Vec::new()
    };

    // A LockLatch, so the foreign caller blocks on the wrapper's
    // completion instead of polling with park_timeout. Same wiring as
    // arena::external_dispatch: the worker running the wrapper holds a
    // core through the fan-out while the caller waits on the latch.
    let plan_copy = *plan;
    let wrapper = StackJob::new(
        move |_stolen: bool| -> Vec<R> {
            let ctx_ptr = current_worker_ctx();
            debug_assert!(
                !ctx_ptr.is_null(),
                "fan_out_external wrapper must run on a worker thread"
            );
            // SAFETY: ctx_ptr was set by worker_loop on the worker
            // that picked up this wrapper; valid until that
            // worker_loop returns.
            let ctx = unsafe { &*ctx_ptr };
            fan_out_in_worker(ctx, &plan_copy, closures, mode)
        },
        LockLatch::new(),
    );

    let numa_hint_byte = plan.numa_hint.unwrap_or(NUMA_HINT_ANY as u32) as u8;
    // SAFETY: the wrapper lives on this stack frame; we wait on
    // its latch before returning.
    unsafe {
        let r = wrapper.as_job_ref(plan.k_outer, numa_hint_byte, plan.variant);
        arena.submit(r, plan.numa_hint);
    }

    // The same ladder arena::external_dispatch uses: a spin on the
    // latch's fast-path flag catches a fan-out that finishes inside
    // the window, and a longer one falls through to the park.
    const SPIN_CYCLES: usize = 500_000;
    wrapper.latch.wait_spin_then_monitor(SPIN_CYCLES);

    // SAFETY: latch is set => wrapper closure ran to completion
    // and wrote the result slot.
    unsafe { wrapper.into_result() }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU32, Ordering};

    fn plan() -> JobPlan {
        JobPlan::new(8, 1)
    }

    // -----------------------------------------------------------------
    // Tree variant (default): N-way recursive bisect
    // -----------------------------------------------------------------

    #[test]
    fn tree_empty_input_returns_empty_vec() {
        let p = plan();
        let v: Vec<Box<dyn FnOnce() -> u32 + Send>> = Vec::new();
        let results = cooperative_join_n(&p, v);
        assert!(results.is_empty());
    }

    #[test]
    fn tree_one_closure_runs_inline() {
        let p = plan();
        let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> =
            vec![Box::new(|| 42)];
        let results = cooperative_join_n(&p, closures);
        assert_eq!(results, vec![42]);
    }

    #[test]
    fn tree_two_closures_route_through_join() {
        let p = plan();
        let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> =
            vec![Box::new(|| 10), Box::new(|| 20)];
        let results = cooperative_join_n(&p, closures);
        assert_eq!(results, vec![10, 20]);
    }

    #[test]
    fn tree_three_closures_preserve_caller_order() {
        let p = plan();
        let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> = vec![
            Box::new(|| 1),
            Box::new(|| 2),
            Box::new(|| 3),
        ];
        let results = cooperative_join_n(&p, closures);
        assert_eq!(results, vec![1, 2, 3]);
    }

    #[test]
    fn tree_eight_closures_balanced_tree() {
        let p = plan();
        let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> =
            (0..8u32).map(|i| Box::new(move || i * 10) as _).collect();
        let results = cooperative_join_n(&p, closures);
        assert_eq!(results, vec![0, 10, 20, 30, 40, 50, 60, 70]);
    }

    #[test]
    fn tree_sixteen_closures() {
        let p = plan();
        let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> =
            (0..16u32).map(|i| Box::new(move || i) as _).collect();
        let results = cooperative_join_n(&p, closures);
        let expected: Vec<u32> = (0..16u32).collect();
        assert_eq!(results, expected);
    }

    // -----------------------------------------------------------------
    // Flat variant: opt-in, one StackJob per closure
    // -----------------------------------------------------------------

    #[test]
    fn flat_empty_input_returns_empty_vec() {
        let p = plan();
        let v: Vec<Box<dyn FnOnce() -> u32 + Send>> = Vec::new();
        let results = cooperative_join_n_flat(&p, v);
        assert!(results.is_empty());
    }

    #[test]
    fn flat_one_closure_runs_inline() {
        let p = plan();
        let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> =
            vec![Box::new(|| 42)];
        let results = cooperative_join_n_flat(&p, closures);
        assert_eq!(results, vec![42]);
    }

    #[test]
    fn flat_two_closures_route_through_join() {
        let p = plan();
        let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> =
            vec![Box::new(|| 10), Box::new(|| 20)];
        let results = cooperative_join_n_flat(&p, closures);
        assert_eq!(results, vec![10, 20]);
    }

    #[test]
    fn flat_three_closures_preserve_caller_order() {
        let p = plan();
        let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> = vec![
            Box::new(|| 1),
            Box::new(|| 2),
            Box::new(|| 3),
        ];
        let results = cooperative_join_n_flat(&p, closures);
        assert_eq!(results, vec![1, 2, 3]);
    }

    #[test]
    fn flat_twelve_closures_match_xeon_simc_shape() {
        // Same N as the Xeon SIMC bench (`2 * physical_cores = 12`
        // on the 6-physical Xeon). The flat variant is the
        // recommended pick for this shape; the body is large
        // enough (~5ms per closure in the real bench) that the
        // per-StackJob overhead amortizes and the lower
        // critical-path depth wins.
        let p = plan();
        let closures: Vec<Box<dyn FnOnce() -> u64 + Send>> = (0..12u64)
            .map(|i| Box::new(move || {
                let mut v: u64 = i.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
                for _ in 0..200_000u64 {
                    v = v.wrapping_mul(0x9E37_79B9_7F4A_7C15);
                    v ^= v >> 31;
                }
                v
            }) as _)
            .collect();
        let results = cooperative_join_n_flat(&p, closures);
        assert_eq!(results.len(), 12);
        for (i, v) in results.iter().enumerate() {
            assert_ne!(*v, 0, "closure {i} produced zero, body did not run");
        }
    }

    #[test]
    fn flat_sixteen_closures_full_fan_out() {
        let p = plan();
        let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> =
            (0..16u32).map(|i| Box::new(move || i) as _).collect();
        let results = cooperative_join_n_flat(&p, closures);
        let expected: Vec<u32> = (0..16u32).collect();
        assert_eq!(results, expected);
    }

    #[test]
    fn flat_results_in_caller_order_invariant_of_execution_thread() {
        let p = plan();
        let exec_order = Arc::new(AtomicU32::new(0));
        let closures: Vec<Box<dyn FnOnce() -> (u32, u32) + Send>> = (0..8u32)
            .map(|i| {
                let order = Arc::clone(&exec_order);
                Box::new(move || {
                    let run_idx = order.fetch_add(1, Ordering::SeqCst);
                    (i, run_idx)
                }) as _
            })
            .collect();
        let results = cooperative_join_n_flat(&p, closures);
        let caller_indices: Vec<u32> = results.iter().map(|(i, _)| *i).collect();
        assert_eq!(caller_indices, vec![0, 1, 2, 3, 4, 5, 6, 7]);
    }

    #[test]
    fn flat_closures_return_different_types_via_boxed_trait_object() {
        let p = plan();
        let closures: Vec<Box<dyn FnOnce() -> String + Send>> = vec![
            Box::new(|| "alpha".to_string()),
            Box::new(|| "beta".to_string()),
            Box::new(|| "gamma".to_string()),
            Box::new(|| "delta".to_string()),
        ];
        let results = cooperative_join_n_flat(&p, closures);
        assert_eq!(
            results,
            vec![
                "alpha".to_string(),
                "beta".to_string(),
                "gamma".to_string(),
                "delta".to_string(),
            ]
        );
    }

    #[test]
    fn nested_tree_inside_flat_composes() {
        let p = plan();

        let mut outer: Vec<Box<dyn FnOnce() -> Vec<u32> + Send>> =
            Vec::with_capacity(4);
        for o in 0..4u32 {
            let p_inner = p;
            outer.push(Box::new(move || {
                let inner: Vec<Box<dyn FnOnce() -> u32 + Send>> = (0..3u32)
                    .map(|i| Box::new(move || o * 100 + i) as _)
                    .collect();
                cooperative_join_n(&p_inner, inner)
            }));
        }
        let results = cooperative_join_n_flat(&p, outer);
        let flat: Vec<u32> = results.into_iter().flatten().collect();
        assert_eq!(
            flat,
            vec![0, 1, 2, 100, 101, 102, 200, 201, 202, 300, 301, 302]
        );
    }

    #[test]
    fn a_deque_fan_out_wider_than_the_ring_completes() {
        // The ring holds ADAPTIVE_SLOT_CAPACITY * 3 jobs per tier per
        // worker, 768 at 256 slots. A deque fan-out pushes N-1 onto one
        // worker's tier, and the wake sits below the push loop, so a
        // width past that once left the producer spinning in `publish`
        // for a consumer nobody had woken. Observed at 1024: every one
        // of the 1024 closures unstarted, all 24 workers parked, one
        // thread at exactly one core.
        //
        // The width is derived from the ring rather than written as a
        // number, so raising the capacity cannot leave this passing
        // while testing nothing - which is what a hardcoded 2048 would
        // do the moment the ring grew past it.
        //
        // Twice the bound, so the refusing push and the inline run of
        // what it refuses are both exercised well clear of the edge.
        let n = 2 * crate::sched::arena_local::ADAPTIVE_SLOT_CAPACITY
            * crate::sched::arena_local::JOBS_PER_SLOT;
        assert!(
            n > crate::sched::arena_local::ADAPTIVE_SLOT_CAPACITY
                * crate::sched::arena_local::JOBS_PER_SLOT,
            "the fan-out must exceed the ring or this tests nothing"
        );
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let p = JobPlan::new(8, 1);
            let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> = (0..n)
                .map(|i| Box::new(move || i as u32) as _)
                .collect();
            tx.send(cooperative_join_n_flat(&p, closures))
                .expect("the test thread holds the receiver until it times out");
        });
        let results = rx
            .recv_timeout(std::time::Duration::from_secs(60))
            .expect("a deque fan-out wider than the ring must complete");
        assert_eq!(results, (0..n as u32).collect::<Vec<_>>());
    }

    #[test]
    fn the_mailbox_gate_sits_where_the_crossing_was_measured() {
        // The band between the pool count and the gate is the one the
        // deque fan-out wins, by 2 to 22 percent across every width
        // measured in it. A gate at the pool count hands that band to
        // the mailbox path, which is what this pins against.
        assert_eq!(mailbox_gate(24), 768, "24 workers, the measured host");
        assert!(
            mailbox_gate(24) > 640,
            "640 is the widest fan-out measured with deque still ahead"
        );

        // Saturating rather than wrapping: an overflowing pool count
        // must yield a gate no fan-out reaches, which selects deque -
        // the mode that is faster everywhere below the crossing. A wrap
        // would yield a small gate and select mailbox everywhere.
        assert_eq!(mailbox_gate(usize::MAX), usize::MAX);
    }

    #[test]
    fn flat_mailbox_completes_once_its_gate_opens() {
        // Mailbox mode engages at `mailbox_gate` and routes each closure
        // to one worker's mailbox. `find_work` pops only the worker's
        // own mailbox and peer-steal reads deques, so a closure routed
        // to an index past the last worker is never executed and the
        // join's CountLatch never reaches zero.
        //
        // N clears the gate and also clears the stealer table's width,
        // which is where a round-robin first covers every external slot.
        // Deriving it from `mailbox_gate` rather than from a width that
        // happened to be above the gate keeps this exercising the
        // mailbox path when the gate moves; a width below it takes the
        // deque path and passes without testing any of the above.
        //
        // The join runs on its own thread so a failure is a timeout
        // rather than a hung test binary.
        let n = mailbox_gate(global_local_arena().local_worker_count()).max(
            global_local_arena().total_workers()
                + crate::sched::arena_local::EXTERNAL_SLOT_COUNT,
        );
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let p = JobPlan::new(8, 1);
            let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> = (0..n)
                .map(|i| Box::new(move || i as u32) as _)
                .collect();
            tx.send(cooperative_join_n_flat_mailbox(&p, closures))
                .expect("the test thread holds the receiver until it times out");
        });
        let results = rx
            .recv_timeout(std::time::Duration::from_secs(60))
            .expect("mailbox fan-out at N >= worker count must complete");
        assert_eq!(results, (0..n as u32).collect::<Vec<_>>());
    }

    #[test]
    fn flat_mailbox_completes_after_a_foreign_pool_has_run() {
        // A mailbox fan-out completes only when every targeted worker
        // drains its own mailbox: peer-steal reads deques and cannot
        // reach a closure sitting in one, so a worker that does not run
        // leaves the join's CountLatch permanently short.
        //
        // rayon::scope brings up its own pool sized to the machine,
        // which competes with this arena's workers for cores. N is the
        // gate itself, the narrowest width that reaches mailbox mode.
        //
        // The join runs on its own thread so a failure to complete is a
        // timeout rather than a hung test binary.
        let n = mailbox_gate(global_local_arena().local_worker_count());

        let mut warm: Vec<u64> = (0..n as u64).collect();
        rayon::scope(|s| {
            for slot in warm.iter_mut() {
                s.spawn(move |_| {
                    *slot = slot.wrapping_mul(0x100000001B3);
                });
            }
        });
        std::hint::black_box(&warm);

        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let p = JobPlan::new(8, 1);
            let closures: Vec<Box<dyn FnOnce() -> u32 + Send>> = (0..n)
                .map(|i| Box::new(move || i as u32) as _)
                .collect();
            tx.send(cooperative_join_n_flat_mailbox(&p, closures))
                .expect("the test thread holds the receiver until it times out");
        });
        let results = rx
            .recv_timeout(std::time::Duration::from_secs(60))
            .expect("mailbox fan-out must complete after a foreign pool has run");
        assert_eq!(results, (0..n as u32).collect::<Vec<_>>());
    }

    /// A worker cap of one runs `sched::join` and every cooperative
    /// variant on the calling thread, under a plan whose tier without
    /// the cap is the pool's, so the cap is what keeps them there.
    #[test]
    fn a_worker_cap_of_one_keeps_every_join_on_the_calling_thread() {
        use crate::numa_topology::numa_topology;
        use crate::sched::plan::{SchedTier, pick_tier};
        use std::thread::ThreadId;

        let uncapped = JobPlan::new(6, 4096);
        assert_ne!(
            pick_tier(&uncapped, numa_topology()),
            SchedTier::Inline,
            "without its cap the plan must reach the pool, or this test cannot see the cap"
        );
        let capped = uncapped.with_workers(1);
        let caller = std::thread::current().id();

        let halves = join(
            &capped,
            || std::thread::current().id(),
            || std::thread::current().id(),
        );
        assert_eq!(
            halves,
            (caller, caller),
            "sched::join ran a half off the calling thread"
        );

        type Shape = fn(&JobPlan, Vec<Box<dyn FnOnce() -> ThreadId + Send>>) -> Vec<ThreadId>;
        let shapes: [(&str, Shape); 4] = [
            ("cooperative_join_n", cooperative_join_n),
            ("cooperative_join_n_tree", cooperative_join_n_tree),
            ("cooperative_join_n_flat", cooperative_join_n_flat),
            (
                "cooperative_join_n_flat_mailbox",
                cooperative_join_n_flat_mailbox,
            ),
        ];
        for (name, run) in shapes {
            let closures: Vec<Box<dyn FnOnce() -> ThreadId + Send>> = (0..64)
                .map(|_| Box::new(|| std::thread::current().id()) as _)
                .collect();
            let ids = run(&capped, closures);
            assert_eq!(ids.len(), 64, "{name} returned every result");
            let elsewhere = ids.iter().filter(|&&id| id != caller).count();
            assert_eq!(
                elsewhere, 0,
                "{name} ran {elsewhere} of 64 closures off the calling thread"
            );
        }
    }
}