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
//! URD: UMWAIT Rendezvous Deque, MMF-backed.
//!
//! Per-thief mailbox cache lines instead of a shared deque. Each
//! mailbox is one 64-byte line carrying state (8 B) + `MAILBOX_ITEMS
//! = 3` line items (48 B) + 8 B trailing padding. The owner picks a
//! mailbox by round-robin (or by an explicit thief target) and
//! writes the items in; the addressed thief observes the
//! cache-line transition and reads its items. There is **no
//! shared head/tail counter on the steal path** - each thief has
//! its own state byte and never CASes a contended atomic.
//!
//! ## Wait strategy: a spin floor, then whatever monitor the host has
//!
//! Thieves idle on their mailbox's state byte. Every wait begins with
//! [`SPIN_BEFORE_WAIT`] polls, so a publish already in flight is
//! caught at spin latency and reaches no monitor at all. What follows
//! the floor is chosen at runtime from CPUID:
//!
//! - **WAITPKG available** (Intel Tremont/Tiger Lake+, AMD Zen 5+):
//!   `UMONITOR` + `UMWAIT` halt until the cache line transitions OR a
//!   TSC deadline fires. Power-efficient; the thief doesn't burn
//!   pipeline slots polling.
//! - **MONITORX available** (AMD 2015+, everything before Zen 5):
//!   `MONITORX` + `MWAITX` on the same terms.
//! - **Neither**: [`std::hint::spin_loop`] (PAUSE on x86) in a tight
//!   Acquire-load loop on the state byte.
//!
//! All three end the wait when `state` carries the ready bit for the
//! expected epoch.
//!
//! What the second stage buys is a core it stops occupying, and that
//! is measured by the co-runner group in `benches/urd_thief_wait.rs`,
//! which times the thief's neighbors rather than the thief. Until
//! that group has run on a host, the choice above rests on the
//! instruction being present and not on it being cheaper there:
//! [`crate::sched::sleep::WaitController`] found the same monitor
//! wait four to fourteen times better on one part and twenty times
//! worse on another. Nothing here calls [`UrdDeque::wait_and_drain`]
//! yet except that bench.
//!
//! ## Why this shape vs Chase-Lev / LOH / KHPD
//!
//! Chase-Lev / LOH / KHPD are *pull-based*: thieves CAS the deque
//! to discover work. URD is *push-based*: the owner picks the
//! target thief by writing its mailbox. Two architectural
//! consequences:
//!
//! 1. **No CAS contention at the steal site.** N thieves on a
//!    shared deque CAS the same head; under contention each push
//!    racing N thieves can take O(N) failed CASes. URD's per-thief
//!    mailbox has zero contention because the owner is the only
//!    writer and the thief is the only reader.
//! 2. **Owner-controlled distribution.** Round-robin / locality-
//!    aware / variance-driven targeting is the owner's choice, not
//!    a thief's victim-pick. The orchestrator gets explicit say in
//!    which thief does what.
//!
//! Trade-offs: the thief is bound to one mailbox (no work-stealing
//! between mailboxes), the owner pays one mailbox-spin per publish
//! if the previous batch hasn't been consumed yet, and the
//! per-mailbox slot count is fixed.

#![allow(clippy::missing_errors_doc)]

use std::fs::{File, OpenOptions};
use std::io;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};

use memmap2::{MmapMut, MmapOptions};

use super::khpd::LineItem;
use crate::cpu_info::{has_monitorx, has_waitpkg};

/// Magic byte sequence marking a valid URD file. ASCII "FURD".
pub const URD_MAGIC: u64 = 0x4655_5244_0000_0001;

/// Cache line size; one mailbox per cache line.
pub const URD_MAILBOX_SIZE: usize = 64;

/// Items per mailbox: state (8 B) + 3 * 16 = 56 B; 8 B trailing pad.
pub const MAILBOX_ITEMS: usize = 3;

/// Wait strategy chosen at runtime per CPUID.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WaitStrategy {
    /// `std::hint::spin_loop` (PAUSE on x86). Universally available
    /// fallback.
    PauseSpin,
    /// `UMONITOR` + `UMWAIT`. Available on Intel Tremont/Tiger Lake+
    /// and AMD Zen 5+; detected via CPUID leaf 7 ECX bit 5.
    Waitpkg,
    /// `MONITORX` + `MWAITX`. Available on AMD from Excavator
    /// onward, so on every Zen; detected via CPUID Fn8000_0001
    /// ECX bit 29.
    Monitorx,
}

/// Polls a thief spins before it hands the core back.
///
/// The first stage of [`UrdDeque::wait_and_drain`]. A publish already
/// in flight lands inside this for a few hundred nanoseconds of
/// spinning; a wait that outlasts it was going to be expensive
/// whatever the thief did, and is better spent not holding a logical
/// CPU. Same order as the parker's spin floor.
pub const SPIN_BEFORE_WAIT: u32 = 512;

