Skip to main content

blake3_servil/
pipeline.rs

1//! The one streaming API ([`Pipeline`]): messages fed through reusable
2//! [`Room`]s, owned values (`owned`), borrowed slices (`lent`), or
3//! [`Batch`]es, hashed across this crate's worker pool within a fixed
4//! memory budget ([`Limits`]).
5//!
6//! Every call takes `&mut Pipeline`, and [`Message`], [`Room`], [`Lent`],
7//! and [`Event`] hold no borrow of the pipeline. Bookkeeping on the
8//! producer side needs no lock, tasks holding a pipeline and its tokens
9//! move freely between threads, and worker threads write only into memory
10//! the pipeline owns or took by value.
11//!
12//! Cross-CPU rings (message slots, rooms, short-message groups, piece nodes,
13//! and source actions) cycle in FIFO order rather than LIFO, so cache lines
14//! written or read by one worker core are reused only after a full lap of
15//! the ring rather than immediately bounced to another core.
16
17use crate::lanes::places::{Kind as PlaceKind, Plan};
18use crate::lanes::sources::{ACTION_SME2, Source};
19use crate::lanes::{MEMBERS, Member, OwnLine, TASK_LEN, Task};
20use crate::throughput::{Batch, Cv, LastCv, Prepared, TreeHasher, level_of};
21use crate::{CHUNK_LEN, Hash, Mode, OUT_LEN};
22use core::future::Future;
23use core::marker::PhantomData;
24use core::mem::MaybeUninit;
25use core::pin::Pin;
26// The primitives the Pipeline runs on: the standard library's here, and
27// Shuttle's in tests/shuttle_pipeline.rs, which compiles this same file
28// beside its own `pipeline_sync` and a stand-in for the pool.
29use crate::pipeline_sync::{AtomicBool, AtomicU64, AtomicUsize, Mutex, Ordering, UnsafeCell, process_static, thread};
30use core::task::{Context, Poll, Waker};
31use std::sync::Arc;
32
33/// Bytes in each [`Room`]: sixty-four chunks (64 KiB), a whole BLAKE3
34/// subtree on a 64-byte boundary. Chosen by empirical measurement across
35/// x86-64 (AVX2 and AVX-512) and ARM64 (NEON and SME2), where 64 KiB
36/// reaches both the 32-lane AVX-512 chunk kernel and SME2's flat subtree
37/// walk with one mechanism (`1 whole Room == 1 worker piece`).
38pub const ROOM_LEN: usize = 64 * 1024;
39const ROOM_LEVEL: u32 = level_of(ROOM_LEN as u64);
40
41/// Minimum subtree size that benefits from the SME2 coprocessor (16 chunks).
42const SME2_MIN_LEN: usize = 16 * CHUNK_LEN;
43
44/// Maximum subtree pieces one in-memory message or batch splits into.
45const MAX_SLOT_PIECES: usize = 64;
46
47/// Initial reference credit placed on a [`Room`] when handed to the caller;
48/// each `commit` consumes 1 credit locally on `&mut Room` without atomic RMW,
49/// and `Room::drop` returns the unused credits in one atomic subtraction.
50const ROOM_CREDITS: usize = 1 << 30;
51/// High bit stamped onto `Rooms::refs[i]` by `Pipeline::drop` after all worker
52/// tasks have finished, marking any still-live [`Room`] that outlives its
53/// `Pipeline` so `Room::drop` releases `PipeStorage::holders` only in that rare
54/// case and `make_room`/`Room::drop` pay zero `holders` atomics while the
55/// `Pipeline` is alive (#494).
56const ROOM_CLOSING_BIT: usize = 1usize << (usize::BITS - 1);
57
58const NONE: u32 = u32::MAX;
59
60/// High bit of `ActionArg::Multi`'s 32-bit `b` payload: selects `PipeStorage::slot_trees[slot]`
61/// instead of `PipeStorage::tree` without a worker-visible per-slot mode table.
62const MULTI_CUSTOM_BIT: u32 = 1u32 << 31;
63
64/// Compact fixed-capacity FIFO ring of `u32` indices over `Box<[u32]>`
65/// (24 B inline on 64-bit, exact capacity, branchless wraparound, no pop write-back, zero `unsafe`).
66struct IndexRing {
67    buf: Box<[u32]>,
68    head: u32,
69    len: u32,
70}
71
72impl IndexRing {
73    fn new(cap: usize) -> Self {
74        assert!(cap <= (u32::MAX / 2) as usize, "IndexRing capacity fits u32 half-range");
75        IndexRing { buf: vec![0u32; cap].into_boxed_slice(), head: 0, len: 0 }
76    }
77
78    #[inline(always)]
79    fn is_empty(&self) -> bool {
80        self.len == 0
81    }
82
83    #[inline(always)]
84    fn front(&self) -> Option<&u32> {
85        if self.len == 0 { None } else { Some(&self.buf[self.head as usize]) }
86    }
87
88    #[inline(always)]
89    fn push_back(&mut self, item: u32) {
90        let cap = self.buf.len();
91        let len = self.len as usize;
92        assert!(len < cap, "IndexRing capacity exceeded");
93        let mut idx = self.head as usize + len;
94        if idx >= cap {
95            idx -= cap;
96        }
97        self.buf[idx] = item;
98        self.len += 1;
99    }
100
101    #[inline(always)]
102    fn pop_front(&mut self) -> Option<u32> {
103        if self.len == 0 {
104            return None;
105        }
106        let item = self.buf[self.head as usize];
107        let next = self.head + 1;
108        self.head = if next as usize == self.buf.len() { 0 } else { next };
109        self.len -= 1;
110        Some(item)
111    }
112}
113
114/// Fixed-capacity FIFO event queue over pre-allocated `VecDeque<X>` (32 B inline
115/// on 64-bit, zero `unsafe`); `Pipeline::reap` enforces the logical `limits.messages`
116/// bound while `push_back` asserts backing capacity so `VecDeque::grow` never runs.
117struct EventRing<X>(std::collections::VecDeque<X>);
118
119// Moving the `VecDeque` handle never moves its heap buffer and `EventRing` exposes
120// no pinned element projection, preserving `Pipeline<T, B, P>: Unpin` even for
121// `!Unpin` tags or owners.
122impl<X> Unpin for EventRing<X> {}
123
124impl<X> EventRing<X> {
125    fn new(cap: usize) -> Self {
126        assert!(core::mem::size_of::<X>() > 0, "EventRing requires non-ZST elements");
127        let inner = std::collections::VecDeque::with_capacity(cap);
128        assert!(inner.capacity() >= cap, "EventRing backing capacity");
129        EventRing(inner)
130    }
131
132    #[inline(always)]
133    fn len(&self) -> usize {
134        self.0.len()
135    }
136
137    #[inline(always)]
138    fn is_empty(&self) -> bool {
139        self.0.is_empty()
140    }
141
142    #[inline(always)]
143    fn push_back(&mut self, item: X) {
144        // In every build: hold callers to the pre-allocated backing buffer so the
145        // queue never reallocates on the hot path; asserting `len != capacity`
146        // proves `!is_full()` to LLVM at inline call sites, eliding `VecDeque::grow`.
147        assert!(self.0.len() != self.0.capacity(), "EventRing backing capacity full");
148        self.0.push_back(item);
149    }
150
151    #[inline(always)]
152    fn pop_front(&mut self) -> Option<X> {
153        self.0.pop_front()
154    }
155}
156
157/// Move-insensitive heap array of uninitialized interior-mutable slots
158/// (matching `Rooms::backing`): held by raw pointer rather than `Box<[...]>`,
159/// so moving `Pipeline` by value never retags pointers derived from inline
160/// values stored inside the array. The caller drops every initialized element
161/// before dropping `RawSlots`; `Drop` frees the backing allocation itself.
162struct RawSlots<T> {
163    ptr: *mut UnsafeCell<MaybeUninit<T>>,
164    len: usize,
165}
166
167// Sound: `RawSlots<T>` exclusively owns its heap allocation of `len` slots.
168unsafe impl<T: Send> Send for RawSlots<T> {}
169
170impl<T> RawSlots<T> {
171    fn new(len: usize) -> Self {
172        let v: Vec<UnsafeCell<MaybeUninit<T>>> = (0..len).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();
173        let ptr = Box::into_raw(v.into_boxed_slice()) as *mut UnsafeCell<MaybeUninit<T>>;
174        RawSlots { ptr, len }
175    }
176
177    #[inline(always)]
178    fn slot(&self, index: usize) -> *mut MaybeUninit<T> {
179        assert!(index < self.len);
180        // Sound: `index < self.len`, within the owned allocation.
181        unsafe { (*self.ptr.add(index)).get() }
182    }
183}
184
185impl<T> Drop for RawSlots<T> {
186    fn drop(&mut self) {
187        // Sound: `ptr` and `len` came from `Box::into_raw(boxed_slice)`; all
188        // initialized elements have already been dropped (or leaked if the
189        // Pipeline was forgotten), and `MaybeUninit<T>` has no drop glue.
190        unsafe {
191            drop(Box::from_raw(core::ptr::slice_from_raw_parts_mut(self.ptr, self.len)));
192        }
193    }
194}
195
196/// Typed representation of a 64-bit action ticket payload carried through
197/// `Source::publish_actions`. Makes invalid kind tags unwriteable and enforces
198/// bitfield bounds in every build (release included).
199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200enum ActionArg {
201    Group { group: u32, custom_slot: u32 },
202    RoomPiece { pnode: u32, custom: bool, sme2: bool },
203    Multi { slot: u32, piece: u32, custom: bool, sme2: bool },
204}
205
206impl ActionArg {
207    const MAX_A: u32 = (1 << 29) - 1;
208
209    #[inline(always)]
210    fn encode(self) -> u64 {
211        let (kind, a, b, sme2): (u64, u32, u32, bool) = match self {
212            ActionArg::Group { group, custom_slot } => (0, group, custom_slot, false),
213            ActionArg::RoomPiece { pnode, custom, sme2 } => (1, pnode, u32::from(custom), sme2),
214            ActionArg::Multi { slot, piece, custom, sme2 } => {
215                assert!(piece < MULTI_CUSTOM_BIT, "multi piece index overlaps custom flag");
216                let custom_bit = if custom { MULTI_CUSTOM_BIT } else { 0 };
217                (2, slot, custom_bit + piece, sme2)
218            }
219        };
220        assert!(a <= Self::MAX_A, "action index exceeds 29-bit field");
221        // Put the SME2 flag bit (bit 63) first so every `+` has a distinct
222        // non-zero right operand (avoiding `x + (1<<63) == x - (1<<63)`).
223        let sme2_bit = if sme2 { ACTION_SME2 } else { 0 };
224        sme2_bit + ((kind << 61) + ((a as u64) << 32) + (b as u64))
225    }
226
227    #[inline(always)]
228    fn decode(arg: u64) -> Self {
229        let sme2 = (arg & ACTION_SME2) != 0;
230        let clean = arg & !ACTION_SME2;
231        let kind = clean >> 61;
232        let a = u32::try_from((clean >> 32) & u64::from(Self::MAX_A)).expect("29-bit field fits u32");
233        let b = u32::from_le_bytes(clean.to_le_bytes()[..4].try_into().unwrap());
234        match kind {
235            0 => ActionArg::Group { group: a, custom_slot: b },
236            1 => ActionArg::RoomPiece { pnode: a, custom: b != 0, sme2 },
237            2 => ActionArg::Multi { slot: a, piece: b & !MULTI_CUSTOM_BIT, custom: (b & MULTI_CUSTOM_BIT) != 0, sme2 },
238            _ => unreachable!("invalid ActionArg kind tag"),
239        }
240    }
241}
242
243/// Fixed memory bounds for a [`Pipeline`].
244///
245/// # Trait implementations
246///
247/// - `Clone` duplicates both capacity bounds.
248/// - `Copy` preserves both counts without reserving any storage.
249/// - `Debug` reports the message and room counts.
250/// - `Eq` identifies limits with equal bounds.
251/// - `PartialEq` compares both counts by value.
252#[derive(Clone, Copy, Debug, PartialEq, Eq)]
253pub struct Limits {
254    /// Messages open or in flight at once; as many finished [`Event`]s
255    /// again may wait to be pulled.
256    pub messages: usize,
257    /// [`Room`]s of [`ROOM_LEN`] bytes for arriving message data.
258    pub rooms: usize,
259}
260
261/// Completion of a message submitted to a [`Pipeline`].
262pub enum Event<T, B = (), P = Batch<'static>> {
263    Hashed { tag: T, hash: Hash, owner: Option<B> },
264    Aborted { tag: T, owner: Option<B> },
265    Batch { tag: T, batch: P, digests: Box<[[u8; 32]]> },
266}
267
268/// An open message on a [`Pipeline`].
269///
270/// Every `Message` goes back to its Pipeline: to [`Pipeline::end`], or to
271/// [`Pipeline::abort`] when its bytes will not all come. Dropping one
272/// panics. In async code an early return through `?` drops what the task
273/// holds, so give the message to `abort` before returning the error.
274///
275/// # Trait implementations
276///
277/// - `Drop` panics on an unfinished message unless the thread is already
278///   unwinding; dropping is not cancellation.
279#[must_use = "end, abort, or hand the message's bytes over; dropping an unfinished Message stops the program"]
280pub struct Message {
281    pipeline_id: u64,
282    slot: u32,
283}
284
285impl Message {
286    #[inline(always)]
287    fn take(self) -> (u64, usize) {
288        let out = (self.pipeline_id, self.slot as usize);
289        core::mem::forget(self);
290        out
291    }
292}
293
294impl Drop for Message {
295    fn drop(&mut self) {
296        if !std::thread::panicking() {
297            panic!("blake3-servil: a Pipeline Message was dropped without end, abort, owned, lent, or batch");
298        }
299    }
300}
301
302/// Guard for a message hashed in place on loan ([`Pipeline::lent`]).
303///
304/// Hold this guard until its message's event has been taken. Dropped
305/// while a worker may still read the bytes (before the message is
306/// hashed), it stops the process: no worker reads freed memory.
307///
308/// # Trait implementations
309///
310/// - `Drop` stops the process (an abort, not a panic) while the loan's
311///   hashing has not finished, even where no worker has been given it yet
312///   or its Pipeline is gone; once it has finished, the guard may be
313///   dropped before its event is taken. The guard reads a monotonic count
314///   of its slot's finished work: after its Pipeline was dropped with the
315///   loan still not handed to a worker, and a later Pipeline has reused
316///   the same slot, the drop may pass though the loan was never hashed,
317///   and no worker reads its bytes then either.
318#[must_use = "hold the guard until the message's event; dropping an active loan aborts the process"]
319pub struct Lent<'a> {
320    completed: &'static AtomicU64,
321    epoch: u64,
322    _bytes: PhantomData<&'a [u8]>,
323}
324
325impl Drop for Lent<'_> {
326    #[inline]
327    fn drop(&mut self) {
328        if self.completed.load(Ordering::Acquire) < self.epoch {
329            stop_process("blake3-servil: a Pipeline Lent guard was dropped before its message finished hashing\n");
330        }
331    }
332}
333
334/// Say why, and end the process: a breach after which a worker would read
335/// freed memory. As the pool's own stop, the words go straight to
336/// descriptor 2: `std::io::stderr` takes a lock, and a thread that holds
337/// it while it waits for this one would wait for ever.
338#[cold]
339#[inline(never)]
340fn stop_process(why: &str) -> ! {
341    crate::lanes::stop(why)
342}
343
344use crate::waker::WakerSlot;
345
346/// Lock-free pre-allocated rooms buffer and per-room credit reference counts.
347/// Aligned to its own 128-byte cache-line pair.
348#[repr(align(128))]
349struct Rooms {
350    /// 64-byte-aligned start of the `count * ROOM_LEN` room bytes inside
351    /// `backing`, kept as a raw pointer so callers and workers alias disjoint
352    /// sub-slices without violating `Box`'s uniqueness.
353    buf: *mut u8,
354    /// Original `Box<[u8]>` backing allocation (`count * ROOM_LEN + 64` bytes
355    /// when `count > 0`, empty when `count == 0`), reconstructed via
356    /// `Box::from_raw` in `Drop`. Keeping 1-byte element alignment lets
357    /// `vec![0u8; size]` route through `alloc_zeroed` (`calloc` / OS lazy
358    /// demand-zero pages on standard allocators).
359    backing: *mut [u8],
360    count: usize,
361    refs: Box<[AtomicUsize]>,
362}
363
364// Sound: `backing` owns the boxed `[u8]` buffer (with `buf` pointing to the
365// 64-byte-aligned `count * ROOM_LEN` slice inside it) until `Rooms::drop`
366// runs (after `PipeStorage`'s final holder drops and every worker task has
367// published completion); what may touch which bytes is governed by `refs`.
368unsafe impl Send for Rooms {}
369// Sound: shared `&Rooms` accesses are disjoint because `Room::bytes_mut`
370// requires `&mut` on the unwritten suffix while `Pipeline::commit` advances
371// the writable offset, atomic `refs` counts prevent room reuse until all
372// worker reads finish, and the backing allocation stays live until
373// `PipeStorage` has zero holders and zero in-flight tasks.
374unsafe impl Sync for Rooms {}
375
376impl Drop for Rooms {
377    fn drop(&mut self) {
378        // Sound: `backing` came from `Box::into_raw` of a boxed `[u8]`, and
379        // `Rooms::drop` runs only once `PipeStorage` has zero live holders and
380        // zero in-flight worker tasks.
381        unsafe { drop(Box::from_raw(self.backing)) };
382    }
383}
384
385impl Rooms {
386    fn new(count: usize) -> Self {
387        let size = if count == 0 { 0 } else { count.checked_mul(ROOM_LEN).and_then(|n| n.checked_add(64)).expect("rooms byte size fits usize") };
388        let backing = Box::into_raw(vec![0u8; size].into_boxed_slice());
389        let raw = backing.cast::<u8>();
390        // Sound: when `count == 0`, `align_offset(64)` is unused (no room
391        // exists); when `count > 0`, `size == count * ROOM_LEN + 64` and
392        // `align_offset(64) < 64`.
393        let buf = if count == 0 { raw } else { unsafe { raw.add(raw.align_offset(64)) } };
394        Rooms { buf, backing, count, refs: (0..count).map(|_| AtomicUsize::new(0)).collect() }
395    }
396
397    #[inline(always)]
398    fn room_ptr(&self, index: usize) -> *mut u8 {
399        assert!(index < self.count, "room index out of bounds");
400        // Sound: `index < self.count`, so `index * ROOM_LEN` lies inside the
401        // `count * ROOM_LEN`-byte allocation at `self.buf`.
402        unsafe { self.buf.add(index * ROOM_LEN) }
403    }
404
405    #[inline(always)]
406    fn init_taken(&self, idx: u32) {
407        self.refs[idx as usize].store(ROOM_CREDITS, Ordering::Relaxed);
408    }
409
410    #[inline(always)]
411    fn release_n(&self, index: u32, n: usize) -> bool {
412        self.refs[index as usize].fetch_sub(n, Ordering::SeqCst) == n
413    }
414}
415
416struct MemberGroup {
417    task: UnsafeCell<Task>,
418    rooms: UnsafeCell<[u32; MEMBERS]>,
419    epoch: UnsafeCell<u64>,
420}
421
422/// Recycled `'static` worker-facing slot (`Source`, `WakerSlot`, and monotonic
423/// completion lines for [`Lent`] guards).
424///
425/// Pool workers touch `source` (while scanning `REGISTERED`), `waker` (after
426/// publishing task completion or when `Room::drop` wakes a waiter), and the
427/// monotonic completion lines (`group_completed`, `loan_completed`). Keeping
428/// this handle alive for the process lets per-`Pipeline` [`PipeStorage`]
429/// (`Rooms`, groups, pieces, slots, and hashes) be freed cleanly on drop with
430/// zero worker-side epoch fences, no worker grace period or join in
431/// `Pipeline::drop`, and zero `holders` atomics on [`Pipeline::lent`] /
432/// [`Lent::drop`] (#465). Matched exact-tier first then best-fit via per-tier
433/// stacks indexed by power-of-two tier capacity (minimum 1,024: a 24 KiB
434/// action ring on multi-worker pools, or 0 action slots on one-thread pools,
435/// plus per-tier loan completion lines and up to 256 group completion lines),
436/// so ascending `Limits` keep retained action-ring and loan-line tier units
437/// below `2x` the largest tier at peak concurrency (while capped group lines
438/// and fixed per-slot headers scale linearly with distinct retained tiers) and
439/// acquisition is O(tiers) independent of peak count.
440struct PipeSlot {
441    source: Source,
442    waker: WakerSlot,
443    /// Per-group monotonic completion epochs (at most 256 cache-line-isolated
444    /// `AtomicU64`s); short `Lent` guards borrow directly from here.
445    group_completed: Box<[OwnLine<AtomicU64>]>,
446    /// Per-slot monotonic completion epochs for multi-piece (`> TASK_LEN`)
447    /// `Lent` guards; `cap / MAX_SLOT_PIECES >= Limits.messages` always holds.
448    loan_completed: Box<[OwnLine<AtomicU64>]>,
449}
450
451/// Recycled `PipeSlot` entry in `FREE_PIPE_SLOTS`, transferring the slot's
452/// monotonic group/loan epoch counters under the free-list lock without
453/// extra atomics on `PipeSlot`.
454struct FreeSlot {
455    slot: &'static PipeSlot,
456    next_group_epoch: u64,
457    next_loan_epoch: u64,
458}
459
460const MIN_SLOT_SHIFT: u32 = 10; // 1,024 actions
461const SLOT_TIERS: usize = 28; // 2^10 .. 2^37 actions (covers all admitted 64-bit Limits)
462
463#[inline]
464fn slot_tier(cap: usize) -> usize {
465    (cap.trailing_zeros() - MIN_SLOT_SHIFT) as usize
466}
467
468process_static! {
469    /// Recycled `'static` worker-facing `PipeSlot`s grouped by power-of-two
470    /// action-ring tier so exact-tier hits are O(1) and best-fit fallback is
471    /// O(SLOT_TIERS), never scanning the historical peak count.
472    static FREE_PIPE_SLOTS: Mutex<[Vec<FreeSlot>; SLOT_TIERS]> = Mutex::new([const { Vec::new() }; SLOT_TIERS]);
473}
474
475#[cfg(any(test, shuttle))]
476process_static! {
477    /// The `PipeSlot`s made so far in this process (or Shuttle run).
478    static PIPE_SLOTS_MADE: AtomicUsize = AtomicUsize::new(0);
479}
480
481#[cfg(any(test, shuttle))]
482process_static! {
483    /// Live `PipeStorage` allocations not yet freed (tests and Shuttle leak checks).
484    static LIVE_STORAGES: AtomicUsize = AtomicUsize::new(0);
485}
486
487#[cfg(shuttle)]
488struct OwnedPipeSlotPtr(*mut PipeSlot);
489
490#[cfg(shuttle)]
491// Sound: only pushed at creation and drained in `free_storages_for_model`
492// after all Shuttle worker threads have joined.
493unsafe impl Send for OwnedPipeSlotPtr {}
494
495#[cfg(shuttle)]
496process_static! {
497    /// Original `Box::into_raw` owning pointers for model teardown so
498    /// `free_storages_for_model` frees the run's `PipeSlot`s without casting
499    /// `&'static PipeSlot` back to `*mut`.
500    static MODEL_OWNED_PIPE_SLOTS: Mutex<Vec<OwnedPipeSlotPtr>> = Mutex::new(Vec::new());
501}
502
503/// The model's alone (tests/shuttle_pipeline.rs): verifies all `PipeStorage`s
504/// were freed and frees the run's `PipeSlot`s at its end.
505#[cfg(shuttle)]
506#[allow(dead_code)]
507#[path = "../tests/model/storages.rs"]
508pub(crate) mod model_storages;
509
510impl PipeSlot {
511    fn acquire(actions: usize, messages: usize) -> (&'static PipeSlot, u64, u64) {
512        let has_workers = crate::lanes::pool_has_workers();
513        let need = if has_workers { actions } else { messages * MAX_SLOT_PIECES };
514        let cap = need.max(1024).checked_next_power_of_two().expect("admitted action capacity fits power of two");
515        let tier = slot_tier(cap);
516        if let Some(FreeSlot { slot, next_group_epoch, next_loan_epoch }) = FREE_PIPE_SLOTS.lock().unwrap()[tier..].iter_mut().find_map(Vec::pop) {
517            return (slot, next_group_epoch, next_loan_epoch);
518        }
519        let max_slots = cap / MAX_SLOT_PIECES;
520        let max_groups = max_slots.clamp(4, 256);
521        #[cfg(any(test, shuttle))]
522        PIPE_SLOTS_MADE.fetch_add(1, Ordering::Relaxed);
523        // A one-thread pool never registers a `Source` or dispatches tickets to
524        // workers, so keep its ticket ring empty while retaining stable waker
525        // and group/loan completion lines for synchronous execution.
526        let source = if has_workers { Source::with_actions(cap, PipeStorage::run_action) } else { Source::new() };
527        let raw = Box::into_raw(Box::new(PipeSlot {
528            source,
529            waker: WakerSlot::new(),
530            group_completed: (0..max_groups).map(|_| OwnLine(AtomicU64::new(0))).collect(),
531            loan_completed: (0..max_slots).map(|_| OwnLine(AtomicU64::new(0))).collect(),
532        }));
533        #[cfg(shuttle)]
534        MODEL_OWNED_PIPE_SLOTS.lock().unwrap().push(OwnedPipeSlotPtr(raw));
535        // Sound: `raw` stays live for the process (freed only after all Shuttle
536        // worker threads join in `model_storages::free_storages_for_model`).
537        (unsafe { &*raw }, 1, 1)
538    }
539
540    fn release(slot: &'static PipeSlot, next_group_epoch: u64, next_loan_epoch: u64) {
541        let tier = slot_tier(slot.loan_completed.len() * MAX_SLOT_PIECES);
542        FREE_PIPE_SLOTS.lock().unwrap()[tier].push(FreeSlot { slot, next_group_epoch, next_loan_epoch });
543    }
544}
545
546/// Per-`Pipeline` heap-allocated backing storage (`Rooms`, short-message
547/// groups, piece nodes, per-slot buffers, and completion flags), freed cleanly
548/// when its `Pipeline` and any surviving [`Room`]s drop (#465).
549pub(crate) struct PipeStorage {
550    slot: crate::pipeline_sync::SlotRef<PipeSlot>,
551    tree: TreeHasher,
552    rooms: Rooms,
553    groups: Box<[MemberGroup]>,
554    /// Per-slot prepared mode, written by the owner only when a slot opens via
555    /// `message_with` (`OverrideOpenMode::install`) before any work for that
556    /// slot is dispatched, and read-only by workers until the slot finishes.
557    /// Default `message()` slots leave this untouched.
558    slot_trees: Box<[UnsafeCell<TreeHasher>]>,
559    hashes: Box<[UnsafeCell<[u8; OUT_LEN]>]>,
560    cvs: Box<[UnsafeCell<PieceValues>]>,
561    slot_done: Box<[OwnLine<AtomicBool>]>,
562    tasks_left: Box<[OwnLine<AtomicUsize>]>,
563    multi: Box<[UnsafeCell<MultiDesc>]>,
564    pieces: Box<[PieceNode]>,
565    /// Who holds this storage: its `Pipeline` while alive (1), plus teardown
566    /// reservations for surviving [`Room`]s stamped with `ROOM_CLOSING_BIT`.
567    holders: OwnLine<AtomicUsize>,
568}
569
570// Sound: each mutable location inside `PipeStorage` has one writer at a time
571// governed by its slot, group, or piece state: the owner before dispatch, a
572// single worker per slot/group/piece — or disjoint elements/fields of
573// `cvs[slot]` written concurrently by distinct multi-piece workers and joined
574// by the `tasks_left` AcqRel countdown — until the completion store, and the
575// owner again after observing it. `PipeStorage` stays live at its heap address
576// until every task has published completion and `holders` reaches 0.
577unsafe impl Send for PipeStorage {}
578// Sound: concurrent worker and owner accesses to `PipeStorage` fields are
579// disjointly synchronized by slot/group/piece atomics and `holders`/`tasks_left`.
580unsafe impl Sync for PipeStorage {}
581
582impl PipeStorage {
583    /// Give up `n` holds on `st` (`Pipeline::drop` or surviving `Room::drop`):
584    /// when `holders` reaches 0, free `PipeStorage` cleanly.
585    ///
586    /// # Safety
587    ///
588    /// `n > 0`, `st` must point to a live `PipeStorage` allocated by
589    /// `PipeStorage::alloc`, and the caller must exclusively surrender `n`
590    /// counted holds in `(*st).holders` without touching `*st` afterwards.
591    /// Releasing the Pipeline's initial hold is valid only after `Pipeline::drop`
592    /// has verified zero outstanding worker work, returned local room credits,
593    /// and reserved one hold per surviving `Room` before stamping
594    /// `ROOM_CLOSING_BIT`; each surviving `Room::drop` releases only its unique
595    /// reserved hold (`n = 1`).
596    #[inline(never)]
597    unsafe fn release_n(st: *mut PipeStorage, n: usize) {
598        // Sound: caller's safety contract guarantees `st` is live and owns `n`
599        // references in `holders`. When `fetch_sub(n, AcqRel)` returns `n`,
600        // every worker task has already published completion (leaving zero
601        // references into `*st`), and no `Pipeline` or `Room` retains any
602        // pointer to `*st`.
603        if unsafe { (*st).holders.fetch_sub(n, Ordering::AcqRel) } == n {
604            // Sound: `holders` reached 0, so no other holder or worker retains
605            // access to `*st`. Under Shuttle, poison `slot` before quarantine so
606            // any late worker access panics deterministically.
607            unsafe { (*st).slot.poison() };
608            #[cfg(any(test, shuttle))]
609            LIVE_STORAGES.fetch_sub(1, Ordering::Relaxed);
610            crate::pipeline_sync::retire_storage!(st);
611        }
612    }
613
614    fn alloc(slot: &'static PipeSlot, tree: TreeHasher, messages: usize, rooms: usize, pieces: usize, groups: usize) -> *mut PipeStorage {
615        #[cfg(any(test, shuttle))]
616        LIVE_STORAGES.fetch_add(1, Ordering::Relaxed);
617        let raw = Box::into_raw(Box::new(PipeStorage {
618            slot: crate::pipeline_sync::SlotRef::new(slot),
619            slot_trees: (0..messages).map(|_| UnsafeCell::new(tree.clone())).collect(),
620            tree,
621            rooms: Rooms::new(rooms),
622            groups: (0..groups)
623                .map(|_| MemberGroup { task: UnsafeCell::new(Task::members(None)), rooms: UnsafeCell::new([NONE; MEMBERS]), epoch: UnsafeCell::new(0) })
624                .collect(),
625            hashes: (0..messages).map(|_| UnsafeCell::new([0u8; OUT_LEN])).collect(),
626            cvs: (0..messages).map(|_| UnsafeCell::new(PieceValues { whole: [Cv::unset(); MAX_SLOT_PIECES], last: None })).collect(),
627            slot_done: (0..messages).map(|_| OwnLine(AtomicBool::new(true))).collect(),
628            tasks_left: (0..messages).map(|_| OwnLine(AtomicUsize::new(0))).collect(),
629            multi: (0..messages).map(|_| UnsafeCell::new(MultiDesc::empty())).collect(),
630            pieces: (0..pieces)
631                .map(|_| PieceNode {
632                    slot: UnsafeCell::new(0),
633                    room: UnsafeCell::new(0),
634                    offset: UnsafeCell::new(0),
635                    len: UnsafeCell::new(0),
636                    index: UnsafeCell::new(0),
637                    out: OwnLine(UnsafeCell::new(RoomValue::Whole(Cv::unset()))),
638                    done: OwnLine(AtomicBool::new(true)),
639                    next: UnsafeCell::new(NONE),
640                })
641                .collect(),
642            holders: OwnLine(AtomicUsize::new(1)),
643        }));
644        crate::pipeline_sync::register_storage!(raw);
645        raw
646    }
647}
648
649/// Reusable `ROOM_LEN`-byte buffer for arriving message bytes.
650///
651/// # Trait implementations
652///
653/// - `Drop` returns the unused credits; workers retain access to committed
654///   bytes until they finish.
655/// - `Send` lets another thread take the token and its exclusive access to
656///   the writable bytes.
657/// - `Sync` permits sharing a reference; writing still requires an
658///   exclusive borrow.
659#[must_use = "commit from the room; a dropped Room gives back what is left of it"]
660pub struct Room {
661    pipeline_id: u64,
662    index: u32,
663    offset: u32,
664    commits: u32,
665    ptr: *mut u8,
666    storage: core::ptr::NonNull<PipeStorage>,
667}
668
669// Sound: a Room is the only way to its uncommitted bytes, and its other fields
670// are plain values; `*storage` stays live until `Room::drop` releases its
671// credits (or its `ROOM_CLOSING_BIT` hold).
672unsafe impl Send for Room {}
673// Sound: `&Room` only exposes immutable room bounds/index and synchronized
674// atomic operations on `*self.storage`.
675unsafe impl Sync for Room {}
676
677#[allow(clippy::len_without_is_empty)]
678impl Room {
679    #[inline(always)]
680    fn storage(&self) -> &PipeStorage {
681        // Sound: this Room's live credit (or `ROOM_CLOSING_BIT` hold after
682        // `Pipeline::drop`) keeps `*self.storage` live until `Room::drop`.
683        unsafe { self.storage.as_ref() }
684    }
685
686    /// Remaining writable bytes in this room, starting on a 64-byte boundary.
687    #[inline(always)]
688    pub fn bytes_mut(&mut self) -> &mut [u8] {
689        let rem = ROOM_LEN - self.offset as usize;
690        // Sound: the bytes from `offset` to the room's end are this Room's
691        // alone: committed bytes lie before `offset`, and no other Room has
692        // this index while this one's credits are out (take_credit).
693        unsafe { core::slice::from_raw_parts_mut(self.as_mut_ptr(), rem) }
694    }
695
696    /// Pointer to the start of the remaining writable bytes.
697    #[inline(always)]
698    pub fn as_mut_ptr(&mut self) -> *mut u8 {
699        // Sound: `offset` is at most ROOM_LEN, inside or one past the room.
700        unsafe { self.ptr.add(self.offset as usize) }
701    }
702
703    /// Number of writable bytes remaining in this room.
704    #[inline(always)]
705    pub fn len(&self) -> usize {
706        ROOM_LEN - self.offset as usize
707    }
708
709    /// Take one of this Room's credits for a commit: the pool counts a
710    /// Room free when all ROOM_CREDITS are back, each commit's from the
711    /// worker that finishes it and the rest from the Room's drop. A Room
712    /// never gives out its last: before that it takes a new set, so the
713    /// pool cannot count it free while the caller holds it. An empty
714    /// commit moves the Room on by nothing, so one Room can take them
715    /// without end (BLAKE3 #418: after ROOM_CREDITS of them a second Room
716    /// was made over the same bytes).
717    #[inline(always)]
718    fn take_credit(&mut self) {
719        if self.commits as usize == ROOM_CREDITS - 1 {
720            self.storage().rooms.refs[self.index as usize].fetch_add(ROOM_CREDITS - 1, Ordering::Relaxed);
721            self.commits = 0;
722        }
723        self.commits += 1;
724    }
725}
726
727#[cfg(test)]
728impl Room {
729    /// Leave this Room `left` of its credits, as that many short of
730    /// ROOM_CREDITS commits would.
731    fn spend_all_but(&mut self, left: u32) {
732        let spent = ROOM_CREDITS as u32 - left;
733        self.storage().rooms.release_n(self.index, spent as usize);
734        self.commits += spent;
735    }
736}
737
738impl Drop for Room {
739    #[inline]
740    fn drop(&mut self) {
741        let unused = ROOM_CREDITS - (self.commits as usize);
742        // End the `&PipeStorage` borrow strictly BEFORE `fetch_sub`: on the
743        // non-closing path (`prev & ROOM_CLOSING_BIT == 0`), once `fetch_sub`
744        // drops `refs[i]` to 0, a concurrent `Pipeline::drop` may immediately
745        // free `*self.storage`, so that path touches only `&'static WakerSlot`
746        // afterwards. On the closing path, `Pipeline::drop` reserved a
747        // `holders` ref keeping `*self.storage` live until `PipeStorage::release`.
748        let (waker, ref_ptr) = {
749            let st = self.storage();
750            (&st.slot.get().waker, core::ptr::addr_of!(st.rooms.refs[self.index as usize]))
751        };
752        // Sound: `ref_ptr` points to `rooms.refs[self.index]` inside `*self.storage`,
753        // which stays live until this `SeqCst` subtraction completes.
754        let prev = unsafe { (*ref_ptr).fetch_sub(unused, Ordering::SeqCst) };
755        if prev & ROOM_CLOSING_BIT != 0 {
756            // `Pipeline::drop` stamped `ROOM_CLOSING_BIT` after all worker
757            // tasks finished and reserved a `holders` ref for this Room; drop
758            // that hold so the last survivor frees `PipeStorage` cleanly.
759            assert_eq!(prev & !ROOM_CLOSING_BIT, unused, "surviving room ref count");
760            // Sound: `Pipeline::drop` reserved one hold in `holders` for every
761            // room that saw `prev != 0` when stamping `ROOM_CLOSING_BIT`, and
762            // this `Room::drop` consumes that unique hold once and never reads
763            // `self.storage` again.
764            unsafe { PipeStorage::release_n(self.storage.as_ptr(), 1) };
765        } else if prev == unused {
766            // Even if `Pipeline::drop` raced right after `fetch_sub` and freed
767            // `PipeStorage`, `waker` lives in `&'static PipeSlot` and waking it
768            // is benign.
769            waker.notify_after_seqcst();
770        }
771    }
772}
773
774struct PieceNode {
775    slot: UnsafeCell<u32>,
776    room: UnsafeCell<u32>,
777    offset: UnsafeCell<u32>,
778    len: UnsafeCell<u32>,
779    index: UnsafeCell<u64>,
780    out: OwnLine<UnsafeCell<RoomValue>>,
781    done: OwnLine<AtomicBool>,
782    next: UnsafeCell<u32>,
783}
784
785#[derive(Clone, Copy)]
786enum RoomValue {
787    // A first room might be the whole message. Keep both children of its root.
788    First([Cv; 2]),
789    Whole(Cv),
790    Last(LastCv),
791}
792
793struct PieceValues {
794    whole: [Cv; MAX_SLOT_PIECES],
795    last: Option<LastCv>,
796}
797
798/// Split-work payload kind inside [`MultiDesc`]: keeps batch-only fields
799/// (`message_len`, `slot_len`, `per_part`, `count`, non-null `digests`)
800/// disjoint from multi-piece slice fields (`total_len`, `piece_level`,
801/// `loan_epoch`) so mixed combinations are unrepresentable.
802#[derive(Clone, Copy)]
803enum MultiKind {
804    Batch { message_len: usize, slot_len: usize, per_part: usize, count: usize, digests: core::ptr::NonNull<[u8; OUT_LEN]> },
805    Slice { total_len: usize, piece_level: u32, loan_epoch: u64 },
806}
807
808#[derive(Clone, Copy)]
809struct MultiDesc {
810    input: *const u8,
811    pieces: usize,
812    kind: MultiKind,
813}
814
815const _: () = assert!(core::mem::size_of::<MultiDesc>() <= 64);
816
817impl MultiDesc {
818    fn empty() -> Self {
819        Self { input: core::ptr::null(), pieces: 0, kind: MultiKind::Slice { total_len: 0, piece_level: level_of(TASK_LEN as u64), loan_epoch: 0 } }
820    }
821}
822
823/// The last thing a worker does for a task: `publish` stores the task's
824/// completion, then `waker` (living in `&'static PipeSlot`) wakes the owner.
825/// Every reference into `PipeStorage` ends BEFORE `publish` runs so that once
826/// `publish` completes, `Pipeline::drop` may immediately free `PipeStorage`
827/// without any worker holding a dangling reference or touching freed memory.
828/// A wake that reaches a later `Pipeline` reusing the same `PipeSlot` is a
829/// benign spurious wake (tests/shuttle_waker.rs checks `WakerSlot` under late
830/// finishers).
831#[inline(always)]
832fn finished(waker: &'static WakerSlot, publish: impl FnOnce()) {
833    publish();
834    waker.notify_after_seqcst();
835}
836
837impl PipeStorage {
838    /// Prepared mode selected by `custom`: either `slot_trees[slot]` (written
839    /// by `OverrideOpenMode::install` before dispatch and immutable until
840    /// completion) or the Pipeline's default `tree`.
841    #[inline(always)]
842    fn tree_for(&self, slot: usize, custom: bool) -> &TreeHasher {
843        if custom {
844            // Sound: the action (or owner-side `SlotMeta::mode`) selects
845            // `slot_trees[slot]` only for a slot opened via `message_with`,
846            // whose tree stays read-only until all work for `slot` finishes.
847            unsafe { &*self.slot_trees[slot].get() }
848        } else {
849            &self.tree
850        }
851    }
852
853    fn tree_for_worker(&self, slot: usize, custom: bool, use_sme2: bool) -> TreeHasher {
854        let base = self.tree_for(slot, custom);
855        if use_sme2 { base.clone() } else { base.clone().on_this_core() }
856    }
857
858    unsafe fn run_action(ctx: *const (), arg: u64, use_sme2: bool) {
859        // Sound: `ctx` is the `*const PipeStorage` its Pipeline dispatched
860        // with, valid until this task publishes completion below. Every
861        // `&PipeStorage` borrow passed to `run_group`, `run_room_piece`,
862        // `run_multi_piece`, and `finish_multi_slot` ends strictly BEFORE the
863        // worker executes its completion atomic (`swap` or `tasks_left.fetch_sub`)
864        // so `Pipeline::drop` may immediately free `*st` once the final
865        // completion store executes.
866        let st = ctx as *const PipeStorage;
867        match ActionArg::decode(arg) {
868            ActionArg::Group { group, custom_slot } => {
869                // Sound: `*st` stays live until `group_completed[group].swap(SeqCst)` below.
870                let (waker, completed, epoch) = unsafe { &*st }.run_group(group as usize, custom_slot, use_sme2);
871                finished(waker, || {
872                    completed.swap(epoch, Ordering::SeqCst);
873                });
874            }
875            ActionArg::RoomPiece { pnode, custom, .. } => {
876                // Sound: `*st` stays live until `pnode.done.swap(SeqCst)` below.
877                let (waker, done_ptr) = unsafe { &*st }.run_room_piece(pnode as usize, custom, use_sme2);
878                finished(waker, || {
879                    // Sound: `done_ptr` points to `pieces[pnode].done` inside `*st`,
880                    // live until this `SeqCst` swap completes.
881                    unsafe { (*done_ptr).swap(true, Ordering::SeqCst) };
882                });
883            }
884            ActionArg::Multi { slot, piece, custom, .. } => {
885                let slot = slot as usize;
886                // Sound: `*st` stays live until `tasks_left.fetch_sub(AcqRel)` below.
887                let (tasks_left_ptr, is_batch) = unsafe { &*st }.run_multi_piece(slot, piece as usize, custom, use_sme2);
888                // `&*st` borrow has ended; non-last pieces touch nothing in `*st`
889                // during or after this decrement.
890                // Sound: `tasks_left_ptr` points to `tasks_left[slot]` inside `*st`,
891                // live until this `AcqRel` decrement completes.
892                if unsafe { (*tasks_left_ptr).fetch_sub(1, Ordering::AcqRel) } == 1 {
893                    // Sound: returning 1 means this worker is the last piece of
894                    // `slot`, so `*st` remains live until `slot_done.swap(SeqCst)` below.
895                    let (waker, done_ptr, loan_mark) = unsafe { &*st }.finish_multi_slot(slot, is_batch, custom);
896                    if let Some((loan_completed, epoch)) = loan_mark {
897                        loan_completed.store(epoch, Ordering::Release);
898                    }
899                    finished(waker, || {
900                        // Sound: `done_ptr` points to `slot_done[slot]` inside `*st`,
901                        // live until this `SeqCst` swap completes.
902                        unsafe { (*done_ptr).swap(true, Ordering::SeqCst) };
903                    });
904                }
905            }
906        }
907    }
908
909    fn run_group(&self, group_idx: usize, custom_slot: u32, use_sme2: bool) -> (&'static WakerSlot, &'static AtomicU64, u64) {
910        let group = &self.groups[group_idx];
911        // Sound: the owner wrote this group's task, epoch, and metas before
912        // dispatching the group (publish_open), and carried `custom_slot` in
913        // the action argument. When `custom_slot != NONE`, that slot belongs
914        // to this group and cannot be reaped or overwritten until
915        // `group_completed[group_idx]` reaches this epoch.
916        let task = unsafe { &*group.task.get() };
917        let tree = self.tree_for_worker(custom_slot as usize, custom_slot != NONE, use_sme2);
918        let count = task.members;
919        // Sound: the owner wrote `group.epoch` and each member's input/output pointers
920        // before dispatch and keeps them valid until `completed_epoch` reaches `epoch`.
921        let epoch = unsafe { *group.epoch.get() };
922        unsafe { task.run_members(&tree) };
923        // Sound: `rooms` was written before dispatch and stays read-only until `group_completed` publishes.
924        let rooms = unsafe { &*group.rooms.get() };
925
926        // Coalesce consecutive members sharing a Room into a single atomic subtraction.
927        let mut cur_room = NONE;
928        let mut cur_n = 0usize;
929        for &room in &rooms[..count] {
930            if room != NONE {
931                if room == cur_room {
932                    cur_n += 1;
933                } else {
934                    if cur_room != NONE {
935                        self.rooms.release_n(cur_room, cur_n);
936                    }
937                    cur_room = room;
938                    cur_n = 1;
939                }
940            }
941        }
942        if cur_room != NONE {
943            self.rooms.release_n(cur_room, cur_n);
944        }
945        // Caller publishes `group_completed[group_idx]` (in `&'static PipeSlot`)
946        // after `&self` drops.
947        let slot = self.slot.get();
948        (&slot.waker, &slot.group_completed[group_idx].0, epoch)
949    }
950
951    fn run_room_piece(&self, pnode_idx: usize, custom: bool, use_sme2: bool) -> (&'static WakerSlot, *const AtomicBool) {
952        let pnode = &self.pieces[pnode_idx];
953        // Sound: the owner wrote the piece's fields before dispatching it
954        // (commit_multi), and touches the node again only once `done` is set,
955        // which is the caller's last store after `&self` drops.
956        let slot = unsafe { *pnode.slot.get() } as usize;
957        let room_idx = unsafe { *pnode.room.get() };
958        let offset = unsafe { *pnode.offset.get() } as usize;
959        let len = unsafe { *pnode.len.get() } as usize;
960        let index = unsafe { *pnode.index.get() };
961        let rooms = &self.rooms;
962        assert!((room_idx as usize) < rooms.count && offset <= ROOM_LEN && len <= ROOM_LEN - offset, "a piece stays within its room");
963        // Sound: these are just the committed bytes. The Room's credit keeps
964        // them from being written again until this task releases them below.
965        let ptr = unsafe { rooms.room_ptr(room_idx as usize).add(offset) };
966        let bytes = unsafe { core::slice::from_raw_parts(ptr, len) };
967        let tree = self.tree_for_worker(slot, custom, use_sme2);
968        let value = if index == 0 {
969            RoomValue::First(tree.subtree_halves(ROOM_LEVEL, index, bytes))
970        } else if len == ROOM_LEN {
971            RoomValue::Whole(tree.subtree_cv(ROOM_LEVEL, index, bytes))
972        } else {
973            RoomValue::Last(tree.last_cv(index << ROOM_LEVEL, bytes))
974        };
975        // Sound: this piece's output is its worker's alone until `done`.
976        unsafe { *pnode.out.0.get() = value };
977        self.rooms.release_n(room_idx, 1);
978        (&self.slot.get().waker, core::ptr::addr_of!(pnode.done.0))
979    }
980
981    fn run_multi_piece(&self, slot: usize, piece_idx: usize, custom: bool, use_sme2: bool) -> (*const AtomicUsize, bool) {
982        // Sound: the owner wrote the description before dispatching the slot's
983        // tasks (batch, submit_multi_slice), and writes it again only after
984        // `slot_done`.
985        let desc = unsafe { *self.multi[slot].get() };
986        assert!(piece_idx < desc.pieces, "the action names a piece of its submission");
987        let tree = self.tree_for_worker(slot, custom, use_sme2);
988        match desc.kind {
989            MultiKind::Batch { message_len, slot_len, per_part, count: total_count, digests: digests_ptr } => {
990                let first = piece_idx * per_part;
991                let count = (total_count - first).min(per_part);
992                // Sound: the batch and its digests stay in the slot (`batches[s]`)
993                // until the slot's event, which waits for `slot_done`; this task's
994                // messages and digests are its own range of them (`first`,
995                // `count`).
996                let bytes = unsafe { core::slice::from_raw_parts(desc.input.add(first * slot_len), count * slot_len) };
997                let digests = unsafe { core::slice::from_raw_parts_mut(digests_ptr.as_ptr().add(first), count) };
998                // Sound: `MultiKind::Batch` came from a validated `Prepared` batch
999                // (including zero-length messages padded to `BLOCK_LEN`) held alive
1000                // in `Pipeline::batches[slot]` until `slot_done`.
1001                let part = unsafe { crate::throughput::Part::from_checked_slots(bytes, message_len, slot_len) };
1002                tree.hash_many(&part, digests);
1003                (core::ptr::addr_of!(self.tasks_left[slot].0), true)
1004            }
1005            MultiKind::Slice { total_len, piece_level: level, .. } => {
1006                // Sound: the owner, or the Lent guard, keeps all the message's
1007                // bytes in place until the slot is done. The chunks of this slice
1008                // are the same partition the submitter put in the action list.
1009                let input = unsafe { core::slice::from_raw_parts(desc.input, total_len) };
1010                let bytes = input.chunks(CHUNK_LEN << level).nth(piece_idx).expect("a piece within its message");
1011                let values = self.cvs[slot].get();
1012                if piece_idx + 1 == desc.pieces {
1013                    let value = tree.last_cv((piece_idx as u64) << level, bytes);
1014                    // Sound: only the last piece writes this field.
1015                    unsafe { (*values).last = Some(value) };
1016                } else {
1017                    let value = tree.subtree_cv(level, piece_idx as u64, bytes);
1018                    // Sound: a separate slot for each index (submit_multi_slice
1019                    // limits the count); form no borrow of other workers' slots.
1020                    unsafe { core::ptr::addr_of_mut!((*values).whole).cast::<Cv>().add(piece_idx).write(value) };
1021                }
1022                (core::ptr::addr_of!(self.tasks_left[slot].0), false)
1023            }
1024        }
1025    }
1026
1027    fn finish_multi_slot(&self, slot: usize, is_batch: bool, custom: bool) -> (&'static WakerSlot, *const AtomicBool, Option<(&'static AtomicU64, u64)>) {
1028        let mut loan_mark = None;
1029        if !is_batch {
1030            // Sound: this is the slot's last task (`tasks_left` reached zero),
1031            // so every piece's value is written and no one else reads or
1032            // writes the slot's values or hash until `slot_done` below.
1033            let desc = unsafe { *self.multi[slot].get() };
1034            let MultiKind::Slice { total_len, loan_epoch, .. } = desc.kind else {
1035                unreachable!("finish_multi_slot called with !is_batch on a batch descriptor");
1036            };
1037            // Sound: last task of `slot` holds exclusive mutable access to `cvs[slot]` until `slot_done` below.
1038            let values = unsafe { &mut *self.cvs[slot].get() };
1039            let last = values.last.take().expect("the last piece supplied its value");
1040            let hash = fold_multi_cvs(self.tree_for(slot, custom), &values.whole[..desc.pieces - 1], last, total_len as u64);
1041            // Sound: last task of `slot` holds exclusive write access to `hashes[slot]` until `slot_done` below.
1042            unsafe { *self.hashes[slot].get() = *hash.as_bytes() };
1043            if loan_epoch != 0 {
1044                loan_mark = Some((&self.slot.get().loan_completed[slot].0, loan_epoch));
1045            }
1046        }
1047        (&self.slot.get().waker, core::ptr::addr_of!(self.slot_done[slot].0), loan_mark)
1048    }
1049}
1050
1051/// Settle the lazy merges of `count` equal-size pieces. The 1-bits of
1052/// `count` name the whole subtrees left on the stack, largest first.
1053fn merge_pieces(tree: &TreeHasher, stack: &mut [Cv], mut used: usize, count: u64) -> usize {
1054    let merges = used.saturating_sub(count.count_ones() as usize);
1055    for _ in 0..merges {
1056        stack[used - 2] = tree.parent_cv(&stack[used - 2], &stack[used - 1]);
1057        used -= 1;
1058    }
1059    used
1060}
1061
1062/// Add a whole piece. The same fold serves slice pieces and rooms.
1063fn push_piece(tree: &TreeHasher, stack: &mut [Cv], used: &mut usize, preceding: u64, piece: Cv) {
1064    let n = merge_pieces(tree, stack, *used, preceding);
1065    stack[n] = piece;
1066    *used = n + 1;
1067}
1068
1069/// The whole subtrees meet the final piece on the right edge. Check the
1070/// root against the submitted length.
1071fn finish_pieces(tree: &TreeHasher, stack: &mut [Cv], used: usize, count: u64, mut last: LastCv, len: u64) -> Hash {
1072    let used = merge_pieces(tree, stack, used, count);
1073    let (first, rest) = stack[..used].split_first().expect("a whole piece before the last");
1074    for left in rest.iter().rev() {
1075        last = tree.last_parent_cv(left, &last);
1076    }
1077    tree.root_hash(first, &last, len)
1078}
1079
1080fn fold_multi_cvs(tree: &TreeHasher, whole: &[Cv], last: LastCv, len: u64) -> Hash {
1081    // There is always a separate last piece. Below a power-of-two cap,
1082    // no push needs more slots than the cap's base-two logarithm.
1083    const { assert!(MAX_SLOT_PIECES.is_power_of_two()) };
1084    let mut stack = [Cv::unset(); MAX_SLOT_PIECES.ilog2() as usize];
1085    let mut used = 0;
1086    for (i, &value) in whole.iter().enumerate() {
1087        push_piece(tree, &mut stack, &mut used, i as u64, value);
1088    }
1089    finish_pieces(tree, &mut stack, used, whole.len() as u64, last, len)
1090}
1091
1092/// Compact hot-path slot state (24 bytes; multi-room state sits in `room_streams`).
1093#[derive(Clone, Copy)]
1094enum SlotKind {
1095    Free,
1096    OpenEmpty,
1097    OpenShort { room: u32, offset: u32, len: u32 },
1098    OpenShortDispatched { group: u32, epoch: u64 },
1099    OpenRooms { sealed: bool },
1100    WaitSingle { has_owner: bool, group: u32, epoch: u64 },
1101    WaitRoomMulti,
1102    WaitMulti { has_owner: bool },
1103    WaitBatch { group: u32, epoch: u64 },
1104    WaitAborted { group: u32, epoch: u64 },
1105}
1106
1107#[derive(Clone, Copy)]
1108struct RoomStream {
1109    len: u64,
1110    head_piece: u32,
1111    tail_piece: u32,
1112    /// Position of this slot in `Pipeline::piece_slots`, or `NONE` when `head_piece == NONE`.
1113    piece_slot_pos: u32,
1114    stack_len: usize,
1115    merged_pieces: u64,
1116}
1117
1118impl RoomStream {
1119    const EMPTY: Self = RoomStream { len: 0, head_piece: NONE, tail_piece: NONE, piece_slot_pos: NONE, stack_len: 0, merged_pieces: 0 };
1120}
1121
1122/// Public mode provenance of a slot for short-message group batching.
1123/// Never inspects or compares secret key bytes: keyed and derived modes
1124/// always use `Custom` and are never grouped across messages.
1125#[derive(Clone, Copy, PartialEq, Eq)]
1126enum SlotMode {
1127    Default,
1128    Plain,
1129    Custom,
1130}
1131
1132struct SlotMeta<T> {
1133    tag: Option<T>,
1134    kind: SlotKind,
1135    mode: SlotMode,
1136}
1137
1138process_static! {
1139    static NEXT_PIPELINE_ID: AtomicU64 = AtomicU64::new(1);
1140}
1141
1142/// Streaming multithreaded hasher with bounded memory and pull-based
1143/// [`Event`] delivery.
1144///
1145/// In a pool of one thread (`initialize_multithreaded` asked for one, or
1146/// a machine with one CPU) there is no worker, and the calling thread
1147/// hashes: in the calls that hand work over
1148/// ([`commit`](Pipeline::commit), [`end`](Pipeline::end),
1149/// [`owned`](Pipeline::owned), [`lent`](Pipeline::lent) and
1150/// [`batch`](Pipeline::batch)), and in the waits
1151/// ([`ready`](Pipeline::ready), [`room`](Pipeline::room) and
1152/// [`message`](Pipeline::message)). Short messages are gathered into
1153/// groups, and a group that is not yet full is hashed by a later call or
1154/// by a wait: so a short message's event may come only after `ready` has
1155/// been awaited, there as with workers, and its [`Lent`] guard is held
1156/// until its event.
1157///
1158/// Pipelines, and the other multithreaded calls made beside them, share
1159/// the pool's workers. A worker looks for work among them in one order,
1160/// and after every 16 takings it takes once from the next of them
1161/// that has any, going round (a taking is one action, or a run of a
1162/// call's pieces): a Pipeline that streams without a pause slows
1163/// another's messages, and does not keep them waiting while it streams.
1164/// The thread kept for SME2, where there is one, takes in the one order
1165/// only.
1166///
1167/// # Memory
1168///
1169/// A Pipeline allocates its per-pipeline storage (`Rooms` — 64 KiB each,
1170/// using a 1-byte-aligned zeroed byte buffer whose layout allows OS lazy
1171/// demand-zero paging under standard allocators such as `System`/`calloc`,
1172/// though custom allocators that eagerly zero on allocation will fault
1173/// those pages — plus its groups, piece nodes, slots, and completion
1174/// buffers) at construction and frees all of it back to the allocator once
1175/// the Pipeline and any surviving [`Room`]s have dropped. Completed
1176/// [`Lent`] guards do not pin per-pipeline storage. Because freeing
1177/// per-pipeline storage on drop makes repeated create/drop of equal limits
1178/// slower than reusing one Pipeline, keep a Pipeline alive across requests
1179/// (as `# Giving up a message` recommends) rather than creating and
1180/// dropping one per short message.
1181///
1182/// Only the worker-facing action ring (on pools with workers), waker slot, and
1183/// monotonic completion lines (`PipeSlot`) are retained for reuse by later
1184/// Pipelines:
1185/// - **Multi-worker pools (`threads > 1`):** 24 bytes per action (at least
1186///   1,024 actions = 24 KiB) plus 128-byte completion lines sized to the
1187///   rounded power-of-two tier (`cap / 64` slot lines and
1188///   `clamp(cap / 64, 4, 256)` group lines), where `cap` rounds up
1189///   `actions` (`messages * 64` when `rooms == 0`, else
1190///   `messages * 64 + rooms + messages + 1 + clamp(messages, 4, 256)`).
1191/// - **One-thread pools (`threads == 1`):** zero ticket slots are allocated or
1192///   retained (`actions_len() == 0`), while waker and completion lines size to
1193///   the power-of-two tier of `(messages * 64).max(1024)` (independent of
1194///   `rooms`).
1195///
1196/// Because slots round to powers of two and match exact-tier first then
1197/// best-fit (`loan_completed.len() * 64 >= need`), ascending `Limits` keep
1198/// retained power-of-two tier units (action-ring tickets on worker pools and
1199/// `loan_completed` lines on all pools) below twice the largest tier per peak
1200/// overlapping slot acquisition (counting concurrent constructors/destructors
1201/// from cache lookup through return to the free list; `group_completed` caps
1202/// at 256 lines per slot and fixed per-slot headers scale linearly with the
1203/// number of distinct retained tiers), and varying `Limits.rooms` within a
1204/// power-of-two tier reuses the same slot. As before, no call of this crate
1205/// wipes freed memory or keys.
1206///
1207/// # Giving up a message
1208///
1209/// The contract is the caller's, and a server's peers must not be able to
1210/// break it for the server:
1211///
1212/// - A message whose bytes will not all come (its client went away) goes
1213///   to [`abort`](Pipeline::abort). The Pipeline forgets it, gives its
1214///   [`Event::Aborted`], and goes on with the others. A `Message` that is
1215///   dropped instead panics.
1216/// - A Pipeline is dropped only when it has nothing left to hash: every
1217///   message ended or aborted, and every message's event taken with
1218///   [`next_event`](Pipeline::next_event). Dropped while a worker may
1219///   still be reading its buffers, it stops the whole process. (Dropped
1220///   earlier than this rule allows at a moment when nothing it has handed
1221///   to the pool is unfinished, it drops what it holds, and what it had
1222///   not handed over is never hashed.)
1223///
1224/// So keep a Pipeline in a task that outlives its clients (one for a
1225/// thread's connections, not one a connection), and do not let a
1226/// time-out or a cancelled task drop it mid-message.
1227///
1228/// # Panics
1229///
1230/// Each call says what it refuses. When `owned`, `lent`, or `batch` panics
1231/// on a [`Message`] of this Pipeline (bytes given two ways, a batch of the
1232/// wrong shape, or an owner's `as_ref` panicking), the rejected message's
1233/// slot is aborted cleanly (releasing any Room credit, dropping any
1234/// unwritten owner, and queuing [`Event::Aborted`]) so the Pipeline stays
1235/// usable and later [`message`](Pipeline::message) calls do not hang.
1236/// A `Message` given by value to another Pipeline is refused before that
1237/// Pipeline touches its own slots (so the refusing Pipeline goes on as it
1238/// was, while the other Pipeline's slot remains open with no `Message` left
1239/// to name it, and that other Pipeline is good only for dropping).
1240/// ([`commit`](Pipeline::commit) borrows its `Message`: after its panic
1241/// the `Message` is still the program's, and its drop panics as any open
1242/// Message's does, unless the thread is unwinding already.)
1243/// A [`Waker`](core::task::Waker) that panics when it is cloned or dropped
1244/// may leave the Pipeline usable only for dropping; a waker that panics
1245/// when it is woken ends the process, on whichever thread it is woken: the
1246/// wake comes in the middle of other work, which a panic would leave half
1247/// done.
1248///
1249/// ```
1250/// # blake3_servil::initialize_multithreaded(None);
1251/// use blake3_servil::{Mode, convenience, throughput::{Event, Limits, Pipeline, block_on}};
1252/// // A client's next bytes, or the error of one that went away.
1253/// async fn read(client: u32, into: &mut [u8]) -> std::io::Result<usize> {
1254///     if client == 1 {
1255///         return Err(std::io::ErrorKind::ConnectionReset.into());
1256///     }
1257///     into[..5].copy_from_slice(b"hello");
1258///     Ok(5)
1259/// }
1260///
1261/// let mut pipeline = Pipeline::new(Mode::Plain, Limits { messages: 2, rooms: 2 });
1262/// block_on(async {
1263///     for client in [0u32, 1, 2] {
1264///         let mut message = pipeline.message(client, None).await;
1265///         let mut room = pipeline.room().await;
1266///         match read(client, room.bytes_mut()).await {
1267///             Ok(n) => {
1268///                 pipeline.commit(&mut message, &mut room, n);
1269///                 pipeline.end(message);
1270///             }
1271///             // Not `?`: the message goes back first.
1272///             Err(_) => pipeline.abort(message),
1273///         }
1274///     }
1275///     // Every event taken: the Pipeline may then be dropped.
1276///     let mut seen = Vec::new();
1277///     while seen.len() < 3 {
1278///         match pipeline.next_event() {
1279///             Some(Event::Hashed { tag, hash, .. }) => seen.push((tag, Some(hash))),
1280///             Some(Event::Aborted { tag, .. }) => seen.push((tag, None)),
1281///             Some(_) => unreachable!(),
1282///             None => pipeline.ready().await,
1283///         }
1284///     }
1285///     let hello = Some(convenience::hash(b"hello"));
1286///     assert_eq!(seen, [(0, hello), (1, None), (2, hello)]);
1287/// });
1288/// ```
1289///
1290/// # Trait implementations
1291///
1292/// - `Drop` stops the process (an abort) if work it has handed to the
1293///   pool is unfinished, whether a worker is hashing it or it still waits
1294///   for one; otherwise it drops quietly, with the messages not yet handed
1295///   over, the events not taken and their owners, frees its per-pipeline
1296///   storage (once any surviving [`Room`]s also drop), and returns its
1297///   worker-facing slot for reuse.
1298/// - `Send` lets a pipeline move between threads when its tags, owners, and
1299///   batches are `Send`, keeping the same messages and tokens.
1300pub struct Pipeline<T, B = (), P = Batch<'static>> {
1301    id: u64,
1302    limits: Limits,
1303    group_count: usize,
1304    source_slot: Option<usize>,
1305    pipe_slot: &'static PipeSlot,
1306    storage: *mut PipeStorage,
1307    slots: Box<[SlotMeta<T>]>,
1308    room_streams: Box<[RoomStream]>,
1309    owners: RawSlots<B>,
1310    batches: RawSlots<(P, Box<[[u8; OUT_LEN]]>)>,
1311    /// FIFO ring of free message slots: slots cycle around the full ring
1312    /// before reuse so worker-written cache lines cool before another worker writes them.
1313    free_slots: IndexRing,
1314    open_messages: usize,
1315    end_queue: IndexRing,
1316    events: EventRing<Event<T, B, P>>,
1317    /// FIFO ring of free rooms, refilled by a circular cursor scan over `rooms.refs`.
1318    local_free_rooms: IndexRing,
1319    room_cursor: usize,
1320    /// FIFO ring of free `PieceNode`s.
1321    free_pieces: IndexRing,
1322    /// Active slots with `room_streams[s].head_piece != NONE` (at most `m.min(p_cap)`),
1323    /// maintained in O(1) so `alloc_piece_node` drains only piece-bearing slots (#465).
1324    piece_slots: Vec<u32>,
1325    /// Monotonic circular cursor over `0..group_count` (`MemberGroup`s cycle in FIFO order).
1326    group_cursor: usize,
1327    open_group: Option<(u32, u64)>,
1328    local_count: usize,
1329    local_bytes: usize,
1330    local_batch: Option<(usize, usize)>,
1331    /// Mode of the open group (`Default` or `Plain`; `Custom` groups publish
1332    /// immediately). Valid whenever `open_group.is_some()`.
1333    local_group_mode: SlotMode,
1334    /// Override slot index in `PipeStorage::slot_trees` for the open group, or
1335    /// `NONE` when the open group uses `PipeStorage::tree` (default mode).
1336    local_custom_slot: u32,
1337    /// Count of registered split `Pipeline::batch` plans not yet reaped.
1338    /// When zero, `try_reap_one` skips `PipelineBufs::batch_plans`.
1339    batches_in_flight: u32,
1340    next_loan_epoch: u64,
1341    next_group_epoch: u64,
1342    assigned_group_epoch: Box<[u64]>,
1343    seen_group_epoch: Box<[u64]>,
1344    bufs: Box<PipelineBufs>,
1345}
1346
1347// Sound: the Pipeline owns its tags, owners, and batches (hence
1348// `T: Send, B: Send, P: Send`); `storage` points to its owned `PipeStorage`
1349// (freed only once all tasks publish completion and all holders drop), and the
1350// other pointers reach buffers it holds.
1351unsafe impl<T: Send, B: Send, P: Send> Send for Pipeline<T, B, P> {}
1352
1353/// Per-pipeline staging buffers kept out of line in one `Box<PipelineBufs>`
1354/// (with `batch_plans` boxed separately: two heap allocations instead of three)
1355/// so hot inline `Pipeline` fields stay compact (BLAKE3 #556).
1356struct PipelineBufs {
1357    local_members: [Member; MEMBERS],
1358    local_rooms: [u32; MEMBERS],
1359    action_buf: [u64; MAX_SLOT_PIECES],
1360    /// Per-slot adaptive locality plan for registered split `Pipeline::batch`
1361    /// submissions (learning covers `[TASK_LEN, places::FAR_LEN)`).
1362    batch_plans: Box<[Option<Plan>]>,
1363}
1364
1365impl<T> Pipeline<T, (), Batch<'static>> {
1366    /// Create a pipeline in `mode` with fixed memory `limits`.
1367    ///
1368    /// # Panics
1369    ///
1370    /// If `limits.messages` is zero, or if `limits.messages` and
1371    /// `limits.rooms` together reach 2^29 - 1 (the Pipeline numbers its
1372    /// work in 29 bits). Before
1373    /// [`initialize_multithreaded`](crate::initialize_multithreaded), and
1374    /// in a child process forked after that call started the pool's
1375    /// threads.
1376    pub fn new(mode: Mode, limits: Limits) -> Self {
1377        Self::create(mode, limits)
1378    }
1379}
1380
1381impl<T, P: Prepared + 'static> Pipeline<T, (), P> {
1382    /// Create a pipeline whose [`Pipeline::batch`] accepts owned prepared
1383    /// batches of type `P`, such as [`Packed<16>`](crate::throughput::Packed),
1384    /// [`Packed<32>`](crate::throughput::Packed),
1385    /// [`Packed<48>`](crate::throughput::Packed), `Vec<[u8; 32]>`,
1386    /// `Box<[[u8; 32]]>`, or [`Batch<'static>`].
1387    ///
1388    /// # Panics
1389    ///
1390    /// As [`new`](Pipeline::new).
1391    pub fn with_batches(mode: Mode, limits: Limits) -> Self {
1392        Self::create(mode, limits)
1393    }
1394}
1395
1396// `B: 'static`: the workers read an owner's bytes until its message is
1397// hashed, and a Pipeline can be forgotten (`core::mem::forget`) while they
1398// do, which no borrow outlives soundly. An owner that borrows nothing
1399// keeps its bytes for as long as the forgotten Pipeline holds it: for
1400// good (BLAKE3 #417: a `&[u8]` was an owner, and safe code could free the
1401// bytes under the workers). Borrowed bytes are [`Pipeline::lent`]'s, which
1402// is unsafe for that reason.
1403impl<T, B: AsRef<[u8]> + 'static> Pipeline<T, B, Batch<'static>> {
1404    /// Create a pipeline that also accepts owned message buffers of type `B`
1405    /// ([`Pipeline::owned`]): a type that owns its bytes, such as `Vec<u8>`
1406    /// or `Box<[u8]>`.
1407    ///
1408    /// ```
1409    /// use blake3_servil::{Mode, throughput::{Limits, Pipeline}};
1410    /// fn pipeline_of<B: AsRef<[u8]> + 'static>(_first: B) -> Pipeline<(), B> {
1411    ///     Pipeline::with_owners(Mode::Plain, Limits { messages: 1, rooms: 0 })
1412    /// }
1413    /// # blake3_servil::initialize_multithreaded(None);
1414    /// let _ = pipeline_of(vec![0u8; 64]);
1415    /// ```
1416    ///
1417    /// A borrowed slice is no owner (the same code but for the borrow, so
1418    /// this fails for that reason):
1419    ///
1420    /// ```compile_fail
1421    /// use blake3_servil::{Mode, throughput::{Limits, Pipeline}};
1422    /// fn pipeline_of<'a>(_first: &'a [u8]) -> Pipeline<(), &'a [u8]> {
1423    ///     Pipeline::with_owners(Mode::Plain, Limits { messages: 1, rooms: 0 })
1424    /// }
1425    /// ```
1426    ///
1427    /// # Panics
1428    ///
1429    /// As [`new`](Pipeline::new).
1430    pub fn with_owners(mode: Mode, limits: Limits) -> Self {
1431        Self::create(mode, limits)
1432    }
1433}
1434
1435impl<T, B: AsRef<[u8]> + 'static, P: Prepared + 'static> Pipeline<T, B, P> {
1436    /// Create a pipeline that accepts both owned message buffers of type `B`
1437    /// ([`Pipeline::owned`]) and owned prepared batches of type `P`
1438    /// ([`Pipeline::batch`]).
1439    ///
1440    /// # Panics
1441    ///
1442    /// As [`new`](Pipeline::new).
1443    pub fn with_owners_and_batches(mode: Mode, limits: Limits) -> Self {
1444        Self::create(mode, limits)
1445    }
1446}
1447
1448impl<T, B: AsRef<[u8]> + 'static, P> Pipeline<T, B, P> {
1449    /// Hash `owner`'s bytes in place and return `owner` in the message's
1450    /// [`Event::Hashed`].
1451    ///
1452    /// # Panics
1453    ///
1454    /// If `message` is another Pipeline's, or has had a commit from a
1455    /// Room already, even one of no bytes: a message's bytes come one way.
1456    #[inline]
1457    pub fn owned(&mut self, message: Message, owner: B) {
1458        assert_eq!(message.pipeline_id, self.id, "Message belongs to a different Pipeline");
1459        let (_, s) = message.take();
1460        self.require_uncommitted(s);
1461
1462        // Sound: the slot is open and has no owner yet (require_uncommitted);
1463        // the owner stays in the move-insensitive raw slot, where its bytes
1464        // cannot move or be retagged by moving `Pipeline`, until the slot's
1465        // event reads it out or the Pipeline's drop drops it.
1466        let slot: *mut B = unsafe { (*self.owners.slot(s)).write(owner) };
1467        let pipe: *mut Self = self;
1468        // `as_ref` is the program's code. Until the slice is submitted
1469        // nothing records that the slot holds an owner, so if `as_ref`
1470        // unwinds, drop the owner in place and abort slot `s` cleanly so
1471        // `open_messages` stays exact and the Pipeline remains usable (#465).
1472        // The pointer fields (`pipe`, `slot`) are raw pointers: an owner may
1473        // hold its bytes inside itself (`[u8; 8]`), and forgetting a guard
1474        // holding `&mut` would retag it after the bytes' pointer was taken
1475        // (Miri, November 20).
1476        struct Unrecorded<T, B, P> {
1477            pipe: *mut Pipeline<T, B, P>,
1478            slot: *mut B,
1479            s: usize,
1480        }
1481        impl<T, B, P> Drop for Unrecorded<T, B, P> {
1482            fn drop(&mut self) {
1483                // Sound: the owner was written just above and nothing else
1484                // holds or records it; `self.pipe` points to this live
1485                // Pipeline; this runs only while `as_ref` unwinds (the guard
1486                // is forgotten once `as_ref` returns).
1487                unsafe {
1488                    core::ptr::drop_in_place(self.slot);
1489                    (*self.pipe).abort_slot(self.s);
1490                }
1491            }
1492        }
1493        let unrecorded = Unrecorded { pipe, slot, s };
1494        // Sound: the owner just written, in its slot, read through a
1495        // shared borrow; nothing else names it.
1496        let bytes: &[u8] = unsafe { &*slot }.as_ref();
1497        let (ptr, len) = (bytes.as_ptr(), bytes.len());
1498        core::mem::forget(unrecorded);
1499        self.open_messages -= 1;
1500        self.submit_slice(s, ptr, len, true);
1501        self.end_queue.push_back(u32::try_from(s).expect("slot fits u32"));
1502    }
1503}
1504
1505impl<T, B, P: Prepared + 'static> Pipeline<T, B, P> {
1506    /// Hash `batch` into `digests` and return both in [`Event::Batch`].
1507    ///
1508    /// Accepts any owned [`Prepared`] batch type `P` chosen when the pipeline
1509    /// was constructed ([`Batch<'static>`] by default, or
1510    /// [`Packed<N>`](crate::throughput::Packed) / `Vec<[u8; N]>` /
1511    /// `Box<[[u8; N]]>` via [`Pipeline::with_batches`] or
1512    /// [`Pipeline::with_owners_and_batches`]).
1513    ///
1514    /// # Panics
1515    ///
1516    /// If `message` is another Pipeline's, or has had a commit from a
1517    /// Room already (even one of no bytes); or if `digests` has not one place
1518    /// for each message of `batch`.
1519    pub fn batch(&mut self, message: Message, batch: P, digests: Box<[[u8; OUT_LEN]]>) {
1520        assert_eq!(message.pipeline_id, self.id, "Message belongs to a different Pipeline");
1521        let (_, s) = message.take();
1522        self.require_uncommitted(s);
1523        struct AbortOnUnwind<'a, T, B, P> {
1524            pipe: &'a mut Pipeline<T, B, P>,
1525            s: usize,
1526        }
1527        impl<T, B, P> Drop for AbortOnUnwind<'_, T, B, P> {
1528            fn drop(&mut self) {
1529                self.pipe.abort_slot(self.s);
1530            }
1531        }
1532        let guard = AbortOnUnwind { pipe: self, s };
1533        crate::assert_slots(batch.bytes(), batch.message_len(), batch.slot(), digests.len());
1534        core::mem::forget(guard);
1535        self.open_messages -= 1;
1536
1537        // Sound: the slot is open and holds no batch (require_uncommitted); the
1538        // batch and digests stay in the move-insensitive raw slot until its
1539        // event reads them out or the Pipeline's drop drops them.
1540        let hold = unsafe { (*self.batches.slot(s)).write((batch, digests)) };
1541        let msg_len = hold.0.message_len();
1542        let slot_len = hold.0.slot();
1543        let bytes = hold.0.bytes();
1544        let count = hold.1.len();
1545        let digests_ptr = hold.1.as_mut_ptr();
1546        let work_slot = slot_len.max(crate::BLOCK_LEN);
1547        let work_bytes = count.saturating_mul(work_slot);
1548
1549        if count == 0 {
1550            self.storage().slot_done[s].store(true, Ordering::Relaxed);
1551            self.slots[s].kind = SlotKind::WaitBatch { group: NONE, epoch: 0 };
1552        } else if work_bytes < TASK_LEN {
1553            let (group, epoch) = self.push_member(s, bytes.as_ptr(), bytes.len(), digests_ptr as *mut u8, NONE, Some((msg_len, slot_len)));
1554            self.slots[s].kind = SlotKind::WaitBatch { group, epoch };
1555        } else {
1556            self.slots[s].kind = SlotKind::WaitBatch { group: NONE, epoch: 0 };
1557            let per_part = (TASK_LEN / work_slot).max(1).max(count.div_ceil(MAX_SLOT_PIECES));
1558            let pieces = count.div_ceil(per_part);
1559            // Debug-only: `per_part` is chosen so `pieces <= MAX_SLOT_PIECES`.
1560            debug_assert!((1..=MAX_SLOT_PIECES).contains(&pieces));
1561            self.storage().slot_done[s].store(false, Ordering::Relaxed);
1562            self.storage().tasks_left[s].store(pieces, Ordering::Relaxed);
1563            let digests = core::ptr::NonNull::new(digests_ptr).expect("batch digest buffer is non-null");
1564            // Sound: no task of this slot is in flight (it was open), so its
1565            // description is the owner's to write before the dispatch below.
1566            unsafe {
1567                *self.storage().multi[s].get() =
1568                    MultiDesc { input: bytes.as_ptr(), pieces, kind: MultiKind::Batch { message_len: msg_len, slot_len, per_part, count, digests } }
1569            };
1570            let s32 = u32::try_from(s).expect("slot fits u32");
1571            let custom = self.slots[s].mode != SlotMode::Default;
1572            for p in 0..pieces {
1573                let first = p.saturating_mul(per_part);
1574                let piece_n = (count - first).min(per_part);
1575                let sme2 = piece_n.saturating_mul(work_slot) >= SME2_MIN_LEN;
1576                self.bufs.action_buf[p] = ActionArg::Multi { slot: s32, piece: u32::try_from(p).expect("piece fits u32"), custom, sme2 }.encode();
1577            }
1578            let near = if self.source_slot.is_some() {
1579                let plan = Plan::new(PlaceKind::PipelineBatch, work_bytes, 1);
1580                let near = plan.near();
1581                self.record_batch_plan(s, plan);
1582                near
1583            } else {
1584                false
1585            };
1586            self.dispatch_many(pieces, near);
1587        }
1588        self.end_queue.push_back(u32::try_from(s).expect("slot fits u32"));
1589    }
1590}
1591
1592/// Validate `Limits` and compute `(p_cap, g_cap, actions_cap)` without
1593/// allocating. Preserves the uniform public `Limits` contract (`messages > 0`
1594/// and `messages + rooms < (1 << 29) - 1`, matching 29-bit action indices in
1595/// `ActionArg`), including when `rooms == 0` allocates zero `PieceNode`s.
1596/// For roomless pipelines (`rooms == 0`), each message slot holds either a
1597/// split submission (at most `MAX_SLOT_PIECES = 64` actions) or a grouped
1598/// short message (at most 1 group ticket, never both), so `m * 64` actions
1599/// bound all unclaimed tickets without adding `g_cap`.
1600fn pipeline_capacities(limits: Limits) -> (usize, usize, usize) {
1601    assert!(limits.messages > 0, "Pipeline Limits.messages must be at least 1");
1602    let m = limits.messages;
1603    assert!(limits.messages.checked_add(limits.rooms).is_some_and(|sum| sum < (1 << 29) - 1), "Pipeline Limits beyond what an action can name");
1604    let g_cap = m.clamp(4, 256);
1605    let (p_cap, actions_cap) = if limits.rooms == 0 {
1606        (0, m * MAX_SLOT_PIECES)
1607    } else {
1608        let p_cap = limits.rooms + m + 1;
1609        (p_cap, m * MAX_SLOT_PIECES + p_cap + g_cap)
1610    };
1611    (p_cap, g_cap, actions_cap)
1612}
1613
1614/// Non-generic initialization of caller-side `IndexRing`s so every
1615/// `Pipeline<T, B, P>::create` monomorphization shares one compiled helper.
1616#[inline(never)]
1617fn init_pipeline_rings(m: usize, rooms: usize, p_cap: usize) -> (IndexRing, IndexRing, IndexRing, IndexRing) {
1618    let filled = |cap: usize| {
1619        let mut ring = IndexRing::new(cap);
1620        for i in 0..cap {
1621            ring.push_back(u32::try_from(i).expect("ring index fits u32"));
1622        }
1623        ring
1624    };
1625    (filled(rooms), filled(m), filled(p_cap), IndexRing::new(m))
1626}
1627
1628impl<T, B, P> Pipeline<T, B, P> {
1629    #[inline(always)]
1630    fn storage(&self) -> &PipeStorage {
1631        // Sound: this `Pipeline` holds a `PipeStorage::holders` reference
1632        // keeping `*self.storage` live until `Pipeline::drop`.
1633        unsafe { &*self.storage }
1634    }
1635
1636    fn create(mode: Mode, limits: Limits) -> Self {
1637        crate::lanes::require();
1638        prepare_thread();
1639        let (p_cap, g_cap, actions_cap) = pipeline_capacities(limits);
1640        let tree = TreeHasher::new(mode);
1641        let m = limits.messages;
1642        // Reserve a non-wrapping identity before acquiring storage or a source
1643        // slot, and keep exhaustion sticky at u64::MAX so a later caller cannot
1644        // wrap back to previously issued IDs.
1645        let id = loop {
1646            let cur = NEXT_PIPELINE_ID.load(Ordering::Relaxed);
1647            assert!(cur < u64::MAX, "Pipeline ID counter exhausted");
1648            if NEXT_PIPELINE_ID.compare_exchange(cur, cur + 1, Ordering::Relaxed, Ordering::Relaxed).is_ok() {
1649                break cur;
1650            }
1651        };
1652
1653        // Build all fallible caller-side arrays (including generic T/B/P slots)
1654        // BEFORE taking a PipeSlot lease, allocating PipeStorage, registering
1655        // the source, or bumping `sources::opened()`, so a layout panic in
1656        // caller-side construction cannot leak process resources.
1657        let (local_free_rooms, free_slots, free_pieces, end_queue) = init_pipeline_rings(m, limits.rooms, p_cap);
1658        let slots: Box<[SlotMeta<T>]> = (0..m).map(|_| SlotMeta { tag: None, kind: SlotKind::Free, mode: SlotMode::Default }).collect();
1659        let room_streams = vec![RoomStream::EMPTY; m].into_boxed_slice();
1660        let owners = RawSlots::new(m);
1661        let batches = RawSlots::new(m);
1662        let batch_plans = vec![None; m].into_boxed_slice();
1663        let events = EventRing::new(m);
1664        let piece_slots = Vec::with_capacity(if limits.rooms == 0 { 0 } else { m });
1665        let assigned_group_epoch = vec![0u64; g_cap].into_boxed_slice();
1666        let seen_group_epoch = vec![0u64; g_cap].into_boxed_slice();
1667        let bufs = Box::new(PipelineBufs {
1668            local_members: [Member { input: core::ptr::null(), len: 0, out: core::ptr::null_mut() }; MEMBERS],
1669            local_rooms: [NONE; MEMBERS],
1670            action_buf: [0; MAX_SLOT_PIECES],
1671            batch_plans,
1672        });
1673
1674        let (pipe_slot, next_group_epoch, next_loan_epoch) = PipeSlot::acquire(actions_cap, m);
1675        let storage = PipeStorage::alloc(pipe_slot, tree, m, limits.rooms, p_cap, g_cap);
1676        // A pool of one thread has no worker to take a published action,
1677        // and only this crate's block_on would run it: an outside executor
1678        // waited for ever. Unregistered, every action runs where it is
1679        // dispatched, as when no slot is free.
1680        let source_slot = if crate::lanes::pool_has_workers() { pipe_slot.source.register() } else { None };
1681        if source_slot.is_some() {
1682            crate::lanes::sources::opened();
1683        }
1684
1685        Pipeline {
1686            id,
1687            limits,
1688            group_count: g_cap,
1689            source_slot,
1690            pipe_slot,
1691            storage,
1692            slots,
1693            room_streams,
1694            owners,
1695            batches,
1696            free_slots,
1697            open_messages: 0,
1698            end_queue,
1699            events,
1700            local_free_rooms,
1701            room_cursor: 0,
1702            free_pieces,
1703            piece_slots,
1704            group_cursor: 0,
1705            open_group: None,
1706            local_count: 0,
1707            local_bytes: 0,
1708            local_batch: None,
1709            local_group_mode: SlotMode::Default,
1710            local_custom_slot: NONE,
1711            batches_in_flight: 0,
1712            next_loan_epoch,
1713            next_group_epoch,
1714            assigned_group_epoch,
1715            seen_group_epoch,
1716            bufs,
1717        }
1718    }
1719
1720    /// Wait for a free message slot and open a [`Message`] in this pipeline's
1721    /// default [`Mode`].
1722    ///
1723    /// `length_hint` is currently ignored (`None` suffices); actual message
1724    /// lengths are determined by the bytes submitted via `commit` + `end`,
1725    /// `lent`, `owned`, or `batch`.
1726    ///
1727    /// # Panics
1728    ///
1729    /// If no slot is free and waiting cannot free one: as many messages
1730    /// as `Limits.messages` are open, or as many events wait to be taken
1731    /// ([`next_event`](Pipeline::next_event)). Only this task could end
1732    /// one or take one, and it is here.
1733    #[inline(always)]
1734    pub fn message(&mut self, tag: T, length_hint: Option<u64>) -> impl Future<Output = Message> + '_ {
1735        let _ = length_hint;
1736        MessageOpenFut { pipe: self, tag: Some(tag), mode: DefaultOpenMode, registered: false }
1737    }
1738
1739    /// Wait for a free message slot and open a [`Message`] hashed in `mode`,
1740    /// overriding this pipeline's default [`Mode`] for that message alone.
1741    ///
1742    /// `length_hint` is currently ignored (`None` suffices); actual message
1743    /// lengths are determined by the bytes submitted via `commit` + `end`,
1744    /// `lent`, `owned`, or `batch`.
1745    ///
1746    /// `mode` is prepared immediately, so the returned future does not borrow
1747    /// `mode`'s key or context string. Short messages opened with
1748    /// [`Pipeline::message`] or `message_with(Mode::Plain, ..)` batch by
1749    /// public provenance; keyed and derived per-message modes are never
1750    /// grouped across messages so dispatch never depends on secret key bytes.
1751    ///
1752    /// # Panics
1753    ///
1754    /// Same as [`Pipeline::message`].
1755    #[inline(always)]
1756    pub fn message_with<'p>(&'p mut self, mode: Mode<'_>, tag: T, length_hint: Option<u64>) -> impl Future<Output = Message> + use<'p, T, B, P> {
1757        let _ = length_hint;
1758        let slot_mode = if matches!(mode, Mode::Plain) { SlotMode::Plain } else { SlotMode::Custom };
1759        MessageOpenFut { pipe: self, tag: Some(tag), mode: OverrideOpenMode(Some((TreeHasher::new(mode), slot_mode))), registered: false }
1760    }
1761
1762    #[cfg(test)]
1763    fn poll_message(&mut self, cx: &mut Context<'_>) -> Poll<u32> {
1764        if let Some(slot) = self.free_slots.pop_front() {
1765            return Poll::Ready(slot);
1766        }
1767        self.poll_message_slow(cx)
1768    }
1769
1770    fn poll_message_slow(&mut self, cx: &mut Context<'_>) -> Poll<u32> {
1771        self.reap();
1772        if let Some(slot) = self.free_slots.pop_front() {
1773            return Poll::Ready(slot);
1774        }
1775        self.assert_message_can_progress();
1776        if self.front_uses_open_group() {
1777            self.publish_open();
1778        }
1779        if in_block_on() {
1780            while self.pipe_slot.source.run_waiting_action() {
1781                self.reap();
1782                if let Some(slot) = self.free_slots.pop_front() {
1783                    return Poll::Ready(slot);
1784                }
1785            }
1786        }
1787        self.pipe_slot.waker.register(cx);
1788        self.reap();
1789        if let Some(slot) = self.free_slots.pop_front() {
1790            self.pipe_slot.waker.clear();
1791            return Poll::Ready(slot);
1792        }
1793        self.assert_message_can_progress();
1794        if self.source_slot.is_some() {
1795            self.pipe_slot.source.wake_for_waiting();
1796        }
1797        Poll::Pending
1798    }
1799
1800    fn assert_message_can_progress(&self) {
1801        assert!(
1802            self.events.len() < self.limits.messages,
1803            "Pipeline::message cannot make progress: {} finished events wait to be pulled (call next_event)",
1804            self.limits.messages
1805        );
1806        assert!(
1807            self.open_messages < self.limits.messages,
1808            "Pipeline::message cannot make progress: all {} message slots are held open by the caller",
1809            self.limits.messages
1810        );
1811    }
1812
1813    /// Wait for a [`Room`] of [`ROOM_LEN`] bytes.
1814    ///
1815    /// A Room is free again when it has been dropped, on any thread, and
1816    /// the bytes committed from it have been hashed. (A message's last
1817    /// commit of less than a whole Room may keep its Room until the
1818    /// message is ended or aborted, or until a wait here sends it on.) A
1819    /// program that keeps every Room alive waits here for ever.
1820    ///
1821    /// # Panics
1822    ///
1823    /// If the Pipeline has no Rooms (`Limits.rooms` is 0).
1824    #[inline(always)]
1825    pub fn room(&mut self) -> impl Future<Output = Room> + '_ {
1826        RoomFut { pipe: self, registered: false, done: false }
1827    }
1828
1829    #[inline(always)]
1830    fn pop_cached_room(&mut self) -> Option<Room> {
1831        let idx = self.local_free_rooms.pop_front()?;
1832        self.room_cursor = (idx as usize + 1) % self.limits.rooms;
1833        self.storage().rooms.init_taken(idx);
1834        Some(self.make_room(idx))
1835    }
1836
1837    #[inline]
1838    fn try_take_room(&mut self) -> Option<Room> {
1839        if self.local_free_rooms.is_empty() {
1840            // Sound: as `storage()`.
1841            let st = unsafe { &*self.storage };
1842            let count = st.rooms.count;
1843            let start = self.room_cursor;
1844            for step in 0..count {
1845                let i = (start + step) % count;
1846                if st.rooms.refs[i].load(Ordering::Acquire) == 0 {
1847                    self.local_free_rooms.push_back(u32::try_from(i).expect("room index fits u32"));
1848                }
1849            }
1850        }
1851        self.pop_cached_room()
1852    }
1853
1854    fn poll_room(&mut self, cx: &mut Context<'_>) -> Poll<Room> {
1855        if let Some(r) = self.try_take_room() {
1856            return Poll::Ready(r);
1857        }
1858        self.reap();
1859        self.flush_sealed_short_rooms();
1860        self.publish_open();
1861        if let Some(r) = self.try_take_room() {
1862            return Poll::Ready(r);
1863        }
1864        self.assert_room_can_progress();
1865        if in_block_on() {
1866            while self.pipe_slot.source.run_waiting_action() {
1867                if let Some(r) = self.try_take_room() {
1868                    return Poll::Ready(r);
1869                }
1870            }
1871        }
1872        self.pipe_slot.waker.register(cx);
1873        if let Some(r) = self.try_take_room() {
1874            self.pipe_slot.waker.clear();
1875            return Poll::Ready(r);
1876        }
1877        self.assert_room_can_progress();
1878        if self.source_slot.is_some() {
1879            self.pipe_slot.source.wake_for_waiting();
1880        }
1881        Poll::Pending
1882    }
1883
1884    #[inline(always)]
1885    fn make_room(&self, index: u32) -> Room {
1886        // Sound: `self.storage` came from `Box::into_raw` and is non-null.
1887        let storage = unsafe { core::ptr::NonNull::new_unchecked(self.storage) };
1888        Room { pipeline_id: self.id, index, offset: 0, commits: 0, ptr: self.storage().rooms.room_ptr(index as usize), storage }
1889    }
1890
1891    /// A Pipeline with no Rooms has none to wait for. One whose Rooms are
1892    /// all alive may be waited on: a Room is `Send`, and another thread's
1893    /// drop of one ends the wait (`Room::drop` wakes it).
1894    fn assert_room_can_progress(&self) {
1895        assert!(self.limits.rooms > 0, "Pipeline::room called on a Pipeline with Limits.rooms == 0");
1896    }
1897
1898    /// Commit the first `written` bytes of `room` as `message`'s next bytes.
1899    ///
1900    /// `room` advances to the next 64-byte boundary. Every commit to a
1901    /// message except its last must be a whole room (`ROOM_LEN` bytes).
1902    ///
1903    /// # Panics
1904    ///
1905    /// If `message` or `room` is another Pipeline's; if `written` is more
1906    /// than `room` has left ([`Room::len`]); if an earlier commit to
1907    /// `message` was of less than a whole Room.
1908    #[inline(always)]
1909    pub fn commit(&mut self, message: &mut Message, room: &mut Room, written: usize) {
1910        assert_eq!(message.pipeline_id, self.id, "Message belongs to a different Pipeline");
1911        assert_eq!(room.pipeline_id, self.id, "Room belongs to a different Pipeline");
1912        assert!(written <= room.len(), "commit wrote {written} bytes into a Room with {} left", room.len());
1913
1914        let s = message.slot as usize;
1915        if matches!(self.slots[s].kind, SlotKind::OpenEmpty) && written < ROOM_LEN {
1916            let start_offset = room.offset;
1917            room.offset = u32::try_from(((start_offset as usize + written).div_ceil(64) * 64).min(ROOM_LEN)).expect("bounded by ROOM_LEN");
1918            room.take_credit();
1919            self.slots[s].kind = SlotKind::OpenShort { room: room.index, offset: start_offset, len: u32::try_from(written).expect("written < ROOM_LEN") };
1920            return;
1921        }
1922        self.commit_multi(s, room, written);
1923    }
1924
1925    #[inline(never)]
1926    fn commit_multi(&mut self, s: usize, room: &mut Room, written: usize) {
1927        let start_offset = room.offset;
1928        let room_idx = room.index;
1929
1930        match self.slots[s].kind {
1931            SlotKind::OpenEmpty => {
1932                // Debug-only: an `OpenEmpty` slot always starts at offset 0 and finishes a full `ROOM_LEN` fill.
1933                debug_assert_eq!(written, ROOM_LEN);
1934                debug_assert_eq!(start_offset, 0);
1935                room.offset = u32::try_from(ROOM_LEN).unwrap();
1936                self.room_streams[s] = RoomStream::EMPTY;
1937                self.slots[s].kind = SlotKind::OpenRooms { sealed: false };
1938            }
1939            SlotKind::OpenShort { .. } | SlotKind::OpenShortDispatched { .. } | SlotKind::OpenRooms { sealed: true } => {
1940                panic!("commit after a commit of less than ROOM_LEN: every commit to a message but its last is a whole room");
1941            }
1942            SlotKind::OpenRooms { ref mut sealed } => {
1943                if written == ROOM_LEN {
1944                    // Debug-only: writing a full `ROOM_LEN` is only possible when starting at offset 0.
1945                    debug_assert_eq!(start_offset, 0);
1946                    room.offset = u32::try_from(ROOM_LEN).unwrap();
1947                } else {
1948                    *sealed = true;
1949                    room.offset = u32::try_from(((start_offset as usize + written).div_ceil(64) * 64).min(ROOM_LEN)).expect("bounded by ROOM_LEN");
1950                    if written == 0 {
1951                        return;
1952                    }
1953                }
1954            }
1955            _ => unreachable!("Message token refers to a non-open slot"),
1956        }
1957
1958        room.take_credit();
1959        let rs = &mut self.room_streams[s];
1960        // The earlier commits all filled a whole room. A short one
1961        // seals the message, so there can be no commit after it.
1962        let index = rs.len / ROOM_LEN as u64;
1963        rs.len = rs.len.checked_add(written as u64).expect("a message fits in u64 bytes");
1964
1965        self.drain_slot_pieces(s);
1966        let pnode = self.alloc_piece_node(s);
1967        // Sound: as `storage()`. The node came off the free list, so no task
1968        // uses it: its fields are the owner's to write before the dispatch
1969        // below.
1970        let st = unsafe { &*self.storage };
1971        let node = &st.pieces[pnode as usize];
1972        unsafe {
1973            *node.slot.get() = u32::try_from(s).expect("slot fits u32");
1974            *node.room.get() = room_idx;
1975            *node.offset.get() = start_offset;
1976            *node.len.get() = u32::try_from(written).expect("written <= ROOM_LEN");
1977            *node.index.get() = index;
1978            *node.next.get() = NONE;
1979        }
1980        node.done.store(false, Ordering::Relaxed);
1981
1982        let rs = &mut self.room_streams[s];
1983        if rs.tail_piece == NONE {
1984            rs.head_piece = pnode;
1985            rs.piece_slot_pos = u32::try_from(self.piece_slots.len()).expect("piece_slots length fits u32");
1986            self.piece_slots.push(u32::try_from(s).expect("slot fits u32"));
1987        } else {
1988            // Sound: `next` is the owner's alone (workers read a node's other
1989            // fields).
1990            unsafe { *st.pieces[rs.tail_piece as usize].next.get() = pnode };
1991        }
1992        rs.tail_piece = pnode;
1993
1994        let arg = ActionArg::RoomPiece { pnode, custom: self.slots[s].mode != SlotMode::Default, sme2: written >= SME2_MIN_LEN }.encode();
1995        self.dispatch_one(arg);
1996    }
1997
1998    fn alloc_piece_node(&mut self, current_slot: usize) -> u32 {
1999        if let Some(p) = self.free_pieces.pop_front() {
2000            return p;
2001        }
2002        loop {
2003            self.drain_slot_pieces(current_slot);
2004            self.reap();
2005            if self.free_pieces.is_empty() {
2006                // Every node may be another open message's: its later
2007                // pieces finished while a worker was on an earlier one,
2008                // and only a commit to it or its end would fold them.
2009                // Scan only slots that currently hold pieces (`<= piece_cap`),
2010                // not all `self.slots.len()` slots (#465). `keep_last = true`
2011                // keeps at least one piece per slot, so `piece_slots` stays fixed.
2012                for idx in 0..self.piece_slots.len() {
2013                    let other = self.piece_slots[idx] as usize;
2014                    self.drain_pieces(other, true);
2015                }
2016            }
2017            if let Some(p) = self.free_pieces.pop_front() {
2018                return p;
2019            }
2020            crate::lanes::require();
2021            if !self.pipe_slot.source.run_waiting_action() {
2022                core::hint::spin_loop();
2023            }
2024        }
2025    }
2026
2027    /// Finish `message` and queue its [`Event::Hashed`] in end order.
2028    ///
2029    /// # Panics
2030    ///
2031    /// If `message` is another Pipeline's.
2032    #[inline(always)]
2033    pub fn end(&mut self, message: Message) {
2034        assert_eq!(message.pipeline_id, self.id, "Message belongs to a different Pipeline");
2035        let s32 = message.slot;
2036        let (_, s) = message.take();
2037        self.open_messages -= 1;
2038
2039        match self.slots[s].kind {
2040            SlotKind::OpenShort { room: room_idx, offset, len } => {
2041                // Sound: the offset is within the room (commit checked
2042                // `written` against what was left).
2043                let ptr = unsafe { self.storage().rooms.room_ptr(room_idx as usize).add(offset as usize) };
2044                let out = self.storage().hashes[s].get() as *mut u8;
2045                let (group, epoch) = self.push_member(s, ptr, len as usize, out, room_idx, None);
2046                self.slots[s].kind = SlotKind::WaitSingle { has_owner: false, group, epoch };
2047                self.end_queue.push_back(s32);
2048            }
2049            _ => self.end_slow(s),
2050        }
2051    }
2052
2053    #[inline(never)]
2054    fn end_slow(&mut self, s: usize) {
2055        match self.slots[s].kind {
2056            SlotKind::OpenEmpty => {
2057                let empty_hash = self.storage().tree_for(s, self.slots[s].mode != SlotMode::Default).hash(&[]);
2058                // Sound: no task runs for an empty message, so the slot's hash
2059                // is the owner's to write.
2060                unsafe { *self.storage().hashes[s].get() = *empty_hash.as_bytes() };
2061                self.slots[s].kind = SlotKind::WaitSingle { has_owner: false, group: NONE, epoch: 0 };
2062            }
2063            SlotKind::OpenShortDispatched { group, epoch } => {
2064                self.slots[s].kind = SlotKind::WaitSingle { has_owner: false, group, epoch };
2065            }
2066            SlotKind::OpenRooms { .. } => {
2067                self.storage().slot_done[s].store(false, Ordering::Relaxed);
2068                self.slots[s].kind = SlotKind::WaitRoomMulti;
2069                self.drain_slot_pieces(s);
2070            }
2071            _ => unreachable!(),
2072        }
2073        self.end_queue.push_back(u32::try_from(s).expect("slot fits u32"));
2074    }
2075
2076    /// Abort `message` and queue its [`Event::Aborted`] in end order.
2077    ///
2078    /// # Panics
2079    ///
2080    /// If `message` is another Pipeline's.
2081    pub fn abort(&mut self, message: Message) {
2082        assert_eq!(message.pipeline_id, self.id, "Message belongs to a different Pipeline");
2083        let (_, s) = message.take();
2084        self.abort_slot(s);
2085    }
2086
2087    fn abort_slot(&mut self, s: usize) {
2088        self.open_messages -= 1;
2089
2090        match self.slots[s].kind {
2091            SlotKind::OpenEmpty => {
2092                self.slots[s].kind = SlotKind::WaitAborted { group: NONE, epoch: 0 };
2093            }
2094            SlotKind::OpenShort { room: room_idx, .. } => {
2095                // The record first, whole, and the wake last: the wake runs
2096                // the program's waker in the middle of this call. (A waker
2097                // that panics ends the process, in the waker slot's wake.
2098                // Until it did, such a panic, caught, could leave a slot
2099                // that still said it held the room's credit, to be given
2100                // back a second time.)
2101                self.slots[s].kind = SlotKind::WaitAborted { group: NONE, epoch: 0 };
2102                self.end_queue.push_back(u32::try_from(s).expect("slot fits u32"));
2103                if self.storage().rooms.release_n(room_idx, 1) {
2104                    self.pipe_slot.waker.notify_after_seqcst();
2105                }
2106                return;
2107            }
2108            SlotKind::OpenShortDispatched { group, epoch } => {
2109                self.slots[s].kind = SlotKind::WaitAborted { group, epoch };
2110            }
2111            SlotKind::OpenRooms { .. } => {
2112                self.slots[s].kind = SlotKind::WaitAborted { group: NONE, epoch: 0 };
2113                self.drain_slot_pieces(s);
2114            }
2115            _ => unreachable!(),
2116        }
2117        self.end_queue.push_back(u32::try_from(s).expect("slot fits u32"));
2118    }
2119
2120    /// Hash `bytes` in place on loan, returning a [`Lent`] guard.
2121    ///
2122    /// # Safety
2123    /// The returned [`Lent`] guard must be dropped and never leaked
2124    /// (`core::mem::forget`, `Box::leak`, a reference cycle, or a leaked
2125    /// task holding it).
2126    ///
2127    /// # Panics
2128    ///
2129    /// If `message` is another Pipeline's, or has had a commit from a
2130    /// Room already, even one of no bytes: a message's bytes come one way.
2131    #[inline(always)]
2132    pub unsafe fn lent<'a>(&mut self, message: Message, bytes: &'a [u8]) -> Lent<'a> {
2133        assert_eq!(message.pipeline_id, self.id, "Message belongs to a different Pipeline");
2134        let (_, s) = message.take();
2135        self.require_uncommitted(s);
2136        self.open_messages -= 1;
2137
2138        let (completed, epoch): (&'static AtomicU64, u64) = if bytes.len() <= TASK_LEN {
2139            let out = self.storage().hashes[s].get() as *mut u8;
2140            let (group, epoch) = self.push_member(s, bytes.as_ptr(), bytes.len(), out, NONE, None);
2141            self.slots[s].kind = SlotKind::WaitSingle { has_owner: false, group, epoch };
2142            (&self.pipe_slot.group_completed[group as usize].0, epoch)
2143        } else {
2144            let epoch = self.next_loan_epoch;
2145            self.next_loan_epoch = epoch.checked_add(1).expect("Pipeline loan epoch counter exhausted");
2146            self.submit_multi_slice(s, bytes.as_ptr(), bytes.len(), false, epoch);
2147            (&self.pipe_slot.loan_completed[s].0, epoch)
2148        };
2149        self.end_queue.push_back(u32::try_from(s).expect("slot fits u32"));
2150        Lent { completed, epoch, _bytes: PhantomData }
2151    }
2152
2153    /// Pull the next finished [`Event`], if one is ready.
2154    ///
2155    /// This takes what is finished and starts nothing. A message's work
2156    /// may wait for [`ready`](Pipeline::ready) (or another wait of this
2157    /// Pipeline) to hand it to the workers, so a loop that calls only
2158    /// this may never be given an event: where this gives `None`, await
2159    /// `ready`.
2160    #[inline(always)]
2161    pub fn next_event(&mut self) -> Option<Event<T, B, P>> {
2162        if let Some(ev) = self.events.pop_front() {
2163            return Some(ev);
2164        }
2165        self.try_reap_one()
2166    }
2167
2168    /// Wait until [`Pipeline::next_event`] has an [`Event`] ready.
2169    ///
2170    /// # Panics
2171    ///
2172    /// If no message has been ended (or aborted, or handed over whole)
2173    /// whose event is still to come: nothing would end the wait.
2174    #[inline(always)]
2175    pub fn ready(&mut self) -> impl Future<Output = ()> + '_ {
2176        ReadyFut { pipe: self, registered: false }
2177    }
2178
2179    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<()> {
2180        self.reap();
2181        if !self.events.is_empty() {
2182            return Poll::Ready(());
2183        }
2184        assert!(!self.end_queue.is_empty(), "Pipeline::ready cannot make progress: no ended messages are in flight");
2185        if self.front_uses_open_group() {
2186            self.publish_open();
2187            self.reap();
2188            if !self.events.is_empty() {
2189                return Poll::Ready(());
2190            }
2191        }
2192        if in_block_on() {
2193            while self.pipe_slot.source.run_waiting_action() {
2194                self.reap();
2195                if !self.events.is_empty() {
2196                    return Poll::Ready(());
2197                }
2198            }
2199        }
2200        self.pipe_slot.waker.register(cx);
2201        self.reap();
2202        if !self.events.is_empty() {
2203            self.pipe_slot.waker.clear();
2204            return Poll::Ready(());
2205        }
2206        if self.source_slot.is_some() {
2207            self.pipe_slot.source.wake_for_waiting();
2208        }
2209        Poll::Pending
2210    }
2211
2212    #[inline(always)]
2213    fn require_uncommitted(&mut self, s: usize) {
2214        match self.slots[s].kind {
2215            SlotKind::OpenEmpty => {}
2216            SlotKind::OpenShort { .. } | SlotKind::OpenShortDispatched { .. } | SlotKind::OpenRooms { .. } => {
2217                self.abort_slot(s);
2218                panic!("bytes given two ways: Message already has committed room bytes")
2219            }
2220            _ => unreachable!("Message token refers to a non-open slot"),
2221        }
2222    }
2223
2224    #[inline]
2225    fn submit_slice(&mut self, s: usize, ptr: *const u8, len: usize, has_owner: bool) {
2226        if len <= TASK_LEN {
2227            let out = self.storage().hashes[s].get() as *mut u8;
2228            let (group, epoch) = self.push_member(s, ptr, len, out, NONE, None);
2229            self.slots[s].kind = SlotKind::WaitSingle { has_owner, group, epoch };
2230            return;
2231        }
2232        self.submit_multi_slice(s, ptr, len, has_owner, 0);
2233    }
2234
2235    #[inline(never)]
2236    fn submit_multi_slice(&mut self, s: usize, ptr: *const u8, len: usize, has_owner: bool, loan_epoch: u64) {
2237        let mut piece_len = TASK_LEN;
2238        while len.div_ceil(piece_len) > MAX_SLOT_PIECES {
2239            piece_len *= 2;
2240        }
2241        let pieces = len.div_ceil(piece_len);
2242        assert!((2..=MAX_SLOT_PIECES).contains(&pieces), "a split message fits its piece slots");
2243        self.storage().slot_done[s].store(false, Ordering::Relaxed);
2244        self.storage().tasks_left[s].store(pieces, Ordering::Relaxed);
2245        // Sound: as `batch`'s, above.
2246        unsafe {
2247            *self.storage().multi[s].get() =
2248                MultiDesc { input: ptr, pieces, kind: MultiKind::Slice { total_len: len, piece_level: level_of(piece_len as u64), loan_epoch } }
2249        };
2250        self.slots[s].kind = SlotKind::WaitMulti { has_owner };
2251        let s32 = u32::try_from(s).expect("slot fits u32");
2252        let custom = self.slots[s].mode != SlotMode::Default;
2253        for p in 0..pieces {
2254            self.bufs.action_buf[p] = ActionArg::Multi { slot: s32, piece: u32::try_from(p).expect("piece fits u32"), custom, sme2: true }.encode();
2255        }
2256        self.dispatch_many(pieces, false);
2257    }
2258
2259    fn flush_sealed_short_rooms(&mut self) {
2260        for s in 0..self.slots.len() {
2261            if let SlotKind::OpenShort { room: room_idx, offset, len } = self.slots[s].kind {
2262                // Sound: as in `end`.
2263                let ptr = unsafe { self.storage().rooms.room_ptr(room_idx as usize).add(offset as usize) };
2264                let out = self.storage().hashes[s].get() as *mut u8;
2265                let (group, epoch) = self.push_member(s, ptr, len as usize, out, room_idx, None);
2266                self.slots[s].kind = SlotKind::OpenShortDispatched { group, epoch };
2267            }
2268        }
2269    }
2270
2271    /// Next free `MemberGroup` in FIFO ring order (`0, 1, ..., group_count - 1, 0, ...`),
2272    /// so a group completed on one worker CPU is not overwritten until a full lap later.
2273    fn acquire_free_group(&mut self) -> u32 {
2274        let count = self.group_count;
2275        loop {
2276            for _ in 0..count {
2277                let g = self.group_cursor;
2278                self.group_cursor = (g + 1) % count;
2279                let assigned = self.assigned_group_epoch[g];
2280                if assigned == 0 {
2281                    return u32::try_from(g).expect("group fits u32");
2282                }
2283                if self.seen_group_epoch[g] < assigned {
2284                    self.seen_group_epoch[g] = self.pipe_slot.group_completed[g].load(Ordering::Acquire);
2285                }
2286                if self.seen_group_epoch[g] >= assigned {
2287                    self.assigned_group_epoch[g] = 0;
2288                    return u32::try_from(g).expect("group fits u32");
2289                }
2290            }
2291            crate::lanes::require();
2292            if !self.pipe_slot.source.run_waiting_action() {
2293                core::hint::spin_loop();
2294            }
2295        }
2296    }
2297
2298    #[inline(always)]
2299    fn push_member(&mut self, slot: usize, input: *const u8, len: usize, out: *mut u8, room: u32, batch: Option<(usize, usize)>) -> (u32, u64) {
2300        let slot_mode = self.slots[slot].mode;
2301        if self.open_group.is_some() && (self.local_batch != batch || self.local_group_mode != slot_mode) {
2302            self.publish_open();
2303        }
2304        let (g, epoch) = match self.open_group {
2305            Some(pair) => pair,
2306            None => self.open_new_group(slot, slot_mode, batch),
2307        };
2308        let idx = self.local_count;
2309        self.bufs.local_members[idx] = Member { input, len, out };
2310        self.bufs.local_rooms[idx] = room;
2311        let after = idx + 1;
2312        let work_len = match batch {
2313            Some((_, slot)) => (len / slot).saturating_mul(slot.max(crate::BLOCK_LEN)),
2314            None => len,
2315        };
2316        let bytes = self.local_bytes.saturating_add(work_len);
2317        self.local_count = after;
2318        self.local_bytes = bytes;
2319        let byte_limit = if batch.is_some() { TASK_LEN } else { TASK_LEN / 4 };
2320        if after == MEMBERS || bytes >= byte_limit || slot_mode == SlotMode::Custom {
2321            self.publish_open();
2322        }
2323        (g, epoch)
2324    }
2325
2326    #[inline(never)]
2327    fn open_new_group(&mut self, slot: usize, slot_mode: SlotMode, batch: Option<(usize, usize)>) -> (u32, u64) {
2328        let g = self.acquire_free_group();
2329        let epoch = self.next_group_epoch;
2330        self.next_group_epoch = epoch.checked_add(1).expect("Pipeline group epoch counter exhausted");
2331        self.local_count = 0;
2332        self.local_bytes = 0;
2333        self.local_batch = batch;
2334        self.local_group_mode = slot_mode;
2335        self.local_custom_slot = if slot_mode == SlotMode::Default { NONE } else { u32::try_from(slot).expect("slot fits u32") };
2336        self.open_group = Some((g, epoch));
2337        (g, epoch)
2338    }
2339
2340    #[inline]
2341    fn front_uses_open_group(&self) -> bool {
2342        let Some((open_g, _)) = self.open_group else { return false };
2343        let Some(&front) = self.end_queue.front() else { return false };
2344        match self.slots[front as usize].kind {
2345            SlotKind::WaitSingle { group, .. } | SlotKind::WaitBatch { group, .. } | SlotKind::WaitAborted { group, .. } => group == open_g,
2346            _ => false,
2347        }
2348    }
2349
2350    #[inline(never)]
2351    fn publish_open(&mut self) {
2352        let Some((group_idx, epoch)) = self.open_group.take() else { return };
2353        let count = self.local_count;
2354        let group = &self.storage().groups[group_idx as usize];
2355        let custom_slot = self.local_custom_slot;
2356        // Sound: the group is not in flight (acquire_free_group gave it), so
2357        // its task, metas, and epoch are the owner's to write before the
2358        // dispatch below.
2359        unsafe {
2360            let task = &mut *group.task.get();
2361            task.batch = self.local_batch;
2362            task.members = count;
2363            task.member[..count].copy_from_slice(&self.bufs.local_members[..count]);
2364            let rooms = &mut *group.rooms.get();
2365            rooms[..count].copy_from_slice(&self.bufs.local_rooms[..count]);
2366            *group.epoch.get() = epoch;
2367        }
2368        self.assigned_group_epoch[group_idx as usize] = epoch;
2369        let arg = ActionArg::Group { group: group_idx, custom_slot }.encode();
2370        self.dispatch_one(arg);
2371    }
2372
2373    #[inline]
2374    fn dispatch_one(&mut self, arg: u64) {
2375        let ctx = self.storage as *const PipeStorage as *const ();
2376        match self.source_slot {
2377            // Sound: this Pipeline exclusively publishes to its `PipeSlot`'s
2378            // source (whose runner is `PipeStorage::run_action`), and
2379            // `*self.storage` stays live until this action publishes completion.
2380            Some(_) => unsafe { self.pipe_slot.source.publish_actions(ctx, core::slice::from_ref(&arg), false) },
2381            // Sound: `ctx` is this Pipeline's `PipeStorage`, as run_action requires.
2382            None => unsafe { PipeStorage::run_action(ctx, arg, false) },
2383        }
2384    }
2385
2386    fn dispatch_many(&mut self, count: usize, near: bool) {
2387        let ctx = self.storage as *const PipeStorage as *const ();
2388        match self.source_slot {
2389            // Sound: as dispatch_one's.
2390            Some(_) => unsafe { self.pipe_slot.source.publish_actions(ctx, &self.bufs.action_buf[..count], near) },
2391            None => {
2392                for i in 0..count {
2393                    let arg = self.bufs.action_buf[i];
2394                    // Sound: as dispatch_one's.
2395                    unsafe { PipeStorage::run_action(ctx, arg, false) };
2396                }
2397            }
2398        }
2399    }
2400
2401    #[inline(always)]
2402    fn group_ready(&mut self, group: u32, epoch: u64) -> bool {
2403        if group == NONE {
2404            return true;
2405        }
2406        let gi = group as usize;
2407        if self.seen_group_epoch[gi] >= epoch {
2408            return true;
2409        }
2410        let now = self.pipe_slot.group_completed[gi].load(Ordering::Acquire);
2411        self.seen_group_epoch[gi] = now;
2412        now >= epoch
2413    }
2414
2415    fn drain_slot_pieces(&mut self, s: usize) {
2416        self.drain_pieces(s, false);
2417    }
2418
2419    /// Fold slot `s`'s finished pieces, in order, up to the first still
2420    /// being hashed. `keep_last` leaves the newest piece: an open
2421    /// message may end with it, and the last piece folds as the root.
2422    fn drain_pieces(&mut self, s: usize, keep_last: bool) {
2423        // Sound: as `storage()`.
2424        let st = unsafe { &*self.storage };
2425        let tree = st.tree_for(s, self.slots[s].mode != SlotMode::Default);
2426        let ended = matches!(self.slots[s].kind, SlotKind::WaitRoomMulti);
2427        let aborted = matches!(self.slots[s].kind, SlotKind::WaitAborted { .. });
2428
2429        loop {
2430            let head = self.room_streams[s].head_piece;
2431            if head == NONE || (keep_last && head == self.room_streams[s].tail_piece) || !st.pieces[head as usize].done.load(Ordering::Acquire) {
2432                return;
2433            }
2434            // Sound: the piece is done (checked above), so its `next` and
2435            // `out` are the owner's again.
2436            let next = unsafe { *st.pieces[head as usize].next.get() };
2437            let out = unsafe { *st.pieces[head as usize].out.0.get() };
2438            self.free_pieces.push_back(head);
2439
2440            let rs = &mut self.room_streams[s];
2441            rs.head_piece = next;
2442            if next == NONE {
2443                rs.tail_piece = NONE;
2444                let pos = rs.piece_slot_pos;
2445                rs.piece_slot_pos = NONE;
2446                let idx = pos as usize;
2447                self.piece_slots.swap_remove(idx);
2448                if let Some(&moved) = self.piece_slots.get(idx) {
2449                    self.room_streams[moved as usize].piece_slot_pos = pos;
2450                }
2451            }
2452            let rs = &mut self.room_streams[s];
2453            if aborted {
2454                continue;
2455            }
2456
2457            // Sound: the caller alone writes a room message's stack
2458            // (workers write a slice message's slots, never both for one slot).
2459            let cvs = unsafe { &mut (*st.cvs[s].get()).whole };
2460            if ended && rs.merged_pieces + 1 == rs.len.div_ceil(ROOM_LEN as u64) {
2461                let root = match out {
2462                    RoomValue::First([left, right]) => tree.root_hash(&left, &right.into(), rs.len),
2463                    RoomValue::Whole(cv) => finish_pieces(tree, cvs, rs.stack_len, rs.merged_pieces, cv.into(), rs.len),
2464                    RoomValue::Last(last) => finish_pieces(tree, cvs, rs.stack_len, rs.merged_pieces, last, rs.len),
2465                };
2466                // Sound: the room message is done, with no other writer.
2467                unsafe { *st.hashes[s].get() = *root.as_bytes() };
2468                st.slot_done[s].store(true, Ordering::Relaxed);
2469                return;
2470            }
2471            let cv = match out {
2472                RoomValue::First([left, right]) => tree.parent_cv(&left, &right),
2473                RoomValue::Whole(cv) => cv,
2474                RoomValue::Last(_) => panic!("a short room is the last piece"),
2475            };
2476            push_piece(tree, cvs, &mut rs.stack_len, rs.merged_pieces, cv);
2477            rs.merged_pieces += 1;
2478        }
2479    }
2480
2481    #[inline(always)]
2482    fn try_reap_one(&mut self) -> Option<Event<T, B, P>> {
2483        let &front = self.end_queue.front()?;
2484        let s = front as usize;
2485
2486        let ready = match self.slots[s].kind {
2487            SlotKind::WaitSingle { group, epoch, .. } => self.group_ready(group, epoch),
2488            SlotKind::WaitMulti { .. } => self.storage().slot_done[s].load(Ordering::Acquire),
2489            SlotKind::WaitBatch { group, epoch } => {
2490                if group != NONE {
2491                    self.group_ready(group, epoch)
2492                } else {
2493                    self.storage().slot_done[s].load(Ordering::Acquire)
2494                }
2495            }
2496            SlotKind::WaitRoomMulti => {
2497                self.drain_slot_pieces(s);
2498                self.storage().slot_done[s].load(Ordering::Acquire)
2499            }
2500            SlotKind::WaitAborted { group, epoch } => {
2501                self.drain_slot_pieces(s);
2502                let rooms_done = self.room_streams[s].head_piece == NONE;
2503                rooms_done && self.group_ready(group, epoch)
2504            }
2505            SlotKind::Free | SlotKind::OpenEmpty | SlotKind::OpenShort { .. } | SlotKind::OpenShortDispatched { .. } | SlotKind::OpenRooms { .. } => {
2506                unreachable!()
2507            }
2508        };
2509        if !ready {
2510            return None;
2511        }
2512
2513        self.end_queue.pop_front();
2514        let tag = self.slots[s].tag.take().expect("ended slot holds its tag");
2515        let kind = core::mem::replace(&mut self.slots[s].kind, SlotKind::Free);
2516        let event = match kind {
2517            SlotKind::WaitAborted { .. } => Event::Aborted { tag, owner: None },
2518            SlotKind::WaitSingle { has_owner, .. } | SlotKind::WaitMulti { has_owner } => {
2519                // Sound: the slot's work is done (`ready`), so its hash has no
2520                // writer; `has_owner` says the slot holds an owner, read out
2521                // here once (the slot is then Free).
2522                let hash = Hash::from_bytes(unsafe { *self.storage().hashes[s].get() });
2523                let owner = if has_owner { Some(unsafe { (*self.owners.slot(s)).assume_init_read() }) } else { None };
2524                Event::Hashed { tag, hash, owner }
2525            }
2526            SlotKind::WaitRoomMulti => {
2527                // Sound: as above.
2528                let hash = Hash::from_bytes(unsafe { *self.storage().hashes[s].get() });
2529                Event::Hashed { tag, hash, owner: None }
2530            }
2531            SlotKind::WaitBatch { .. } => {
2532                if self.batches_in_flight != 0 {
2533                    self.finish_batch_plan(s);
2534                }
2535                // Sound: a WaitBatch slot holds its batch and digests (batch
2536                // wrote them), read out here once.
2537                let (batch, digests) = unsafe { (*self.batches.slot(s)).assume_init_read() };
2538                Event::Batch { tag, batch, digests }
2539            }
2540            _ => unreachable!(),
2541        };
2542        self.free_slots.push_back(front);
2543        return Some(event);
2544    }
2545
2546    #[cold]
2547    #[inline(never)]
2548    fn record_batch_plan(&mut self, s: usize, mut plan: Plan) {
2549        self.batches_in_flight += 1;
2550        plan.in_flight = self.batches_in_flight as usize;
2551        self.bufs.batch_plans[s] = Some(plan);
2552    }
2553
2554    #[cold]
2555    #[inline(never)]
2556    fn finish_batch_plan(&mut self, s: usize) {
2557        if let Some(plan) = self.bufs.batch_plans[s].take() {
2558            self.batches_in_flight -= 1;
2559            plan.done();
2560        }
2561    }
2562
2563    fn reap(&mut self) {
2564        while self.events.len() < self.limits.messages {
2565            let Some(ev) = self.try_reap_one() else { break };
2566            self.events.push_back(ev);
2567        }
2568    }
2569
2570    fn has_in_flight_work(&self) -> bool {
2571        let st = self.storage();
2572        let slot = self.pipe_slot;
2573        for g in 0..self.group_count {
2574            let assigned = self.assigned_group_epoch[g];
2575            if assigned != 0 && slot.group_completed[g].load(Ordering::Acquire) < assigned {
2576                return true;
2577            }
2578        }
2579        for p in &st.pieces {
2580            if !p.done.load(Ordering::Acquire) {
2581                return true;
2582            }
2583        }
2584        for s in 0..self.slots.len() {
2585            match self.slots[s].kind {
2586                SlotKind::WaitMulti { .. } | SlotKind::WaitBatch { group: NONE, .. } => {
2587                    if !st.slot_done[s].load(Ordering::Acquire) {
2588                        return true;
2589                    }
2590                }
2591                _ => {}
2592            }
2593        }
2594        false
2595    }
2596}
2597
2598impl<T, B, P> Drop for Pipeline<T, B, P> {
2599    fn drop(&mut self) {
2600        if self.has_in_flight_work() {
2601            stop_process("blake3-servil: Pipeline dropped while worker tasks are still in flight\n");
2602        }
2603        // Release any credits held on uncommitted short rooms sitting in un-ended slots
2604        // (e.g. during panic unwind after a precondition check failed with zero workers running).
2605        for s in 0..self.slots.len() {
2606            if let SlotKind::OpenShort { room: room_idx, .. } = self.slots[s].kind {
2607                self.storage().rooms.release_n(room_idx, 1);
2608            }
2609        }
2610        if self.open_group.take().is_some() {
2611            for &r in &self.bufs.local_rooms[..self.local_count] {
2612                if r != NONE {
2613                    self.storage().rooms.release_n(r, 1);
2614                }
2615            }
2616        }
2617        if let Some(slot) = self.source_slot {
2618            Source::unregister(slot);
2619            crate::lanes::sources::closed();
2620        }
2621        let storage_ptr = self.storage;
2622        let storage = self.storage();
2623        let pipe_slot = self.pipe_slot;
2624        // Pre-reserve one hold per room slot before stamping ROOM_CLOSING_BIT so
2625        // any surviving Room dropped concurrently on another thread cannot drop
2626        // `storage.holders` to 0 while this loop is still running.
2627        let room_count = storage.rooms.count;
2628        storage.holders.fetch_add(room_count, Ordering::Relaxed);
2629        let mut survivors = 0usize;
2630        for r in &storage.rooms.refs {
2631            let prev = r.fetch_or(ROOM_CLOSING_BIT, Ordering::SeqCst);
2632            if prev != 0 {
2633                survivors += 1;
2634            }
2635        }
2636        let release_holds = (room_count - survivors) + 1;
2637        let next_group_epoch = self.next_group_epoch;
2638        let next_loan_epoch = self.next_loan_epoch;
2639        struct ReleaseStorage {
2640            storage: *mut PipeStorage,
2641            holds: usize,
2642            slot: &'static PipeSlot,
2643            next_group_epoch: u64,
2644            next_loan_epoch: u64,
2645        }
2646        impl Drop for ReleaseStorage {
2647            fn drop(&mut self) {
2648                PipeSlot::release(self.slot, self.next_group_epoch, self.next_loan_epoch);
2649                // Sound: `Pipeline::drop` verified zero outstanding worker work,
2650                // returned local room credits, reserved `room_count` holds before
2651                // stamping `ROOM_CLOSING_BIT`, and surrenders
2652                // `release_holds = (room_count - survivors) + 1` unique holds
2653                // (all non-surviving rooms plus the Pipeline's initial hold).
2654                unsafe { PipeStorage::release_n(self.storage, self.holds) };
2655            }
2656        }
2657        struct DrainPending<'a, T, B, P>(&'a mut Pipeline<T, B, P>);
2658        impl<T, B, P> Drop for DrainPending<'_, T, B, P> {
2659            fn drop(&mut self) {
2660                while let Some(s_idx) = self.0.end_queue.pop_front() {
2661                    let s = s_idx as usize;
2662                    match core::mem::replace(&mut self.0.slots[s].kind, SlotKind::Free) {
2663                        SlotKind::WaitSingle { has_owner: true, .. } | SlotKind::WaitMulti { has_owner: true } => {
2664                            let ptr = self.0.owners.slot(s);
2665                            let _rest = DrainPending(&mut *self.0);
2666                            // Sound: a slot waiting with `has_owner` holds an owner no
2667                            // event took.
2668                            unsafe { (*ptr).assume_init_drop() };
2669                            core::mem::forget(_rest);
2670                        }
2671                        SlotKind::WaitBatch { .. } => {
2672                            let ptr = self.0.batches.slot(s);
2673                            let _rest = DrainPending(&mut *self.0);
2674                            // Sound: a WaitBatch slot holds its batch and digests.
2675                            unsafe { (*ptr).assume_init_drop() };
2676                            core::mem::forget(_rest);
2677                        }
2678                        _ => {}
2679                    }
2680                }
2681            }
2682        }
2683        // Guards run in LIFO order (`_drain` then `_release`), so even if
2684        // dropping the saved waker or one owner unwinds, every remaining owner
2685        // and batch still drops, `PipeSlot` returns to `FREE_PIPE_SLOTS`, and
2686        // `PipeStorage` is released cleanly.
2687        let _release = ReleaseStorage { storage: storage_ptr, holds: release_holds, slot: pipe_slot, next_group_epoch, next_loan_epoch };
2688        let _drain = DrainPending(self);
2689        pipe_slot.waker.clear();
2690    }
2691}
2692
2693trait OpenSlotMode {
2694    fn install(&mut self, storage: &PipeStorage, slot: usize) -> SlotMode;
2695}
2696
2697struct DefaultOpenMode;
2698impl OpenSlotMode for DefaultOpenMode {
2699    #[inline(always)]
2700    fn install(&mut self, _storage: &PipeStorage, _slot: usize) -> SlotMode {
2701        SlotMode::Default
2702    }
2703}
2704
2705struct OverrideOpenMode(Option<(TreeHasher, SlotMode)>);
2706impl OpenSlotMode for OverrideOpenMode {
2707    #[inline(always)]
2708    fn install(&mut self, storage: &PipeStorage, slot: usize) -> SlotMode {
2709        let (tree, slot_mode) = self.0.take().expect("message_with tree present before completion");
2710        // Sound: `slot` just came off `free_slots`, so no worker task reads
2711        // `slot_trees[slot]` until work is dispatched for `slot`.
2712        unsafe { *storage.slot_trees[slot].get() = tree };
2713        slot_mode
2714    }
2715}
2716
2717struct MessageOpenFut<'a, T, B, P, M: OpenSlotMode> {
2718    pipe: &'a mut Pipeline<T, B, P>,
2719    tag: Option<T>,
2720    mode: M,
2721    registered: bool,
2722}
2723
2724impl<T, B, P, M: OpenSlotMode> Unpin for MessageOpenFut<'_, T, B, P, M> {}
2725
2726impl<T, B, P, M: OpenSlotMode> Drop for MessageOpenFut<'_, T, B, P, M> {
2727    fn drop(&mut self) {
2728        if self.registered {
2729            self.pipe.pipe_slot.waker.clear();
2730        }
2731    }
2732}
2733
2734impl<T, B, P, M: OpenSlotMode> Future for MessageOpenFut<'_, T, B, P, M> {
2735    type Output = Message;
2736
2737    #[inline(always)]
2738    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Message> {
2739        let this = &mut *self;
2740        assert!(this.tag.is_some(), "Pipeline::message future polled after completion");
2741        let slot = match this.pipe.free_slots.pop_front() {
2742            Some(s) => s,
2743            None => match this.pipe.poll_message_slow(cx) {
2744                Poll::Ready(s) => s,
2745                Poll::Pending => {
2746                    this.registered = true;
2747                    return Poll::Pending;
2748                }
2749            },
2750        };
2751        this.registered = false;
2752        let mode = this.mode.install(this.pipe.storage(), slot as usize);
2753        let sm = &mut this.pipe.slots[slot as usize];
2754        sm.tag = this.tag.take();
2755        sm.kind = SlotKind::OpenEmpty;
2756        sm.mode = mode;
2757        this.pipe.open_messages += 1;
2758        Poll::Ready(Message { pipeline_id: this.pipe.id, slot })
2759    }
2760}
2761
2762struct RoomFut<'a, T, B, P> {
2763    pipe: &'a mut Pipeline<T, B, P>,
2764    registered: bool,
2765    done: bool,
2766}
2767
2768impl<T, B, P> Unpin for RoomFut<'_, T, B, P> {}
2769
2770impl<T, B, P> Drop for RoomFut<'_, T, B, P> {
2771    fn drop(&mut self) {
2772        if self.registered {
2773            self.pipe.pipe_slot.waker.clear();
2774        }
2775    }
2776}
2777
2778impl<T, B, P> Future for RoomFut<'_, T, B, P> {
2779    type Output = Room;
2780
2781    #[inline(always)]
2782    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Room> {
2783        assert!(!self.done, "Pipeline::room future polled after completion");
2784        if let Some(r) = self.pipe.pop_cached_room() {
2785            self.registered = false;
2786            self.done = true;
2787            return Poll::Ready(r);
2788        }
2789        match self.pipe.poll_room(cx) {
2790            Poll::Ready(r) => {
2791                self.registered = false;
2792                self.done = true;
2793                Poll::Ready(r)
2794            }
2795            Poll::Pending => {
2796                self.registered = true;
2797                Poll::Pending
2798            }
2799        }
2800    }
2801}
2802
2803struct ReadyFut<'a, T, B, P> {
2804    pipe: &'a mut Pipeline<T, B, P>,
2805    registered: bool,
2806}
2807
2808impl<T, B, P> Unpin for ReadyFut<'_, T, B, P> {}
2809
2810impl<T, B, P> Drop for ReadyFut<'_, T, B, P> {
2811    fn drop(&mut self) {
2812        if self.registered {
2813            self.pipe.pipe_slot.waker.clear();
2814        }
2815    }
2816}
2817
2818impl<T, B, P> Future for ReadyFut<'_, T, B, P> {
2819    type Output = ();
2820
2821    #[inline(always)]
2822    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
2823        if !self.pipe.events.is_empty() {
2824            self.registered = false;
2825            return Poll::Ready(());
2826        }
2827        match self.pipe.poll_ready(cx) {
2828            Poll::Ready(()) => {
2829                self.registered = false;
2830                Poll::Ready(())
2831            }
2832            Poll::Pending => {
2833                self.registered = true;
2834                Poll::Pending
2835            }
2836        }
2837    }
2838}
2839
2840/// `block_on`'s waker: it wakes its thread, and remembers that it did.
2841struct ThreadPark {
2842    thread: thread::Thread,
2843    /// Set by a wake; taken by `block_on` before it sleeps. The thread's
2844    /// park token alone would not do: another wait on the same thread (a
2845    /// `block_on` inside a poll, a blocking receive) takes the token, and
2846    /// the wake with it.
2847    woken: AtomicBool,
2848}
2849
2850impl std::task::Wake for ThreadPark {
2851    fn wake(self: Arc<Self>) {
2852        self.wake_by_ref();
2853    }
2854    fn wake_by_ref(self: &Arc<Self>) {
2855        self.woken.store(true, Ordering::Release);
2856        self.thread.unpark();
2857    }
2858}
2859
2860crate::pipeline_sync::thread_local! {
2861    static BLOCK_ON_PARK: Arc<ThreadPark> = Arc::new(ThreadPark { thread: thread::current(), woken: AtomicBool::new(false) });
2862    static BLOCK_ON_WAKER: Waker = BLOCK_ON_PARK.with(|park| Waker::from(Arc::clone(park)));
2863    static IN_BLOCK_ON: core::cell::Cell<bool> = const { core::cell::Cell::new(false) };
2864}
2865
2866#[inline(always)]
2867fn in_block_on() -> bool {
2868    IN_BLOCK_ON.try_with(core::cell::Cell::get).unwrap_or(false)
2869}
2870
2871fn prepare_thread() {
2872    let _ = BLOCK_ON_WAKER.try_with(|_| {});
2873}
2874
2875/// Drive `future` to completion on the current thread, parking between polls.
2876///
2877/// A `block_on` may run inside a poll of another on the same thread (a
2878/// future whose poll calls a helper built on this function). The two
2879/// share the thread's waker, and the inner one may take a wake that was
2880/// the outer one's: so when the inner one has taken a wake (whether it
2881/// slept for it or found it noted already), the outer future is polled
2882/// once more before it sleeps, whether or not the wake was its own. A
2883/// future whose every poll runs a `block_on` that takes a wake is
2884/// therefore polled again after each, with no wake of its own.
2885///
2886/// # Panics
2887///
2888/// On a thread that is ending, once its thread-local values are being
2889/// destroyed: `block_on` keeps its waker and its state in thread-local
2890/// storage, and a call from the destructor of another thread-local value
2891/// may find them gone (the standard library's panic for that).
2892///
2893/// # Examples
2894///
2895/// Two messages open at once, fed in turns, with `Pipeline` called again while
2896/// handling a completed event:
2897/// ```
2898/// # blake3_servil::initialize_multithreaded(None);
2899/// use blake3_servil::{Mode, convenience, throughput::{Event, Limits, Pipeline, block_on}};
2900///
2901/// let mut pipeline = Pipeline::new(Mode::Plain, Limits { messages: 4, rooms: 4 });
2902/// block_on(async {
2903///     let mut a = pipeline.message("A", None).await;
2904///     let mut b = pipeline.message("B", None).await;
2905///     let mut room = pipeline.room().await;
2906///     room.bytes_mut()[..3].copy_from_slice(b"foo");
2907///     pipeline.commit(&mut a, &mut room, 3);
2908///     room.bytes_mut()[..4].copy_from_slice(b"quux");
2909///     pipeline.commit(&mut b, &mut room, 4);
2910///     drop(room);
2911///     pipeline.end(a);
2912///     pipeline.end(b);
2913///     pipeline.ready().await;
2914///     let mut seen = Vec::new();
2915///     while seen.len() < 2 {
2916///         if let Some(Event::Hashed { tag, hash, .. }) = pipeline.next_event() {
2917///             seen.push((tag, hash));
2918///             if tag == "A" {
2919///                 let follow = pipeline.message("C", None).await;
2920///                 pipeline.end(follow);
2921///             }
2922///         } else {
2923///             pipeline.ready().await;
2924///         }
2925///     }
2926///     assert_eq!(seen[0], ("A", convenience::hash(b"foo")));
2927///     assert_eq!(seen[1], ("B", convenience::hash(b"quux")));
2928///     while pipeline.next_event().is_none() {
2929///         pipeline.ready().await;
2930///     }
2931/// });
2932/// ```
2933///
2934/// A task holding a `Pipeline`, `Message`, and `Room` across `.await` is `Send`
2935/// and `'static` (what `tokio::spawn` requires):
2936/// ```
2937/// # blake3_servil::initialize_multithreaded(None);
2938/// use blake3_servil::{Mode, throughput::{Limits, Pipeline, block_on}};
2939/// fn assert_send_static<F: core::future::Future + Send + 'static>(f: F) -> F { f }
2940/// async fn read(into: &mut [u8]) -> usize { into[..5].copy_from_slice(b"hello"); 5 }
2941///
2942/// let task = assert_send_static(async {
2943///     let mut pipeline = Pipeline::<u64, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 2, rooms: 4 });
2944///     let mut m = pipeline.message(7, None).await;
2945///     let mut room = pipeline.room().await;
2946///     let n = read(room.bytes_mut()).await;
2947///     pipeline.commit(&mut m, &mut room, n);
2948///     drop(room);
2949///     pipeline.end(m);
2950///     let whole = pipeline.message(8, None).await;
2951///     pipeline.owned(whole, vec![1, 2, 3]);
2952///     let mut got = 0;
2953///     while got < 2 {
2954///         if pipeline.next_event().is_some() { got += 1; } else { pipeline.ready().await; }
2955///     }
2956/// });
2957/// block_on(task);
2958/// ```
2959///
2960/// A message used after `end` is refused by the compiler:
2961/// ```compile_fail,E0382
2962/// use blake3_servil::throughput::{Pipeline, Room};
2963/// async fn bad(pipeline: &mut Pipeline<u64>, room: &mut Room) {
2964///     let mut m = pipeline.message(1, None).await;
2965///     pipeline.end(m);
2966///     pipeline.commit(&mut m, room, 1);
2967/// }
2968/// ```
2969///
2970/// A lent buffer cannot be freed while its [`Lent`] guard lives:
2971/// ```compile_fail,E0505
2972/// use blake3_servil::throughput::Pipeline;
2973/// async fn bad(pipeline: &mut Pipeline<u64>) {
2974///     let buffer = vec![0u8; 1024];
2975///     let m = pipeline.message(1, None).await;
2976///     let guard = unsafe { pipeline.lent(m, &buffer) };
2977///     drop(buffer);
2978///     pipeline.ready().await;
2979///     drop(guard);
2980/// }
2981/// ```
2982///
2983/// nor mutated while its [`Lent`] guard lives:
2984/// ```compile_fail,E0502
2985/// use blake3_servil::throughput::Pipeline;
2986/// async fn bad(pipeline: &mut Pipeline<u64>) {
2987///     let mut buffer = vec![0u8; 1024];
2988///     let m = pipeline.message(1, None).await;
2989///     let guard = unsafe { pipeline.lent(m, &buffer) };
2990///     buffer[0] = 1;
2991///     pipeline.ready().await;
2992///     drop(guard);
2993/// }
2994/// ```
2995///
2996/// Held until the event exists, `lent` compiles and drops cleanly before the buffer:
2997/// ```
2998/// # blake3_servil::initialize_multithreaded(None);
2999/// use blake3_servil::{Mode, convenience, throughput::{Event, Limits, Pipeline, block_on}};
3000/// let mut pipeline = Pipeline::new(Mode::Plain, Limits { messages: 2, rooms: 0 });
3001/// block_on(async {
3002///     let buffer = vec![9u8; 1 << 20];
3003///     let m = pipeline.message(1u64, None).await;
3004///     let _guard = unsafe { pipeline.lent(m, &buffer) };
3005///     pipeline.ready().await;
3006/// });
3007/// match pipeline.next_event() {
3008///     Some(Event::Hashed { hash, .. }) => assert_eq!(hash, convenience::hash(&vec![9u8; 1 << 20])),
3009///     _ => panic!("expected Hashed"),
3010/// }
3011/// ```
3012///
3013/// `Pipeline::new` (without owner type) exposes no `owned` method:
3014/// ```compile_fail,E0599
3015/// use blake3_servil::throughput::Pipeline;
3016/// async fn bad(pipeline: &mut Pipeline<u64>) {
3017///     let m = pipeline.message(1, None).await;
3018///     pipeline.owned(m, ());
3019/// }
3020/// ```
3021///
3022/// A batch over borrowed blocks is refused (`Batch<'static>` required):
3023/// ```compile_fail,E0521
3024/// use blake3_servil::throughput::{Batch, Block, Pipeline};
3025/// async fn bad(pipeline: &mut Pipeline<u64>, blocks: &[Block]) {
3026///     let batch = Batch::from_blocks(blocks, 64);
3027///     let m = pipeline.message(1, None).await;
3028///     pipeline.batch(m, batch, Box::new([]));
3029/// }
3030/// ```
3031///
3032/// Two concurrent waits on one pipeline are refused (`&mut Pipeline`):
3033/// ```compile_fail,E0499
3034/// use blake3_servil::throughput::Pipeline;
3035/// async fn bad(pipeline: &mut Pipeline<u64>) {
3036///     let slot = pipeline.message(1, None);
3037///     let ev = pipeline.ready();
3038///     let _ = (slot.await, ev.await);
3039/// }
3040/// ```
3041pub fn block_on<F: Future>(future: F) -> F::Output {
3042    /// Whether this `block_on` runs inside another, and whether it took a wake.
3043    struct Guard(bool, bool);
3044    impl Drop for Guard {
3045        fn drop(&mut self) {
3046            IN_BLOCK_ON.with(|f| f.set(self.0));
3047            if self.0 && self.1 {
3048                // This `block_on` ran inside a poll of another, on the one
3049                // waker the two share: a wake it took may have been the
3050                // other's, which polls once more before it sleeps. Only
3051                // where it took one: an outer future that runs a
3052                // `block_on` in each poll would otherwise never sleep.
3053                BLOCK_ON_PARK.with(|park| park.woken.store(true, Ordering::Release));
3054            }
3055        }
3056    }
3057    let prev = IN_BLOCK_ON.with(|f| f.replace(true));
3058    let mut guard = Guard(prev, false);
3059    let mut future = core::pin::pin!(future);
3060    BLOCK_ON_PARK.with(|park| {
3061        BLOCK_ON_WAKER.with(|waker| {
3062            let mut cx = Context::from_waker(waker);
3063            if let Poll::Ready(output) = future.as_mut().poll(&mut cx) {
3064                return output;
3065            }
3066            let started = crate::lanes::now();
3067            let mut yielded = started;
3068            loop {
3069                crate::lanes::poll_pause(&mut yielded);
3070                if crate::lanes::now() - started >= crate::lanes::SPIN_BEFORE_SLEEP {
3071                    if let Poll::Ready(output) = future.as_mut().poll(&mut cx) {
3072                        return output;
3073                    }
3074                    // Asleep until a wake, one that came during the poll
3075                    // included, whoever took the thread's park token since.
3076                    while !park.woken.swap(false, Ordering::Acquire) {
3077                        thread::park();
3078                    }
3079                    guard.1 = true;
3080                } else if let Poll::Ready(output) = future.as_mut().poll(&mut cx) {
3081                    return output;
3082                }
3083            }
3084        })
3085    })
3086}
3087
3088// The standard library's tests alone: under Shuttle
3089// (tests/shuttle_pipeline.rs) this file is compiled without them.
3090#[cfg(all(test, not(shuttle)))]
3091mod test {
3092    use super::*;
3093
3094    #[test]
3095    #[should_panic(expected = "the children are not siblings")]
3096    fn the_piece_fold_refuses_swapped_values() {
3097        crate::initialize();
3098        let tree = TreeHasher::new(Mode::Plain);
3099        let left = Cv::at(ROOM_LEVEL, 0, [1; OUT_LEN]);
3100        let next = Cv::at(ROOM_LEVEL, 1, [2; OUT_LEN]);
3101        let last = LastCv::at(2 * (ROOM_LEN / CHUNK_LEN) as u64, 1, [3; OUT_LEN]);
3102        fold_multi_cvs(&tree, &[next, left], last, 2 * ROOM_LEN as u64 + 1);
3103    }
3104
3105    #[test]
3106    #[should_panic(expected = "the root's children hold")]
3107    fn the_piece_fold_checks_the_submitted_length() {
3108        crate::initialize();
3109        let tree = TreeHasher::new(Mode::Plain);
3110        let left = Cv::at(ROOM_LEVEL, 0, [1; OUT_LEN]);
3111        let last = LastCv::at((ROOM_LEN / CHUNK_LEN) as u64, 1, [2; OUT_LEN]);
3112        fold_multi_cvs(&tree, &[left], last, ROOM_LEN as u64 + 2);
3113    }
3114
3115    #[test]
3116    fn aaa_unit_single_step_every_stage() {
3117        crate::initialize_multithreaded(None);
3118        let step_until = |source: &Source, cond: &dyn Fn() -> bool, what: &str| {
3119            for i in 0..200_000usize {
3120                let ran = source.run_waiting_action();
3121                if cond() {
3122                    return;
3123                }
3124                if !ran && i % 64 == 63 {
3125                    std::thread::yield_now();
3126                } else {
3127                    core::hint::spin_loop();
3128                }
3129            }
3130            panic!("bounded step failed: {what}");
3131        };
3132
3133        assert!(!in_block_on());
3134        block_on(core::future::poll_fn(|_| {
3135            assert!(in_block_on());
3136            Poll::Ready(())
3137        }));
3138        let _ = std::panic::catch_unwind(|| {
3139            block_on(async {
3140                assert!(in_block_on());
3141                panic!("unwind guard test");
3142            });
3143        });
3144        assert!(!in_block_on());
3145
3146        // Exact power-of-two boundary for actions_cap = m*64 + (rooms+m+1) + g_cap:
3147        // (248, 15) -> 15872 + 264 + 248 = 16384; (248, 16) -> 16385 -> 32768.
3148        // On a one-thread pool (e.g. `taskset -c 0`), ticket slots stay 0 while
3149        // `loan_completed` sizes to `(messages * 64).next_power_of_two() / 64 = 256`.
3150        let has_workers = crate::lanes::pool_has_workers();
3151        let p_cap_exact = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 248, rooms: 15 });
3152        assert_eq!(p_cap_exact.storage().slot.get().source.actions_len(), if has_workers { 16384 } else { 0 });
3153        assert_eq!(p_cap_exact.storage().slot.get().loan_completed.len(), 256);
3154        let p_cap_over = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 248, rooms: 16 });
3155        assert_eq!(p_cap_over.storage().slot.get().source.actions_len(), if has_workers { 32768 } else { 0 });
3156        assert_eq!(p_cap_over.storage().slot.get().loan_completed.len(), if has_workers { 512 } else { 256 });
3157        drop((p_cap_exact, p_cap_over));
3158
3159        let mut p = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 4, rooms: 2 });
3160        let Poll::Ready(r_first) = poll_once(p.room()) else { panic!("room 0 ready") };
3161        let Poll::Ready(mut r) = poll_once(p.room()) else { panic!("room 1 ready") };
3162        assert_eq!(p.room_cursor, 0, "room_cursor wraps modulo rooms");
3163        drop(r_first);
3164        let Poll::Ready(mut m) = poll_once(p.message(1, None)) else { panic!("msg ready") };
3165        r.bytes_mut()[..ROOM_LEN].fill(0x33);
3166        p.commit(&mut m, &mut r, ROOM_LEN);
3167        drop(r);
3168        let pnode = p.room_streams[0].head_piece as usize;
3169        let src = &p.storage().slot.get().source;
3170        let pieces_ref = &p.storage().pieces;
3171        step_until(src, &|| pieces_ref[pnode].done.load(Ordering::Acquire), "dispatch_one + run_room_piece");
3172        p.end(m);
3173        assert_eq!(p.room_streams[0].head_piece, NONE, "end drained room piece");
3174        p.reap();
3175        assert_eq!(p.events.len(), 1, "reap moved completed event");
3176        match p.next_event() {
3177            Some(Event::Hashed { tag: 1, hash, owner: None }) => assert_eq!(hash, convenience::hash(&vec![0x33; ROOM_LEN])),
3178            _ => panic!("unexpected event"),
3179        }
3180
3181        let mut p_short = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 4, rooms: 0 });
3182        for round in 0..10usize {
3183            let ep = p_short.next_group_epoch;
3184            let Poll::Ready(ms) = poll_once(p_short.message(round, None)) else { panic!("short msg ready") };
3185            p_short.owned(ms, vec![round as u8; 128]);
3186            p_short.publish_open();
3187            let g = round % 4;
3188            let src = &p_short.storage().slot.get().source;
3189            let completed = &p_short.storage().slot.get().group_completed;
3190            step_until(src, &|| completed[g].load(Ordering::Acquire) >= ep, "publish_open + run_group");
3191            assert!(p_short.group_ready(g as u32, ep));
3192            let Some(Event::Hashed { tag, hash, owner: Some(_) }) = p_short.try_reap_one() else {
3193                panic!("try_reap_one ready");
3194            };
3195            assert_eq!(tag, round);
3196            assert_eq!(hash, convenience::hash(&vec![round as u8; 128]));
3197        }
3198
3199        let mut p_multi = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 2, rooms: 0 });
3200        let Poll::Ready(mm) = poll_once(p_multi.message(99, None)) else { panic!("multi msg ready") };
3201        p_multi.owned(mm, vec![0x44; MAX_SLOT_PIECES * TASK_LEN]);
3202        assert!(
3203            matches!(unsafe { (*p_multi.storage().multi[0].get()).kind }, MultiKind::Slice { piece_level, .. } if piece_level == level_of(TASK_LEN as u64))
3204        );
3205        let src = &p_multi.storage().slot.get().source;
3206        let sd = &p_multi.storage().slot_done;
3207        step_until(src, &|| sd[0].load(Ordering::Acquire), "dispatch_many + run_multi_piece");
3208        assert!(p_multi.try_reap_one().is_some(), "run_multi_piece completed all pieces");
3209        drop(p_multi);
3210
3211        let mut p_meta = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 4, rooms: 1 });
3212        let Poll::Ready(ma) = poll_once(p_meta.message(1, None)) else { panic!() };
3213        assert_eq!(p_meta.open_messages, 1);
3214        p_meta.abort(ma);
3215        assert_eq!(p_meta.open_messages, 0);
3216        let _ = p_meta.next_event();
3217
3218        let Poll::Ready(mb) = poll_once(p_meta.message(2, None)) else { panic!() };
3219        assert_eq!(p_meta.open_messages, 1);
3220        p_meta.batch(mb, Batch::new(1024, 128), vec![[0u8; 32]; 128].into_boxed_slice());
3221        assert_eq!(p_meta.open_messages, 0);
3222        assert!(matches!(p_meta.slots[1].kind, SlotKind::WaitBatch { group: NONE, .. }));
3223        assert!(matches!(unsafe { (*p_meta.storage().multi[1].get()).kind }, MultiKind::Batch { per_part: 64, .. }));
3224        let src = &p_meta.storage().slot.get().source;
3225        let sd = &p_meta.storage().slot_done;
3226        step_until(src, &|| sd[1].load(Ordering::Acquire), "batch 128 multi");
3227        let _ = p_meta.try_reap_one();
3228
3229        let Poll::Ready(mb64) = poll_once(p_meta.message(3, None)) else { panic!() };
3230        p_meta.batch(mb64, Batch::new(1024, 64), vec![[0u8; 32]; 64].into_boxed_slice());
3231        assert!(matches!(p_meta.slots[2].kind, SlotKind::WaitBatch { group: NONE, .. }));
3232        let src = &p_meta.storage().slot.get().source;
3233        let sd = &p_meta.storage().slot_done;
3234        step_until(src, &|| sd[2].load(Ordering::Acquire), "batch 64 multi");
3235        let _ = p_meta.try_reap_one();
3236        drop(p_meta);
3237
3238        {
3239            let mut p_wb = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
3240            let Poll::Ready(m0) = poll_once(p_wb.message(0, None)) else { panic!() };
3241            p_wb.end(m0);
3242            p_wb.reap();
3243            let ep = p_wb.next_group_epoch;
3244            let Poll::Ready(m1) = poll_once(p_wb.message(1, None)) else { panic!() };
3245            p_wb.batch(m1, Batch::new(64, 1), vec![[0u8; 32]; 1].into_boxed_slice());
3246            p_wb.publish_open();
3247            let src = &p_wb.storage().slot.get().source;
3248            let completed = &p_wb.storage().slot.get().group_completed;
3249            step_until(src, &|| completed[0].load(Ordering::Acquire) >= ep, "WaitBatch drop setup");
3250        }
3251        {
3252            let mut p_forget = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 2, rooms: 1 });
3253            let Poll::Ready(mut m0) = poll_once(p_forget.message(0, None)) else { panic!() };
3254            let Poll::Ready(mut r0) = poll_once(p_forget.room()) else { panic!() };
3255            p_forget.commit(&mut m0, &mut r0, 64);
3256            drop(r0);
3257            core::mem::forget(m0);
3258        }
3259    }
3260
3261    use crate::convenience;
3262
3263    fn drain_all<T, B, P>(pipeline: &mut Pipeline<T, B, P>, want: usize) -> Vec<Event<T, B, P>> {
3264        let mut out = Vec::with_capacity(want);
3265        while out.len() < want {
3266            if let Some(ev) = pipeline.next_event() {
3267                out.push(ev);
3268            } else {
3269                block_on(pipeline.ready());
3270            }
3271        }
3272        out
3273    }
3274
3275    #[test]
3276    fn rooms_owned_lent_and_modes_match_reference_across_boundaries() {
3277        crate::initialize_multithreaded(None);
3278        let max_len = (5 << 20) + 123;
3279        let mut input = vec![0u8; max_len];
3280        crate::test::paint_test_input(&mut input);
3281        let key = [0x5Au8; 32];
3282        let ctx_key = crate::throughput::context_key("pipeline modes");
3283        let lens = [
3284            0,
3285            1,
3286            63,
3287            64,
3288            65,
3289            1023,
3290            1024,
3291            1025,
3292            16 * 1024,
3293            ROOM_LEN - 1,
3294            ROOM_LEN,
3295            ROOM_LEN + 1,
3296            2 * ROOM_LEN,
3297            3 * ROOM_LEN + 77,
3298            200_000,
3299            1 << 20,
3300            (4 << 20) + 7,
3301            max_len,
3302        ];
3303
3304        // The same limits across modes exercise the reuse of PipeSlot.
3305        for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("pipeline derive"), Mode::DeriveKeyWith(&ctx_key)] {
3306            let expected = lens.map(|len| {
3307                let bytes = &input[..len];
3308                match mode {
3309                    Mode::Plain => *blake3::hash(bytes).as_bytes(),
3310                    Mode::Keyed(key) => *blake3::keyed_hash(key, bytes).as_bytes(),
3311                    Mode::DeriveKey(context) => blake3::derive_key(context, bytes),
3312                    Mode::DeriveKeyWith(_) => blake3::derive_key("pipeline modes", bytes),
3313                }
3314            });
3315            let mut pipe = Pipeline::new(mode, Limits { messages: 4, rooms: 3 });
3316            for (idx, &len) in lens.iter().enumerate() {
3317                block_on(async {
3318                    let mut m = pipe.message(idx, Some(len as u64)).await;
3319                    let mut pos = 0;
3320                    if len == 0 && idx % 2 == 1 {
3321                        let mut r = pipe.room().await;
3322                        pipe.commit(&mut m, &mut r, 0);
3323                    }
3324                    while pos < len {
3325                        let mut r = pipe.room().await;
3326                        let n = (len - pos).min(ROOM_LEN);
3327                        r.bytes_mut()[..n].copy_from_slice(&input[pos..pos + n]);
3328                        pipe.commit(&mut m, &mut r, n);
3329                        pos += n;
3330                    }
3331                    pipe.end(m);
3332                });
3333                if idx % 3 == 2 {
3334                    for ev in drain_all(&mut pipe, 3) {
3335                        match ev {
3336                            Event::Hashed { tag, hash, owner: None } => {
3337                                assert_eq!(*hash.as_bytes(), expected[tag], "room len={}", lens[tag]);
3338                            }
3339                            _ => panic!("unexpected event"),
3340                        }
3341                    }
3342                }
3343            }
3344            let rem = lens.len() % 3;
3345            for ev in drain_all(&mut pipe, rem) {
3346                if let Event::Hashed { tag, hash, .. } = ev {
3347                    assert_eq!(*hash.as_bytes(), expected[tag]);
3348                } else {
3349                    panic!("unexpected event");
3350                }
3351            }
3352            drop(pipe);
3353
3354            let mut owned_pipe = Pipeline::<usize, Vec<u8>>::with_owners(mode, Limits { messages: 6, rooms: 0 });
3355            for (idx, &len) in lens.iter().enumerate() {
3356                while owned_pipe.events.len() == 6 || owned_pipe.free_slots.is_empty() {
3357                    if let Some(Event::Hashed { tag, hash, owner: Some(buf) }) = owned_pipe.next_event() {
3358                        assert_eq!(buf.len(), lens[tag]);
3359                        assert_eq!(*hash.as_bytes(), expected[tag]);
3360                    } else {
3361                        block_on(owned_pipe.ready());
3362                    }
3363                }
3364                let m = block_on(owned_pipe.message(idx, None));
3365                owned_pipe.owned(m, input[..len].to_vec());
3366            }
3367            while !owned_pipe.end_queue.is_empty() || !owned_pipe.events.is_empty() {
3368                if let Some(Event::Hashed { tag, hash, owner: Some(buf) }) = owned_pipe.next_event() {
3369                    assert_eq!(buf.len(), lens[tag]);
3370                    assert_eq!(*hash.as_bytes(), expected[tag]);
3371                } else {
3372                    block_on(owned_pipe.ready());
3373                }
3374            }
3375            drop(owned_pipe);
3376
3377            let mut lent_pipe = Pipeline::new(mode, Limits { messages: 2, rooms: 0 });
3378            for (idx, &len) in lens.iter().enumerate() {
3379                let slice = &input[..len];
3380                let m = block_on(lent_pipe.message(idx, None));
3381                let guard = unsafe { lent_pipe.lent(m, slice) };
3382                block_on(lent_pipe.ready());
3383                drop(guard);
3384                match lent_pipe.next_event() {
3385                    Some(Event::Hashed { tag, hash, owner: None }) => {
3386                        assert_eq!(tag, idx);
3387                        assert_eq!(*hash.as_bytes(), expected[tag], "lent len={len}");
3388                    }
3389                    _ => panic!("expected Hashed"),
3390                }
3391            }
3392        }
3393    }
3394
3395    #[test]
3396    fn inline_array_owner_never_aliases_or_corrupts() {
3397        let mut pipe = Pipeline::<usize, [u8; 100]>::with_owners(Mode::Plain, Limits { messages: 8, rooms: 0 });
3398        for i in 0..32usize {
3399            while pipe.free_slots.is_empty() {
3400                if let Some(Event::Hashed { tag, hash, owner: Some(arr) }) = pipe.next_event() {
3401                    assert_eq!(arr, [tag as u8; 100]);
3402                    assert_eq!(hash, convenience::hash(&[tag as u8; 100]));
3403                } else {
3404                    block_on(pipe.ready());
3405                }
3406            }
3407            let m = block_on(pipe.message(i, None));
3408            pipe.owned(m, [i as u8; 100]);
3409        }
3410        while !pipe.end_queue.is_empty() || !pipe.events.is_empty() {
3411            if let Some(Event::Hashed { tag, hash, owner: Some(arr) }) = pipe.next_event() {
3412                assert_eq!(arr, [tag as u8; 100]);
3413                assert_eq!(hash, convenience::hash(&[tag as u8; 100]));
3414            } else {
3415                block_on(pipe.ready());
3416            }
3417        }
3418    }
3419
3420    #[test]
3421    fn shared_room_many_short_messages_and_fifo_room_cycling() {
3422        let mut pipe = Pipeline::new(Mode::Plain, Limits { messages: 8, rooms: 3 });
3423        let mut room = block_on(pipe.room());
3424        assert_eq!(room.len(), ROOM_LEN);
3425        assert_eq!(room.as_mut_ptr() as usize % 64, 0);
3426
3427        let count = 1500usize;
3428        let mut pulled = Vec::with_capacity(count);
3429        for i in 0..count {
3430            let msg_len = (i * 13) % 200;
3431            if room.len() < msg_len {
3432                drop(room);
3433                room = block_on(pipe.room());
3434            }
3435            while pipe.free_slots.is_empty() {
3436                if let Some(ev) = pipe.next_event() {
3437                    pulled.push(ev);
3438                } else {
3439                    block_on(pipe.ready());
3440                }
3441            }
3442            let mut m = block_on(pipe.message((i, msg_len), None));
3443            let pat = (i as u8).wrapping_mul(7);
3444            room.bytes_mut()[..msg_len].fill(pat);
3445            pipe.commit(&mut m, &mut room, msg_len);
3446            assert_eq!(room.as_mut_ptr() as usize % 64, 0, "room stays 64-byte aligned");
3447            pipe.end(m);
3448        }
3449        drop(room);
3450        while pulled.len() < count {
3451            if let Some(ev) = pipe.next_event() {
3452                pulled.push(ev);
3453            } else {
3454                block_on(pipe.ready());
3455            }
3456        }
3457        for (idx, ev) in pulled.into_iter().enumerate() {
3458            match ev {
3459                Event::Hashed { tag: (i, len), hash, owner: None } => {
3460                    assert_eq!(i, idx);
3461                    let pat = (i as u8).wrapping_mul(7);
3462                    assert_eq!(hash, convenience::hash(&vec![pat; len]));
3463                }
3464                _ => panic!("unexpected event"),
3465            }
3466        }
3467
3468        // FIFO ring cycling check: rooms cycle 0 -> 1 -> 2 -> 0 -> 1 -> 2, cooling cache lines before reuse.
3469        let mut seen = Vec::new();
3470        for _ in 0..6 {
3471            let r = block_on(pipe.room());
3472            seen.push(r.index);
3473            drop(r);
3474        }
3475        for w in seen.windows(3) {
3476            assert!(w[0] != w[1] && w[1] != w[2] && w[0] != w[2], "rooms cycle around all 3 before reuse: {seen:?}");
3477        }
3478    }
3479
3480    #[test]
3481    fn interleaved_messages_deliver_in_end_order_and_handle_aborts() {
3482        let mut pipe = Pipeline::new(Mode::Plain, Limits { messages: 4, rooms: 4 });
3483        let data_a = vec![0xAAu8; 3 * ROOM_LEN + 500];
3484        let data_b = vec![0xBBu8; 900];
3485        let data_c = vec![0xCCu8; 2 * ROOM_LEN + 100];
3486
3487        block_on(async {
3488            let mut a = pipe.message("A", None).await;
3489            let mut b = pipe.message("B", None).await;
3490            let mut c = pipe.message("C", None).await;
3491
3492            let mut r = pipe.room().await;
3493            r.bytes_mut().copy_from_slice(&data_a[..ROOM_LEN]);
3494            pipe.commit(&mut a, &mut r, ROOM_LEN);
3495            drop(r);
3496
3497            let mut r = pipe.room().await;
3498            r.bytes_mut().copy_from_slice(&data_c[..ROOM_LEN]);
3499            pipe.commit(&mut c, &mut r, ROOM_LEN);
3500            drop(r);
3501
3502            let mut r = pipe.room().await;
3503            r.bytes_mut()[..data_b.len()].copy_from_slice(&data_b);
3504            pipe.commit(&mut b, &mut r, data_b.len());
3505            drop(r);
3506
3507            pipe.end(b);
3508            pipe.abort(c);
3509
3510            for chunk in data_a[ROOM_LEN..].chunks(ROOM_LEN) {
3511                let mut r = pipe.room().await;
3512                r.bytes_mut()[..chunk.len()].copy_from_slice(chunk);
3513                pipe.commit(&mut a, &mut r, chunk.len());
3514            }
3515            pipe.end(a);
3516        });
3517
3518        let events = drain_all(&mut pipe, 3);
3519        match &events[0] {
3520            Event::Hashed { tag: "B", hash, .. } => assert_eq!(*hash, convenience::hash(&data_b)),
3521            _ => panic!("expected B first"),
3522        }
3523        match &events[1] {
3524            Event::Aborted { tag: "C", owner: None } => {}
3525            _ => panic!("expected C aborted second"),
3526        }
3527        match &events[2] {
3528            Event::Hashed { tag: "A", hash, .. } => assert_eq!(*hash, convenience::hash(&data_a)),
3529            _ => panic!("expected A third"),
3530        }
3531    }
3532
3533    #[test]
3534    fn batches_empty_small_and_large_match_hash_many() {
3535        let mut pipe = Pipeline::new(Mode::Plain, Limits { messages: 8, rooms: 0 });
3536        for (tag, (msg_len, count)) in [(64, 0), (0, 5), (64, 16), (100, 33), (64, 2048), (300, 600)].into_iter().enumerate() {
3537            let mut batch = Batch::new(msg_len, count);
3538            for i in 0..count {
3539                let msg = vec![(i as u8).wrapping_add(tag as u8); msg_len];
3540                batch.set(i, &msg);
3541            }
3542            let digests = vec![[0u8; 32]; count].into_boxed_slice();
3543            let m = block_on(pipe.message((tag, msg_len, count), None));
3544            pipe.batch(m, batch, digests);
3545        }
3546
3547        for ev in drain_all(&mut pipe, 6) {
3548            match ev {
3549                Event::Batch { tag: (tag, msg_len, count), batch, digests } => {
3550                    assert_eq!(batch.len(), count);
3551                    assert_eq!(digests.len(), count);
3552                    for i in 0..count {
3553                        let want = convenience::hash(&vec![(i as u8).wrapping_add(tag as u8); msg_len]);
3554                        assert_eq!(digests[i], *want.as_bytes());
3555                    }
3556                }
3557                _ => panic!("expected Batch"),
3558            }
3559        }
3560    }
3561
3562    /// A Pipeline frees its per-pipeline `PipeStorage` cleanly on drop while
3563    /// reusing its small `'static` `PipeSlot` across Pipelines — even across
3564    /// different `Limits.rooms` and `Limits.messages` within the same
3565    /// power-of-two action tier — and each Pipeline hashes in its own mode
3566    /// (#399, #465).
3567    #[test]
3568    fn a_pipelines_slot_is_reused_while_its_storage_is_freed() {
3569        crate::initialize_multithreaded(None);
3570        let live_before = LIVE_STORAGES.load(Ordering::Relaxed);
3571        let limits = Limits { messages: 3, rooms: 2 };
3572        let first = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Plain, limits);
3573        let slot: *const PipeSlot = first.storage().slot.get();
3574        assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before + 1);
3575        drop(first);
3576        assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before, "first PipeStorage freed on drop");
3577        let key = [9u8; 32];
3578        let mut second = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Keyed(&key), limits);
3579        assert_eq!(second.storage().slot.get() as *const PipeSlot, slot, "the next Pipeline reuses the PipeSlot");
3580        let m = block_on(second.message(0, None));
3581        second.owned(m, vec![5u8; 1 << 20]);
3582        match drain_all(&mut second, 1).pop().unwrap() {
3583            Event::Hashed { hash, .. } => assert_eq!(hash, convenience::hash_with(Mode::Keyed(&key), &vec![5u8; 1 << 20]), "in its own mode"),
3584            _ => panic!("expected Hashed"),
3585        }
3586        drop(second);
3587        assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before, "second PipeStorage freed on drop");
3588        // A Pipeline with different rooms and messages in the same action tier
3589        // still reuses the same PipeSlot while allocating and freeing its own PipeStorage.
3590        let mut larger = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 10, rooms: 5 });
3591        assert_eq!(larger.storage().slot.get() as *const PipeSlot, slot, "the PipeSlot serves different Limits in the same action tier");
3592        for tag in 0..10 {
3593            let m = block_on(larger.message(tag, None));
3594            larger.owned(m, vec![tag as u8; 300_000]);
3595        }
3596        for event in drain_all(&mut larger, 10) {
3597            match event {
3598                Event::Hashed { tag, hash, .. } => assert_eq!(hash, convenience::hash(&vec![tag as u8; 300_000])),
3599                _ => panic!("expected Hashed"),
3600            }
3601        }
3602        drop(larger);
3603        assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before, "larger PipeStorage freed on drop");
3604    }
3605
3606    #[test]
3607    fn event_backpressure_holds_excess_completions_in_slots_without_loss() {
3608        let mut pipe = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 2, rooms: 0 });
3609        for i in 0..2 {
3610            let m = block_on(pipe.message(i, None));
3611            pipe.owned(m, vec![i as u8; 128]);
3612        }
3613        block_on(pipe.ready());
3614        while pipe.events.len() < 2 {
3615            if !pipe.storage().slot.get().source.run_waiting_action() {
3616                pipe.storage().slot.get().source.wake_for_waiting();
3617                std::thread::yield_now();
3618            }
3619            pipe.reap();
3620        }
3621        for i in 2..4 {
3622            let m = block_on(pipe.message(i, None));
3623            pipe.owned(m, vec![i as u8; 128]);
3624        }
3625        pipe.publish_open();
3626        while pipe.has_in_flight_work() {
3627            if !pipe.storage().slot.get().source.run_waiting_action() {
3628                pipe.storage().slot.get().source.wake_for_waiting();
3629                std::thread::yield_now();
3630            }
3631        }
3632        pipe.reap();
3633        assert_eq!(pipe.events.len(), 2, "events capped at limits.messages");
3634        assert_eq!(pipe.end_queue.len, 2, "wave 2 holds its slots until pulled");
3635
3636        let all = drain_all(&mut pipe, 4);
3637        for (i, ev) in all.into_iter().enumerate() {
3638            match ev {
3639                Event::Hashed { tag, hash, owner: Some(v) } => {
3640                    assert_eq!(tag, i);
3641                    assert_eq!(hash, convenience::hash(&v));
3642                }
3643                _ => panic!("expected Hashed"),
3644            }
3645        }
3646    }
3647
3648    #[test]
3649    fn guard_pages_catch_any_underread_or_overread_on_owned_and_lent() {
3650        struct GuardedBytes {
3651            _g: crate::test::guard::Guarded,
3652            ptr: *const u8,
3653            len: usize,
3654        }
3655        impl GuardedBytes {
3656            fn new(len: usize, at_end: bool) -> Self {
3657                let mut g = crate::test::guard::filled(len, at_end);
3658                let ptr = g.bytes().as_ptr();
3659                GuardedBytes { _g: g, ptr, len }
3660            }
3661        }
3662        impl AsRef<[u8]> for GuardedBytes {
3663            fn as_ref(&self) -> &[u8] {
3664                unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
3665            }
3666        }
3667
3668        let mut pipe = Pipeline::<usize, GuardedBytes>::with_owners(Mode::Plain, Limits { messages: 2, rooms: 0 });
3669        for at_end in [false, true] {
3670            for len in [0, 1, 63, 64, 65, 1024, 16 * 1024, ROOM_LEN, ROOM_LEN + 65] {
3671                let gb = GuardedBytes::new(len, at_end);
3672                let want = convenience::hash(gb.as_ref());
3673
3674                let m = block_on(pipe.message(len, None));
3675                let guard = unsafe { pipe.lent(m, gb.as_ref()) };
3676                block_on(pipe.ready());
3677                drop(guard);
3678                match pipe.next_event() {
3679                    Some(Event::Hashed { hash, owner: None, .. }) => assert_eq!(hash, want, "lent len={len} at_end={at_end}"),
3680                    _ => panic!("expected Hashed"),
3681                }
3682
3683                let m = block_on(pipe.message(len, None));
3684                pipe.owned(m, gb);
3685                block_on(pipe.ready());
3686                match pipe.next_event() {
3687                    Some(Event::Hashed { hash, owner: Some(back), .. }) => {
3688                        assert_eq!(back.as_ref().len(), len);
3689                        assert_eq!(hash, want, "owned len={len} at_end={at_end}");
3690                    }
3691                    _ => panic!("expected Hashed"),
3692                }
3693            }
3694
3695            let count = 65;
3696            let gb_batch = GuardedBytes::new(count * CHUNK_LEN, at_end);
3697            let blocks: &'static [crate::throughput::Block] =
3698                unsafe { core::mem::transmute(crate::throughput::Block::from_bytes(gb_batch.as_ref()).expect("guard-page batch starts aligned")) };
3699            let m = block_on(pipe.message(count, None));
3700            pipe.batch(m, Batch::in_place(blocks, CHUNK_LEN), vec![[0u8; 32]; count].into_boxed_slice());
3701            block_on(pipe.ready());
3702            match pipe.next_event() {
3703                Some(Event::Batch { batch, digests, .. }) => {
3704                    for i in 0..count {
3705                        assert_eq!(digests[i], *convenience::hash(&gb_batch.as_ref()[i * CHUNK_LEN..][..CHUNK_LEN]).as_bytes());
3706                    }
3707                    drop(batch);
3708                }
3709                _ => panic!("expected Batch"),
3710            }
3711            drop(gb_batch);
3712        }
3713    }
3714
3715    #[test]
3716    #[should_panic(expected = "Limits.messages must be at least 1")]
3717    fn contract_zero_messages_panics() {
3718        let _ = Pipeline::<()>::new(Mode::Plain, Limits { messages: 0, rooms: 1 });
3719    }
3720
3721    #[test]
3722    fn contract_limits_beyond_what_an_action_names_panic() {
3723        // Test the allocation-free capacity validator directly so even a
3724        // regression in the check cannot trigger a multi-GiB allocation on the
3725        // test host; covers exact boundaries, wrapping sum, and just-below.
3726        assert_eq!(pipeline_capacities(Limits { messages: (1 << 29) - 2, rooms: 0 }).0, 0);
3727        assert_eq!(pipeline_capacities(Limits { messages: 64, rooms: 0 }), (0, 64, 64 * MAX_SLOT_PIECES));
3728        assert_eq!(pipeline_capacities(Limits { messages: 63, rooms: 1 }), (65, 63, 63 * MAX_SLOT_PIECES + 65 + 63));
3729        for limits in [
3730            Limits { messages: (1 << 29) - 1, rooms: 0 },
3731            Limits { messages: 1 << 29, rooms: 0 },
3732            Limits { messages: 1, rooms: (1 << 29) - 2 },
3733            Limits { messages: 1, rooms: usize::MAX },
3734        ] {
3735            let refused = std::panic::catch_unwind(|| pipeline_capacities(limits)).err().expect("limits past 29 bits are refused");
3736            let why = refused.downcast_ref::<&str>().copied().map(String::from).or_else(|| refused.downcast_ref::<String>().cloned()).unwrap_or_default();
3737            assert!(why.contains("Pipeline Limits beyond what an action can name"), "{limits:?}: {why}");
3738        }
3739        // End-to-end constructor check on wrapping limit.
3740        let refused = std::panic::catch_unwind(|| Pipeline::<()>::new(Mode::Plain, Limits { messages: 1, rooms: usize::MAX }))
3741            .err()
3742            .expect("constructor refuses limits past 29 bits");
3743        let why = refused.downcast_ref::<&str>().copied().map(String::from).or_else(|| refused.downcast_ref::<String>().cloned()).unwrap_or_default();
3744        assert!(why.contains("Pipeline Limits beyond what an action can name"), "{why}");
3745    }
3746
3747    #[test]
3748    fn ring_enforces_hard_capacity_limit() {
3749        for cap in [0usize, 1, 3] {
3750            let mut ring = IndexRing::new(cap);
3751            for i in 0..cap {
3752                ring.push_back(u32::try_from(i).unwrap());
3753            }
3754            let over = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ring.push_back(99)));
3755            assert!(over.is_err(), "IndexRing::push_back must panic past cap {cap}");
3756            let drained: Vec<u32> = std::iter::from_fn(|| ring.pop_front()).collect();
3757            let want: Vec<u32> = (0..cap).map(|i| u32::try_from(i).unwrap()).collect();
3758            assert_eq!(drained, want, "IndexRing contents preserved after rejected over-push at cap {cap}");
3759        }
3760        // Wrap-around fill, over-push rejection, and full FIFO drain past `head == cap`.
3761        let mut wrap = IndexRing::new(3);
3762        wrap.push_back(10);
3763        wrap.push_back(20);
3764        assert_eq!(wrap.pop_front(), Some(10));
3765        wrap.push_back(30);
3766        wrap.push_back(40);
3767        assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| wrap.push_back(50))).is_err(), "wrapped IndexRing must reject over-push");
3768        assert_eq!(wrap.front(), Some(&20));
3769        let wrap_drained: Vec<u32> = std::iter::from_fn(|| wrap.pop_front()).collect();
3770        assert_eq!(wrap_drained, vec![20, 30, 40]);
3771        assert!(wrap.is_empty() && wrap.front().is_none() && wrap.pop_front().is_none());
3772        // Capacity above u32::MAX / 2 must be refused so `head + len` cannot overflow.
3773        let cap_too_big = std::panic::catch_unwind(|| IndexRing::new((u32::MAX / 2) as usize + 1));
3774        assert!(cap_too_big.is_err(), "IndexRing::new must reject cap > u32::MAX / 2");
3775        assert_eq!(IndexRing::new(257).buf.len(), 257);
3776
3777        // EventRing rejects ZSTs, enforces non-reallocation at backing capacity,
3778        // and never over-reserves past `VecDeque::with_capacity`.
3779        assert!(std::panic::catch_unwind(|| EventRing::<()>::new(3)).is_err(), "EventRing::new must reject ZSTs");
3780        for cap in [0usize, 1, 3] {
3781            let mut ev_ring = EventRing::<u32>::new(cap);
3782            let backing = ev_ring.0.capacity();
3783            for i in 0..backing {
3784                ev_ring.push_back(u32::try_from(i).unwrap());
3785            }
3786            let over = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ev_ring.push_back(99)));
3787            assert!(over.is_err(), "EventRing::push_back must panic past backing cap {backing}");
3788            let drained: Vec<u32> = std::iter::from_fn(|| ev_ring.pop_front()).collect();
3789            let want: Vec<u32> = (0..backing).map(|i| u32::try_from(i).unwrap()).collect();
3790            assert_eq!(drained, want, "EventRing contents preserved after rejected over-push");
3791        }
3792        assert_eq!(EventRing::<u32>::new(257).0.capacity(), std::collections::VecDeque::<u32>::with_capacity(257).capacity());
3793        assert_eq!(core::mem::size_of::<IndexRing>(), 2 * core::mem::size_of::<usize>() + 8);
3794        assert_eq!(core::mem::size_of::<EventRing<Event<usize, (), Batch<'static>>>>(), 4 * core::mem::size_of::<usize>());
3795    }
3796
3797    #[test]
3798    fn roomless_action_tier_boundary_64_vs_65() {
3799        // Run in an isolated 2-thread subprocess so worker action-ring tier
3800        // boundaries (64 -> 4,096 actions; 65 -> 8,192 actions) are always
3801        // verified even when the test binary runs under a 1-CPU affinity mask.
3802        const ENV: &str = "BLAKE3_PIPELINE_ROOMLESS_TIER_2T";
3803        if std::env::var_os(ENV).is_some() {
3804            crate::initialize_multithreaded(core::num::NonZeroUsize::new(2));
3805            let p64 = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 64, rooms: 0 });
3806            assert_eq!(p64.storage().slot.get().source.actions_len(), 4096);
3807            assert_eq!(p64.storage().slot.get().loan_completed.len(), 64);
3808            assert!(p64.storage().pieces.is_empty());
3809            drop(p64);
3810            let p65 = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 65, rooms: 0 });
3811            assert_eq!(p65.storage().slot.get().source.actions_len(), 8192);
3812            assert_eq!(p65.storage().slot.get().loan_completed.len(), 128);
3813            assert!(p65.storage().pieces.is_empty());
3814            return;
3815        }
3816        let exe = std::env::current_exe().unwrap();
3817        let out = std::process::Command::new(&exe)
3818            .env(ENV, "1")
3819            .args(["--exact", "pipeline::test::roomless_action_tier_boundary_64_vs_65", "--nocapture"])
3820            .output()
3821            .unwrap();
3822        let stdout = std::string::String::from_utf8_lossy(&out.stdout);
3823        let stderr = std::string::String::from_utf8_lossy(&out.stderr);
3824        assert!(
3825            out.status.success() && stdout.contains("1 passed"),
3826            "roomless 2-thread tier check failed: status={:?}\nstdout:\n{stdout}\nstderr:\n{stderr}",
3827            out.status
3828        );
3829    }
3830
3831    fn poll_once<F: Future>(f: F) -> Poll<F::Output> {
3832        let mut cx = Context::from_waker(Waker::noop());
3833        core::pin::pin!(f).poll(&mut cx)
3834    }
3835
3836    #[test]
3837    #[should_panic(expected = "all 1 message slots are held open")]
3838    fn contract_message_deadlock_all_open_panics() {
3839        let mut pipe = Pipeline::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
3840        let _a = block_on(pipe.message(1, None));
3841        let _ = poll_once(pipe.message(2, None));
3842    }
3843
3844    #[test]
3845    #[should_panic(expected = "finished events wait to be pulled")]
3846    fn contract_message_deadlock_events_full_panics() {
3847        let mut pipe = Pipeline::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
3848        let a = block_on(pipe.message(1, None));
3849        pipe.end(a);
3850        block_on(pipe.ready());
3851        let b = block_on(pipe.message(2, None));
3852        pipe.end(b);
3853        let _ = poll_once(pipe.message(3, None));
3854    }
3855
3856    /// A Room that takes empty commits never gives out its last credit:
3857    /// while the caller holds it, no second Room is made over its bytes
3858    /// (BLAKE3 #418: an empty commit moves the Room on by nothing, so one
3859    /// Room can take them without end, and after ROOM_CREDITS of them the
3860    /// pool counted it free). The Room here starts a few credits from the
3861    /// end, where a billion commits would bring it.
3862    #[test]
3863    fn a_room_held_through_its_last_credits_is_not_handed_out_again() {
3864        crate::initialize_multithreaded(None);
3865        let mut pipe = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 2, rooms: 3 });
3866        block_on(async {
3867            let mut room = pipe.room().await;
3868            room.spend_all_but(4);
3869            // At each count of empty commits around the last credit: the
3870            // other two Rooms, taken and given back until the pool has
3871            // looked again at which are free.
3872            for n in 0..12u32 {
3873                let mut m = pipe.message(n, None).await;
3874                pipe.commit(&mut m, &mut room, 0);
3875                pipe.end(m);
3876                loop {
3877                    match pipe.next_event() {
3878                        Some(Event::Hashed { tag, hash, .. }) => {
3879                            assert_eq!((tag, hash), (n, crate::convenience::hash(b"")));
3880                            break;
3881                        }
3882                        Some(_) => {}
3883                        None => pipe.ready().await,
3884                    }
3885                }
3886                // Its commits all finished: the pool holds what the Room
3887                // has yet to give out, no more and no less (with more, the
3888                // Room would never be free again once dropped).
3889                let held = room.storage().rooms.refs[room.index as usize].load(Ordering::SeqCst);
3890                assert_eq!(held, ROOM_CREDITS - room.commits as usize, "after {} empty commits", n + 1);
3891                for _ in 0..4 {
3892                    let (a, b) = (pipe.room().await, pipe.room().await);
3893                    assert!(a.index != room.index && b.index != room.index, "two Rooms over the same bytes, after {} empty commits", n + 1);
3894                }
3895            }
3896            assert_eq!(room.len(), ROOM_LEN, "empty commits use none of it");
3897            drop(room);
3898            // All three are free again, each one Room.
3899            let (a, b, c) = (pipe.room().await, pipe.room().await, pipe.room().await);
3900            assert!(a.index != b.index && b.index != c.index && a.index != c.index);
3901        });
3902    }
3903
3904    /// Multiple Rooms outliving their Pipeline hold `PipeStorage::holders`
3905    /// until the last surviving Room drops, then free `PipeStorage` cleanly
3906    /// while `PipeSlot` returns immediately on `Pipeline::drop`. Completed
3907    /// `Lent` guards read monotonic completion lines on `'static PipeSlot` and
3908    /// do not pin `PipeStorage` (#465, #494).
3909    #[test]
3910    fn surviving_rooms_and_lent_free_storage_after_pipeline_drop() {
3911        crate::initialize_multithreaded(None);
3912        let live_before = LIVE_STORAGES.load(Ordering::Relaxed);
3913        let short = [0xABu8; 128];
3914        let long = vec![0xCDu8; TASK_LEN + 4096];
3915        let mut pipe = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 4, rooms: 4 });
3916        let slot: *const PipeSlot = pipe.storage().slot.get();
3917        let (r0, r1) = block_on(async { (pipe.room().await, pipe.room().await) });
3918        let (i0, i1) = (r0.index as usize, r1.index as usize);
3919        assert_eq!(r0.storage().holders.load(Ordering::SeqCst), 1, "live Rooms do not bump holders while Pipeline lives");
3920        // Submit the long loan FIRST so it occupies slot 0 (`loan_completed[0]`),
3921        // matching the slot used on reuse below.
3922        let m_long = block_on(pipe.message(2, None));
3923        let lent_long = unsafe { pipe.lent(m_long, &long) };
3924        let m_short = block_on(pipe.message(1, None));
3925        let lent_short = unsafe { pipe.lent(m_short, &short) };
3926        assert_eq!(r0.storage().holders.load(Ordering::SeqCst), 1, "Lent guards do not bump PipeStorage::holders");
3927        let _ = drain_all(&mut pipe, 2);
3928        drop(pipe);
3929        // `PipeSlot` is already back in `FREE_PIPE_SLOTS` while `PipeStorage`
3930        // stays alive for the two surviving `Room`s only (not `Lent` guards).
3931        assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before + 1);
3932        assert_eq!(r0.storage().holders.load(Ordering::SeqCst), 2, "only the two surviving Rooms hold PipeStorage");
3933        for i in 0..4 {
3934            let v = r0.storage().rooms.refs[i].load(Ordering::SeqCst);
3935            if i == i0 || i == i1 {
3936                assert_eq!(v, ROOM_CLOSING_BIT | ROOM_CREDITS, "surviving room {i} stamped");
3937            } else {
3938                assert_eq!(v, ROOM_CLOSING_BIT, "idle room {i} stamped with closing bit");
3939            }
3940        }
3941        let mut next = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 2, rooms: 4 });
3942        assert_eq!(next.storage().slot.get() as *const PipeSlot, slot, "PipeSlot returned on Pipeline::drop");
3943        for i in 0..4 {
3944            assert_eq!(next.storage().rooms.refs[i].load(Ordering::SeqCst), 0);
3945        }
3946        // Reusing `PipeSlot` must advance multi-piece `loan_completed[0]`
3947        // strictly beyond the prior Pipeline's nonzero completed loan epoch.
3948        let prev_loan_done = next.pipe_slot.loan_completed[0].load(Ordering::Acquire);
3949        assert_ne!(prev_loan_done, 0, "prior Pipeline must have completed a long loan on slot 0");
3950        let m_next_long = block_on(next.message(3, None));
3951        let lent_next_long = unsafe { next.lent(m_next_long, &long) };
3952        let _ = drain_all(&mut next, 1);
3953        let next_loan_done = next.pipe_slot.loan_completed[0].load(Ordering::Acquire);
3954        assert!(next_loan_done > prev_loan_done, "reused PipeSlot must advance loan_completed epoch: prev={prev_loan_done} next={next_loan_done}");
3955        drop(lent_next_long);
3956        drop(next);
3957        drop(r0);
3958        assert_eq!(r1.storage().holders.load(Ordering::SeqCst), 1);
3959        drop(r1);
3960        assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before, "PipeStorage freed once last Room drops, even while Lent guards survive");
3961        drop(lent_short);
3962        drop(lent_long);
3963    }
3964
3965    /// Creating and dropping Pipelines across 40 distinct `Limits.rooms` values
3966    /// (the #465 reviewer scenario, 820 cumulative Rooms = 51.25 MiB) frees every
3967    /// `PipeStorage` cleanly — even while another thread hammers
3968    /// `hash_multithreaded` concurrently — and reuses at most one `PipeSlot`
3969    /// per power-of-two action tier.
3970    #[test]
3971    fn varied_room_counts_free_every_storage_and_share_pipe_slots() {
3972        crate::initialize_multithreaded(None);
3973        let live_before = LIVE_STORAGES.load(Ordering::Relaxed);
3974        let slots_before = PIPE_SLOTS_MADE.load(Ordering::Relaxed);
3975        let stop = Arc::new(AtomicBool::new(false));
3976        let stop_bg = Arc::clone(&stop);
3977        let (tx, rx) = std::sync::mpsc::channel::<()>();
3978        let bg_input = crate::test::message(&vec![0x5Au8; 1 << 20]);
3979        let expected = convenience::hash(&vec![0x5Au8; 1 << 20]);
3980        let worker = std::thread::spawn(move || {
3981            while !stop_bg.load(Ordering::Relaxed) {
3982                assert_eq!(crate::throughput::hash_multithreaded(Mode::Plain, &bg_input, 1 << 20), expected);
3983                let _ = tx.send(());
3984            }
3985        });
3986        // Wait for one background hash before churn starts; a worker panic
3987        // disconnects `rx` immediately instead of spinning to timeout.
3988        rx.recv().expect("background worker completed initial hash");
3989        for rooms in 1usize..=40 {
3990            let room_u32 = u32::try_from(rooms).unwrap();
3991            let fill = u8::try_from(rooms).unwrap();
3992            let mut pipe = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 4, rooms });
3993            let mut m = block_on(pipe.message(room_u32, None));
3994            let mut r = block_on(pipe.room());
3995            r.bytes_mut()[..64].fill(fill);
3996            pipe.commit(&mut m, &mut r, 64);
3997            drop(r);
3998            pipe.end(m);
3999            let evs = drain_all(&mut pipe, 1);
4000            match &evs[0] {
4001                Event::Hashed { hash, .. } => assert_eq!(*hash, convenience::hash(&[fill; 64])),
4002                _ => panic!("expected Hashed"),
4003            }
4004            // Mid-churn, observe a fresh background hash while `pipe` is still live.
4005            if rooms == 20 {
4006                while rx.try_recv().is_ok() {}
4007                rx.recv().expect("background worker completed hash while Pipeline was live");
4008            }
4009            drop(pipe);
4010        }
4011        stop.store(true, Ordering::Relaxed);
4012        worker.join().unwrap();
4013        assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before, "all 40 PipeStorages freed");
4014        // messages=4, rooms=1..=40 -> actions_cap = 256 + (rooms+5) + 4 <= 305 <= 1024,
4015        // so all 40 distinct room counts share a single 1024-action PipeSlot.
4016        assert!(PIPE_SLOTS_MADE.load(Ordering::Relaxed) - slots_before <= 1, "single PipeSlot shared across all 40 room counts");
4017    }
4018
4019    #[test]
4020    fn public_types_preserve_auto_traits() {
4021        fn assert_send<T: Send>() {}
4022        fn assert_sync<T: Sync>() {}
4023        fn assert_unpin<T: Unpin>() {}
4024        fn assert_unwind<T: core::panic::UnwindSafe + core::panic::RefUnwindSafe>() {}
4025        assert_send::<Lent<'_>>();
4026        assert_sync::<Lent<'_>>();
4027        assert_unwind::<Lent<'_>>();
4028        assert_send::<Room>();
4029        assert_sync::<Room>();
4030        assert_send::<Pipeline<u32>>();
4031        assert_unpin::<Pipeline<core::marker::PhantomPinned>>();
4032        assert_unpin::<Pipeline<u32, core::marker::PhantomPinned>>();
4033        assert_send::<Message>();
4034        assert_sync::<Message>();
4035        assert_send::<Event<u32>>();
4036        assert_eq!(core::mem::size_of::<Lent<'_>>(), 16);
4037        assert_eq!(core::mem::size_of::<Option<Lent<'_>>>(), 16);
4038        assert_eq!(core::mem::size_of::<Room>(), 40);
4039        assert_eq!(core::mem::size_of::<Option<Room>>(), 40);
4040    }
4041
4042    /// Clockless deterministic check of `acquire_free_group` predicates:
4043    /// 1) When group 0 is assigned with stale `seen_group_epoch[0] < assigned`
4044    ///    and `group_completed[0] >= assigned`, `acquire_free_group` must
4045    ///    refresh `seen_group_epoch[0]` and return group 0 rather than skipping
4046    ///    to free group 1 (kills `< -> ==` and `< -> >`).
4047    /// 2) When group 0 is assigned and still incomplete (`group_completed[0] <
4048    ///    assigned`), `acquire_free_group` must skip group 0 and return free
4049    ///    group 1 rather than overwriting group 0 (kills `== -> !=`).
4050    #[test]
4051    fn acquire_free_group_refreshes_stale_seen_and_skips_busy_group() {
4052        crate::initialize_multithreaded(None);
4053        let mut pipe = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 4, rooms: 0 });
4054        let base_ep = pipe.pipe_slot.group_completed[0].load(Ordering::Acquire) + 1;
4055        // Advance `next_group_epoch` past the synthetic epochs we write so
4056        // returning this PipeSlot to `FREE_PIPE_SLOTS` preserves the invariant
4057        // `next_group_epoch > group_completed[g]` for future leases.
4058        pipe.next_group_epoch = base_ep + 2;
4059
4060        // Case 1: group 0 completed, cached seen_group_epoch stale (< assigned), group 1 free.
4061        pipe.pipe_slot.group_completed[0].store(base_ep, Ordering::Release);
4062        pipe.assigned_group_epoch[0] = base_ep;
4063        pipe.seen_group_epoch[0] = 0;
4064        pipe.assigned_group_epoch[1] = 0;
4065        pipe.group_cursor = 0;
4066        assert_eq!(pipe.acquire_free_group(), 0, "stale seen_group_epoch must reload group_completed and reuse group 0");
4067        assert_eq!(pipe.assigned_group_epoch[0], 0);
4068        assert_eq!(pipe.seen_group_epoch[0], base_ep);
4069
4070        // Case 2: group 0 assigned and NOT yet completed, group 1 free.
4071        pipe.assigned_group_epoch[0] = base_ep + 1;
4072        pipe.seen_group_epoch[0] = base_ep;
4073        pipe.assigned_group_epoch[1] = 0;
4074        pipe.group_cursor = 0;
4075        assert_eq!(pipe.acquire_free_group(), 1, "busy group 0 must be skipped in favor of free group 1");
4076        assert_eq!(pipe.assigned_group_epoch[0], base_ep + 1);
4077        // Clear synthetic busy state before drop so Pipeline::drop sees no in-flight group.
4078        pipe.assigned_group_epoch[0] = 0;
4079        assert!(pipe.next_group_epoch > pipe.pipe_slot.group_completed[0].load(Ordering::Relaxed));
4080    }
4081
4082    /// Submitting 257 custom-mode short messages without reaping fills all 256
4083    /// physical groups while `seen_group_epoch` is still 0; the 257th call to
4084    /// `acquire_free_group` must reload `group_completed` (`seen < assigned`)
4085    /// and deliver every keyed digest cleanly.
4086    #[test]
4087    fn no_reap_group_pressure_refreshes_seen_group_epoch() {
4088        crate::initialize_multithreaded(None);
4089        let key = [0x42u8; 32];
4090        let input_for = |i: usize| -> [u8; 32] {
4091            let mut buf = [0u8; 32];
4092            buf[..8].copy_from_slice(&(i as u64).to_le_bytes());
4093            buf[8..].fill((i & 0xFF) as u8);
4094            buf
4095        };
4096        let mut pipe = Pipeline::<usize, [u8; 32]>::with_owners(Mode::Plain, Limits { messages: 257, rooms: 0 });
4097        for i in 0..257usize {
4098            let m = block_on(pipe.message_with(Mode::Keyed(&key), i, None));
4099            pipe.owned(m, input_for(i));
4100        }
4101        let evs = drain_all(&mut pipe, 257);
4102        for (i, ev) in evs.into_iter().enumerate() {
4103            match ev {
4104                Event::Hashed { tag, hash, .. } => {
4105                    assert_eq!(tag, i);
4106                    assert_eq!(hash.as_bytes(), blake3::keyed_hash(&key, &input_for(i)).as_bytes());
4107                }
4108                _ => panic!("expected Hashed"),
4109            }
4110        }
4111    }
4112
4113    /// A commit that finds no piece node free takes back the finished ones
4114    /// of every open message, not only its own. One message's later
4115    /// pieces finish while a worker is still on an earlier one, and they
4116    /// then hold every node; a commit to another message waited for ever,
4117    /// even once all of them had finished (the 0.10 delta audit, BLAKE3
4118    /// #461). The earlier piece is held back here by its done flag.
4119    /// Without the taking back, the commit to the second message never
4120    /// returns, and the run's clock ends the test (.config/nextest.toml).
4121    #[test]
4122    fn a_commit_takes_back_piece_nodes_another_open_message_holds() {
4123        crate::initialize_multithreaded(None);
4124        let data: Vec<u8> = (0..5 * ROOM_LEN).map(|i| (i % 251) as u8).collect();
4125        let mut pipe = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 2, rooms: 2 });
4126        block_on(async {
4127            let mut a = pipe.message(0, None).await;
4128            let mut b = pipe.message(1, None).await;
4129            let mut held = NONE;
4130            for part in data.chunks_exact(ROOM_LEN) {
4131                let mut room = pipe.room().await;
4132                room.bytes_mut().copy_from_slice(part);
4133                pipe.commit(&mut a, &mut room, ROOM_LEN);
4134                if held == NONE {
4135                    held = pipe.room_streams.iter().map(|stream| stream.head_piece).find(|&head| head != NONE).unwrap();
4136                    // A lone action waits for its owner's next await
4137                    // (publish_actions wakes a worker at two): run it
4138                    // here, unless a worker that was awake has it.
4139                    let done = &pipe.storage().pieces[held as usize].done;
4140                    while !done.load(Ordering::SeqCst) {
4141                        if !pipe.storage().slot.get().source.run_waiting_action() {
4142                            std::thread::yield_now();
4143                        }
4144                    }
4145                    done.store(false, Ordering::SeqCst);
4146                }
4147            }
4148            assert!(pipe.free_pieces.is_empty(), "the first message holds every node");
4149            pipe.storage().pieces[held as usize].done.store(true, Ordering::SeqCst);
4150            // Two whole rooms: a piece each.
4151            for part in data[ROOM_LEN - 5..].chunks(ROOM_LEN).take(2) {
4152                let mut room = pipe.room().await;
4153                room.bytes_mut()[..part.len()].copy_from_slice(part);
4154                pipe.commit(&mut b, &mut room, part.len());
4155            }
4156            pipe.end(b);
4157            pipe.end(a);
4158        });
4159        let events = drain_all(&mut pipe, 2);
4160        let hashes: Vec<_> = events.iter().map(|event| if let Event::Hashed { tag, hash, .. } = event { (*tag, *hash) } else { panic!("a hash") }).collect();
4161        assert_eq!(hashes, [(1, crate::convenience::hash(&data[ROOM_LEN - 5..3 * ROOM_LEN - 5])), (0, crate::convenience::hash(&data[..5 * ROOM_LEN]))]);
4162    }
4163
4164    /// `PipeSlot`s are reused however many Pipelines were alive at once and
4165    /// across varying `Limits.rooms`, while every `PipeStorage` is freed when
4166    /// the last of its Pipeline and surviving `Room`s drops (#427, #465).
4167    #[test]
4168    fn pipe_slots_are_reused_and_storages_freed_across_waves() {
4169        crate::initialize_multithreaded(None);
4170        let live_before = LIVE_STORAGES.load(Ordering::Relaxed);
4171        let wave = |rooms_count: usize, late_rooms: bool| {
4172            let limits = Limits { messages: 3, rooms: rooms_count };
4173            let mut pipes: Vec<Pipeline<u32>> = (0..40).map(|_| Pipeline::new(Mode::Plain, limits)).collect();
4174            let rooms: Vec<Room> = if late_rooms { pipes.iter_mut().map(|p| block_on(p.room())).collect() } else { Vec::new() };
4175            drop(pipes);
4176            if late_rooms {
4177                assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before + 40, "late Rooms keep PipeStorages alive");
4178            }
4179            drop(rooms);
4180            assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before, "every PipeStorage freed after wave");
4181        };
4182        let before = PIPE_SLOTS_MADE.load(Ordering::Relaxed);
4183        wave(5, false);
4184        assert_eq!(PIPE_SLOTS_MADE.load(Ordering::Relaxed) - before, 40, "one PipeSlot each, the first time");
4185        wave(2, false);
4186        wave(7, true);
4187        wave(1, true);
4188        assert_eq!(PIPE_SLOTS_MADE.load(Ordering::Relaxed) - before, 40, "zero new PipeSlots across varying Limits.rooms");
4189        let mut pipe = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 3, rooms: 5 });
4190        let rooms: Vec<Room> = (0..4).map(|_| block_on(pipe.room())).collect();
4191        let mut seen: Vec<u32> = rooms.iter().map(|r| r.index).collect();
4192        seen.sort_unstable();
4193        seen.dedup();
4194        assert_eq!(seen.len(), 4);
4195    }
4196
4197    #[test]
4198    #[should_panic(expected = "Limits.rooms == 0")]
4199    fn contract_room_with_zero_rooms_panics() {
4200        let mut pipe = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4201        let _ = poll_once(pipe.room());
4202    }
4203
4204    #[test]
4205    fn a_wait_for_a_room_ends_when_another_thread_drops_one() {
4206        let mut pipe = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 1 });
4207        let held = block_on(pipe.room());
4208        let index = held.index;
4209        // Every Room is alive, and the wait is no deadlock: a Room is
4210        // Send, and whoever holds this one may drop it.
4211        assert!(poll_once(pipe.room()).is_pending());
4212        std::thread::spawn(move || drop(held)).join().unwrap();
4213        assert_eq!(block_on(pipe.room()).index, index);
4214    }
4215
4216    /// A message of `p` ended and, for all `p` can see, still being
4217    /// hashed: its slot.
4218    fn message_in_flight(p: &mut Pipeline<u32>) -> usize {
4219        let (_, s) = block_on(p.message(7, None)).take();
4220        p.open_messages -= 1;
4221        p.slots[s].kind = SlotKind::WaitMulti { has_owner: false };
4222        p.storage().slot_done[s].store(false, Ordering::SeqCst);
4223        p.end_queue.push_back(s as u32);
4224        s
4225    }
4226
4227    #[test]
4228    fn every_pending_wait_registers_its_waker_even_during_block_on_spin() {
4229        struct Count(AtomicUsize);
4230        impl std::task::Wake for Count {
4231            fn wake(self: Arc<Self>) {
4232                self.0.fetch_add(1, Ordering::SeqCst);
4233            }
4234        }
4235        fn notify(p: &Pipeline<u32>) {
4236            p.storage().slot.get().waker.notify_after_seqcst();
4237        }
4238        let wakes = Arc::new(Count(AtomicUsize::new(0)));
4239        let other = Waker::from(Arc::clone(&wakes));
4240        let own_woken = || BLOCK_ON_PARK.with(|park| park.woken.swap(false, Ordering::SeqCst));
4241
4242        let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 1 });
4243        let mut room = Some(block_on(p.room()));
4244        let s = message_in_flight(&mut p);
4245        block_on(core::future::poll_fn(|own| {
4246            assert!(in_block_on());
4247            // Even while block_on spins, every Pending poll registers its
4248            // waker so composed outer futures that gate child polls never lose
4249            // a wake.
4250            own_woken();
4251            assert!(p.poll_ready(own).is_pending());
4252            notify(&p);
4253            assert!(own_woken(), "ready() must register waker on first Pending poll");
4254            assert!(p.poll_message(own).is_pending());
4255            notify(&p);
4256            assert!(own_woken(), "message() must register waker on first Pending poll");
4257            assert!(p.poll_room(own).is_pending());
4258            notify(&p);
4259            assert!(own_woken(), "room() must register waker on first Pending poll");
4260            // Under another waker: also kept and woken.
4261            let mut cx = Context::from_waker(&other);
4262            assert!(p.poll_ready(&mut cx).is_pending());
4263            notify(&p);
4264            assert_eq!(wakes.0.load(Ordering::SeqCst), 1, "ready() kept no waker");
4265            assert!(p.poll_message(&mut cx).is_pending());
4266            notify(&p);
4267            assert_eq!(wakes.0.load(Ordering::SeqCst), 2, "message() kept no waker");
4268            assert!(p.poll_room(&mut cx).is_pending());
4269            // A Room's drop is the notice a wait for a Room has.
4270            drop(room.take());
4271            assert_eq!(wakes.0.load(Ordering::SeqCst), 3, "room() kept no waker");
4272            Poll::Ready(())
4273        }));
4274        // The hashing ends, and the Pipeline is as any other.
4275        p.storage().slot_done[s].store(true, Ordering::SeqCst);
4276        assert!(matches!(p.next_event(), Some(Event::Hashed { tag: 7, .. })));
4277    }
4278
4279    /// A composed outer future under `block_on` that polls `room()` once during
4280    /// spin and then waits on a producer flag (set right before dropping the
4281    /// Room) must be woken when the Room drops rather than sleeping forever.
4282    #[test]
4283    fn composed_wait_under_block_on_receives_room_wake() {
4284        let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 1 });
4285        let room = block_on(p.room());
4286        let first_poll = Arc::new(AtomicBool::new(false));
4287        let first_poll_p = Arc::clone(&first_poll);
4288        let flag = Arc::new(AtomicBool::new(false));
4289        let flag_p = Arc::clone(&flag);
4290        let producer = std::thread::spawn(move || {
4291            while !first_poll_p.load(Ordering::Acquire) {
4292                std::thread::yield_now();
4293            }
4294            std::thread::sleep(5 * crate::lanes::SPIN_BEFORE_SLEEP);
4295            flag_p.store(true, Ordering::Release);
4296            drop(room);
4297        });
4298        let mut polled_child = false;
4299        let got = block_on(core::future::poll_fn(|cx| {
4300            if !polled_child {
4301                polled_child = true;
4302                assert!(p.poll_room(cx).is_pending());
4303                first_poll.store(true, Ordering::Release);
4304                return Poll::Pending;
4305            }
4306            if !flag.load(Ordering::Acquire) {
4307                return Poll::Pending;
4308            }
4309            p.poll_room(cx)
4310        }));
4311        producer.join().unwrap();
4312        drop(got);
4313    }
4314
4315    #[test]
4316    fn action_arg_roundtrips_every_field() {
4317        let cases = [
4318            ActionArg::Group { group: 0, custom_slot: 0 },
4319            ActionArg::Group { group: ActionArg::MAX_A, custom_slot: u32::MAX },
4320            ActionArg::RoomPiece { pnode: 7, custom: false, sme2: false },
4321            ActionArg::RoomPiece { pnode: ActionArg::MAX_A, custom: true, sme2: true },
4322            ActionArg::Multi { slot: 12345, piece: 67890, custom: false, sme2: false },
4323            ActionArg::Multi { slot: ActionArg::MAX_A, piece: MULTI_CUSTOM_BIT - 1, custom: true, sme2: true },
4324        ];
4325        for arg in cases {
4326            let encoded = arg.encode();
4327            assert_eq!(ActionArg::decode(encoded), arg);
4328        }
4329    }
4330
4331    #[test]
4332    #[should_panic(expected = "action index exceeds 29-bit field")]
4333    fn action_arg_rejects_oversized_index() {
4334        let _ = ActionArg::Group { group: ActionArg::MAX_A + 1, custom_slot: 0 }.encode();
4335    }
4336
4337    #[test]
4338    #[should_panic(expected = "multi piece index overlaps custom flag")]
4339    fn action_arg_rejects_piece_overlapping_custom_bit() {
4340        let _ = ActionArg::Multi { slot: 0, piece: MULTI_CUSTOM_BIT, custom: false, sme2: false }.encode();
4341    }
4342
4343    /// Dropping a cancelled `room()`, `message()`, or `ready()` future must
4344    /// immediately release the installed Waker so no reference cycle lingers.
4345    #[test]
4346    fn cancelling_wait_future_releases_its_waker() {
4347        struct Track(AtomicUsize);
4348        impl std::task::Wake for Track {
4349            fn wake(self: Arc<Self>) {
4350                self.0.fetch_add(1, Ordering::SeqCst);
4351            }
4352        }
4353        let track = Arc::new(Track(AtomicUsize::new(0)));
4354        let waker = Waker::from(Arc::clone(&track));
4355        let mut cx = Context::from_waker(&waker);
4356        let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 1 });
4357        let room = block_on(p.room());
4358        {
4359            let mut fut = core::pin::pin!(p.room());
4360            assert!(fut.as_mut().poll(&mut cx).is_pending());
4361            assert_eq!(Arc::strong_count(&track), 3, "room(): track + waker + WakerSlot");
4362        }
4363        assert_eq!(Arc::strong_count(&track), 2, "dropping cancelled room() future must clear WakerSlot");
4364        // Now hold the single message slot in flight and cancel both message() and ready().
4365        let s = message_in_flight(&mut p);
4366        {
4367            let mut fut = core::pin::pin!(p.message(9, None));
4368            assert!(fut.as_mut().poll(&mut cx).is_pending());
4369            assert_eq!(Arc::strong_count(&track), 3, "message(): track + waker + WakerSlot");
4370        }
4371        assert_eq!(Arc::strong_count(&track), 2, "dropping cancelled message() future must clear WakerSlot");
4372        {
4373            let mut fut = core::pin::pin!(p.ready());
4374            assert!(fut.as_mut().poll(&mut cx).is_pending());
4375            assert_eq!(Arc::strong_count(&track), 3, "ready(): track + waker + WakerSlot");
4376        }
4377        assert_eq!(Arc::strong_count(&track), 2, "dropping cancelled ready() future must clear WakerSlot");
4378        p.storage().slot_done[s].store(true, Ordering::SeqCst);
4379        assert!(matches!(p.next_event(), Some(Event::Hashed { tag: 7, .. })));
4380        drop(room);
4381    }
4382
4383    /// If dropping one unreaped owner panics during `Pipeline::drop`, all
4384    /// remaining owners must still drop, `PipeStorage` must still be freed,
4385    /// and `PipeSlot` must still return to `FREE_PIPE_SLOTS`.
4386    #[test]
4387    fn pipeline_drop_cleans_remaining_owners_and_storage_after_panicking_owner() {
4388        struct DropOwner {
4389            data: [u8; 8],
4390            drops: Arc<AtomicUsize>,
4391            panic_on_drop: bool,
4392        }
4393        impl AsRef<[u8]> for DropOwner {
4394            fn as_ref(&self) -> &[u8] {
4395                &self.data
4396            }
4397        }
4398        impl Drop for DropOwner {
4399            fn drop(&mut self) {
4400                self.drops.fetch_add(1, Ordering::SeqCst);
4401                if self.panic_on_drop {
4402                    panic!("deliberate owner drop panic");
4403                }
4404            }
4405        }
4406        let drops = Arc::new(AtomicUsize::new(0));
4407        let live_before = LIVE_STORAGES.load(Ordering::Relaxed);
4408        let mut p = Pipeline::<u32, DropOwner>::with_owners(Mode::Plain, Limits { messages: 2, rooms: 0 });
4409        let slot: *const PipeSlot = p.storage().slot.get();
4410        let m1 = block_on(p.message(1, None));
4411        let m2 = block_on(p.message(2, None));
4412        // Short messages stay buffered locally in open_group (not dispatched),
4413        // so Pipeline::drop drops them quietly without aborting.
4414        p.owned(m1, DropOwner { data: [1; 8], drops: Arc::clone(&drops), panic_on_drop: true });
4415        p.owned(m2, DropOwner { data: [2; 8], drops: Arc::clone(&drops), panic_on_drop: false });
4416        let res = std::panic::catch_unwind(core::panic::AssertUnwindSafe(move || drop(p)));
4417        assert!(res.is_err(), "first owner panic should unwind");
4418        assert_eq!(drops.load(Ordering::SeqCst), 2, "second owner must still be dropped on unwind");
4419        assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before, "PipeStorage must be freed on unwind");
4420        let p2 = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 2, rooms: 0 });
4421        assert_eq!(p2.storage().slot.get() as *const PipeSlot, slot, "PipeSlot must return to FREE_PIPE_SLOTS on unwind");
4422    }
4423
4424    /// Polling a completed `Pipeline::message` future a second time panics
4425    /// before popping another free slot.
4426    #[test]
4427    fn repolling_completed_message_future_panics_without_taking_slot() {
4428        let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 2, rooms: 0 });
4429        let waker = Waker::noop();
4430        let mut cx = Context::from_waker(waker);
4431        let msg = {
4432            let mut fut = core::pin::pin!(p.message(42, None));
4433            let Poll::Ready(msg) = fut.as_mut().poll(&mut cx) else { panic!("first poll must succeed") };
4434            let res = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
4435                let _ = fut.as_mut().poll(&mut cx);
4436            }));
4437            assert!(res.is_err(), "repolling completed MessageFut must panic");
4438            msg
4439        };
4440        assert_eq!(p.open_messages, 1, "repoll must not consume a second slot");
4441        p.end(msg);
4442        block_on(p.ready());
4443        assert!(matches!(p.next_event(), Some(Event::Hashed { tag: 42, .. })));
4444    }
4445
4446    /// Moving a `Pipeline` holding pending inline (`[u8; 64]`) owners by value
4447    /// to another thread before publishing/reaping must preserve exact digests
4448    /// and owners via the move-insensitive `RawSlots` backing.
4449    #[test]
4450    fn moving_pipeline_with_pending_inline_owners_across_threads() {
4451        let mut p = Pipeline::<u32, [u8; 64]>::with_owners(Mode::Plain, Limits { messages: 4, rooms: 0 });
4452        for i in 0..4u32 {
4453            let m = block_on(p.message(i, None));
4454            p.owned(m, [i as u8 + 1; 64]);
4455        }
4456        let results = std::thread::spawn(move || {
4457            let mut out = Vec::new();
4458            while out.len() < 4 {
4459                if let Some(Event::Hashed { tag, hash, owner }) = p.next_event() {
4460                    out.push((tag, hash, owner.unwrap()));
4461                } else {
4462                    block_on(p.ready());
4463                }
4464            }
4465            out
4466        })
4467        .join()
4468        .unwrap();
4469        for (tag, hash, owner) in results {
4470            assert_eq!(owner, [tag as u8 + 1; 64]);
4471            assert_eq!(hash, crate::convenience::hash(&owner));
4472        }
4473    }
4474
4475    #[test]
4476    fn a_wake_is_kept_though_another_wait_takes_the_park_token() {
4477        let mut armed = false;
4478        let mut polls = 0;
4479        block_on(core::future::poll_fn(|cx| {
4480            if !armed {
4481                armed = true;
4482                cx.waker().wake_by_ref();
4483                return Poll::Pending;
4484            }
4485            if polls == 0 && BLOCK_ON_PARK.with(|park| park.woken.load(Ordering::SeqCst)) {
4486                return Poll::Pending;
4487            }
4488            // From here block_on has consumed the arming wake in its sleep
4489            // loop and now sleeps between polls.
4490            polls += 1;
4491            if polls == 1 {
4492                cx.waker().wake_by_ref();
4493                // A wait of the poll's own (a blocking receive, say) takes
4494                // the park token that wake left: this returns at once.
4495                std::thread::park();
4496                return Poll::Pending;
4497            }
4498            Poll::Ready(())
4499        }));
4500        assert_eq!(polls, 2);
4501    }
4502
4503    #[test]
4504    fn a_block_on_inside_a_poll_leaves_the_outer_one_its_wake() {
4505        let mut armed = false;
4506        let mut polls = 0;
4507        block_on(core::future::poll_fn(|cx| {
4508            if !armed {
4509                armed = true;
4510                cx.waker().wake_by_ref();
4511                return Poll::Pending;
4512            }
4513            if polls == 0 && BLOCK_ON_PARK.with(|park| park.woken.load(Ordering::SeqCst)) {
4514                return Poll::Pending;
4515            }
4516            polls += 1;
4517            if polls == 1 {
4518                // This future's wake comes, and then a block_on that
4519                // sleeps: the two share the thread's waker, and the inner
4520                // one takes the wake for its own.
4521                cx.waker().wake_by_ref();
4522                // The inner future is ready only once that wake is gone:
4523                // it stays pending until the inner block_on has slept on
4524                // it. (An inner one that only spun would leave the wake
4525                // where it was, and prove nothing of the giving back.)
4526                let woken = || BLOCK_ON_PARK.with(|park| park.woken.load(Ordering::SeqCst));
4527                assert!(woken());
4528                block_on(core::future::poll_fn(|_| if woken() { Poll::Pending } else { Poll::Ready(()) }));
4529                assert!(in_block_on(), "the outer block_on is still active");
4530                assert!(BLOCK_ON_PARK.with(|park| park.woken.load(Ordering::SeqCst)), "the inner block_on took the wake and left none");
4531                return Poll::Pending;
4532            }
4533            Poll::Ready(())
4534        }));
4535        assert_eq!(polls, 2);
4536    }
4537
4538    /// A `block_on` inside a poll of one that sleeps between its polls
4539    /// keeps a wait's waker from its first poll: the outer one sleeps on
4540    /// it. Here the inner one's future polls the wait for a Room once and
4541    /// gives the `Poll` back as its value, with the only Room out; the
4542    /// notice a Room's return sends then wakes the thread.
4543    #[test]
4544    fn a_wait_polled_once_by_a_block_on_inside_a_sleeping_one_keeps_its_waker() {
4545        let own_woken = || BLOCK_ON_PARK.with(|park| park.woken.swap(false, Ordering::SeqCst));
4546        let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 1 });
4547        let room = block_on(p.room());
4548        let mut armed = false;
4549        let mut polls = 0;
4550        block_on(core::future::poll_fn(|cx| {
4551            if !armed {
4552                armed = true;
4553                cx.waker().wake_by_ref();
4554                return Poll::Pending;
4555            }
4556            if polls == 0 && BLOCK_ON_PARK.with(|park| park.woken.load(Ordering::SeqCst)) {
4557                return Poll::Pending;
4558            }
4559            // From here the outer block_on sleeps between polls.
4560            polls += 1;
4561            own_woken();
4562            let pending = block_on(core::future::poll_fn(|cx| Poll::Ready(p.poll_room(cx).is_pending())));
4563            assert!(pending, "the only Room is out");
4564            assert!(in_block_on(), "the outer block_on is still active");
4565            p.storage().slot.get().waker.notify_after_seqcst();
4566            assert!(own_woken(), "the wait kept no waker, and the outer block_on would sleep on");
4567            Poll::Ready(())
4568        }));
4569        assert_eq!(polls, 1);
4570        drop(room);
4571    }
4572
4573    /// An owner whose `as_ref` panics is dropped and its slot aborted, keeping
4574    /// the Pipeline usable.
4575    #[test]
4576    fn an_owner_whose_as_ref_panics_is_dropped() {
4577        struct Owner {
4578            _held: Arc<()>,
4579        }
4580        impl AsRef<[u8]> for Owner {
4581            fn as_ref(&self) -> &[u8] {
4582                panic!("an owner that cannot give its bytes")
4583            }
4584        }
4585        let held = Arc::new(());
4586        let mut p = Pipeline::<u32, Owner>::with_owners(Mode::Plain, Limits { messages: 1, rooms: 0 });
4587        let message = block_on(p.message(7, None));
4588        let owner = Owner { _held: Arc::clone(&held) };
4589        let refused = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| p.owned(message, owner)));
4590        assert!(refused.is_err());
4591        assert_eq!(Arc::strong_count(&held), 1, "the owner was not dropped");
4592        drop(p);
4593        assert_eq!(Arc::strong_count(&held), 1);
4594    }
4595
4596    #[test]
4597    fn a_block_on_that_took_no_wake_leaves_the_outer_one_none() {
4598        // The outer block_on's poll runs one that is ready at once: it
4599        // took no wake, and notes none. (It noted one whenever it ended
4600        // inside another, and an outer future that runs a block_on in
4601        // each poll was then polled without end and never slept.)
4602        let mut armed = false;
4603        let mut polls = 0;
4604        block_on(core::future::poll_fn(|cx| {
4605            if !armed {
4606                armed = true;
4607                cx.waker().wake_by_ref();
4608                return Poll::Pending;
4609            }
4610            if polls == 0 && BLOCK_ON_PARK.with(|park| park.woken.load(Ordering::SeqCst)) {
4611                return Poll::Pending;
4612            }
4613            polls += 1;
4614            block_on(async {});
4615            assert!(in_block_on(), "the outer block_on is still active");
4616            if polls == 1 {
4617                assert!(!BLOCK_ON_PARK.with(|park| park.woken.load(Ordering::SeqCst)), "a block_on that took no wake noted one");
4618                // This future's one wake: its next poll is its last.
4619                cx.waker().wake_by_ref();
4620                return Poll::Pending;
4621            }
4622            Poll::Ready(())
4623        }));
4624        assert_eq!(polls, 2);
4625    }
4626
4627    #[test]
4628    #[should_panic(expected = "no ended messages are in flight")]
4629    fn contract_ready_with_nothing_ended_panics() {
4630        let mut pipe = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 2, rooms: 0 });
4631        block_on(async {
4632            let _open = pipe.message(1, None).await;
4633            pipe.ready().await;
4634        });
4635    }
4636
4637    #[test]
4638    #[should_panic(expected = "every commit to a message but its last is a whole room")]
4639    fn contract_commit_after_partial_room_panics() {
4640        let mut pipe = Pipeline::new(Mode::Plain, Limits { messages: 1, rooms: 2 });
4641        block_on(async {
4642            let mut m = pipe.message(1, None).await;
4643            let mut r = pipe.room().await;
4644            pipe.commit(&mut m, &mut r, 64);
4645            pipe.commit(&mut m, &mut r, 64);
4646        });
4647    }
4648
4649    #[test]
4650    #[should_panic(expected = "commit wrote 65537 bytes into a Room with 65536 left")]
4651    fn contract_commit_past_room_len_panics() {
4652        let mut pipe = Pipeline::new(Mode::Plain, Limits { messages: 1, rooms: 1 });
4653        block_on(async {
4654            let mut m = pipe.message(1, None).await;
4655            let mut r = pipe.room().await;
4656            pipe.commit(&mut m, &mut r, ROOM_LEN + 1);
4657        });
4658    }
4659
4660    #[test]
4661    #[should_panic(expected = "bytes given two ways")]
4662    fn contract_bytes_given_two_ways_panics() {
4663        let mut pipe = Pipeline::<u32, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 1, rooms: 1 });
4664        block_on(async {
4665            let mut m = pipe.message(1, None).await;
4666            let mut r = pipe.room().await;
4667            pipe.commit(&mut m, &mut r, 10);
4668            pipe.owned(m, vec![1, 2, 3]);
4669        });
4670    }
4671
4672    #[test]
4673    #[should_panic(expected = "Message belongs to a different Pipeline")]
4674    fn contract_foreign_message_panics() {
4675        let mut p1 = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4676        let mut p2 = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4677        let m1 = block_on(p1.message(1, None));
4678        p2.end(m1);
4679    }
4680
4681    #[test]
4682    #[should_panic(expected = "Room belongs to a different Pipeline")]
4683    fn contract_foreign_room_panics() {
4684        let mut p1 = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 1 });
4685        let mut p2 = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 1 });
4686        let mut m1 = block_on(p1.message(1, None));
4687        let mut r2 = block_on(p2.room());
4688        p1.commit(&mut m1, &mut r2, 0);
4689    }
4690
4691    #[test]
4692    #[should_panic(expected = "Message was dropped without end, abort, owned, lent, or batch")]
4693    fn contract_dropped_unfinished_message_panics() {
4694        let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4695        let _m = block_on(p.message(1, None));
4696    }
4697
4698    #[test]
4699    fn active_loan_drop_and_active_pipeline_drop_abort_the_process() {
4700        use std::os::unix::process::ExitStatusExt as _;
4701        const ENV: &str = "BLAKE3_PIPELINE_ABORT_CASE";
4702        if let Ok(which) = std::env::var(ENV) {
4703            // Each case aborts on purpose: keep the kernel's crash
4704            // handler (Ubuntu's apport: 1 s of D-Bus timeout a child,
4705            // serialized across shards) from inspecting a deliberate
4706            // SIGABRT under the mutation profile's 15 s clock.
4707            #[cfg(target_os = "linux")]
4708            {
4709                // Sound: PR_SET_DUMPABLE(0) affects only this child process.
4710                let rc = unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0 as libc::c_ulong, 0 as libc::c_ulong, 0 as libc::c_ulong, 0 as libc::c_ulong) };
4711                assert_eq!(rc, 0, "prctl(PR_SET_DUMPABLE, 0) failed");
4712            }
4713            match which.as_str() {
4714                "lent" => {
4715                    let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4716                    let m = block_on(p.message(1, None));
4717                    let data = [1u8; 8];
4718                    // Buffered locally in open_group (not dispatched); dropping
4719                    // Lent before hashing completes must abort the process.
4720                    let guard = unsafe { p.lent(m, &data) };
4721                    core::mem::forget(p);
4722                    drop(guard);
4723                }
4724                "lent_after_pipeline_drop" => {
4725                    let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4726                    let m = block_on(p.message(1, None));
4727                    let data = [1u8; 8];
4728                    // Buffered locally in open_group (not dispatched); even
4729                    // after Pipeline::drop frees PipeStorage, Lent still reads
4730                    // its completion line on the retained PipeSlot and aborts
4731                    // on drop because that epoch was never completed.
4732                    let guard = unsafe { p.lent(m, &data) };
4733                    drop(p);
4734                    drop(guard);
4735                }
4736                "pipeline" => {
4737                    let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4738                    p.assigned_group_epoch[0] = u64::MAX;
4739                    drop(p);
4740                }
4741                "pipeline_multi" => {
4742                    let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4743                    p.slots[0].kind = SlotKind::WaitMulti { has_owner: false };
4744                    p.storage().slot_done[0].store(false, Ordering::SeqCst);
4745                    drop(p);
4746                }
4747                "pipeline_piece" => {
4748                    let p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 1 });
4749                    p.storage().pieces[0].done.store(false, Ordering::SeqCst);
4750                    drop(p);
4751                }
4752                "pipeline_batch" => {
4753                    let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4754                    p.slots[0].kind = SlotKind::WaitBatch { group: NONE, epoch: 0 };
4755                    p.storage().slot_done[0].store(false, Ordering::SeqCst);
4756                    drop(p);
4757                }
4758                "abort_on_unwind" => {
4759                    crate::lanes::drop_abort_on_unwind_for_test();
4760                }
4761                "worker_start" => {
4762                    crate::lanes::fail_worker_start_for_test();
4763                }
4764                // A waker that panics ends the process, on the owner's
4765                // thread too: an abort of a short message frees its room
4766                // and wakes the wait before the call has returned.
4767                "waker_panics" => {
4768                    struct Panics;
4769                    impl std::task::Wake for Panics {
4770                        fn wake(self: Arc<Self>) {
4771                            panic!("this waker panics");
4772                        }
4773                    }
4774                    let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 2, rooms: 1 });
4775                    let mut message = block_on(p.message(1, None));
4776                    let mut room = block_on(p.room());
4777                    p.commit(&mut message, &mut room, 3);
4778                    drop(room);
4779                    let _other = message_in_flight(&mut p);
4780                    let waker = Waker::from(Arc::new(Panics));
4781                    assert!(p.poll_ready(&mut Context::from_waker(&waker)).is_pending());
4782                    let _ = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| p.abort(message)));
4783                    // Not reached: the panic did not unwind into the catch.
4784                    std::process::exit(0);
4785                }
4786                // The stop takes no lock: this thread holds stderr's and
4787                // waits for the one that stops.
4788                "lent_stderr_locked" => {
4789                    let _held = std::io::stderr().lock();
4790                    let breach = || {
4791                        let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4792                        let m = block_on(p.message(1, None));
4793                        let data = [1u8; 8];
4794                        let guard = unsafe { p.lent(m, &data) };
4795                        core::mem::forget(p);
4796                        drop(guard);
4797                    };
4798                    std::thread::spawn(breach).join().unwrap();
4799                }
4800                // The stop does not wait for its words: stderr is a full
4801                // blocking pipe here, and a blocking write would never return.
4802                "lent_stderr_full" => {
4803                    crate::lanes::fill_stderr_for_test();
4804                    let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4805                    let m = block_on(p.message(1, None));
4806                    let data = [1u8; 8];
4807                    let guard = unsafe { p.lent(m, &data) };
4808                    core::mem::forget(p);
4809                    drop(guard);
4810                }
4811                // Write a diagnostic line first, then trigger a stop: a regular
4812                // file stderr (2>log or 2>>log) must keep earlier lines intact
4813                // and append the stop message at the current offset/end.
4814                "lent_stderr_after_line" => {
4815                    use std::io::Write as _;
4816                    let mut err = std::io::stderr();
4817                    err.write_all(b"EARLIER-DIAGNOSTIC-LINE\n").unwrap();
4818                    err.flush().unwrap();
4819                    let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4820                    let m = block_on(p.message(1, None));
4821                    let data = [1u8; 8];
4822                    let guard = unsafe { p.lent(m, &data) };
4823                    core::mem::forget(p);
4824                    drop(guard);
4825                }
4826                // Restore default unblocked SIGPIPE (as in a C host or CLI) with
4827                // stderr on a pipe whose read end is closed: fail-stop must still
4828                // end in SIGABRT (6), never SIGPIPE (13).
4829                "lent_stderr_broken_pipe" => {
4830                    unsafe {
4831                        let _ = libc::signal(libc::SIGPIPE, libc::SIG_DFL);
4832                        let mut set: libc::sigset_t = core::mem::zeroed();
4833                        let _ = libc::sigemptyset(&mut set);
4834                        let _ = libc::sigaddset(&mut set, libc::SIGPIPE);
4835                        let _ = libc::pthread_sigmask(libc::SIG_UNBLOCK, &set, core::ptr::null_mut());
4836                    }
4837                    let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
4838                    let m = block_on(p.message(1, None));
4839                    let data = [1u8; 8];
4840                    let guard = unsafe { p.lent(m, &data) };
4841                    core::mem::forget(p);
4842                    drop(guard);
4843                }
4844                // The stop does not wait for its words: stderr is a full
4845                // blocking pipe here, and a blocking write would never return.
4846                "worker_start_stderr_full" => {
4847                    crate::lanes::fill_stderr_for_test();
4848                    crate::lanes::fail_worker_start_for_test();
4849                }
4850                _ => unreachable!(),
4851            }
4852            std::process::exit(0);
4853        }
4854
4855        for (case, needle) in [
4856            ("lent", "Lent guard was dropped before its message finished"),
4857            ("lent_after_pipeline_drop", "Lent guard was dropped before its message finished"),
4858            ("lent_stderr_locked", "Lent guard was dropped before its message finished"),
4859            ("lent_stderr_full", ""),
4860            ("waker_panics", "this waker panics"),
4861            ("pipeline", "Pipeline dropped while worker tasks are still in flight"),
4862            ("pipeline_multi", "Pipeline dropped while worker tasks are still in flight"),
4863            ("pipeline_piece", "Pipeline dropped while worker tasks are still in flight"),
4864            ("pipeline_batch", "Pipeline dropped while worker tasks are still in flight"),
4865            ("abort_on_unwind", ""),
4866            ("worker_start", "BLAKE3: start a worker thread"),
4867            ("worker_start_stderr_full", ""),
4868        ] {
4869            let out = std::process::Command::new(std::env::current_exe().unwrap())
4870                .args(["--exact", "pipeline::test::active_loan_drop_and_active_pipeline_drop_abort_the_process", "--nocapture"])
4871                .env(ENV, case)
4872                .output()
4873                .unwrap();
4874            assert_eq!(out.status.signal(), Some(6), "case {case} must SIGABRT: {:?}", out.status);
4875            let stderr = String::from_utf8_lossy(&out.stderr);
4876            assert!(stderr.contains(needle), "case {case} stderr: {stderr}");
4877        }
4878
4879        // Verify fail-stop on redirected regular files (2>>log, 2>log, and a
4880        // mid-file seek offset), a broken anonymous pipe under default unblocked
4881        // SIGPIPE, and a Unix socketpair, using a private 0o700 temporary
4882        // directory with exclusively created files and RAII cleanup.
4883        let tmp = crate::lanes::TempDir::new("stop");
4884        let tmp_dir_path = tmp.path().to_path_buf();
4885        {
4886            use std::io::{Read as _, Seek as _, SeekFrom, Write as _};
4887            let (append_path, mut init) = tmp.create_exclusive("append.log");
4888            let prior = "PRIOR-RUN-LINE-1\nPRIOR-RUN-LINE-2\n";
4889            init.write_all(prior.as_bytes()).unwrap();
4890            drop(init);
4891            let append_file = std::fs::OpenOptions::new().append(true).open(&append_path).unwrap();
4892            let status = std::process::Command::new(std::env::current_exe().unwrap())
4893                .args(["--exact", "pipeline::test::active_loan_drop_and_active_pipeline_drop_abort_the_process", "--nocapture"])
4894                .env(ENV, "lent")
4895                .stdout(std::process::Stdio::null())
4896                .stderr(std::process::Stdio::from(append_file))
4897                .status()
4898                .unwrap();
4899            assert_eq!(status.signal(), Some(6), "append-file stop must SIGABRT: {status:?}");
4900            let append_body = std::fs::read_to_string(&append_path).unwrap();
4901            assert!(append_body.starts_with(prior), "append-file stop overwrote prior log: {append_body:?}");
4902            assert!(append_body.contains("Lent guard was dropped before its message finished"), "append-file stop missing reason: {append_body:?}");
4903
4904            let (trunc_path, trunc_file) = tmp.create_exclusive("trunc.log");
4905            let status = std::process::Command::new(std::env::current_exe().unwrap())
4906                .args(["--exact", "pipeline::test::active_loan_drop_and_active_pipeline_drop_abort_the_process", "--nocapture"])
4907                .env(ENV, "lent_stderr_after_line")
4908                .stdout(std::process::Stdio::null())
4909                .stderr(std::process::Stdio::from(trunc_file))
4910                .status()
4911                .unwrap();
4912            assert_eq!(status.signal(), Some(6), "trunc-file stop must SIGABRT: {status:?}");
4913            let trunc_body = std::fs::read_to_string(&trunc_path).unwrap();
4914            assert!(trunc_body.starts_with("EARLIER-DIAGNOSTIC-LINE\n"), "trunc-file stop overwrote earlier line: {trunc_body:?}");
4915            assert!(trunc_body.contains("Lent guard was dropped before its message finished"), "trunc-file stop missing reason: {trunc_body:?}");
4916
4917            // Mid-file seek offset on a regular file (NOT at EOF and NOT O_APPEND):
4918            // fail-stop must write at the current offset rather than offset 0 or EOF.
4919            let (_mid_path, mut mid_file) = tmp.create_exclusive("mid.log");
4920            let header = b"HEADER-LINE\n";
4921            let padding = vec![b'X'; 256];
4922            mid_file.write_all(header).unwrap();
4923            mid_file.write_all(&padding).unwrap();
4924            mid_file.seek(SeekFrom::Start(header.len() as u64)).unwrap();
4925            let mid_child = mid_file.try_clone().unwrap();
4926            let status = std::process::Command::new(std::env::current_exe().unwrap())
4927                .args(["--exact", "pipeline::test::active_loan_drop_and_active_pipeline_drop_abort_the_process", "--nocapture"])
4928                .env(ENV, "lent")
4929                .stdout(std::process::Stdio::null())
4930                .stderr(std::process::Stdio::from(mid_child))
4931                .status()
4932                .unwrap();
4933            assert_eq!(status.signal(), Some(6), "mid-offset stop must SIGABRT: {status:?}");
4934            mid_file.seek(SeekFrom::Start(0)).unwrap();
4935            let mut mid_body = String::new();
4936            mid_file.read_to_string(&mut mid_body).unwrap();
4937            assert!(mid_body.starts_with("HEADER-LINE\nblake3-servil: "), "mid-offset stop did not write at seek offset: {mid_body:?}");
4938            assert!(mid_body.contains("Lent guard was dropped before its message finished"), "mid-offset stop missing reason: {mid_body:?}");
4939            assert!(mid_body.ends_with("XXXX"), "mid-offset stop truncated or appended past suffix: {mid_body:?}");
4940        }
4941        drop(tmp);
4942        assert!(!tmp_dir_path.exists(), "TempDir::drop must remove {tmp_dir_path:?}");
4943
4944        // Broken anonymous pipe with default SIGPIPE must exit with SIGABRT (6),
4945        // never SIGPIPE (13).
4946        {
4947            use std::os::fd::FromRawFd as _;
4948            let mut pipe_fds = [0i32; 2];
4949            assert_eq!(unsafe { libc::pipe(pipe_fds.as_mut_ptr()) }, 0);
4950            unsafe { libc::close(pipe_fds[0]) };
4951            let broken_writer = unsafe { std::fs::File::from_raw_fd(pipe_fds[1]) };
4952            let status = std::process::Command::new(std::env::current_exe().unwrap())
4953                .args(["--exact", "pipeline::test::active_loan_drop_and_active_pipeline_drop_abort_the_process", "--nocapture"])
4954                .env(ENV, "lent_stderr_broken_pipe")
4955                .stdout(std::process::Stdio::null())
4956                .stderr(std::process::Stdio::from(broken_writer))
4957                .status()
4958                .unwrap();
4959            assert_eq!(status.signal(), Some(6), "broken-pipe stop with SIG_DFL SIGPIPE must SIGABRT, not SIGPIPE: {status:?}");
4960        }
4961
4962        // Unix socketpair stderr delivers the message and exits with SIGABRT.
4963        {
4964            use std::io::Read as _;
4965            use std::os::fd::FromRawFd as _;
4966            let mut sock_fds = [0i32; 2];
4967            assert_eq!(unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM, 0, sock_fds.as_mut_ptr()) }, 0);
4968            let mut reader = unsafe { std::fs::File::from_raw_fd(sock_fds[0]) };
4969            let writer = unsafe { std::fs::File::from_raw_fd(sock_fds[1]) };
4970            let status = std::process::Command::new(std::env::current_exe().unwrap())
4971                .args(["--exact", "pipeline::test::active_loan_drop_and_active_pipeline_drop_abort_the_process", "--nocapture"])
4972                .env(ENV, "lent")
4973                .stdout(std::process::Stdio::null())
4974                .stderr(std::process::Stdio::from(writer))
4975                .status()
4976                .unwrap();
4977            assert_eq!(status.signal(), Some(6), "socketpair stop must SIGABRT: {status:?}");
4978            let mut msg = String::new();
4979            let _ = reader.read_to_string(&mut msg);
4980            assert!(msg.contains("Lent guard was dropped before its message finished"), "socketpair stop missing reason: {msg:?}");
4981        }
4982    }
4983
4984    /// A stop says why where a person reads it: on a terminal, via the shared
4985    /// `self_test::fail_stop_bytes` fail-stop path.
4986    #[test]
4987    #[cfg(any(target_os = "linux", target_os = "macos"))]
4988    fn a_stop_says_why_on_a_terminal() {
4989        use std::io::{Read as _, Write as _};
4990        use std::os::fd::FromRawFd as _;
4991        use std::os::unix::fs::OpenOptionsExt as _;
4992        use std::os::unix::process::ExitStatusExt as _;
4993        unsafe extern "C" {
4994            fn posix_openpt(flags: i32) -> i32;
4995            fn grantpt(fd: i32) -> i32;
4996            fn unlockpt(fd: i32) -> i32;
4997            fn ptsname(fd: i32) -> *const core::ffi::c_char;
4998        }
4999        const O_RDWR: i32 = 2;
5000        #[cfg(target_os = "linux")]
5001        const O_NOCTTY: i32 = 0o400;
5002        #[cfg(target_os = "macos")]
5003        const O_NOCTTY: i32 = 0x20000;
5004        // Sound: the descriptor posix_openpt returns is this function's
5005        // own, and ptsname's string is copied before any call that could
5006        // write over it.
5007        let (mut ours, name) = unsafe {
5008            let fd = posix_openpt(O_RDWR | O_NOCTTY);
5009            assert!(fd >= 0, "this test needs a pseudo-terminal: {}", std::io::Error::last_os_error());
5010            assert_eq!((grantpt(fd), unlockpt(fd)), (0, 0), "{}", std::io::Error::last_os_error());
5011            let name = ptsname(fd);
5012            assert!(!name.is_null(), "{}", std::io::Error::last_os_error());
5013            (std::fs::File::from_raw_fd(fd), core::ffi::CStr::from_ptr(name).to_str().unwrap().to_owned())
5014        };
5015        // The terminal as a program has it: the child's descriptor 2. It
5016        // stays open here until the words are read: a terminal that
5017        // nobody has open any more may drop what was written to it.
5018        let mut terminal = std::fs::OpenOptions::new().read(true).write(true).custom_flags(O_NOCTTY).open(&name).unwrap();
5019        let status = std::process::Command::new(std::env::current_exe().unwrap())
5020            .args(["--exact", "pipeline::test::active_loan_drop_and_active_pipeline_drop_abort_the_process", "--nocapture"])
5021            .env("BLAKE3_PIPELINE_ABORT_CASE", "worker_start")
5022            .stdin(std::process::Stdio::null())
5023            .stdout(std::process::Stdio::null())
5024            .stderr(terminal.try_clone().unwrap())
5025            .status()
5026            .unwrap();
5027        assert_eq!(status.signal(), Some(6), "{status:?}");
5028        // A mark after whatever the child said, so that the reading ends.
5029        terminal.write_all(b"\nTHE END\n").unwrap();
5030        let mut said = Vec::new();
5031        let mut some = [0u8; 256];
5032        while !said.windows(7).any(|bytes| bytes == b"THE END") {
5033            let count = ours.read(&mut some).unwrap();
5034            assert_ne!(count, 0, "the terminal closed");
5035            said.extend_from_slice(&some[..count]);
5036        }
5037        let said = String::from_utf8_lossy(&said);
5038        assert!(said.contains("BLAKE3: start a worker thread"), "the terminal got {said:?}");
5039    }
5040
5041    #[test]
5042    fn unit_ring_pack_rooms_and_thread_park_primitives() {
5043        let arc = Arc::new(());
5044        {
5045            let mut ring = EventRing::new(3);
5046            assert!(ring.is_empty() && ring.len() == 0 && ring.pop_front().is_none());
5047            ring.push_back((10, Arc::clone(&arc)));
5048            ring.push_back((20, Arc::clone(&arc)));
5049            assert_eq!(ring.len(), 2);
5050            assert_eq!(ring.pop_front().unwrap().0, 10);
5051            ring.push_back((30, Arc::clone(&arc)));
5052            ring.push_back((40, Arc::clone(&arc)));
5053            assert_eq!(ring.pop_front().unwrap().0, 20);
5054            assert_eq!(Arc::strong_count(&arc), 3);
5055        }
5056        assert_eq!(Arc::strong_count(&arc), 1, "EventRing::drop must drop remaining elements");
5057
5058        for arg in [
5059            ActionArg::Group { group: 0x1234_5678, custom_slot: 0x9abc_def0 },
5060            ActionArg::RoomPiece { pnode: 0x1234_5678, custom: true, sme2: false },
5061            ActionArg::RoomPiece { pnode: 0x1234_5678, custom: false, sme2: true },
5062            ActionArg::Multi { slot: 0x1234_5678, piece: 0x1abc_def0, custom: true, sme2: true },
5063            ActionArg::Multi { slot: 0x1234_5678, piece: 0x1abc_def0, custom: false, sme2: false },
5064        ] {
5065            let raw = arg.encode();
5066            assert_eq!(ActionArg::decode(raw), arg);
5067        }
5068
5069        let rooms = Rooms::new(2);
5070        rooms.init_taken(0);
5071        assert!(!rooms.release_n(0, 5));
5072        assert!(rooms.release_n(0, ROOM_CREDITS - 5));
5073
5074        let tp = Arc::new(ThreadPark { thread: std::thread::current(), woken: AtomicBool::new(false) });
5075        std::thread::park_timeout(std::time::Duration::ZERO);
5076        std::task::Wake::wake_by_ref(&tp);
5077        assert!(tp.woken.swap(false, Ordering::SeqCst), "a wake is remembered");
5078        let t0 = std::time::Instant::now();
5079        std::thread::park_timeout(std::time::Duration::from_millis(200));
5080        assert!(t0.elapsed() < std::time::Duration::from_millis(150));
5081
5082        std::thread::park_timeout(std::time::Duration::ZERO);
5083        std::task::Wake::wake(Arc::clone(&tp));
5084        assert!(tp.woken.load(Ordering::SeqCst), "a wake is remembered");
5085        let t1 = std::time::Instant::now();
5086        std::thread::park_timeout(std::time::Duration::from_millis(200));
5087        assert!(t1.elapsed() < std::time::Duration::from_millis(150));
5088    }
5089
5090    #[test]
5091    fn unit_internal_capacities_group_thresholds_aborts_and_drop_cleanup() {
5092        crate::initialize_multithreaded(None);
5093        let has_workers = crate::lanes::pool_has_workers();
5094
5095        let live_before = LIVE_STORAGES.load(Ordering::Relaxed);
5096        let p_small = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 2, rooms: 1 });
5097        assert_eq!(p_small.free_pieces.buf.len(), 1 + 2 + 1);
5098        assert_eq!(p_small.group_count, 4);
5099        assert_eq!(slot_tier(1024), 0);
5100        assert_eq!(slot_tier(2048), 1);
5101        assert_eq!(slot_tier(16384), 4);
5102        assert_eq!(slot_tier(32768), 5);
5103        assert_eq!(p_small.storage().slot.get().source.actions_len(), if has_workers { 1024 } else { 0 });
5104        assert_eq!(p_small.storage().slot.get().loan_completed.len(), 1024 / MAX_SLOT_PIECES);
5105        assert_eq!(p_small.storage().slot.get().group_completed.len(), 16);
5106        let slot_small = p_small.storage().slot.get() as *const PipeSlot as usize;
5107
5108        // Per-tier exact-hit and best-fit fallback across TWO eligible larger
5109        // tiers (2,048 and 16,384): distinguishes `min` from `max`/first-fit
5110        // and proves fallback picks the smallest larger free tier.
5111        let p_mid = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 17, rooms: 0 });
5112        assert_eq!(p_mid.free_pieces.buf.len(), 0, "roomless Pipeline allocates zero PieceNodes");
5113        assert_eq!(p_mid.local_free_rooms.buf.len(), 0, "roomless Pipeline allocates zero local_free_rooms");
5114        assert!(p_mid.storage().pieces.is_empty(), "roomless PipeStorage has zero PieceNodes");
5115        assert_eq!(p_mid.storage().slot.get().source.actions_len(), if has_workers { 2048 } else { 0 });
5116        assert_eq!(p_mid.storage().slot.get().loan_completed.len(), 2048 / MAX_SLOT_PIECES);
5117        let slot_mid = p_mid.storage().slot.get() as *const PipeSlot as usize;
5118        let p_big = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 200, rooms: 1 });
5119        assert_eq!(p_big.storage().slot.get().source.actions_len(), if has_workers { 16384 } else { 0 });
5120        assert_eq!(p_big.storage().slot.get().loan_completed.len(), 16384 / MAX_SLOT_PIECES);
5121        let slot_big = p_big.storage().slot.get() as *const PipeSlot as usize;
5122        assert_ne!(slot_big, slot_small);
5123        assert_ne!(slot_mid, slot_small);
5124        assert_ne!(slot_big, slot_mid);
5125        drop(p_big);
5126        drop(p_mid);
5127        drop(p_small);
5128        let slots_before_reuse = PIPE_SLOTS_MADE.load(Ordering::Relaxed);
5129        let p_best_fit = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 2, rooms: 2 });
5130        assert_eq!(p_best_fit.storage().slot.get() as *const PipeSlot as usize, slot_small, "exact tier 1024 picked even when larger tiers exist");
5131        // With 1,024 held and BOTH 2,048 and 16,384 free, a 1,024 fallback
5132        // request must pick 2,048 (smallest sufficient tier), leaving 16,384
5133        // free for the concurrent 16,384 request with zero new allocations.
5134        let p_fallback = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 2, rooms: 1 });
5135        assert_eq!(
5136            p_fallback.storage().slot.get() as *const PipeSlot as usize,
5137            slot_mid,
5138            "best-fit fallback picks 2,048 over 16,384 when exact 1,024 tier is absent"
5139        );
5140        let p_exact_big = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 248, rooms: 15 });
5141        assert_eq!(p_exact_big.storage().slot.get() as *const PipeSlot as usize, slot_big, "exact tier match reuses 16,384 PipeSlot");
5142        assert_eq!(PIPE_SLOTS_MADE.load(Ordering::Relaxed), slots_before_reuse, "no extra PipeSlot allocated across exact + best-fit fallback");
5143        drop(p_exact_big);
5144        drop(p_fallback);
5145        // Free slots are 2,048 and 16,384; requesting past 16,384 must NOT take either
5146        // (for multi-worker pools `(248, 16)` crosses 16,384 via rooms; for 1-thread
5147        // pools `(257, 0)` crosses 256 messages = 16,384).
5148        let too_big_limits = if has_workers { Limits { messages: 248, rooms: 16 } } else { Limits { messages: 257, rooms: 0 } };
5149        let p_too_big = Pipeline::<usize>::new(Mode::Plain, too_big_limits);
5150        assert_eq!(p_too_big.storage().slot.get().source.actions_len(), if has_workers { 32768 } else { 0 });
5151        assert_eq!(p_too_big.storage().slot.get().loan_completed.len(), 32768 / MAX_SLOT_PIECES);
5152        assert_ne!(p_too_big.storage().slot.get() as *const PipeSlot as usize, slot_big, "off-by-one larger request must not take 16384 slot");
5153        drop((p_too_big, p_best_fit));
5154        assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before);
5155
5156        // Surviving Room keeps its PipeStorage alive until the Room drops,
5157        // while PipeSlot is returned immediately on Pipeline::drop.
5158        let mut p_held = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 2, rooms: 3 });
5159        let held_room = block_on(p_held.room());
5160        drop(p_held);
5161        assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before + 1);
5162        drop(held_room);
5163        assert_eq!(LIVE_STORAGES.load(Ordering::Relaxed), live_before);
5164
5165        let mut pipe = Pipeline::new(Mode::Plain, Limits { messages: 4, rooms: 2 });
5166        block_on(async {
5167            let mut m1 = pipe.message(1usize, None).await;
5168            let mut r0 = pipe.room().await;
5169            pipe.commit(&mut m1, &mut r0, ROOM_LEN);
5170            assert_eq!(r0.len(), 0);
5171            assert_eq!(r0.bytes_mut().len(), 0);
5172            drop(r0);
5173
5174            let mut r1 = pipe.room().await;
5175            r1.bytes_mut()[..100].fill(0x55);
5176            pipe.commit(&mut m1, &mut r1, 100);
5177            assert_eq!(r1.len(), ROOM_LEN - 128);
5178            assert_eq!(r1.bytes_mut().len(), ROOM_LEN - 128);
5179
5180            let mut m2 = pipe.message(2usize, None).await;
5181            r1.bytes_mut()[..50].fill(0x77);
5182            pipe.commit(&mut m2, &mut r1, 50);
5183            assert_eq!(r1.bytes_mut().len(), ROOM_LEN - 192);
5184            drop(r1);
5185            pipe.end(m1);
5186            pipe.end(m2);
5187        });
5188        let evs = drain_all(&mut pipe, 2);
5189        let mut expected_m1 = vec![0u8; ROOM_LEN];
5190        expected_m1.extend_from_slice(&[0x55; 100]);
5191        match &evs[0] {
5192            Event::Hashed { hash, .. } => assert_eq!(*hash, convenience::hash(&expected_m1)),
5193            _ => panic!("expected Hashed"),
5194        }
5195        match &evs[1] {
5196            Event::Hashed { hash, .. } => assert_eq!(*hash, convenience::hash(&[0x77; 50])),
5197            _ => panic!("expected Hashed"),
5198        }
5199
5200        let mut p1 = Pipeline::new(Mode::Plain, Limits { messages: 1, rooms: 0 });
5201        let m_empty = block_on(p1.message(10usize, None));
5202        p1.abort(m_empty);
5203        assert!(matches!(p1.next_event(), Some(Event::Aborted { tag: 10, owner: None })));
5204        let m_batch = block_on(p1.message(11usize, None));
5205        p1.batch(m_batch, Batch::new(64, 2), vec![[0u8; 32]; 2].into_boxed_slice());
5206        block_on(p1.ready());
5207        assert!(matches!(p1.next_event(), Some(Event::Batch { tag: 11, .. })));
5208        let m_after_batch = block_on(p1.message(12usize, None));
5209        p1.end(m_after_batch);
5210        assert!(matches!(p1.next_event(), Some(Event::Hashed { tag: 12, .. })));
5211
5212        let mut p_flush = Pipeline::new(Mode::Plain, Limits { messages: 3, rooms: 1 });
5213        block_on(async {
5214            let mut ma = p_flush.message(1usize, None).await;
5215            let mut mb = p_flush.message(2usize, None).await;
5216            let mut r = p_flush.room().await;
5217            r.bytes_mut()[..CHUNK_LEN].fill(0xAA);
5218            p_flush.commit(&mut ma, &mut r, CHUNK_LEN);
5219            r.bytes_mut()[..64].fill(0xBB);
5220            p_flush.commit(&mut mb, &mut r, 64);
5221            drop(r);
5222            let r_reclaimed = p_flush.room().await;
5223            drop(r_reclaimed);
5224            p_flush.end(ma);
5225            p_flush.abort(mb);
5226        });
5227        let fevs = drain_all(&mut p_flush, 2);
5228        match &fevs[0] {
5229            Event::Hashed { tag: 1, hash, .. } => assert_eq!(*hash, convenience::hash(&[0xAA; CHUNK_LEN])),
5230            _ => panic!("expected ma Hashed"),
5231        }
5232        assert!(matches!(fevs[1], Event::Aborted { tag: 2, owner: None }));
5233
5234        let mut p_thresh = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 128, rooms: 0 });
5235        let m_sub = block_on(p_thresh.message(0, None));
5236        p_thresh.owned(m_sub, vec![1u8; TASK_LEN / 4 - 1]);
5237        assert!(p_thresh.open_group.is_some());
5238        assert!(p_thresh.front_uses_open_group());
5239        let m_tip = block_on(p_thresh.message(1, None));
5240        p_thresh.owned(m_tip, vec![2u8; 1]);
5241        assert!(p_thresh.open_group.is_none());
5242        let m_next = block_on(p_thresh.message(2, None));
5243        p_thresh.owned(m_next, vec![3u8; 64]);
5244        assert!(p_thresh.open_group.is_some());
5245        assert!(!p_thresh.front_uses_open_group());
5246        let _ = drain_all(&mut p_thresh, 3);
5247
5248        let mut p_bound = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 8, rooms: 0 });
5249        let mb1 = block_on(p_bound.message(0, None));
5250        p_bound.batch(mb1, Batch::new(1024, 63), vec![[0u8; 32]; 63].into_boxed_slice());
5251        assert!(p_bound.open_group.is_some());
5252        let mb2 = block_on(p_bound.message(1, None));
5253        p_bound.batch(mb2, Batch::new(1024, 1), vec![[0u8; 32]; 1].into_boxed_slice());
5254        assert!(p_bound.open_group.is_none());
5255        let mb3 = block_on(p_bound.message(2, None));
5256        p_bound.batch(mb3, Batch::new(1024, 64), vec![[0u8; 32]; 64].into_boxed_slice());
5257        let _ = drain_all(&mut p_bound, 3);
5258
5259        let owner_arc: Arc<[u8]> = Arc::from([9u8; 8]);
5260        {
5261            let mut p_drop = Pipeline::<usize, Arc<[u8]>>::with_owners(Mode::Plain, Limits { messages: 1, rooms: 0 });
5262            let m0 = block_on(p_drop.message(0, None));
5263            p_drop.end(m0);
5264            block_on(p_drop.ready());
5265            assert_eq!(p_drop.events.len(), 1);
5266            let m1 = block_on(p_drop.message(1, None));
5267            p_drop.owned(m1, Arc::clone(&owner_arc));
5268            p_drop.publish_open();
5269            while p_drop.has_in_flight_work() {
5270                if !p_drop.storage().slot.get().source.run_waiting_action() {
5271                    p_drop.storage().slot.get().source.wake_for_waiting();
5272                    std::thread::yield_now();
5273                }
5274            }
5275            assert_eq!(Arc::strong_count(&owner_arc), 2);
5276        }
5277        assert_eq!(Arc::strong_count(&owner_arc), 1);
5278
5279        {
5280            let mut p_ab = Pipeline::<usize>::new(Mode::Plain, Limits { messages: 2, rooms: 1 });
5281            let pnode = p_ab.free_pieces.pop_front().unwrap();
5282            p_ab.storage().pieces[pnode as usize].done.store(false, Ordering::SeqCst);
5283            unsafe { *p_ab.storage().pieces[pnode as usize].next.get() = NONE };
5284            p_ab.room_streams[0] = RoomStream { len: ROOM_LEN as u64, head_piece: pnode, tail_piece: pnode, piece_slot_pos: 0, stack_len: 0, merged_pieces: 0 };
5285            p_ab.piece_slots.push(0);
5286            let pending_ep = p_ab.storage().slot.get().group_completed[0].load(Ordering::SeqCst) + 5;
5287            p_ab.slots[0] = SlotMeta { tag: Some(77), kind: SlotKind::WaitAborted { group: 0, epoch: pending_ep }, mode: SlotMode::Default };
5288            p_ab.free_slots.pop_front();
5289            p_ab.end_queue.push_back(0);
5290            assert!(p_ab.try_reap_one().is_none());
5291            p_ab.storage().pieces[pnode as usize].done.store(true, Ordering::SeqCst);
5292            assert!(p_ab.try_reap_one().is_none());
5293            p_ab.storage().slot.get().group_completed[0].store(pending_ep, Ordering::SeqCst);
5294            assert!(matches!(p_ab.try_reap_one(), Some(Event::Aborted { tag: 77, owner: None })));
5295        }
5296    }
5297
5298    #[test]
5299    fn per_message_modes_match_reference_across_all_paths() {
5300        let key_a = [0x11u8; 32];
5301        let key_b = [0x22u8; 32];
5302        let ctx_a = "pipeline per-message mode test A";
5303        let ctx_b = "pipeline per-message mode test B";
5304        let dk_a = [0x33u8; 32];
5305        let dk_b = [0x44u8; 32];
5306
5307        let ref_hash = |mode: Mode, data: &[u8]| -> [u8; 32] {
5308            let mut h = blake3_servil_core::convenience::Hasher::new(mode, None);
5309            h.update(data);
5310            *h.finalize().as_bytes()
5311        };
5312
5313        let collect_hashes = |pipe: &mut Pipeline<usize, Vec<u8>>, n: usize| -> Vec<(usize, [u8; 32])> {
5314            drain_all(pipe, n)
5315                .into_iter()
5316                .map(|ev| match ev {
5317                    Event::Hashed { tag, hash, .. } => (tag, *hash.as_bytes()),
5318                    _ => panic!("expected Event::Hashed"),
5319                })
5320                .collect()
5321        };
5322
5323        let mut pipe = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 16, rooms: 4 });
5324        let mut expected: Vec<(usize, [u8; 32])> = Vec::new();
5325        let mut tag = 0usize;
5326
5327        // 1. Empty messages across all four Mode variants (including default `message()`).
5328        let modes =
5329            [None, Some(Mode::Plain), Some(Mode::Keyed(&key_a)), Some(Mode::Keyed(&key_b)), Some(Mode::DeriveKey(ctx_a)), Some(Mode::DeriveKeyWith(&dk_b))];
5330        for om in modes {
5331            let m = match om {
5332                None => block_on(pipe.message(tag, None)),
5333                Some(mode) => block_on(pipe.message_with(mode, tag, None)),
5334            };
5335            pipe.end(m);
5336            expected.push((tag, ref_hash(om.unwrap_or(Mode::Plain), &[])));
5337            tag += 1;
5338        }
5339        assert_eq!(collect_hashes(&mut pipe, expected.len()), expected);
5340        expected.clear();
5341
5342        // 2. Short owned messages: alternating modes AND consecutive same-mode
5343        // (explicit Plain shares an open group; every custom mode dispatches its
5344        // own closed singleton group immediately).
5345        let short_cases: &[(Option<Mode>, usize)] = &[
5346            (None, 32),
5347            (Some(Mode::Plain), 64),
5348            (Some(Mode::Plain), 64),
5349            (Some(Mode::Keyed(&key_a)), 48),
5350            (Some(Mode::Keyed(&key_a)), 80),
5351            (Some(Mode::Keyed(&key_b)), 48),
5352            (Some(Mode::DeriveKeyWith(&dk_a)), 96),
5353            (Some(Mode::DeriveKeyWith(&dk_a)), 128),
5354            (Some(Mode::DeriveKey(ctx_b)), 64),
5355            (Some(Mode::DeriveKey(ctx_b)), 64),
5356            (None, 1024),
5357        ];
5358        let mut plain_group_epoch = None;
5359        for (i, &(om, len)) in short_cases.iter().enumerate() {
5360            let data: Vec<u8> = (0..len).map(|j| ((i * 31 + j * 7) & 0xff) as u8).collect();
5361            let exp = ref_hash(om.unwrap_or(Mode::Plain), &data);
5362            let ep_before = pipe.next_group_epoch;
5363            let m = match om {
5364                None => block_on(pipe.message(tag, Some(len as u64))),
5365                Some(mode) => block_on(pipe.message_with(mode, tag, Some(len as u64))),
5366            };
5367            pipe.owned(m, data);
5368            match om {
5369                Some(Mode::Plain) => {
5370                    let (_, open_ep) = pipe.open_group.expect("short explicit Plain stays in an open group");
5371                    match plain_group_epoch {
5372                        None => {
5373                            assert_eq!(pipe.next_group_epoch, ep_before + 1, "first explicit Plain opens its own group");
5374                            plain_group_epoch = Some(open_ep);
5375                        }
5376                        Some(first_ep) => assert_eq!(open_ep, first_ep, "consecutive explicit Plain shorts share one group"),
5377                    }
5378                }
5379                Some(_) => {
5380                    assert_eq!(pipe.next_group_epoch, ep_before + 1, "custom short submission {i} must open and dispatch a group");
5381                    assert!(pipe.open_group.is_none(), "custom short submission {i} must close and dispatch immediately");
5382                }
5383                None => {}
5384            }
5385            expected.push((tag, exp));
5386            tag += 1;
5387        }
5388        assert_eq!(collect_hashes(&mut pipe, expected.len()), expected);
5389        expected.clear();
5390
5391        // 3. Multi-piece owned, lent, and streaming room messages with distinct per-message modes.
5392        let long_len = 2 * ROOM_LEN + 137;
5393        let owned_long: Vec<u8> = (0..long_len).map(|j| ((j * 13 + 3) & 0xff) as u8).collect();
5394        let lent_long: Vec<u8> = (0..long_len).map(|j| ((j * 17 + 9) & 0xff) as u8).collect();
5395        let stream_long: Vec<u8> = (0..long_len).map(|j| ((j * 23 + 5) & 0xff) as u8).collect();
5396        let stream_short: Vec<u8> = (0..120).map(|j| ((j * 29 + 1) & 0xff) as u8).collect();
5397
5398        let m_owned = block_on(pipe.message_with(Mode::Keyed(&key_a), tag, Some(long_len as u64)));
5399        expected.push((tag, ref_hash(Mode::Keyed(&key_a), &owned_long)));
5400        pipe.owned(m_owned, owned_long);
5401        tag += 1;
5402
5403        let m_lent = block_on(pipe.message_with(Mode::DeriveKeyWith(&dk_b), tag, Some(long_len as u64)));
5404        expected.push((tag, ref_hash(Mode::DeriveKeyWith(&dk_b), &lent_long)));
5405        let guard = unsafe { pipe.lent(m_lent, &lent_long) };
5406        tag += 1;
5407
5408        let mut m_stream = block_on(pipe.message_with(Mode::DeriveKey(ctx_a), tag, Some(long_len as u64)));
5409        expected.push((tag, ref_hash(Mode::DeriveKey(ctx_a), &stream_long)));
5410        for chunk in stream_long.chunks(ROOM_LEN) {
5411            let mut r = block_on(pipe.room());
5412            r.bytes_mut()[..chunk.len()].copy_from_slice(chunk);
5413            pipe.commit(&mut m_stream, &mut r, chunk.len());
5414        }
5415        pipe.end(m_stream);
5416        tag += 1;
5417
5418        let mut m_short_room = block_on(pipe.message_with(Mode::Keyed(&key_b), tag, None));
5419        expected.push((tag, ref_hash(Mode::Keyed(&key_b), &stream_short)));
5420        {
5421            let mut r = block_on(pipe.room());
5422            r.bytes_mut()[..stream_short.len()].copy_from_slice(&stream_short);
5423            pipe.commit(&mut m_short_room, &mut r, stream_short.len());
5424        }
5425        pipe.end(m_short_room);
5426        tag += 1;
5427
5428        let mut got = Vec::new();
5429        while got.len() < expected.len() {
5430            if let Some(ev) = pipe.next_event() {
5431                if let Event::Hashed { tag: t, hash, .. } = ev {
5432                    got.push((t, *hash.as_bytes()));
5433                }
5434            } else {
5435                block_on(pipe.ready());
5436            }
5437        }
5438        drop(guard);
5439        assert_eq!(got, expected);
5440
5441        // 4. Short and multi-piece batches with per-message modes.
5442        for &(mode, count, msg_len) in &[(Mode::Keyed(&key_a), 8usize, 64usize), (Mode::DeriveKeyWith(&dk_b), 2048usize, 64usize)] {
5443            let mut b = Batch::new(msg_len, count);
5444            for i in 0..count {
5445                b.message_mut(i).fill(((i * 5 + 1) & 0xff) as u8);
5446            }
5447            let digests = vec![[0u8; 32]; count].into_boxed_slice();
5448            let bm = block_on(pipe.message_with(mode, tag, None));
5449            pipe.batch(bm, b, digests);
5450            tag += 1;
5451            let ev = loop {
5452                if let Some(ev) = pipe.next_event() {
5453                    break ev;
5454                }
5455                block_on(pipe.ready());
5456            };
5457            let Event::Batch { mut batch, digests, .. } = ev else {
5458                panic!("expected Event::Batch");
5459            };
5460            for i in 0..count {
5461                assert_eq!(digests[i], ref_hash(mode, batch.message_mut(i)));
5462            }
5463        }
5464
5465        // 5. Key-independent group dispatch: identical vs distinct secret keys
5466        //    must publish the exact same number of MemberGroups.
5467        let mut p_same = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 8, rooms: 0 });
5468        let e0 = p_same.next_group_epoch;
5469        for i in 0..2 {
5470            let m = block_on(p_same.message_with(Mode::Keyed(&key_a), i, None));
5471            p_same.owned(m, vec![i as u8; 64]);
5472            assert!(p_same.open_group.is_none(), "Custom message must publish immediately");
5473        }
5474        let same_groups = p_same.next_group_epoch - e0;
5475        let _ = drain_all(&mut p_same, 2);
5476
5477        let mut p_diff = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 8, rooms: 0 });
5478        let e1 = p_diff.next_group_epoch;
5479        let m0 = block_on(p_diff.message_with(Mode::Keyed(&key_a), 0, None));
5480        p_diff.owned(m0, vec![0u8; 64]);
5481        let m1 = block_on(p_diff.message_with(Mode::Keyed(&key_b), 1, None));
5482        p_diff.owned(m1, vec![1u8; 64]);
5483        let diff_groups = p_diff.next_group_epoch - e1;
5484        let _ = drain_all(&mut p_diff, 2);
5485        assert_eq!(same_groups, diff_groups, "keyed group dispatch must not depend on secret key equality");
5486        assert_eq!(same_groups, 2);
5487
5488        // 6. RPIT lifetime independence (`+ use<'p, T, B>`) and unpolled drop.
5489        fn open_with_local_ctx<'p>(p: &'p mut Pipeline<usize, Vec<u8>>, tag: usize) -> impl Future<Output = Message> + use<'p> {
5490            let local_ctx = String::from("ephemeral local derive context");
5491            p.message_with(Mode::DeriveKey(&local_ctx), tag, None)
5492        }
5493        // Drop an unpolled message_with future without affecting pipeline state.
5494        let _unpolled = pipe.message_with(Mode::Keyed(&key_a), 9999, None);
5495        drop(_unpolled);
5496        let m_local = block_on(open_with_local_ctx(&mut pipe, tag));
5497        pipe.owned(m_local, vec![0xAB; 64]);
5498        let got_local = collect_hashes(&mut pipe, 1);
5499        assert_eq!(got_local, vec![(tag, ref_hash(Mode::DeriveKey("ephemeral local derive context"), &[0xAB; 64]))]);
5500
5501        // 7. Keyed-default Pipeline: adjacent same-length Default -> Plain and
5502        //    Default -> Custom transitions must flush open groups (killing both
5503        //    `|| -> &&` mutants in `push_member`), plus room-pressure flush.
5504        let mut p_keyed = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Keyed(&key_a), Limits { messages: 8, rooms: 1 });
5505        let md0 = block_on(p_keyed.message(0, None));
5506        p_keyed.owned(md0, vec![0x11; 64]);
5507        let mp1 = block_on(p_keyed.message_with(Mode::Plain, 1, None));
5508        p_keyed.owned(mp1, vec![0x22; 64]);
5509        let mc2 = block_on(p_keyed.message_with(Mode::Keyed(&key_b), 2, None));
5510        p_keyed.owned(mc2, vec![0x33; 64]);
5511        let got_k = collect_hashes(&mut p_keyed, 3);
5512        assert_eq!(got_k[0], (0, ref_hash(Mode::Keyed(&key_a), &[0x11; 64])));
5513        assert_eq!(got_k[1], (1, ref_hash(Mode::Plain, &[0x22; 64])));
5514        assert_eq!(got_k[2], (2, ref_hash(Mode::Keyed(&key_b), &[0x33; 64])));
5515
5516        // Room-pressure flush on Keyed-default Pipeline with explicit Plain room.
5517        let mut mr0 = block_on(p_keyed.message(10, None));
5518        let mut mr1 = block_on(p_keyed.message_with(Mode::Plain, 11, None));
5519        {
5520            let mut r = block_on(p_keyed.room());
5521            r.bytes_mut()[..64].fill(0x44);
5522            p_keyed.commit(&mut mr0, &mut r, 64);
5523            r.bytes_mut()[..64].fill(0x55);
5524            p_keyed.commit(&mut mr1, &mut r, 64);
5525        }
5526        // Re-acquiring the only room forces flush_sealed_short_rooms before end().
5527        let r2 = block_on(p_keyed.room());
5528        drop(r2);
5529        p_keyed.end(mr1);
5530        p_keyed.end(mr0);
5531        let got_r = collect_hashes(&mut p_keyed, 2);
5532        assert_eq!(got_r[0], (11, ref_hash(Mode::Plain, &[0x55; 64])));
5533        assert_eq!(got_r[1], (10, ref_hash(Mode::Keyed(&key_a), &[0x44; 64])));
5534
5535        // 8. Dropping a Pending MessageOpenFut (override mode) must clear the registered Waker.
5536        struct NoopWake;
5537        impl std::task::Wake for NoopWake {
5538            fn wake(self: Arc<Self>) {}
5539        }
5540        let mut p1 = Pipeline::<usize, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 1, rooms: 0 });
5541        let cur_epoch = p1.storage().slot.get().group_completed[0].load(Ordering::SeqCst);
5542        let pending_epoch = cur_epoch + 1;
5543        p1.slots[0] = SlotMeta { tag: Some(0), kind: SlotKind::WaitAborted { group: 0, epoch: pending_epoch }, mode: SlotMode::Default };
5544        p1.free_slots.pop_front();
5545        p1.end_queue.push_back(0);
5546        let wake_arc = Arc::new(NoopWake);
5547        {
5548            let waker = Waker::from(Arc::clone(&wake_arc));
5549            let mut cx = Context::from_waker(&waker);
5550            let mut fut = Box::pin(p1.message_with(Mode::Keyed(&key_a), 1, None));
5551            assert!(fut.as_mut().poll(&mut cx).is_pending());
5552            drop(waker);
5553            assert_eq!(Arc::strong_count(&wake_arc), 2, "Pending poll must register waker");
5554            drop(fut);
5555        }
5556        assert_eq!(Arc::strong_count(&wake_arc), 1, "Dropping Pending MessageOpenFut must clear waker");
5557        p1.storage().slot.get().group_completed[0].store(pending_epoch, Ordering::SeqCst);
5558        assert!(matches!(p1.try_reap_one(), Some(Event::Aborted { tag: 0, owner: None })));
5559    }
5560
5561    #[test]
5562    fn packed_batches_in_pipeline_match_reference() {
5563        use crate::throughput::Packed;
5564        let key = [0x66u8; 32];
5565        let fill_msg = |dst: &mut [u8], tag: usize, idx: usize| {
5566            // Encode full u32 index + position-dependent bytes so no period-256
5567            // aliasing hides offset bugs across multi-piece batch tasks.
5568            let idx_bytes = (idx as u32).to_le_bytes();
5569            let tag_byte = (tag as u8).wrapping_mul(31).wrapping_add(7);
5570            for (j, b) in dst.iter_mut().enumerate() {
5571                *b = if j < 4 {
5572                    idx_bytes[j] ^ tag_byte
5573                } else {
5574                    ((idx.wrapping_mul(17).wrapping_add(j.wrapping_mul(13)).wrapping_add(tag.wrapping_mul(5))) & 0xff) as u8
5575                };
5576            }
5577        };
5578
5579        // 1. Packed<32> (inferred without turbofish!): empty, small (MemberGroup),
5580        //    multi-piece BLINCS batch (6,144 msgs -> 6 pieces), and 1,025-msg tail
5581        //    checking per-piece sme2 flag (piece 0: 1,024 msgs >= SME2_MIN_LEN,
5582        //    piece 1: 1 msg < SME2_MIN_LEN).
5583        let mut p32_pipe = Pipeline::with_batches(Mode::Plain, Limits { messages: 4, rooms: 0 });
5584        for &(tag, count, mode) in &[(0usize, 0usize, Mode::Plain), (1, 37, Mode::Plain), (2, 6144, Mode::Keyed(&key)), (3, 1025, Mode::Plain)] {
5585            let mut batch = Packed::<32>::new(count);
5586            for i in 0..count {
5587                fill_msg(&mut batch[i], tag, i);
5588            }
5589            let digests = vec![[0u8; 32]; count].into_boxed_slice();
5590            let m = block_on(p32_pipe.message_with(mode, tag, None));
5591            let slot_idx = m.slot as usize;
5592            p32_pipe.batch(m, batch, digests);
5593            let got_pieces = if count >= 1024 { unsafe { (*p32_pipe.storage().multi[slot_idx].get()).pieces } } else { 0 };
5594            let tail_sme2 =
5595                if count == 1025 { Some((p32_pipe.bufs.action_buf[0] & ACTION_SME2 != 0, p32_pipe.bufs.action_buf[1] & ACTION_SME2 != 0)) } else { None };
5596            let ev = loop {
5597                if let Some(ev) = p32_pipe.next_event() {
5598                    break ev;
5599                }
5600                block_on(p32_pipe.ready());
5601            };
5602            if count == 6144 {
5603                // Verify 6,144 x 32 B split into 6 compression-work pieces (1,024 msgs each).
5604                assert_eq!(got_pieces, 6);
5605            }
5606            if let Some((p0_sme2, p1_sme2)) = tail_sme2 {
5607                assert_eq!(got_pieces, 2);
5608                assert_eq!(p0_sme2, 1024 * crate::BLOCK_LEN >= SME2_MIN_LEN);
5609                assert!(!p1_sme2, "1-message tail piece must not claim Sme2Turn");
5610            }
5611            let Event::Batch { tag: got_tag, batch, digests } = ev else {
5612                panic!("expected Event::Batch");
5613            };
5614            assert_eq!(got_tag, tag);
5615            for i in 0..count {
5616                let want = *blake3_servil_core::convenience::hash_with(mode, &batch[i]).as_bytes();
5617                assert_eq!(digests[i], want, "Packed<32> tag={tag} msg={i}");
5618            }
5619        }
5620
5621        // 2. Compression-work flushing in push_member: 1,023 x 32 B (32,736 raw B,
5622        //    65,472 work B < 65,536) stays in open_group, then +1 x 32 B pushes
5623        //    work bytes to 65,536 == TASK_LEN and flushes open_group immediately
5624        //    (raw bytes would only be 32,768 < TASK_LEN).
5625        {
5626            let mut flush_pipe = Pipeline::with_batches(Mode::Plain, Limits { messages: 4, rooms: 0 });
5627            let mut b1 = Packed::<32>::new(1023);
5628            for i in 0..1023 {
5629                fill_msg(&mut b1[i], 10, i);
5630            }
5631            let m1 = block_on(flush_pipe.message(10usize, None));
5632            flush_pipe.batch(m1, b1, vec![[0u8; 32]; 1023].into_boxed_slice());
5633            assert!(flush_pipe.open_group.is_some(), "1023 x 32 B (< TASK_LEN work) stays buffered");
5634            let mut b2 = Packed::<32>::new(1);
5635            fill_msg(&mut b2[0], 11, 0);
5636            let m2 = block_on(flush_pipe.message(11usize, None));
5637            flush_pipe.batch(m2, b2, vec![[0u8; 32]; 1].into_boxed_slice());
5638            assert!(flush_pipe.open_group.is_none(), "1023 + 1 x 32 B reaches TASK_LEN compression work and flushes");
5639            let events = drain_all(&mut flush_pipe, 2);
5640            for ev in events {
5641                let Event::Batch { batch, digests, .. } = ev else { panic!("expected Event::Batch") };
5642                for i in 0..batch.len() {
5643                    assert_eq!(digests[i], *blake3_servil_core::convenience::hash(&batch[i]).as_bytes());
5644                }
5645            }
5646        }
5647
5648        // 3. Packed<16> and Packed<48> (small + multi-piece) and owned Vec<[u8; 32]>.
5649        let mut p16_pipe = Pipeline::<usize, (), Packed<16>>::with_batches(Mode::Plain, Limits { messages: 2, rooms: 0 });
5650        for &count in &[17usize, 2051] {
5651            let mut batch = Packed::<16>::new(count);
5652            for i in 0..count {
5653                fill_msg(&mut batch[i], 4, i);
5654            }
5655            let m = block_on(p16_pipe.message(count, None));
5656            p16_pipe.batch(m, batch, vec![[0u8; 32]; count].into_boxed_slice());
5657            let Event::Batch { batch, digests, .. } = drain_all(&mut p16_pipe, 1).pop().unwrap() else {
5658                panic!("expected Event::Batch");
5659            };
5660            for i in 0..count {
5661                assert_eq!(digests[i], *blake3_servil_core::convenience::hash(&batch[i]).as_bytes());
5662            }
5663        }
5664
5665        let mut p48_pipe = Pipeline::<usize, (), Packed<48>>::with_batches(Mode::Keyed(&key), Limits { messages: 2, rooms: 0 });
5666        for &count in &[19usize, 1500] {
5667            let mut batch = Packed::<48>::new(count);
5668            for i in 0..count {
5669                fill_msg(&mut batch[i], 5, i);
5670            }
5671            let m = block_on(p48_pipe.message(count, None));
5672            p48_pipe.batch(m, batch, vec![[0u8; 32]; count].into_boxed_slice());
5673            let Event::Batch { batch, digests, .. } = drain_all(&mut p48_pipe, 1).pop().unwrap() else {
5674                panic!("expected Event::Batch");
5675            };
5676            for i in 0..count {
5677                assert_eq!(digests[i], *blake3_servil_core::convenience::hash_with(Mode::Keyed(&key), &batch[i]).as_bytes());
5678            }
5679        }
5680
5681        let mut vec_pipe = Pipeline::<usize, Vec<u8>, Vec<[u8; 32]>>::with_owners_and_batches(Mode::Plain, Limits { messages: 2, rooms: 0 });
5682        let vec_batch: Vec<[u8; 32]> = (0..1200)
5683            .map(|i| {
5684                let mut msg = [0u8; 32];
5685                fill_msg(&mut msg, 6, i);
5686                msg
5687            })
5688            .collect();
5689        let m = block_on(vec_pipe.message(1, None));
5690        vec_pipe.batch(m, vec_batch, vec![[0u8; 32]; 1200].into_boxed_slice());
5691        let Event::Batch { batch, digests, .. } = drain_all(&mut vec_pipe, 1).pop().unwrap() else {
5692            panic!("expected Event::Batch");
5693        };
5694        for i in 0..1200 {
5695            assert_eq!(digests[i], *blake3_servil_core::convenience::hash(&batch[i]).as_bytes());
5696        }
5697
5698        // Verify Pipeline::with_owners still infers P = Batch<'static> with no batch() call,
5699        // and Box<[[u8; 32]]> works through with_batches.
5700        let mut inferred_owners = Pipeline::with_owners(Mode::Plain, Limits { messages: 1, rooms: 0 });
5701        let mo = block_on(inferred_owners.message(9usize, None));
5702        inferred_owners.owned(mo, vec![0x42u8; 64]);
5703        let Event::Hashed { tag: 9, hash, .. } = drain_all(&mut inferred_owners, 1).pop().unwrap() else {
5704            panic!("expected Event::Hashed");
5705        };
5706        assert_eq!(hash, blake3_servil_core::convenience::hash(&[0x42u8; 64]));
5707
5708        let mut box_pipe = Pipeline::with_batches(Mode::Plain, Limits { messages: 2, rooms: 0 });
5709        let boxed: Box<[[u8; 32]]> = (0..600)
5710            .map(|i| {
5711                let mut msg = [0u8; 32];
5712                fill_msg(&mut msg, 7, i);
5713                msg
5714            })
5715            .collect::<Vec<_>>()
5716            .into_boxed_slice();
5717        let mb = block_on(box_pipe.message(7usize, None));
5718        box_pipe.batch(mb, boxed, vec![[0u8; 32]; 600].into_boxed_slice());
5719        let Event::Batch { tag: 7, batch, digests } = drain_all(&mut box_pipe, 1).pop().unwrap() else {
5720            panic!("expected Event::Batch");
5721        };
5722        for i in 0..600 {
5723            assert_eq!(digests[i], *blake3_servil_core::convenience::hash(&batch[i]).as_bytes());
5724        }
5725    }
5726
5727    /// Panicking inside an owner's `AsRef::as_ref` drops the owner in place,
5728    /// aborts the slot cleanly, keeps `open_messages` exact, and lets the
5729    /// single-slot Pipeline keep serving subsequent messages (#465).
5730    #[test]
5731    fn panicking_as_ref_aborts_slot_and_keeps_pipeline_usable() {
5732        struct MaybePanicOwner {
5733            bytes: [u8; 16],
5734            drops: Arc<AtomicUsize>,
5735            panic: bool,
5736        }
5737        impl AsRef<[u8]> for MaybePanicOwner {
5738            fn as_ref(&self) -> &[u8] {
5739                if self.panic {
5740                    panic!("deliberate as_ref panic");
5741                }
5742                &self.bytes
5743            }
5744        }
5745        impl Drop for MaybePanicOwner {
5746            fn drop(&mut self) {
5747                self.drops.fetch_add(1, Ordering::SeqCst);
5748            }
5749        }
5750        let drops = Arc::new(AtomicUsize::new(0));
5751        let mut p = Pipeline::<u32, MaybePanicOwner>::with_owners(Mode::Plain, Limits { messages: 1, rooms: 0 });
5752        let m1 = block_on(p.message(1, None));
5753        let res = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
5754            p.owned(m1, MaybePanicOwner { bytes: [0xaa; 16], drops: Arc::clone(&drops), panic: true });
5755        }));
5756        assert!(res.is_err(), "panicking as_ref must unwind");
5757        assert_eq!(drops.load(Ordering::SeqCst), 1, "owner must be dropped on as_ref unwind");
5758        assert_eq!(p.open_messages, 0, "open_messages must reflect aborted slot");
5759        block_on(p.ready());
5760        assert!(matches!(p.next_event(), Some(Event::Aborted { tag: 1, owner: None })), "aborted slot must yield Event::Aborted");
5761
5762        // Slot must be back on free_slots so a subsequent message succeeds without hanging.
5763        let m2 = block_on(p.message(2, None));
5764        p.owned(m2, MaybePanicOwner { bytes: [0x55; 16], drops: Arc::clone(&drops), panic: false });
5765        let Event::Hashed { tag: 2, hash, owner } = drain_all(&mut p, 1).pop().unwrap() else {
5766            panic!("expected Event::Hashed");
5767        };
5768        assert_eq!(hash, blake3_servil_core::convenience::hash(&[0x55; 16]));
5769        drop(owner);
5770        assert_eq!(drops.load(Ordering::SeqCst), 2);
5771    }
5772
5773    /// Rejected `owned`, `lent`, and `batch` calls (bytes given two ways or
5774    /// mismatched batch digest count) abort the slot and release any Room
5775    /// credit so a 1-message / 1-room Pipeline stays usable after `catch_unwind` (#465).
5776    #[test]
5777    fn rejected_owned_lent_and_batch_abort_slot_and_release_room() {
5778        let mut p = Pipeline::<u32, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 1, rooms: 1 });
5779
5780        // 1. owned after Room commit releases room and aborts slot.
5781        let mut m1 = block_on(p.message(1, None));
5782        let mut r1 = block_on(p.room());
5783        r1.bytes_mut()[..8].copy_from_slice(b"12345678");
5784        p.commit(&mut m1, &mut r1, 8);
5785        drop(r1);
5786        let res = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
5787            p.owned(m1, vec![1, 2, 3]);
5788        }));
5789        assert!(res.is_err(), "owned after commit must panic");
5790        block_on(p.ready());
5791        assert!(matches!(p.next_event(), Some(Event::Aborted { tag: 1, owner: None })));
5792
5793        // 2. lent after Room commit releases room and aborts slot.
5794        let mut m2 = block_on(p.message(2, None));
5795        let mut r2 = block_on(p.room());
5796        r2.bytes_mut()[..4].copy_from_slice(b"abcd");
5797        p.commit(&mut m2, &mut r2, 4);
5798        drop(r2);
5799        let res = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
5800            let _ = unsafe { p.lent(m2, b"efgh") };
5801        }));
5802        assert!(res.is_err(), "lent after commit must panic");
5803        block_on(p.ready());
5804        assert!(matches!(p.next_event(), Some(Event::Aborted { tag: 2, owner: None })));
5805
5806        // 3. owned after whole-room OpenRooms commit releases room and aborts slot.
5807        let mut m3 = block_on(p.message(3, None));
5808        let mut r3 = block_on(p.room());
5809        r3.bytes_mut().fill(0xab);
5810        p.commit(&mut m3, &mut r3, ROOM_LEN);
5811        drop(r3);
5812        assert!(matches!(p.slots[m3.slot as usize].kind, SlotKind::OpenRooms { .. }));
5813        let res = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
5814            p.owned(m3, vec![9, 8, 7]);
5815        }));
5816        assert!(res.is_err(), "owned after OpenRooms commit must panic");
5817        block_on(p.ready());
5818        assert!(matches!(p.next_event(), Some(Event::Aborted { tag: 3, owner: None })));
5819
5820        // 4. lent after OpenShortDispatched (flushed short room) aborts cleanly.
5821        let mut m4 = block_on(p.message(4, None));
5822        let mut r4 = block_on(p.room());
5823        r4.bytes_mut()[..12].copy_from_slice(b"short-in-flt");
5824        p.commit(&mut m4, &mut r4, 12);
5825        drop(r4);
5826        p.flush_sealed_short_rooms();
5827        assert!(matches!(p.slots[m4.slot as usize].kind, SlotKind::OpenShortDispatched { .. }));
5828        let res = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
5829            let _ = unsafe { p.lent(m4, b"extra") };
5830        }));
5831        assert!(res.is_err(), "lent after OpenShortDispatched must panic");
5832        block_on(p.ready());
5833        assert!(matches!(p.next_event(), Some(Event::Aborted { tag: 4, owner: None })));
5834
5835        // 5. batch with bytes given two ways (after Room commit) aborts cleanly.
5836        let mut m5 = block_on(p.message(5, None));
5837        let mut r5 = block_on(p.room());
5838        r5.bytes_mut()[..4].copy_from_slice(b"room");
5839        p.commit(&mut m5, &mut r5, 4);
5840        drop(r5);
5841        let batch_two_ways = Batch::new(1, 64);
5842        let res = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
5843            p.batch(m5, batch_two_ways, vec![[0u8; 32]; 1].into_boxed_slice());
5844        }));
5845        assert!(res.is_err(), "batch after commit must panic");
5846        block_on(p.ready());
5847        assert!(matches!(p.next_event(), Some(Event::Aborted { tag: 5, owner: None })));
5848
5849        // 6. batch with mismatched digest count aborts slot cleanly.
5850        let m6 = block_on(p.message(6, None));
5851        let bad_batch = Batch::new(2, 64);
5852        let res = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
5853            p.batch(m6, bad_batch, vec![[0u8; 32]; 1].into_boxed_slice());
5854        }));
5855        assert!(res.is_err(), "batch with wrong digest len must panic");
5856        block_on(p.ready());
5857        assert!(matches!(p.next_event(), Some(Event::Aborted { tag: 6, owner: None })));
5858
5859        // 7. Both the single message slot and single room must now work end to end.
5860        let mut m7 = block_on(p.message(7, None));
5861        let mut r7 = block_on(p.room());
5862        r7.bytes_mut()[..5].copy_from_slice(b"hello");
5863        p.commit(&mut m7, &mut r7, 5);
5864        drop(r7);
5865        p.end(m7);
5866        let Event::Hashed { tag: 7, hash, .. } = drain_all(&mut p, 1).pop().unwrap() else {
5867            panic!("expected Event::Hashed");
5868        };
5869        assert_eq!(hash, blake3_servil_core::convenience::hash(b"hello"));
5870    }
5871
5872    /// A one-thread pool allocates zero worker ticket slots and recycles its
5873    /// `PipeSlot` across Pipelines (including multi-piece loans) without
5874    /// allocating a fresh slot.
5875    #[test]
5876    fn one_thread_pool_pipeline_allocates_zero_worker_tickets() {
5877        const ENV: &str = "BLAKE3_PIPELINE_ONE_THREAD_TICKETS";
5878        if std::env::var_os(ENV).is_some() {
5879            crate::initialize_multithreaded(core::num::NonZeroUsize::new(1));
5880            let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 1024, rooms: 0 });
5881            assert!(p.source_slot.is_none(), "one-thread pool must not register a worker Source");
5882            assert_eq!(p.pipe_slot.source.actions_len(), 0, "one-thread pool must allocate zero ticket slots");
5883            assert_eq!(p.pipe_slot.loan_completed.len(), 1024);
5884            assert_eq!(p.pipe_slot.group_completed.len(), 256);
5885            let slot_ptr = p.pipe_slot as *const PipeSlot as usize;
5886            let made_after_p = PIPE_SLOTS_MADE.load(Ordering::Relaxed);
5887            // Prove the synchronous execution path hashes messages and recycles the slot.
5888            let msg = [0x5Au8; 64];
5889            let m = block_on(p.message(7, None));
5890            // Sound: `lent` is held across `ready()` and dropped only after completion.
5891            let lent = unsafe { p.lent(m, &msg) };
5892            block_on(p.ready());
5893            drop(lent);
5894            match p.next_event() {
5895                Some(Event::Hashed { tag: 7, hash, .. }) => assert_eq!(hash.as_bytes(), blake3::hash(&msg).as_bytes()),
5896                _ => panic!("expected Hashed event"),
5897            }
5898            drop(p);
5899            let mut p2 = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 16, rooms: 2 });
5900            assert_eq!(p2.pipe_slot as *const PipeSlot as usize, slot_ptr, "one-thread PipeSlot must be recycled by identity");
5901            assert_eq!(PIPE_SLOTS_MADE.load(Ordering::Relaxed), made_after_p, "recycling one-thread PipeSlot allocates no new slot");
5902            assert_eq!(p2.pipe_slot.source.actions_len(), 0, "reused one-thread PipeSlot keeps zero ticket slots");
5903            // Exercise a multi-piece (> TASK_LEN) loan across the recycled slot.
5904            let big = vec![0xA5u8; 200_000];
5905            let m2 = block_on(p2.message(9, None));
5906            // Sound: `lent2` is held across `ready()` and dropped only after completion.
5907            let lent2 = unsafe { p2.lent(m2, &big) };
5908            block_on(p2.ready());
5909            drop(lent2);
5910            match p2.next_event() {
5911                Some(Event::Hashed { tag: 9, hash, .. }) => assert_eq!(hash.as_bytes(), blake3::hash(&big).as_bytes()),
5912                _ => panic!("expected Hashed event for multi-piece loan"),
5913            }
5914            return;
5915        }
5916        let exe = std::env::current_exe().unwrap();
5917        let out = std::process::Command::new(&exe)
5918            .env(ENV, "1")
5919            .args(["--exact", "pipeline::test::one_thread_pool_pipeline_allocates_zero_worker_tickets", "--nocapture"])
5920            .output()
5921            .unwrap();
5922        let stdout = std::string::String::from_utf8_lossy(&out.stdout);
5923        let stderr = std::string::String::from_utf8_lossy(&out.stderr);
5924        assert!(
5925            out.status.success() && stdout.contains("1 passed"),
5926            "one-thread ticket-capacity check failed: status={:?}\nstdout:\n{stdout}\nstderr:\n{stderr}",
5927            out.status
5928        );
5929    }
5930
5931    /// Pure aggregate deadline selector for
5932    /// [`forked_child_stops_in_acquire_free_group_and_alloc_piece_node`]:
5933    /// `-P mutants` and `-P mutants-map` always get 8 s (well below nextest's
5934    /// 15 s / 30 s mutants clocks even if `BLAKE3_EMULATED` is inherited),
5935    /// `-P emulated` or an active emulator (`BLAKE3_EMULATED` non-empty and
5936    /// non-zero, or Cargo's SDE/QEMU target runner) gets 30 s, and native runs
5937    /// get 8 s (#557, #591, #592).
5938    fn fork_wait_limit_secs(profile: Option<&std::ffi::OsStr>, emulated_env: Option<&std::ffi::OsStr>, runner_env: Option<&std::ffi::OsStr>) -> u64 {
5939        if profile.and_then(|p| p.to_str()).is_some_and(|p| p.starts_with("mutants")) {
5940            8
5941        } else if profile == Some(std::ffi::OsStr::new("emulated"))
5942            || emulated_env.is_some_and(|v| !v.is_empty() && v != "0")
5943            || runner_env.is_some_and(|v| {
5944                let s = v.to_string_lossy();
5945                let exe = s.split_whitespace().next().unwrap_or("");
5946                let name = std::path::Path::new(exe).file_name().and_then(|n| n.to_str()).unwrap_or("");
5947                matches!(name, "sde" | "sde64") || name.starts_with("qemu-")
5948            })
5949        {
5950            30
5951        } else {
5952            8
5953        }
5954    }
5955
5956    #[test]
5957    fn fork_wait_limit_secs_precedence_and_emulators() {
5958        use std::ffi::OsStr;
5959        let s = OsStr::new;
5960        // Native runs default to 8 s.
5961        assert_eq!(fork_wait_limit_secs(None, None, None), 8);
5962        assert_eq!(fork_wait_limit_secs(Some(s("default")), Some(s("")), None), 8);
5963        assert_eq!(fork_wait_limit_secs(Some(s("default")), Some(s("0")), Some(s("valgrind --tool=memcheck"))), 8);
5964        // Emulated profile, non-zero BLAKE3_EMULATED, or SDE/QEMU runner selects 30 s.
5965        assert_eq!(fork_wait_limit_secs(Some(s("emulated")), None, None), 30);
5966        assert_eq!(fork_wait_limit_secs(None, Some(s("1")), None), 30);
5967        assert_eq!(fork_wait_limit_secs(None, None, Some(s("/opt/intel/sde64 -spr --"))), 30);
5968        assert_eq!(fork_wait_limit_secs(None, None, Some(s("sde --"))), 30);
5969        assert_eq!(fork_wait_limit_secs(None, None, Some(s("/usr/bin/qemu-aarch64"))), 30);
5970        // Any `mutants*` profile always wins over inherited emulator variables.
5971        assert_eq!(fork_wait_limit_secs(Some(s("mutants")), Some(s("1")), Some(s("sde64 --"))), 8);
5972        assert_eq!(fork_wait_limit_secs(Some(s("mutants-map")), Some(s("1")), Some(s("qemu-aarch64"))), 8);
5973    }
5974
5975    /// Forked children entering `acquire_free_group` or `alloc_piece_node`
5976    /// while waiting on work must stop via `lanes::require()` instead of
5977    /// spinning forever (#465).
5978    #[test]
5979    fn forked_child_stops_in_acquire_free_group_and_alloc_piece_node() {
5980        const ENV: &str = "BLAKE3_PIPELINE_FORK_WAIT_CASE";
5981        if let Ok(which) = std::env::var(ENV) {
5982            // Exercise a real multi-worker pool (`threads == 2`) using the
5983            // calling-thread override so background workers stay unaffected and
5984            // `Pipeline::drop` runs cleanly after the guard drops.
5985            crate::initialize_multithreaded(core::num::NonZeroUsize::new(2));
5986            assert!(crate::lanes::pool_has_workers(), "expected a multi-worker pool for fork wait test");
5987            let mut p = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 2, rooms: 1 });
5988            // Mark every group / piece unavailable, then set the calling-thread
5989            // fork override in this normal un-forked subprocess (no UB from
5990            // calling allocator or unwinding after a multithreaded fork()).
5991            if which == "group" {
5992                for slot in &mut p.assigned_group_epoch {
5993                    *slot = u64::MAX;
5994                }
5995            } else {
5996                while p.free_pieces.pop_front().is_some() {}
5997            }
5998            let res = {
5999                let _fork_guard = crate::lanes::mark_forked_for_test();
6000                std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
6001                    if which == "group" {
6002                        let _ = p.acquire_free_group();
6003                    } else {
6004                        let _ = p.alloc_piece_node(0);
6005                    }
6006                }))
6007            };
6008            // Clear synthetic busy state before any assertion so `Drop` stays clean.
6009            for slot in &mut p.assigned_group_epoch {
6010                *slot = 0;
6011            }
6012            let fork_panic = match res {
6013                Err(payload) => {
6014                    let msg =
6015                        payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<std::string::String>().map(|s| s.as_str())).unwrap_or("");
6016                    msg.contains("fork")
6017                }
6018                Ok(()) => false,
6019            };
6020            assert!(fork_panic, "expected fork panic on {which}");
6021            return;
6022        }
6023        let exe = std::env::current_exe().unwrap();
6024        let tmp = crate::lanes::TempDir::new("fork-wait");
6025        let profile = std::env::var_os("NEXTEST_PROFILE");
6026        let emulated = std::env::var_os("BLAKE3_EMULATED");
6027        let runner_var = if cfg!(target_arch = "x86_64") {
6028            Some("CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER")
6029        } else if cfg!(target_arch = "aarch64") {
6030            Some("CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUNNER")
6031        } else {
6032            None
6033        };
6034        let runner = runner_var.and_then(std::env::var_os);
6035        let limit_secs = fork_wait_limit_secs(profile.as_deref(), emulated.as_deref(), runner.as_deref());
6036        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(limit_secs);
6037        for case in ["group", "piece"] {
6038            // Redirect stdout and stderr to exclusively created temporary files
6039            // inside a private 0o700 directory so verbose child output (e.g.
6040            // `LD_DEBUG=all`) cannot fill a 64 KiB pipe buffer and stall before
6041            // the parent stops calling `try_wait`.
6042            let (out_path, out_file) = tmp.create_exclusive(&std::format!("{case}.out"));
6043            let (err_path, err_file) = tmp.create_exclusive(&std::format!("{case}.err"));
6044            let mut child = std::process::Command::new(&exe)
6045                .env(ENV, case)
6046                .env("RUST_BACKTRACE", "0")
6047                .args(["--exact", "pipeline::test::forked_child_stops_in_acquire_free_group_and_alloc_piece_node", "--nocapture"])
6048                .stdout(std::process::Stdio::from(out_file))
6049                .stderr(std::process::Stdio::from(err_file))
6050                .spawn()
6051                .unwrap();
6052            let mut timed_out = false;
6053            let status = loop {
6054                if let Some(status) = child.try_wait().unwrap() {
6055                    break status;
6056                }
6057                if std::time::Instant::now() >= deadline {
6058                    timed_out = true;
6059                    let _ = child.kill();
6060                    break child.wait().unwrap();
6061                }
6062                std::thread::sleep(std::time::Duration::from_millis(5));
6063            };
6064            let stdout = std::fs::read_to_string(&out_path).unwrap_or_default();
6065            let stderr = std::fs::read_to_string(&err_path).unwrap_or_default();
6066            assert!(
6067                !timed_out,
6068                "fork wait exceeded aggregate {limit_secs} s parent deadline while waiting on case {case}\nstdout:\n{stdout}\nstderr:\n{stderr}"
6069            );
6070            assert!(status.success() && stdout.contains("1 passed"), "fork wait case {case} failed: status={status:?}\nstdout:\n{stdout}\nstderr:\n{stderr}");
6071        }
6072    }
6073
6074    #[cfg(not(shuttle))]
6075    #[test]
6076    fn batch_plans_and_non_batch_dispatch_locality_contract() {
6077        let pinned_two_places = crate::lanes::places::test::init_two_places_and_pin();
6078        let mut pipe = Pipeline::<u32, Vec<u8>>::with_owners(Mode::Plain, Limits { messages: 4, rooms: 2 });
6079        let drain_one = |pipe: &mut Pipeline<u32, Vec<u8>>| loop {
6080            if let Some(ev) = pipe.next_event() {
6081                return ev;
6082            }
6083            block_on(pipe.ready());
6084        };
6085        let expect_registered = crate::lanes::pool_has_workers();
6086        assert_eq!(pipe.source_slot.is_some(), expect_registered, "single Pipeline in a fresh process must register a source slot iff pool has workers");
6087        let is_registered = expect_registered;
6088
6089        // Split batch (>= TASK_LEN = 64 KiB) records a BatchPlan when
6090        // registered, tracks real depths (1, 2) across interleaved short/empty
6091        // batches, publishes the plan's near hint on every ticket (both 1-ticket
6092        // and multi-ticket ranges), retires plans and decrements
6093        // batches_in_flight only on plan-bearing reaps ([1, 1, 1, 0]), and
6094        // produces exact digests for every distinct message.
6095        let one_ticket_count = TASK_LEN / 64; // 1,024 x 64 B = 64 KiB (1 ticket)
6096        let multi_ticket_count = (2 * TASK_LEN) / 64; // 2,048 x 64 B = 128 KiB (2+ tickets)
6097        let make_batch = |count: usize, seed: u8| {
6098            let mut b = Batch::new(64, count);
6099            for i in 0..count {
6100                let m = b.message_mut(i);
6101                let byte = seed.wrapping_add(i as u8);
6102                m.fill(byte);
6103                m[1] = (i >> 8) as u8;
6104            }
6105            b
6106        };
6107        let pub_before_m1 = pipe.storage().slot.get().source.published_count();
6108        let m1 = block_on(pipe.message(10, None));
6109        let s1 = m1.slot as usize;
6110        pipe.batch(m1, make_batch(one_ticket_count, 0), vec![[0u8; OUT_LEN]; one_ticket_count].into_boxed_slice());
6111        let d1 = pipe.bufs.batch_plans[s1].as_ref().map(|p| p.in_flight);
6112        let p1_near = pipe.bufs.batch_plans[s1].as_ref().map(|p| p.near());
6113        let m1_nears = pipe.storage().slot.get().source.published_nears(pub_before_m1);
6114        let m_short_b = block_on(pipe.message(11, None));
6115        let s_short = m_short_b.slot as usize;
6116        pipe.batch(m_short_b, make_batch(4, 3), vec![[0u8; OUT_LEN]; 4].into_boxed_slice());
6117        let m_empty_b = block_on(pipe.message(12, None));
6118        let s_empty = m_empty_b.slot as usize;
6119        pipe.batch(m_empty_b, Batch::new(64, 0), Box::new([]));
6120        let pub_before_m2 = pipe.storage().slot.get().source.published_count();
6121        let m2 = block_on(pipe.message(13, None));
6122        let s2 = m2.slot as usize;
6123        pipe.batch(m2, make_batch(multi_ticket_count, 7), vec![[0u8; OUT_LEN]; multi_ticket_count].into_boxed_slice());
6124        let d2 = pipe.bufs.batch_plans[s2].as_ref().map(|p| p.in_flight);
6125        let p2_near = pipe.bufs.batch_plans[s2].as_ref().map(|p| p.near());
6126        let m2_nears = pipe.storage().slot.get().source.published_nears(pub_before_m2);
6127        let recorded_in_flight = pipe.batches_in_flight;
6128        assert!(pipe.bufs.batch_plans[s_short].is_none());
6129        assert!(pipe.bufs.batch_plans[s_empty].is_none());
6130        if is_registered {
6131            assert_eq!(d1, Some(1), "first registered split batch must carry depth 1");
6132            assert_eq!(m1_nears, vec![p1_near.unwrap()], "1024 x 64 B split batch must publish one ticket matching plan");
6133            assert_eq!(d2, Some(2), "second registered split batch before reap must carry depth 2");
6134            assert!(m2_nears.len() >= 2, "2048 x 64 B split batch must publish multiple tickets");
6135            assert!(m2_nears.iter().all(|&n| Some(n) == p2_near), "every published split-batch ticket (head..tail) must match plan");
6136            assert_eq!(recorded_in_flight, 2);
6137        } else {
6138            assert_eq!(recorded_in_flight, 0);
6139        }
6140        // Flush the short batch's open group and reap strictly one event at a
6141        // time via try_reap_one() (without reap_all batching) to verify the
6142        // exact [1, 1, 1, 0] batches_in_flight progression and per-slot plan retirement.
6143        pipe.publish_open();
6144        let expected_after_reap: &[(u32, usize, u8, u32, bool)] =
6145            &[(10, one_ticket_count, 0, 1, true), (11, 4, 3, 1, true), (12, 0, 0, 1, true), (13, multi_ticket_count, 7, 0, false)];
6146        for &(expected_tag, expected_count, seed, want_in_flight, s2_plan_live) in expected_after_reap {
6147            let ev = loop {
6148                if let Some(ev) = pipe.try_reap_one() {
6149                    break ev;
6150                }
6151                if !pipe.storage().slot.get().source.run_waiting_action() {
6152                    std::thread::yield_now();
6153                }
6154            };
6155            let Event::Batch { tag, batch, digests } = ev else { panic!("expected Batch event") };
6156            assert_eq!(tag, expected_tag);
6157            assert_eq!(batch.len(), expected_count, "returned batch count for tag {tag}");
6158            assert_eq!(digests.len(), expected_count, "returned digest count for tag {tag}");
6159            let want_batch = make_batch(expected_count, seed);
6160            assert_eq!(batch.bytes(), want_batch.bytes(), "returned batch input bytes must match seed for tag {tag}");
6161            for (idx, digest) in digests.iter().enumerate() {
6162                assert_eq!(*digest, *blake3::hash(&want_batch.bytes()[idx * 64..(idx + 1) * 64]).as_bytes());
6163            }
6164            if is_registered {
6165                assert_eq!(pipe.batches_in_flight, want_in_flight, "batches_in_flight after reaping tag {tag}");
6166                assert!(pipe.bufs.batch_plans[s1].is_none(), "slot s1 plan must retire after tag 10");
6167                assert_eq!(pipe.bufs.batch_plans[s2].is_some(), s2_plan_live, "slot s2 plan state after reaping tag {tag}");
6168            }
6169        }
6170        assert_eq!(pipe.batches_in_flight, 0);
6171        assert!(pipe.bufs.batch_plans.iter().all(Option::is_none), "all batch plans must retire after drain");
6172
6173        // With a deterministic two-place topology and the caller pinned to a
6174        // staffed place, verify (1) a 128 KiB split batch advances ONLY the
6175        // `PlaceKind::PipelineBatch` row at its expected size class in the TLS
6176        // learner table, and (2) ten trials of BOTH 1-ticket (1,024 x 64 B) and
6177        // multi-ticket (2,048 x 64 B) split batches publish Near on every ticket.
6178        if is_registered && pinned_two_places {
6179            let want_kind = PlaceKind::PipelineBatch as usize;
6180            let want_class = crate::lanes::places::test::size_class(multi_ticket_count * 64);
6181            let jobs_before = crate::lanes::places::test::learned_jobs();
6182            let m_row = block_on(pipe.message(19, None));
6183            pipe.batch(m_row, make_batch(multi_ticket_count, 9), vec![[0u8; OUT_LEN]; multi_ticket_count].into_boxed_slice());
6184            let _ = drain_one(&mut pipe);
6185            let jobs_after = crate::lanes::places::test::learned_jobs();
6186            for k in 0..jobs_before.len() {
6187                for c in 0..jobs_before[k].len() {
6188                    if k == want_kind && c == want_class {
6189                        assert_eq!(jobs_after[k][c], jobs_before[k][c] + 1, "PipelineBatch learner cell ({k},{c}) must advance by 1");
6190                    } else {
6191                        assert_eq!(jobs_after[k][c], jobs_before[k][c], "non-target learner cell ({k},{c}) must not advance");
6192                    }
6193                }
6194            }
6195
6196            for (label, count, want_multi) in [("one-ticket", one_ticket_count, false), ("multi-ticket", multi_ticket_count, true)] {
6197                let mut saw_near = false;
6198                for i in 0..10u32 {
6199                    let before = pipe.storage().slot.get().source.published_count();
6200                    let m = block_on(pipe.message(20 + i + if want_multi { 100 } else { 0 }, None));
6201                    let s = m.slot as usize;
6202                    pipe.batch(m, make_batch(count, i as u8), vec![[0u8; OUT_LEN]; count].into_boxed_slice());
6203                    let want_near = pipe.bufs.batch_plans[s].as_ref().expect("registered split plan").near();
6204                    let nears = pipe.storage().slot.get().source.published_nears(before);
6205                    if want_multi {
6206                        assert!(nears.len() >= 2, "{label} trial {i} must publish >= 2 tickets");
6207                    } else {
6208                        assert_eq!(nears.len(), 1, "{label} trial {i} must publish exactly 1 ticket");
6209                    }
6210                    assert!(nears.iter().all(|&n| n == want_near), "every published ticket on {label} trial {i} must match plan.near()");
6211                    saw_near |= want_near;
6212                    let _ = drain_one(&mut pipe);
6213                }
6214                assert!(saw_near, "ten {label} split-batch trials on a pinned staffed place must publish Near");
6215            }
6216        }
6217
6218        // Short group (KIND_GROUP), full room piece (KIND_ROOM_PIECE), and
6219        // split non-batch owned message (128 KiB) never set batch_plans and
6220        // never mark their queued actions near.
6221        let before = pipe.storage().slot.get().source.published_count();
6222        let mut m_short = block_on(pipe.message(2, Some(64)));
6223        let mut room = block_on(pipe.room());
6224        room.bytes_mut()[..64].fill(0x33);
6225        pipe.commit(&mut m_short, &mut room, 64);
6226        drop(room);
6227        pipe.end(m_short);
6228        pipe.publish_open();
6229        let short_nears = pipe.storage().slot.get().source.published_nears(before);
6230        let _ = drain_one(&mut pipe);
6231        if is_registered {
6232            assert_eq!(short_nears, vec![false]);
6233        }
6234        assert_eq!(pipe.batches_in_flight, 0);
6235
6236        let before = pipe.storage().slot.get().source.published_count();
6237        let mut m_room = block_on(pipe.message(3, Some((ROOM_LEN * 2) as u64)));
6238        let mut r1 = block_on(pipe.room());
6239        r1.bytes_mut().fill(0x44);
6240        pipe.commit(&mut m_room, &mut r1, ROOM_LEN);
6241        drop(r1);
6242        let room_nears = pipe.storage().slot.get().source.published_nears(before);
6243        let mut r2 = block_on(pipe.room());
6244        r2.bytes_mut().fill(0x55);
6245        pipe.commit(&mut m_room, &mut r2, ROOM_LEN);
6246        drop(r2);
6247        pipe.end(m_room);
6248        let _ = drain_one(&mut pipe);
6249        if is_registered {
6250            assert_eq!(room_nears, vec![false]);
6251        }
6252        assert_eq!(pipe.batches_in_flight, 0);
6253
6254        let before = pipe.storage().slot.get().source.published_count();
6255        let m_owned = block_on(pipe.message(4, Some((TASK_LEN * 2) as u64)));
6256        pipe.owned(m_owned, vec![0x66u8; TASK_LEN * 2]);
6257        let owned_nears = pipe.storage().slot.get().source.published_nears(before);
6258        let _ = drain_one(&mut pipe);
6259        if is_registered {
6260            assert!(owned_nears.len() >= 2 && owned_nears.iter().all(|&n| !n));
6261        }
6262        assert_eq!(pipe.batches_in_flight, 0);
6263    }
6264
6265    #[test]
6266    fn custom_mode_reuse_across_groups_and_pipelines_leaves_default_clean() {
6267        crate::initialize_multithreaded(core::num::NonZeroUsize::new(2));
6268        let key = [0x42u8; 32];
6269        let limits = Limits { messages: 8, rooms: 4 };
6270        let short_data = [0x19u8; 128];
6271        let long_data = vec![0x7Au8; TASK_LEN * 2 + 17];
6272        let want_plain_short = blake3::hash(&short_data);
6273        let want_keyed_short = blake3::keyed_hash(&key, &short_data);
6274        let want_plain_long = blake3::hash(&long_data);
6275        let want_keyed_long = blake3::keyed_hash(&key, &long_data);
6276
6277        let mut p1 = Pipeline::<u32, Vec<u8>>::with_owners(Mode::Plain, limits);
6278        let m_ab = block_on(p1.message_with(Mode::Plain, 0, Some(64)));
6279        p1.abort(m_ab);
6280        let Event::Aborted { .. } = drain_all(&mut p1, 1).pop().unwrap() else { panic!("expected Aborted") };
6281
6282        // Full lap of `group_count` keyed shorts followed by `group_count`
6283        // default shorts ensures every physical group transitions custom -> default live.
6284        let groups = p1.group_count;
6285        for r in 0..groups {
6286            let e_before = p1.next_group_epoch;
6287            let m_custom = block_on(p1.message_with(Mode::Keyed(&key), r as u32, Some(short_data.len() as u64)));
6288            p1.owned(m_custom, short_data.to_vec());
6289            assert!(p1.open_group.is_none(), "custom short message must publish immediately");
6290            assert_eq!(p1.next_group_epoch, e_before + 1, "custom short message must dispatch a group");
6291            let Event::Hashed { hash, .. } = drain_all(&mut p1, 1).pop().unwrap() else { panic!("expected Hashed") };
6292            assert_eq!(hash.as_bytes(), want_keyed_short.as_bytes(), "custom short group lap {r}");
6293        }
6294        for r in 0..groups {
6295            let m_plain = block_on(p1.message(100 + r as u32, Some(short_data.len() as u64)));
6296            p1.owned(m_plain, short_data.to_vec());
6297            let Event::Hashed { hash, .. } = drain_all(&mut p1, 1).pop().unwrap() else { panic!("expected Hashed") };
6298            assert_eq!(hash.as_bytes(), want_plain_short.as_bytes(), "plain short after custom group lap {r}");
6299        }
6300        // Keyed-default pipeline: slot 0 explicit Plain -> drain -> cycle slot 1 ->
6301        // submit default slot 0 + explicit Plain slot 1 before draining (catches
6302        // stale owner slot provenance); also verify two explicit Plain shorts share one group.
6303        {
6304            let mut pk = Pipeline::<u32, Vec<u8>>::with_owners(Mode::Keyed(&key), Limits { messages: 2, rooms: 0 });
6305            let m0 = block_on(pk.message_with(Mode::Plain, 1, Some(64)));
6306            pk.owned(m0, short_data.to_vec());
6307            let Event::Hashed { hash, .. } = drain_all(&mut pk, 1).pop().unwrap() else { panic!("expected Hashed") };
6308            assert_eq!(hash.as_bytes(), want_plain_short.as_bytes());
6309            let m1 = block_on(pk.message(2, Some(64)));
6310            pk.abort(m1);
6311            let _ = drain_all(&mut pk, 1);
6312
6313            let m_def = block_on(pk.message(3, Some(64)));
6314            let m_exp = block_on(pk.message_with(Mode::Plain, 4, Some(64)));
6315            pk.owned(m_def, short_data.to_vec());
6316            pk.owned(m_exp, short_data.to_vec());
6317            let evs = drain_all(&mut pk, 2);
6318            let Event::Hashed { tag: 3, hash: h_def, .. } = &evs[0] else { panic!("expected default tag 3") };
6319            let Event::Hashed { tag: 4, hash: h_exp, .. } = &evs[1] else { panic!("expected plain tag 4") };
6320            assert_eq!(h_def.as_bytes(), want_keyed_short.as_bytes(), "reused slot 0 default must stay keyed");
6321            assert_eq!(h_exp.as_bytes(), want_plain_short.as_bytes(), "slot 1 explicit Plain must stay plain");
6322
6323            // Two consecutive explicit Plain shorts share one group (one epoch advance).
6324            let e0 = pk.next_group_epoch;
6325            let p_a = block_on(pk.message_with(Mode::Plain, 5, Some(64)));
6326            let p_b = block_on(pk.message_with(Mode::Plain, 6, Some(64)));
6327            pk.owned(p_a, short_data.to_vec());
6328            pk.owned(p_b, short_data.to_vec());
6329            assert_eq!(pk.next_group_epoch, e0 + 1, "two explicit Plain shorts must share one group");
6330            for ev in drain_all(&mut pk, 2) {
6331                let Event::Hashed { hash, .. } = ev else { panic!("expected Hashed") };
6332                assert_eq!(hash.as_bytes(), want_plain_short.as_bytes());
6333            }
6334
6335            // Open-group transition (`Plain -> Default`) on a 4-slot
6336            // keyed-default pipeline: keep both explicit Plain messages active
6337            // while pushing two consecutive Default (Keyed) shorts so
6338            // `push_member` flushes the incompatible Plain group and coalesces
6339            // the two Default shorts into one group (distinct from physical
6340            // slot reuse checked in the 2-slot case above).
6341            let mut pk4 = Pipeline::<u32, Vec<u8>>::with_owners(Mode::Keyed(&key), Limits { messages: 4, rooms: 2 });
6342            let e4 = pk4.next_group_epoch;
6343            let pa4 = block_on(pk4.message_with(Mode::Plain, 15, Some(64)));
6344            let pb4 = block_on(pk4.message_with(Mode::Plain, 16, Some(64)));
6345            let da4 = block_on(pk4.message(17, Some(64)));
6346            let db4 = block_on(pk4.message(18, Some(64)));
6347            pk4.owned(pa4, short_data.to_vec());
6348            pk4.owned(pb4, short_data.to_vec());
6349            assert_eq!(pk4.next_group_epoch, e4 + 1, "two explicit Plain shorts must share one group");
6350            assert!(pk4.open_group.is_some(), "Plain group must still be open before Default push");
6351            assert_ne!(pk4.local_custom_slot, NONE, "open Plain group must hold override representative");
6352            pk4.owned(da4, short_data.to_vec());
6353            assert_eq!(pk4.next_group_epoch, e4 + 2, "Default short after open Plain group must flush Plain and open Default group");
6354            assert!(pk4.open_group.is_some(), "Default group must remain open after first Default short");
6355            assert_eq!(pk4.local_custom_slot, NONE, "open Default group must hold NONE representative");
6356            pk4.owned(db4, short_data.to_vec());
6357            assert_eq!(pk4.next_group_epoch, e4 + 2, "second Default short must coalesce into open Default group");
6358            let events = drain_all(&mut pk4, 4);
6359            for (idx, ev) in events.into_iter().enumerate() {
6360                let Event::Hashed { hash, .. } = ev else { panic!("expected Hashed") };
6361                let want = if idx < 2 { &want_plain_short } else { &want_keyed_short };
6362                assert_eq!(hash.as_bytes(), want.as_bytes(), "4-slot Plain->Default event {idx}");
6363            }
6364        }
6365
6366        // Exercise custom multi-piece path on every slot, then reuse every slot
6367        // with default-mode multi-piece messages inside the same pipeline.
6368        for i in 0..limits.messages {
6369            let m_long_custom = block_on(p1.message_with(Mode::Keyed(&key), 900 + i as u32, Some(long_data.len() as u64)));
6370            p1.owned(m_long_custom, long_data.clone());
6371            let Event::Hashed { hash, .. } = drain_all(&mut p1, 1).pop().unwrap() else { panic!("expected Hashed") };
6372            assert_eq!(hash.as_bytes(), want_keyed_long.as_bytes(), "custom long slot {i}");
6373        }
6374        for i in 0..limits.messages {
6375            let m_long_plain = block_on(p1.message(950 + i as u32, Some(long_data.len() as u64)));
6376            p1.owned(m_long_plain, long_data.clone());
6377            let Event::Hashed { hash, .. } = drain_all(&mut p1, 1).pop().unwrap() else { panic!("expected Hashed") };
6378            assert_eq!(hash.as_bytes(), want_plain_long.as_bytes(), "reused slot plain long {i}");
6379        }
6380        // Leave an open override aborted before drop (unreaped); reusing
6381        // PipeSlot on a fresh Pipeline must leave default messages untouched by
6382        // prior override trees because actions carry their own override bits.
6383        let m_drop = block_on(p1.message_with(Mode::Keyed(&key), 999, Some(64)));
6384        p1.abort(m_drop);
6385        let slot_ptr: *const PipeSlot = p1.pipe_slot;
6386        drop(p1);
6387
6388        let mut p2 = Pipeline::<u32, Vec<u8>>::with_owners(Mode::Plain, limits);
6389        assert!(core::ptr::eq(p2.pipe_slot, slot_ptr), "expected reused PipeSlot");
6390        for i in 0..limits.messages * 2 {
6391            let m = block_on(p2.message(i as u32, Some(short_data.len() as u64)));
6392            p2.owned(m, short_data.to_vec());
6393            let Event::Hashed { hash, .. } = drain_all(&mut p2, 1).pop().unwrap() else { panic!("expected Hashed") };
6394            assert_eq!(hash.as_bytes(), want_plain_short.as_bytes(), "reused pipeline short {i}");
6395        }
6396        for i in 0..limits.messages {
6397            let m = block_on(p2.message(100 + i as u32, Some(long_data.len() as u64)));
6398            p2.owned(m, long_data.clone());
6399            let Event::Hashed { hash, .. } = drain_all(&mut p2, 1).pop().unwrap() else { panic!("expected Hashed") };
6400            assert_eq!(hash.as_bytes(), want_plain_long.as_bytes(), "reused pipeline long {i}");
6401        }
6402    }
6403
6404    #[test]
6405    fn room_future_polled_after_completion_panics_on_fast_and_slow_paths() {
6406        crate::initialize_multithreaded(core::num::NonZeroUsize::new(1));
6407        let mut pipe = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 2, rooms: 2 });
6408        let waker = core::task::Waker::noop();
6409        let mut cx = Context::from_waker(waker);
6410
6411        // 1. Fast path (`pop_cached_room`): poll to Ready, then verify repoll
6412        // panics without taking the second free room.
6413        let r0 = {
6414            let mut fut = core::pin::pin!(pipe.room());
6415            let Poll::Ready(r) = fut.as_mut().poll(&mut cx) else { panic!("cached room ready immediately") };
6416            let err = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
6417                let _ = fut.as_mut().poll(&mut cx);
6418            }));
6419            assert!(err.is_err(), "repolling completed fast-path RoomFut must panic");
6420            r
6421        };
6422        assert_eq!(pipe.local_free_rooms.len, 1, "repoll must not lease a second room");
6423
6424        // 2. Slow path (`poll_room` -> Pending -> Ready): exhaust both rooms,
6425        // poll once to Pending, drop `r0`, poll to Ready, then verify repoll panics.
6426        let r1 = block_on(pipe.room());
6427        let r_slow = {
6428            let mut fut = core::pin::pin!(pipe.room());
6429            assert!(fut.as_mut().poll(&mut cx).is_pending(), "all rooms held: slow path returns Pending");
6430            drop(r0);
6431            let Poll::Ready(r) = fut.as_mut().poll(&mut cx) else { panic!("released room ready on slow path") };
6432            let err = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
6433                let _ = fut.as_mut().poll(&mut cx);
6434            }));
6435            assert!(err.is_err(), "repolling completed slow-path RoomFut must panic");
6436            r
6437        };
6438        drop(r_slow);
6439        drop(r1);
6440    }
6441
6442    #[test]
6443    fn piece_slots_tracks_active_multi_room_slots_in_o1_and_reclaims_in_alloc_piece_node() {
6444        crate::initialize_multithreaded(core::num::NonZeroUsize::new(1));
6445        // 0. Zero-room pipelines reserve no piece_slots capacity (#465).
6446        let zero_rooms = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 8, rooms: 0 });
6447        assert_eq!(zero_rooms.piece_slots.capacity(), 0);
6448        drop(zero_rooms);
6449
6450        // 1. Verify O(1) push and swap-remove position updates on sparse,
6451        // non-zero slot IDs [2, 4, 6] (with non-room placeholders occupying
6452        // slots 0, 1, 3, 5), exercising middle-slot abort and head/tail ends
6453        // without leaving stale indices or reallocating.
6454        let mut pipe = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 8, rooms: 4 });
6455        let initial_cap = pipe.piece_slots.capacity();
6456        assert_eq!(initial_cap, 8);
6457        assert!(pipe.piece_slots.is_empty());
6458        let pad0 = block_on(pipe.message(100, None));
6459        let pad1 = block_on(pipe.message(101, None));
6460        let mut m2 = block_on(pipe.message(2, None));
6461        let pad3 = block_on(pipe.message(103, None));
6462        let mut m4 = block_on(pipe.message(4, None));
6463        let pad5 = block_on(pipe.message(105, None));
6464        let mut m6 = block_on(pipe.message(6, None));
6465        assert_eq!([m2.slot, m4.slot, m6.slot], [2, 4, 6]);
6466        let mut d2 = Vec::new();
6467        let mut d6 = Vec::new();
6468        for (m, fill, buf) in [(&mut m2, 0x22u8, Some(&mut d2)), (&mut m4, 0x44u8, None), (&mut m6, 0x66u8, Some(&mut d6))] {
6469            let mut r = block_on(pipe.room());
6470            r.bytes_mut().fill(fill);
6471            if let Some(out) = buf {
6472                out.extend_from_slice(r.bytes_mut());
6473            }
6474            pipe.commit(m, &mut r, ROOM_LEN);
6475            drop(r);
6476        }
6477        assert_eq!(pipe.piece_slots, [2, 4, 6]);
6478        assert_eq!([pipe.room_streams[2].piece_slot_pos, pipe.room_streams[4].piece_slot_pos, pipe.room_streams[6].piece_slot_pos], [0, 1, 2]);
6479        for empty_slot in [0usize, 1, 3, 5, 7] {
6480            assert_eq!(pipe.room_streams[empty_slot].piece_slot_pos, NONE);
6481        }
6482        assert_eq!(pipe.piece_slots.capacity(), initial_cap, "piece_slots must not reallocate");
6483
6484        // Abort the middle active slot (slot 4 at index 1): swap_remove moves
6485        // slot 6 into index 1 and updates slot 6's piece_slot_pos to 1.
6486        pipe.abort(m4);
6487        assert_eq!(pipe.piece_slots, [2, 6]);
6488        assert_eq!(pipe.room_streams[4].piece_slot_pos, NONE);
6489        assert_eq!(pipe.room_streams[2].piece_slot_pos, 0);
6490        assert_eq!(pipe.room_streams[6].piece_slot_pos, 1);
6491
6492        // End slot 2 (index 0): swap_remove moves slot 6 into index 0.
6493        pipe.end(m2);
6494        let (tag2, hash2) = loop {
6495            if let Some(Event::Hashed { tag, hash, .. }) = pipe.next_event() {
6496                break (tag, hash);
6497            }
6498            block_on(pipe.ready());
6499        };
6500        assert_eq!((tag2, *hash2.as_bytes()), (2, *blake3::hash(&d2).as_bytes()));
6501        assert_eq!(pipe.piece_slots, [6]);
6502        assert_eq!(pipe.room_streams[2].piece_slot_pos, NONE);
6503        assert_eq!(pipe.room_streams[6].piece_slot_pos, 0);
6504
6505        // End slot 6 last: piece_slots returns empty.
6506        pipe.end(m6);
6507        let (tag6, hash6) = loop {
6508            if let Some(Event::Hashed { tag, hash, .. }) = pipe.next_event() {
6509                break (tag, hash);
6510            }
6511            block_on(pipe.ready());
6512        };
6513        assert_eq!((tag6, *hash6.as_bytes()), (6, *blake3::hash(&d6).as_bytes()));
6514        assert!(pipe.piece_slots.is_empty());
6515        assert_eq!(pipe.room_streams[6].piece_slot_pos, NONE);
6516        for pad in [pad0, pad1, pad3, pad5] {
6517            pipe.abort(pad);
6518        }
6519
6520        // 2. Exhaust `free_pieces` while sparse slot 5 holds finished foldable
6521        // pieces on a 64-message pipeline, and slot 1 also holds a finished
6522        // foldable stream temporarily detached from `piece_slots`: `alloc_piece_node`
6523        // must scan only `piece_slots` (reclaiming slot 5 without touching slot 1,
6524        // catching both a revert to a full 0..m scan and an `idx` vs `piece_slots[idx]`
6525        // mix-up), then produce official `blake3::hash` digests for every message.
6526        let mut p2 = Pipeline::<u32>::new(Mode::Plain, Limits { messages: 64, rooms: 2 });
6527        let pad0 = block_on(p2.message(200, None));
6528        let mut m_untracked = block_on(p2.message(30, None));
6529        let pads_mid: Vec<_> = (2..5).map(|i| block_on(p2.message(200 + i, None))).collect();
6530        let mut m_a = block_on(p2.message(10, None));
6531        let pad6 = block_on(p2.message(206, None));
6532        let mut m_b = block_on(p2.message(20, None));
6533        assert_eq!((m_untracked.slot, m_a.slot, m_b.slot), (1, 5, 7));
6534
6535        let mut data_u = Vec::new();
6536        let mut ru0 = block_on(p2.room());
6537        ru0.bytes_mut().fill(0x30);
6538        data_u.extend_from_slice(ru0.bytes_mut());
6539        p2.commit(&mut m_untracked, &mut ru0, ROOM_LEN);
6540        drop(ru0);
6541        let pu0 = p2.room_streams[1].head_piece as usize;
6542        p2.storage().pieces[pu0].done.store(false, Ordering::SeqCst);
6543        let mut ru1 = block_on(p2.room());
6544        ru1.bytes_mut().fill(0x31);
6545        data_u.extend_from_slice(ru1.bytes_mut());
6546        p2.commit(&mut m_untracked, &mut ru1, ROOM_LEN);
6547        drop(ru1);
6548        assert_ne!(p2.room_streams[1].head_piece, p2.room_streams[1].tail_piece, "slot 1 holds two pieces");
6549        p2.storage().pieces[pu0].done.store(true, Ordering::SeqCst);
6550
6551        let mut data_a = Vec::new();
6552        // Commit 2 full rooms to `m_a` (slot 5), keeping piece 0's `done` bit
6553        // clear across the second commit (matching the multi-worker case where
6554        // a worker is still hashing piece 0 when piece 1 is submitted), then
6555        // mark piece 0 done so slot 5 holds two finished pieces (`head != tail`).
6556        let mut r0 = block_on(p2.room());
6557        r0.bytes_mut().fill(0x10);
6558        data_a.extend_from_slice(r0.bytes_mut());
6559        p2.commit(&mut m_a, &mut r0, ROOM_LEN);
6560        drop(r0);
6561        let p0 = p2.room_streams[5].head_piece as usize;
6562        p2.storage().pieces[p0].done.store(false, Ordering::SeqCst);
6563
6564        let mut r1 = block_on(p2.room());
6565        r1.bytes_mut().fill(0x11);
6566        data_a.extend_from_slice(r1.bytes_mut());
6567        p2.commit(&mut m_a, &mut r1, ROOM_LEN);
6568        drop(r1);
6569        assert_ne!(p2.room_streams[5].head_piece, p2.room_streams[5].tail_piece, "m_a holds two pieces");
6570        p2.storage().pieces[p0].done.store(true, Ordering::SeqCst);
6571
6572        // Temporarily detach slot 1 from `piece_slots` (leaving only [5]) and
6573        // park all remaining free piece nodes so `m_b`'s commit forces
6574        // `alloc_piece_node` to reclaim strictly through `piece_slots`.
6575        assert_eq!(p2.piece_slots, [1, 5]);
6576        p2.piece_slots.swap_remove(0);
6577        p2.room_streams[5].piece_slot_pos = 0;
6578        p2.room_streams[1].piece_slot_pos = NONE;
6579        let mut parked_nodes = Vec::new();
6580        while let Some(node) = p2.free_pieces.pop_front() {
6581            parked_nodes.push(node);
6582        }
6583        assert!(p2.free_pieces.is_empty());
6584        assert_eq!(p2.piece_slots, [5]);
6585
6586        let mut data_b = Vec::new();
6587        let mut r = block_on(p2.room());
6588        r.bytes_mut().fill(0x77);
6589        data_b.extend_from_slice(r.bytes_mut());
6590        p2.commit(&mut m_b, &mut r, ROOM_LEN);
6591        drop(r);
6592        assert_ne!(p2.room_streams[1].head_piece, p2.room_streams[1].tail_piece, "untracked lower slot 1 must not be scanned");
6593        assert_eq!(p2.room_streams[5].head_piece, p2.room_streams[5].tail_piece, "tracked sparse slot 5 piece p0 reclaimed");
6594        assert_eq!(p2.piece_slots, [5, 7]);
6595        assert_eq!([p2.room_streams[5].piece_slot_pos, p2.room_streams[7].piece_slot_pos], [0, 1]);
6596
6597        // Re-attach slot 1 to `piece_slots` before finishing all messages.
6598        p2.room_streams[1].piece_slot_pos = 2;
6599        p2.piece_slots.push(1);
6600        for node in parked_nodes {
6601            p2.free_pieces.push_back(node);
6602        }
6603        p2.end(m_untracked);
6604        p2.end(m_a);
6605        p2.end(m_b);
6606        let mut got = Vec::new();
6607        while got.len() < 3 {
6608            if let Some(Event::Hashed { tag, hash, .. }) = p2.next_event() {
6609                got.push((tag, *hash.as_bytes()));
6610            } else {
6611                block_on(p2.ready());
6612            }
6613        }
6614        assert_eq!(got, [(30, *blake3::hash(&data_u).as_bytes()), (10, *blake3::hash(&data_a).as_bytes()), (20, *blake3::hash(&data_b).as_bytes())]);
6615        assert!(p2.piece_slots.is_empty());
6616        p2.abort(pad0);
6617        for pad in pads_mid {
6618            p2.abort(pad);
6619        }
6620        p2.abort(pad6);
6621    }
6622}