1use 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;
26use crate::pipeline_sync::{AtomicBool, AtomicU64, AtomicUsize, Mutex, Ordering, UnsafeCell, process_static, thread};
30use core::task::{Context, Poll, Waker};
31use std::sync::Arc;
32
33pub const ROOM_LEN: usize = 64 * 1024;
39const ROOM_LEVEL: u32 = level_of(ROOM_LEN as u64);
40
41const SME2_MIN_LEN: usize = 16 * CHUNK_LEN;
43
44const MAX_SLOT_PIECES: usize = 64;
46
47const ROOM_CREDITS: usize = 1 << 30;
51const ROOM_CLOSING_BIT: usize = 1usize << (usize::BITS - 1);
57
58const NONE: u32 = u32::MAX;
59
60const MULTI_CUSTOM_BIT: u32 = 1u32 << 31;
63
64struct 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
114struct EventRing<X>(std::collections::VecDeque<X>);
118
119impl<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 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
157struct RawSlots<T> {
163 ptr: *mut UnsafeCell<MaybeUninit<T>>,
164 len: usize,
165}
166
167unsafe 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 unsafe { (*self.ptr.add(index)).get() }
182 }
183}
184
185impl<T> Drop for RawSlots<T> {
186 fn drop(&mut self) {
187 unsafe {
191 drop(Box::from_raw(core::ptr::slice_from_raw_parts_mut(self.ptr, self.len)));
192 }
193 }
194}
195
196#[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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
253pub struct Limits {
254 pub messages: usize,
257 pub rooms: usize,
259}
260
261pub 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#[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#[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#[cold]
339#[inline(never)]
340fn stop_process(why: &str) -> ! {
341 crate::lanes::stop(why)
342}
343
344use crate::waker::WakerSlot;
345
346#[repr(align(128))]
349struct Rooms {
350 buf: *mut u8,
354 backing: *mut [u8],
360 count: usize,
361 refs: Box<[AtomicUsize]>,
362}
363
364unsafe impl Send for Rooms {}
369unsafe impl Sync for Rooms {}
375
376impl Drop for Rooms {
377 fn drop(&mut self) {
378 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 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 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
422struct PipeSlot {
441 source: Source,
442 waker: WakerSlot,
443 group_completed: Box<[OwnLine<AtomicU64>]>,
446 loan_completed: Box<[OwnLine<AtomicU64>]>,
449}
450
451struct FreeSlot {
455 slot: &'static PipeSlot,
456 next_group_epoch: u64,
457 next_loan_epoch: u64,
458}
459
460const MIN_SLOT_SHIFT: u32 = 10; const SLOT_TIERS: usize = 28; #[inline]
464fn slot_tier(cap: usize) -> usize {
465 (cap.trailing_zeros() - MIN_SLOT_SHIFT) as usize
466}
467
468process_static! {
469 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 static PIPE_SLOTS_MADE: AtomicUsize = AtomicUsize::new(0);
479}
480
481#[cfg(any(test, shuttle))]
482process_static! {
483 static LIVE_STORAGES: AtomicUsize = AtomicUsize::new(0);
485}
486
487#[cfg(shuttle)]
488struct OwnedPipeSlotPtr(*mut PipeSlot);
489
490#[cfg(shuttle)]
491unsafe impl Send for OwnedPipeSlotPtr {}
494
495#[cfg(shuttle)]
496process_static! {
497 static MODEL_OWNED_PIPE_SLOTS: Mutex<Vec<OwnedPipeSlotPtr>> = Mutex::new(Vec::new());
501}
502
503#[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 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 (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
546pub(crate) struct PipeStorage {
550 slot: crate::pipeline_sync::SlotRef<PipeSlot>,
551 tree: TreeHasher,
552 rooms: Rooms,
553 groups: Box<[MemberGroup]>,
554 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 holders: OwnLine<AtomicUsize>,
568}
569
570unsafe impl Send for PipeStorage {}
578unsafe impl Sync for PipeStorage {}
581
582impl PipeStorage {
583 #[inline(never)]
597 unsafe fn release_n(st: *mut PipeStorage, n: usize) {
598 if unsafe { (*st).holders.fetch_sub(n, Ordering::AcqRel) } == n {
604 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#[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
669unsafe impl Send for Room {}
673unsafe impl Sync for Room {}
676
677#[allow(clippy::len_without_is_empty)]
678impl Room {
679 #[inline(always)]
680 fn storage(&self) -> &PipeStorage {
681 unsafe { self.storage.as_ref() }
684 }
685
686 #[inline(always)]
688 pub fn bytes_mut(&mut self) -> &mut [u8] {
689 let rem = ROOM_LEN - self.offset as usize;
690 unsafe { core::slice::from_raw_parts_mut(self.as_mut_ptr(), rem) }
694 }
695
696 #[inline(always)]
698 pub fn as_mut_ptr(&mut self) -> *mut u8 {
699 unsafe { self.ptr.add(self.offset as usize) }
701 }
702
703 #[inline(always)]
705 pub fn len(&self) -> usize {
706 ROOM_LEN - self.offset as usize
707 }
708
709 #[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 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 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 let prev = unsafe { (*ref_ptr).fetch_sub(unused, Ordering::SeqCst) };
755 if prev & ROOM_CLOSING_BIT != 0 {
756 assert_eq!(prev & !ROOM_CLOSING_BIT, unused, "surviving room ref count");
760 unsafe { PipeStorage::release_n(self.storage.as_ptr(), 1) };
765 } else if prev == unused {
766 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 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#[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#[inline(always)]
832fn finished(waker: &'static WakerSlot, publish: impl FnOnce()) {
833 publish();
834 waker.notify_after_seqcst();
835}
836
837impl PipeStorage {
838 #[inline(always)]
842 fn tree_for(&self, slot: usize, custom: bool) -> &TreeHasher {
843 if custom {
844 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 let st = ctx as *const PipeStorage;
867 match ActionArg::decode(arg) {
868 ActionArg::Group { group, custom_slot } => {
869 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 let (waker, done_ptr) = unsafe { &*st }.run_room_piece(pnode as usize, custom, use_sme2);
878 finished(waker, || {
879 unsafe { (*done_ptr).swap(true, Ordering::SeqCst) };
882 });
883 }
884 ActionArg::Multi { slot, piece, custom, .. } => {
885 let slot = slot as usize;
886 let (tasks_left_ptr, is_batch) = unsafe { &*st }.run_multi_piece(slot, piece as usize, custom, use_sme2);
888 if unsafe { (*tasks_left_ptr).fetch_sub(1, Ordering::AcqRel) } == 1 {
893 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 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 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 let epoch = unsafe { *group.epoch.get() };
922 unsafe { task.run_members(&tree) };
923 let rooms = unsafe { &*group.rooms.get() };
925
926 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 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 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 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 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 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 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 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 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 unsafe { (*values).last = Some(value) };
1016 } else {
1017 let value = tree.subtree_cv(level, piece_idx as u64, bytes);
1018 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 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 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 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
1051fn 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
1062fn 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
1069fn 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 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#[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 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#[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
1142pub 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 free_slots: IndexRing,
1314 open_messages: usize,
1315 end_queue: IndexRing,
1316 events: EventRing<Event<T, B, P>>,
1317 local_free_rooms: IndexRing,
1319 room_cursor: usize,
1320 free_pieces: IndexRing,
1322 piece_slots: Vec<u32>,
1325 group_cursor: usize,
1327 open_group: Option<(u32, u64)>,
1328 local_count: usize,
1329 local_bytes: usize,
1330 local_batch: Option<(usize, usize)>,
1331 local_group_mode: SlotMode,
1334 local_custom_slot: u32,
1337 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
1347unsafe impl<T: Send, B: Send, P: Send> Send for Pipeline<T, B, P> {}
1352
1353struct PipelineBufs {
1357 local_members: [Member; MEMBERS],
1358 local_rooms: [u32; MEMBERS],
1359 action_buf: [u64; MAX_SLOT_PIECES],
1360 batch_plans: Box<[Option<Plan>]>,
1363}
1364
1365impl<T> Pipeline<T, (), Batch<'static>> {
1366 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 pub fn with_batches(mode: Mode, limits: Limits) -> Self {
1392 Self::create(mode, limits)
1393 }
1394}
1395
1396impl<T, B: AsRef<[u8]> + 'static> Pipeline<T, B, Batch<'static>> {
1404 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 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 #[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 let slot: *mut B = unsafe { (*self.owners.slot(s)).write(owner) };
1467 let pipe: *mut Self = self;
1468 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 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 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 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 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_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 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
1592fn 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#[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 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 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 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 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 #[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 #[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 #[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 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 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 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 #[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_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_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 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 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 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 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 #[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 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 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 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 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 #[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 #[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 #[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 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 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 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 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 Some(_) => unsafe { self.pipe_slot.source.publish_actions(ctx, core::slice::from_ref(&arg), false) },
2381 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 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 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 fn drain_pieces(&mut self, s: usize, keep_last: bool) {
2423 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 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 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 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 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 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 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 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 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 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 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 unsafe { (*ptr).assume_init_drop() };
2676 core::mem::forget(_rest);
2677 }
2678 _ => {}
2679 }
2680 }
2681 }
2682 }
2683 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 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
2840struct ThreadPark {
2842 thread: thread::Thread,
2843 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
2875pub fn block_on<F: Future>(future: F) -> F::Output {
3042 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 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 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#[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 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 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 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 #[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 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 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 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 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 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 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 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 #[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 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 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 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 #[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 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 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 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 #[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 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 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 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 #[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 pipe.next_group_epoch = base_ep + 2;
4059
4060 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 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 pipe.assigned_group_epoch[0] = 0;
4079 assert!(pipe.next_group_epoch > pipe.pipe_slot.group_completed[0].load(Ordering::Relaxed));
4080 }
4081
4082 #[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 #[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 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 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 #[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 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 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 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 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 drop(room.take());
4271 assert_eq!(wakes.0.load(Ordering::SeqCst), 3, "room() kept no waker");
4272 Poll::Ready(())
4273 }));
4274 p.storage().slot_done[s].store(true, Ordering::SeqCst);
4276 assert!(matches!(p.next_event(), Some(Event::Hashed { tag: 7, .. })));
4277 }
4278
4279 #[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 #[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 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 #[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 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 #[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 #[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 polls += 1;
4491 if polls == 1 {
4492 cx.waker().wake_by_ref();
4493 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 cx.waker().wake_by_ref();
4522 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 #[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 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 #[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 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 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 #[cfg(target_os = "linux")]
4708 {
4709 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 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 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 "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 std::process::exit(0);
4785 }
4786 "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 "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 "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 "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 "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 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 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 {
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 {
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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 {
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 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 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 #[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 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 #[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 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 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 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 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 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 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 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 #[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 let msg = [0x5Au8; 64];
5889 let m = block_on(p.message(7, None));
5890 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 let big = vec![0xA5u8; 200_000];
5905 let m2 = block_on(p2.message(9, None));
5906 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 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 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 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 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 #[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 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 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 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 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 let one_ticket_count = TASK_LEN / 64; let multi_ticket_count = (2 * TASK_LEN) / 64; 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 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 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 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 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 {
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}