impl WaitStrategy {
    /// What a thief waits on after its spin floor: the best monitor
    /// wait this host has, or more spinning where it has none.
    ///
    /// # This does not compete with the spin
    ///
    /// The spin runs first and always, and is what makes a short wait
    /// fast. This is the second stage and its job is to stop a long
    /// wait holding a core. They are stages rather than alternatives,
    /// so a measurement that ranks one against the other is answering
    /// a question neither of them poses.
    ///
    /// Measured on a 7900X with NO floor, so the monitor wait was
    /// doing the spin's job as well as its own, publish to drained,
    /// best median of three:
    ///
    /// ```text
    ///                PAUSE-spin   MONITORX
    ///   idle   50us     1.54 us    2.00 us
    ///   idle  500us     1.69 us    1.60 us
    ///   load   50us     1.66 us    1.92 us
    ///   load  500us     1.63 us    1.85 us
    /// ```
    ///
    /// Slower in three cells of four, which is what a monitor wait
    /// costs when it has to catch wakes the spin would have caught.
    /// With the floor in front of it those never reach it.
    ///
    /// # What it gives back is narrower than a core
    ///
    /// A `PAUSE`-spin issues into the pipeline the whole time it
    /// waits, so it takes both the physical core's execution
    /// resources and a logical CPU the operating system could have
    /// given to something else. `MWAITX` halts the logical processor,
    /// which hands the physical core's issue width to its SMT
    /// sibling. It does not deschedule the thread: the kernel still
    /// counts it as occupying that logical CPU, so a runnable thread
    /// elsewhere on the machine does not get one from it.
    ///
    /// Those are different gifts. The first is real for a sibling
    /// sharing the core; the second is what a pool with more
    /// runnable work than CPUs actually wants, and the monitor wait
    /// does not supply it. Which one a host needs depends on the
    /// workload rather than on the instruction.
    ///
    /// The co-runner group in `benches/urd_thief_wait.rs` is what
    /// measures this, not the rows above, which time the thief
    /// rather than its neighbors. It oversubscribes deliberately,
    /// one neighbor per logical CPU, because that is the
    /// arrangement in which the difference has somewhere to show.
    /// It has not run on any host.
    pub fn pick() -> Self {
        if has_waitpkg() {
            Self::Waitpkg
        } else if has_monitorx() {
            Self::Monitorx
        } else {
            Self::PauseSpin
        }
    }
}

/// State word packed-bit layout: top 32 bits = epoch, bits 16..32 =
/// n_items, bits 0..16 = claim (0 = EMPTY, 1 = READY).
const STATE_EMPTY: u64 = 0;
const CLAIM_READY: u64 = 1;

/// Header sits at file offset 0.
#[repr(C, align(64))]
pub struct UrdHeader {
    /// Magic constant.
    pub magic: u64,
    /// Number of mailboxes (one per thief).
    pub n_mailboxes: u64,
    /// Pid of the owner process; informational. Cleared on
    /// `close_owner()`.
    pub owner_pid: AtomicU64,
    /// Shutdown epoch counter.
    pub epoch: AtomicU64,
    /// Padding to push `rr_cursor` to its own cache line.
    pub _pad_meta: [u8; 24],
    /// Round-robin cursor the owner uses to pick the next target
    /// mailbox when no explicit target is supplied.
    pub rr_cursor: AtomicU64,
    /// Padding to round to two cache lines.
    pub _pad_rr: [u8; 56],
}

/// One per-thief mailbox cache line.
#[repr(C, align(64))]
pub struct Mailbox {
    /// State word: `(epoch:32) << 32 | (n_items:16) << 16 | claim:16`.
    pub state: AtomicU64,
    /// Inline items.
    pub items: [LineItem; MAILBOX_ITEMS],
    /// Trailing padding.
    pub _pad: [u8; 8],
}

/// Total file size for a URD with `n_mailboxes` mailboxes.
pub const fn urd_file_size(n_mailboxes: usize) -> usize {
    std::mem::size_of::<UrdHeader>() + n_mailboxes * URD_MAILBOX_SIZE
}

/// Outcome of [`UrdDeque::publish_to`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PublishError {
    /// Caller-supplied target mailbox index is out of range.
    BadTarget(usize),
    /// More items than [`MAILBOX_ITEMS`] passed in one publish call.
    TooManyItems,
    /// Args payload exceeded [`super::khpd::KHPD_ARGS_INLINE_BYTES`].
    PayloadTooLarge,
}

/// Outcome of [`UrdDeque::drain_mailbox`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Drain {
    /// Got items.
    Success(DrainResult),
    /// Mailbox empty (no published items past this thief's last
    /// consume).
    Empty,
}

/// Items pulled from a mailbox.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DrainResult {
    /// How many of the `items` slots are filled.
    pub n_items: usize,
    /// The items.
    pub items: [LineItem; MAILBOX_ITEMS],
}

/// MMF-backed URD. Single owner, N pre-configured thieves.
pub struct UrdDeque {
    _file: File,
    mmap: MmapMut,
    n_mailboxes: usize,
    wait_strategy: WaitStrategy,
}

// SAFETY: All fields are Send. The mmap handle is Send+Sync per
// memmap2. Every mailbox access goes through the per-mailbox
// state-atomic protocol.
unsafe impl Send for UrdDeque {}
// SAFETY: same justification as the Send impl directly above.
unsafe impl Sync for UrdDeque {}

impl UrdDeque {
    /// Create a fresh URD file with `n_mailboxes` mailboxes (one
    /// per intended thief). Minimum 1. The round-robin cursor
    /// reduces modulo `n_mailboxes` (no pow2 requirement so a
    /// single-thief bench can use n=1).
    pub fn create<P: AsRef<Path>>(path: P, n_mailboxes: usize) -> io::Result<Self> {
        let n_mailboxes = n_mailboxes.max(1);
        let size = urd_file_size(n_mailboxes);

        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(path.as_ref())?;
        file.set_len(size as u64)?;

        // SAFETY: `map_mut` is unsafe because the kernel cannot
        // prevent another process from truncating the file. This
        // call site upholds the soundness contract by writing only
        // through the per-mailbox state-atomic protocol.
        let mut mmap = unsafe { MmapOptions::new().len(size).map_mut(&file)? };

        let header_ptr = mmap.as_mut_ptr() as *mut UrdHeader;
        // SAFETY: mmap is page-aligned (>= 64-byte alignment); the
        // map covers `urd_file_size(n_mailboxes)` bytes by
        // construction.
        unsafe {
            (*header_ptr).magic = URD_MAGIC;
            (*header_ptr).n_mailboxes = n_mailboxes as u64;
            (*header_ptr).owner_pid = AtomicU64::new(std::process::id() as u64);
            (*header_ptr).epoch = AtomicU64::new(0);
            std::ptr::write_bytes((*header_ptr)._pad_meta.as_mut_ptr(), 0, 24);
            (*header_ptr).rr_cursor = AtomicU64::new(0);
            std::ptr::write_bytes((*header_ptr)._pad_rr.as_mut_ptr(), 0, 56);
        }

        // Zero all mailboxes (state == STATE_EMPTY).
        let mailboxes_start = std::mem::size_of::<UrdHeader>();
        // SAFETY: write_bytes covers the unwritten tail of the map.
        unsafe {
            std::ptr::write_bytes(
                mmap.as_mut_ptr().add(mailboxes_start),
                0,
                n_mailboxes * URD_MAILBOX_SIZE,
            );
        }

        mmap.flush()?;
        let wait_strategy = WaitStrategy::pick();
        Ok(Self {
            _file: file,
            mmap,
            n_mailboxes,
            wait_strategy,
        })
    }

    /// Open an existing URD file.
    pub fn open<P: AsRef<Path>>(path: P) -> io::Result<Self> {
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(path.as_ref())?;
        let size = file.metadata()?.len() as usize;
        if size < std::mem::size_of::<UrdHeader>() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "urd file too small",
            ));
        }
        // SAFETY: same protocol-only-access justification as `create`.
        let mmap = unsafe { MmapOptions::new().len(size).map_mut(&file)? };
        let header_ptr = mmap.as_ptr() as *const UrdHeader;
        // SAFETY: map size verified to cover header.
        let (magic, n_mailboxes) =
            unsafe { ((*header_ptr).magic, (*header_ptr).n_mailboxes as usize) };
        if magic != URD_MAGIC {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("urd magic mismatch {magic:#x}"),
            ));
        }
        if n_mailboxes == 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "urd n_mailboxes must be >= 1",
            ));
        }
        if size < urd_file_size(n_mailboxes) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "urd file size below header expected",
            ));
        }
        let wait_strategy = WaitStrategy::pick();
        Ok(Self {
            _file: file,
            mmap,
            n_mailboxes,
            wait_strategy,
        })
    }

    /// Number of configured mailboxes.
    pub fn n_mailboxes(&self) -> usize {
        self.n_mailboxes
    }

    /// Wait strategy this URD instance picked (per CPUID).
    pub fn wait_strategy(&self) -> WaitStrategy {
        self.wait_strategy
    }

    /// Override the wait strategy for benches and tests that need to
    /// A/B against the auto-picked one.
    ///
    /// The thief's choice is the one worth measuring rather than
    /// assuming: a `PAUSE`-spin is already the fastest wake there is,
    /// because it never stopped looking, so replacing it with a
    /// monitor wait trades some of that latency for a core it stops
    /// occupying. Which way that comes out is a property of the host
    /// and cannot be read off the instruction set.
    ///
    /// # Panics
    ///
    /// Panics on a strategy this host cannot execute, since the
    /// alternative is a `#UD` inside the steal path with nothing to
    /// say which caller asked for it.
    pub fn set_wait_strategy(&mut self, strategy: WaitStrategy) {
        match strategy {
            WaitStrategy::Waitpkg => assert!(
                has_waitpkg(),
                "this host has no WAITPKG, so UMONITOR would be an illegal instruction"
            ),
            WaitStrategy::Monitorx => assert!(
                has_monitorx(),
                "this host has no MONITORX, so MONITORX would be an illegal instruction"
            ),
            WaitStrategy::PauseSpin => {}
        }
        self.wait_strategy = strategy;
    }

    /// Owner pid at create time, or 0 after `close_owner()`.
    pub fn owner_pid(&self) -> u64 {
        self.header().owner_pid.load(Ordering::Acquire)
    }

    /// Owner shutdown: zero pid + advance epoch.
    pub fn close_owner(&self) {
        self.header().owner_pid.store(0, Ordering::Release);
        self.header().epoch.fetch_add(1, Ordering::Release);
    }

    fn header(&self) -> &UrdHeader {
        // SAFETY: header is at the start of the map.
        unsafe { &*(self.mmap.as_ptr() as *const UrdHeader) }
    }

    fn mailbox_ptr(&self, idx: usize) -> *mut Mailbox {
        let off = std::mem::size_of::<UrdHeader>() + idx * URD_MAILBOX_SIZE;
        // SAFETY: idx < n_mailboxes by caller contract; `off` is
        // in-bounds + 64-byte aligned.
        unsafe { self.mmap.as_ptr().add(off) as *mut Mailbox }
    }

    fn mailbox(&self, idx: usize) -> &Mailbox {
        // SAFETY: same as mailbox_ptr.
        unsafe { &*self.mailbox_ptr(idx) }
    }

    /// Owner-side: publish `items` to mailbox `target`. Spins until
    /// the mailbox is EMPTY (the previous batch has been consumed),
    /// writes items, Release-stores state to READY. Returns the
    /// number of items published.
    pub fn publish_to(
        &self,
        target: usize,
        items: &[LineItem],
    ) -> Result<usize, PublishError> {
        if target >= self.n_mailboxes {
            return Err(PublishError::BadTarget(target));
        }
        if items.len() > MAILBOX_ITEMS {
            return Err(PublishError::TooManyItems);
        }
        if items.is_empty() {
            return Ok(0);
        }
        let mb = self.mailbox(target);
        // Spin-wait for the mailbox to be EMPTY (previous batch
        // consumed). The owner is on the WRITE side so a brief
        // PAUSE-spin is the right primitive here regardless of the
        // thief's WAITPKG availability.
        loop {
            let s = mb.state.load(Ordering::Acquire);
            if s == STATE_EMPTY {
                break;
            }
            std::hint::spin_loop();
        }
        // Write items.
        // SAFETY: mailbox is in-bounds + aligned; we have exclusive
        // access until the Release-store below transitions state to
        // READY.
        unsafe {
            let mb_ptr = self.mailbox_ptr(target);
            for (i, item) in items.iter().enumerate() {
                (*mb_ptr).items[i] = *item;
            }
        }
        let epoch = self.header().epoch.load(Ordering::Relaxed);
        let new_state = (epoch << 32) | ((items.len() as u64) << 16) | CLAIM_READY;
        mb.state.store(new_state, Ordering::Release);
        Ok(items.len())
    }

    /// Owner-side: publish `items` to the next round-robin mailbox.
    /// Returns `(target, n_published)`.
    pub fn publish_round_robin(
        &self,
        items: &[LineItem],
    ) -> Result<(usize, usize), PublishError> {
        let cursor = self.header().rr_cursor.fetch_add(1, Ordering::Relaxed) as usize;
        // Use modulo (not bit-mask) so non-pow2 mailbox counts work;
        // common case is `n_mailboxes` being a small constant the
        // compiler reduces to a strength-reduced multiply.
        let target = cursor % self.n_mailboxes;
        let n = self.publish_to(target, items)?;
        Ok((target, n))
    }

    /// Thief-side: drain own mailbox if it has READY items.
    /// `mailbox_idx` is the thief's pre-assigned mailbox. Returns
    /// [`Drain::Empty`] when the state byte is EMPTY (no work
    /// published yet).
    pub fn drain_mailbox(&self, mailbox_idx: usize) -> Drain {
        if mailbox_idx >= self.n_mailboxes {
            return Drain::Empty;
        }
        let mb = self.mailbox(mailbox_idx);
        let s = mb.state.load(Ordering::Acquire);
        if s & 0xFFFF != CLAIM_READY {
            return Drain::Empty;
        }
        let n_items = ((s >> 16) & 0xFFFF) as usize;
        let n_items = n_items.min(MAILBOX_ITEMS);
        // SAFETY: state's READY bit is set; the publisher's Release-
        // store synchronizes-with our Acquire-load above so item
        // bytes are visible.
        let result = unsafe {
            DrainResult {
                n_items,
                items: (*self.mailbox_ptr(mailbox_idx)).items,
            }
        };
        // Release the mailbox: state -> EMPTY. The owner's next
        // publish_to(target) spin sees EMPTY and writes.
        mb.state.store(STATE_EMPTY, Ordering::Release);
        Drain::Success(result)
    }

    /// Thief-side: block until the mailbox transitions to READY,
    /// then drain it.
    ///
    /// # A spin floor, then a wait that gives the core back
    ///
    /// The two are not alternatives and choosing between them was the
    /// mistake. A `PAUSE`-spin is the fastest wake there is, because
    /// it never stopped looking, and it is also the most expensive
    /// way to be idle, because it holds a logical CPU and issues into
    /// the pipeline for as long as it waits. Which matters depends
    /// entirely on how long this particular wait turns out to be, and
    /// that is not knowable when it starts.
    ///
    /// So the thief spins for [`SPIN_BEFORE_WAIT`] polls, which
    /// covers a publish already in flight at the cost of a few
    /// hundred nanoseconds, and then hands the core back through
    /// whatever monitor wait the host has. A wait that ends quickly
    /// never reaches the second stage; one that does not was going to
    /// be expensive either way and now costs a core less. This is the
    /// shape [`crate::sched::sleep::Parker`] already uses, where the
    /// spin floor precedes the park.
    ///
    /// Measured against the unbounded spin on a 7900X, publish to
    /// drained, the monitor wait alone was slower in three cells of
    /// four (1.54 against 2.00 us idle at a 50 us inter-arrival).
    /// That measured the first stage's job and said nothing about the
    /// second's, which is the core a long wait returns; the spin
    /// floor keeps the former and the monitor wait supplies the
    /// latter.
    ///
    /// `deadline_tsc` bounds a single monitor wait, not the call:
    /// `u64::MAX` means no bound, and the loop re-checks the state
    /// byte after every wait however it ended.
    pub fn wait_and_drain(&self, mailbox_idx: usize, deadline_tsc: u64) -> Drain {
        if mailbox_idx >= self.n_mailboxes {
            return Drain::Empty;
        }
        let mb = self.mailbox(mailbox_idx);
        let state_addr = (&raw const mb.state).cast::<u8>();
        let mut spins = 0u32;
        loop {
            let s = mb.state.load(Ordering::Acquire);
            if s & 0xFFFF == CLAIM_READY {
                break;
            }
            // The floor: a publish already on its way lands here and
            // the thief never reaches a monitor wait at all.
            if spins < SPIN_BEFORE_WAIT {
                spins += 1;
                std::hint::spin_loop();
                continue;
            }

            match self.wait_strategy {
                WaitStrategy::PauseSpin => std::hint::spin_loop(),
                WaitStrategy::Waitpkg => {
                    // SAFETY: WAITPKG was confirmed available by
                    // CPUID at construction time. `state_addr` is a
                    // valid pointer into the mmap; UMONITOR arms the
                    // hardware monitor on its cache line. UMWAIT
                    // suspends until the monitor fires, an interrupt
                    // arrives, or the TSC deadline is reached. The
                    // double-check on the next loop iteration
                    // re-validates the state byte.
                    unsafe { wait_with_waitpkg(state_addr, deadline_tsc) };
                }
                WaitStrategy::Monitorx => {
                    // SAFETY: MONITORX was confirmed available by
                    // CPUID at construction time. Same pointer and
                    // same double-check as the WAITPKG arm; MWAITX
                    // suspends on the same terms, and returning early
                    // costs one more turn of this loop.
                    unsafe { wait_with_monitorx(state_addr, deadline_tsc) };
                }
            }
        }
        self.drain_mailbox(mailbox_idx)
    }

    /// Force any dirty pages to disk.
    pub fn flush_to_disk(&self) -> io::Result<()> {
        self.mmap.flush()
    }
}

/// `UMONITOR` + `UMWAIT` wait primitive. Halts the calling logical
/// CPU until the monitored cache line transitions OR the TSC
/// reaches `deadline_tsc` (whichever comes first). Pass
/// `deadline_tsc = u64::MAX` for "no deadline".
///
/// # Safety
///
/// The caller must have confirmed WAITPKG is available via
/// [`crate::cpu_info::has_waitpkg`] - executing `UMONITOR` /
/// `UMWAIT` on hardware without WAITPKG raises an illegal-
/// instruction trap (`#UD`).
///
/// `state_addr` must be a valid pointer into accessible memory;
/// `UMONITOR` reads no payload, only the address.
#[cfg(target_arch = "x86_64")]
#[inline(always)]
unsafe fn wait_with_waitpkg(state_addr: *const u8, deadline_tsc: u64) {
    use std::arch::asm;
    let lo = deadline_tsc as u32;
    let hi = (deadline_tsc >> 32) as u32;
    // Two separate asm blocks: UMONITOR needs the address in RAX,
    // UMWAIT needs EAX (low half of RAX) for the deadline low
    // dword. We cannot bind RAX and EAX to different values in
    // one asm! call, so we split. The monitor stays armed across
    // the second asm block; UMWAIT in C0.1 (hint = 1) is the light
    // wait state with low wake latency.
    //
    // SAFETY: caller-asserted WAITPKG availability + valid pointer.
    unsafe {
        asm!(
            "umonitor rax",
            in("rax") state_addr,
            options(nostack, preserves_flags),
        );
        asm!(
            "umwait {hint:e}",
            hint = in(reg) 1u32,
            in("eax") lo,
            in("edx") hi,
            options(nostack),
        );
    }
}

#[cfg(not(target_arch = "x86_64"))]
#[inline(always)]
unsafe fn wait_with_waitpkg(_state_addr: *const u8, _deadline_tsc: u64) {
    // Non-x86_64: WAITPKG cannot be available; this function is
    // never called on those targets (the WaitStrategy::Waitpkg
    // branch is gated on has_waitpkg() which returns false).
    std::hint::spin_loop();
}

/// `MONITORX` + `MWAITX` wait primitive, AMD's user-mode pair.
/// Halts the calling logical core until the monitored line
/// transitions, an interrupt arrives, or the timer runs out.
///
/// Takes the same absolute `deadline_tsc` the WAITPKG primitive
/// takes and converts it, because MWAITX counts a relative number
/// of EBX units rather than reaching a TSC value. The conversion
/// passes the remaining cycle count through unscaled, which is
/// deliberate: an EBX unit is never longer than a TSC cycle (on a
/// Ryzen 9 7900X it is half of one), so the wait can only end at or
/// before the deadline, never after it. Undershooting costs another
/// turn of the caller's loop; overshooting would hold a thief past
/// a deadline it was given. That asymmetry is why this does not try
/// to measure the ratio and correct for it.
///
/// # Safety
///
/// Caller must have confirmed MONITORX via
/// [`crate::cpu_info::has_monitorx`] - executing `MONITORX` /
/// `MWAITX` without it raises an illegal-instruction trap (`#UD`).
///
/// `state_addr` must be a valid pointer into accessible memory;
/// `MONITORX` reads no payload, only the address.
#[cfg(target_arch = "x86_64")]
#[inline(always)]
unsafe fn wait_with_monitorx(state_addr: *const u8, deadline_tsc: u64) {
    use std::arch::asm;

    // SAFETY: `_rdtsc` is a no-side-effect read of the TSC counter.
    let now = unsafe { std::arch::x86_64::_rdtsc() };
    // A deadline already past asks for the shortest wait the timer
    // can express rather than the longest, which is what a zero
    // would otherwise be read as.
    let remaining = deadline_tsc.saturating_sub(now).max(1);
    let ask = u32::try_from(remaining).unwrap_or(u32::MAX);

    // Split for the same reason the WAITPKG pair is split: MONITORX
    // needs the address in RAX and MWAITX needs EAX for its hints,
    // and one asm! call cannot bind both. The monitor stays armed
    // across the two blocks.
    //
    // Encoded as bytes because the mnemonics need a target feature
    // this crate does not set; the encodings are fixed.
    //
    // SAFETY: caller-asserted MONITORX availability + valid pointer.
    unsafe {
        // The zeros arrive as operands rather than through `xor`,
        // because `xor` writes flags and this block promises not to.
        // MONITORX itself leaves them alone, so the promise holds
        // only while no instruction here breaks it.
        asm!(
            ".byte 0x0f, 0x01, 0xfa",
            in("rax") state_addr,
            in("ecx") 0u32,
            in("edx") 0u32,
            options(nostack, preserves_flags),
        );
        // EAX[7:4] is the requested C-state minus one, so 0xF0 asks
        // for C0, matching the WAITPKG arm's C0.1 hint; ECX bit 1
        // enables the EBX timer and EBX carries the count, which
        // `remaining` floors at one because a zero count with that bit
        // set is an unbounded wait on Zen 1 and Zen+.
        //
        // rbx is reserved by LLVM and cannot be an operand, so it is
        // saved and restored inside the block. That is why this one
        // does not claim `nostack`: it pushes, and a red zone below
        // rsp would be live under that promise. MWAITX reports
        // timer-versus-wake exit in CF, so flags are not preserved
        // either.
        asm!(
            "push rbx",
            "mov ebx, {ask:e}",
            ".byte 0x0f, 0x01, 0xfb",
            "pop rbx",
            ask = in(reg) ask,
            inout("eax") 0xF0u32 => _,
            inout("ecx") 2u32 => _,
        );
    }
}

#[cfg(not(target_arch = "x86_64"))]
#[inline(always)]
unsafe fn wait_with_monitorx(_state_addr: *const u8, _deadline_tsc: u64) {
    // Non-x86_64: MONITORX cannot be available, for the same reason
    // the WAITPKG stub above is never called.
    std::hint::spin_loop();
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::sync::atomic::Ordering as O;
    use std::thread;

    fn temp_path(name: &str) -> std::path::PathBuf {
        let mut p = std::env::temp_dir();
        let pid = std::process::id();
        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        p.push(format!("flynnel_urd_{pid}_{nonce}_{name}.bin"));
        p
    }

    /// Delete a test's backing file, reporting a failure rather than
    /// discarding it. A leaked mapping shows up here first, and a
    /// silent drop would leave the next run to find the file instead.
    fn remove_temp(path: &std::path::Path) {
        if let Err(e) = std::fs::remove_file(path) {
            eprintln!("urd test: could not remove {}: {e}", path.display());
        }
    }

    fn item(id: u32) -> LineItem {
        LineItem::new(id, u32::MAX, &id.to_le_bytes()).expect("item")
    }

    #[test]
    fn create_open_round_trips_header() {
        let path = temp_path("create_open");
        let _u = UrdDeque::create(&path, 4).expect("create");
        let o = UrdDeque::open(&path).expect("open");
        assert_eq!(o.n_mailboxes(), 4);
        assert_eq!(o.owner_pid(), std::process::id() as u64);
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn wait_strategy_matches_host() {
        let path = temp_path("strategy");
        let u = UrdDeque::create(&path, 2).expect("create");
        let s = u.wait_strategy();
        // The order is the assertion: WAITPKG, then MONITORX, then
        // the spin, which is what remains on a host with neither.
        // This names the stage after the spin floor, so the spin
        // appearing here means the host has no monitor wait at all.
        if has_waitpkg() {
            assert_eq!(s, WaitStrategy::Waitpkg);
        } else if has_monitorx() {
            assert_eq!(s, WaitStrategy::Monitorx);
        } else {
            assert_eq!(s, WaitStrategy::PauseSpin);
        }
        remove_temp(&path);
    }

    #[test]
    fn the_second_stage_is_the_best_monitor_wait_the_host_has() {
        // pick() names what follows the spin floor, not what competes
        // with it, so on a host with a monitor wait it is that wait.
        // The floor is why this is not the regression the
        // latency-only comparison suggested: wakes the spin would
        // have caught never reach here.
        let want = if has_waitpkg() {
            WaitStrategy::Waitpkg
        } else if has_monitorx() {
            WaitStrategy::Monitorx
        } else {
            WaitStrategy::PauseSpin
        };
        assert_eq!(WaitStrategy::pick(), want);
    }

    #[test]
    fn the_spin_floor_is_long_enough_to_be_worth_having() {
        // A floor of nothing makes the second stage catch every wake,
        // which is the configuration measured slower in three cells
        // of four. Pinned so it cannot be tuned to zero without the
        // reason being revisited.
        //
        // In a const block, so the pin holds at compile time rather
        // than needing this test to be reached. A value that breaks
        // it stops the build instead of failing a run somebody has
        // to make.
        const { assert!(SPIN_BEFORE_WAIT >= 64) };
    }

    #[test]
    fn the_thief_never_picks_a_wait_its_host_cannot_execute() {
        // The strategy names an instruction, so picking one the CPUID
        // probe did not confirm is a `#UD` on the steal path rather
        // than a wrong answer. Read from the strategy toward the
        // probe, which is the direction that catches a `pick` whose
        // arms have been reordered out from under the detections.
        //
        // The spin carries no precondition of its own, so its arm
        // asserts only that neither monitor wait was available.
        let path = temp_path("strategy_executable");
        let u = UrdDeque::create(&path, 2).expect("create");
        match u.wait_strategy() {
            WaitStrategy::Waitpkg => assert!(has_waitpkg()),
            WaitStrategy::Monitorx => assert!(has_monitorx()),
            WaitStrategy::PauseSpin => {}
        }
        remove_temp(&path);
    }

    #[test]
    fn publish_then_drain_round_trips() {
        let path = temp_path("publish_drain");
        let u = UrdDeque::create(&path, 2).expect("create");
        let items = [item(1), item(2), item(3)];
        let n = u.publish_to(0, &items).expect("publish");
        assert_eq!(n, 3);
        match u.drain_mailbox(0) {
            Drain::Success(r) => {
                assert_eq!(r.n_items, 3);
                assert_eq!(r.items[0].closure_id, 1);
                assert_eq!(r.items[1].closure_id, 2);
                assert_eq!(r.items[2].closure_id, 3);
            }
            Drain::Empty => panic!("expected ready mailbox"),
        }
        // After drain, mailbox is EMPTY.
        assert!(matches!(u.drain_mailbox(0), Drain::Empty));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn publish_round_robin_cycles_targets() {
        let path = temp_path("rr");
        let u = UrdDeque::create(&path, 4).expect("create");
        let items = [item(1)];
        let (t0, _) = u.publish_round_robin(&items).expect("rr 0");
        // Consume so the next publish doesn't spin on a busy mb;
        // bare statements discard the Drain return value (it's a
        // Copy enum, so `drop` would be a no-op clippy warning).
        u.drain_mailbox(t0);
        let (t1, _) = u.publish_round_robin(&items).expect("rr 1");
        u.drain_mailbox(t1);
        let (t2, _) = u.publish_round_robin(&items).expect("rr 2");
        u.drain_mailbox(t2);
        let (t3, _) = u.publish_round_robin(&items).expect("rr 3");
        // The four picks must cover all mailboxes (mod n_mailboxes).
        let mut targets = [t0, t1, t2, t3];
        targets.sort();
        assert_eq!(targets, [0, 1, 2, 3]);
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn too_many_items_rejected() {
        let path = temp_path("too_many");
        let u = UrdDeque::create(&path, 2).expect("create");
        let items: Vec<LineItem> = (0..(MAILBOX_ITEMS + 1) as u32).map(item).collect();
        let err = u.publish_to(0, &items).expect_err("too many");
        assert_eq!(err, PublishError::TooManyItems);
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn bad_target_rejected() {
        let path = temp_path("bad_target");
        let u = UrdDeque::create(&path, 2).expect("create");
        let err = u.publish_to(99, &[item(1)]).expect_err("bad target");
        assert_eq!(err, PublishError::BadTarget(99));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn empty_publish_is_noop() {
        let path = temp_path("empty");
        let u = UrdDeque::create(&path, 2).expect("create");
        assert_eq!(u.publish_to(0, &[]).expect("publish"), 0);
        assert!(matches!(u.drain_mailbox(0), Drain::Empty));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn close_owner_zeros_pid_and_advances_epoch() {
        let path = temp_path("close");
        let u = UrdDeque::create(&path, 2).expect("create");
        let before = u.header().epoch.load(O::Acquire);
        u.close_owner();
        assert_eq!(u.owner_pid(), 0);
        assert_eq!(u.header().epoch.load(O::Acquire), before + 1);
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn four_thieves_no_double_take() {
        // Stress: owner publishes round-robin to 4 mailboxes; 4
        // thieves each drain their own mailbox. Sum invariant.
        //
        // Shrunk to n=400 (from a larger N) so the test stays under
        // the cargo-test 60s starvation timeout when many other
        // stress tests are running in parallel. The thieves use
        // `yield_now` instead of `spin_loop` so they release CPU to
        // the publisher and to other concurrent test threads under
        // CPU saturation. A 30-second wall-clock deadline on the
        // thief loops surfaces a clear panic if the URD primitive
        // ever stalls under contention instead of silently hanging.
        use std::sync::atomic::AtomicUsize;
        use std::time::{Duration, Instant};
        let path = temp_path("stress");
        let u = Arc::new(UrdDeque::create(&path, 4).expect("create"));
        let n = 400usize;
        let consumed = Arc::new(AtomicUsize::new(0));
        let sum = Arc::new(AtomicUsize::new(0));

        let mut thieves = Vec::new();
        for tid in 0..4 {
            let u = Arc::clone(&u);
            let consumed = Arc::clone(&consumed);
            let sum = Arc::clone(&sum);
            thieves.push(thread::spawn(move || {
                let deadline = Instant::now() + Duration::from_secs(30);
                while consumed.load(O::Relaxed) < n {
                    assert!(
                        Instant::now() < deadline,
                        "URD stress: thief {tid} starved past 30s deadline",
                    );
                    match u.drain_mailbox(tid) {
                        Drain::Success(r) => {
                            for i in 0..r.n_items {
                                consumed.fetch_add(1, O::Relaxed);
                                sum.fetch_add(
                                    r.items[i].closure_id as usize,
                                    O::Relaxed,
                                );
                            }
                        }
                        Drain::Empty => std::thread::yield_now(),
                    }
                }
            }));
        }

        // Publisher: round-robin batches of MAILBOX_ITEMS items.
        let mut pushed = 0usize;
        while pushed < n {
            let want = MAILBOX_ITEMS.min(n - pushed);
            let mut batch = [item(0); MAILBOX_ITEMS];
            for slot in batch.iter_mut().take(want) {
                *slot = item(pushed as u32);
                pushed += 1;
            }
            u.publish_round_robin(&batch[..want]).expect("rr publish");
        }

        for t in thieves {
            t.join().expect("thief");
        }
        let expected: usize = (0..n).sum();
        assert_eq!(
            sum.load(O::Relaxed),
            expected,
            "URD stress sum invariant (every item consumed exactly once)"
        );
        std::fs::remove_file(&path).ok();
    }
}