Skip to main content

byteflow/scheduler/mailbox/
mod.rs

1//! Per-flow inbox: bounded hop queue + parked waiter (anti lost-wakeup).
2//!
3//! # Memory contract
4//!
5//! Unbounded growth without a logical limit is not a capacity API — it is
6//! an OOM path when many flows share few workers. Every mailbox is constructed
7//! with a [`MailboxConfig`]: a validated [`MailboxCapacity`], a [`MailboxBytes`]
8//! budget, and an [`OverflowPolicy`]. Logical bound ≠ physical allocation;
9//! the queue grows geometrically up to the limit (see [`queue`]).
10//!
11//! Both bounds are load-bearing. A hop count alone stopped being a memory
12//! bound once hops could carry `Str` / `Bytes`: at the default capacity,
13//! 256 hops is ~12 KiB of scalars or ~256 MiB of 1 MiB blobs. Whichever
14//! bound is reached first refuses the hop, and [`MailboxFull::reason`] says
15//! which one it was.
16//!
17//! There is **no** `Block` policy. Blocking an OS worker on a full inbox
18//! would stall every other flow on that thread. Overflow is Reject /
19//! DropNewest / DropOldest. Scheduler-level [`Mailbox::park_sender`]
20//! (`WAITING_SEND`) parks the **sender flow** in this mailbox and wakes
21//! **one** waiter per freed slot (no wake storm).
22//!
23//! # Wake
24//!
25//! `park` and `push` share one mutex (lost-wakeup invariant — keep this
26//! comment and the race diagram). A hop that does not match a selective
27//! waiter is queued (if the bound allows) and the waiter stays parked.
28//! Overflow that **drops** a hop never produces [`Delivery::Handoff`].
29//!
30//! See `docs/mailbox.md`.
31
32mod capacity;
33mod metrics;
34mod policy;
35mod queue;
36
37use std::collections::VecDeque;
38use std::sync::{Arc, Mutex};
39
40use crate::bytecode::{payload_matches, Value};
41
42use super::error::RuntimeError;
43use super::process::{Flow, FlowId};
44use super::sync_lock;
45
46pub use capacity::{MailboxBytes, MailboxCapacity};
47pub use metrics::MailboxStats;
48pub use policy::{MailboxConfig, OverflowPolicy};
49
50use queue::{EnqueueEffect, MailboxQueue};
51
52/// Selective wait criterion installed while a flow is parked in its mailbox.
53///
54/// Used by classic `Receive`, `ReceiveMatch`, and `Ask`. Matching always
55/// **skips** (never drops) non-matching hops already in the queue.
56#[derive(Debug, Clone, PartialEq)]
57pub(crate) enum WaitFilter {
58    /// `Receive`: consume the oldest value regardless of contents.
59    Any,
60    /// `ReceiveMatch`: oldest `Message` whose application `tag` matches.
61    Tag(u16),
62    /// `ReceiveMatchKind`: oldest `Message` whose `payload.wire_tag()` matches.
63    PayloadKind(u8),
64    /// `ReceiveMatchEq`: oldest hop with this tag and `Int` payload.
65    TagPayload { tag: u16, payload: i64 },
66    /// `ReceiveMatchValue`: oldest hop with this tag and a payload equal
67    /// to `payload` ([`crate::payload_matches`]).
68    TagValue { tag: u16, payload: Arc<Value> },
69    /// `ReceiveMatchCmp`: oldest hop with this tag whose `Int` payload
70    /// passes `cmp` against `bound`. A non-int payload does not match.
71    TagCmp {
72        tag: u16,
73        cmp: crate::bytecode::IntCmp,
74        bound: i64,
75    },
76    /// `Ask`: reply belonging to one specific request.
77    ///
78    /// `expect_request_id` is the RPC correlation key.
79    /// `expect_sender`, when present, additionally constrains reply origin.
80    /// Ask uses `Some(resolved_target_FlowId)` so a hop with the same
81    /// `request_id` from an unrelated flow cannot complete the RPC.
82    /// Compare against FlowId, never CapId (S2 after FlowCap).
83    Correlation {
84        expect_request_id: u64,
85        expect_sender: Option<u64>,
86    },
87    /// Fire-and-forget correlated receive: tag + request_id, any sender.
88    TaggedCorrelation { tag: u16, expect_request_id: u64 },
89}
90
91impl WaitFilter {
92    #[inline]
93    pub(crate) fn matches(&self, value: &Value) -> bool {
94        match *self {
95            Self::Any => true,
96            Self::Tag(expected_tag) => match value.as_message() {
97                Some(m) => m.tag == expected_tag,
98                None => false,
99            },
100            Self::PayloadKind(kind) => match value.as_message() {
101                Some(m) => m.payload.wire_tag() == kind,
102                None => false,
103            },
104            Self::TagPayload { tag, payload } => match value.as_message() {
105                Some(m) => {
106                    m.tag == tag && matches!(m.payload.as_ref(), Value::Int(n) if *n == payload)
107                }
108                None => false,
109            },
110            Self::TagValue { tag, ref payload } => payload_matches(tag, payload, value),
111            Self::TagCmp { tag, cmp, bound } => match value.as_message() {
112                Some(message) => {
113                    message.tag == tag
114                        && matches!(message.payload.as_ref(), Value::Int(n) if cmp.holds(*n, bound))
115                }
116                None => false,
117            },
118            Self::Correlation {
119                expect_request_id,
120                expect_sender,
121            } => match value.as_message() {
122                Some(m) => {
123                    let id_ok = m.request_id == expect_request_id;
124                    let sender_ok = match expect_sender {
125                        Some(s) => m.sender == s,
126                        None => true,
127                    };
128                    id_ok && sender_ok
129                }
130                None => false,
131            },
132            Self::TaggedCorrelation {
133                tag,
134                expect_request_id,
135            } => match value.as_message() {
136                Some(m) => m.tag == tag && m.request_id == expect_request_id,
137                None => false,
138            },
139        }
140    }
141}
142
143/// A flow's inbox, plus (when the owning flow is blocked on
144/// `Receive` / `ReceiveMatch` / `Ask` with nothing to read) the parked flow itself.
145///
146/// # Why the flow lives *inside* its own mailbox while waiting
147///
148/// Internally, a flow is reachable through its [`FlowId`](crate::FlowId), which
149/// resolves (via the runtime's flow directory) to this `Mailbox`. Bytecode
150/// does **not** address by Pid anymore (FlowCap): `Send` / `Ask` resolve a
151/// Cap to a FlowId first, then look up here. Host [`crate::Runtime::send`]
152/// still uses FlowId directly (trusted).
153///
154/// Storing the blocked `Box<Flow>` directly in `MailboxInner::parked`, behind
155/// the same mutex that guards the message queue, turns "deliver a message and
156/// wake the receiver if it was waiting" into a single critical section — which
157/// is what actually prevents the classic lost-wakeup race:
158///
159/// ```text
160/// racing without a shared lock:
161///   receiver: queue.pop() -> None
162///   sender:   queue.push(msg); wake(receiver)   // receiver isn't parked yet!
163///   receiver: park()                            // ...and now sleeps forever
164///
165/// with both steps under one mutex (what this type does):
166///   receiver: lock; queue.pop() -> None; store self in `parked`; unlock
167///   sender:   lock; parked.take() -> Some(receiver); unlock; wake(receiver)
168/// ```
169/// Because "check the queue" and "become parked" happen atomically with
170/// respect to "push and check for a parked receiver", there is no window
171/// where a message can be pushed without either landing in the queue for a
172/// later `Receive` or immediately waking an already-parked one.
173///
174/// Wake only happens when a hop is **accepted and matches** the waiter.
175/// A flow that is already runnable (message queued, nobody parked) does
176/// not generate extra scheduler work — no wake storm on every `Send`.
177///
178/// # Selective wait (`ReceiveMatch` / `Ask`)
179///
180/// When parked with a selective (non-`Any`) filter, only a hop that
181/// satisfies the filter wakes the flow. Other hops are appended to the
182/// queue (subject to the bound) and the waiter stays parked (FIFO skip,
183/// never drop matching semantics).
184///
185/// # Bound
186///
187/// `push` may return [`MailboxFull`] when the policy is Reject and the
188/// logical capacity is already occupied **and** nobody matching is parked.
189/// A parked waiter that matches the hop still takes a **handoff** — that
190/// hop never occupies a queue slot.
191pub struct Mailbox {
192    inner: Mutex<MailboxInner>,
193    config: MailboxConfig,
194}
195
196struct MailboxInner {
197    queue: MailboxQueue,
198    parked: Option<Box<Flow>>,
199    /// Active while `parked` is `Some`. Ignored when nobody is waiting.
200    parked_filter: WaitFilter,
201    /// Bumped on every park install, so a deadline armed for an earlier
202    /// wait can be told apart from the current one. See [`WaitEpoch`].
203    wait_epoch: u64,
204    stats: MailboxStats,
205    /// Bytecode senders waiting for a free slot (`WAITING_SEND`).
206    /// Woken one-at-a-time from [`Mailbox::admit_waiting_sender`].
207    waiting_senders: VecDeque<WaitingSender>,
208    /// Set by [`Mailbox::close`] during finalize so a late `park_sender`
209    /// cannot land after `drain_waiting_senders` and leak the sender.
210    closed: bool,
211}
212
213struct WaitingSender {
214    flow: Box<Flow>,
215    message: Value,
216}
217
218/// Outcome of pushing a message.
219///
220/// `Queued*` means the hop (or a replacement under DropOldest) lives in
221/// the inbox for a later `Receive`. [`Handoff`](Delivery::Handoff) means a parked flow was
222/// waiting for **this** hop — the caller (`worker::deliver` /
223/// [`crate::Runtime::send`]) must `resume_with` and re-enqueue the flow.
224/// Dropped variants never wake a waiter.
225pub enum Delivery {
226    Queued,
227    QueuedDropOldest,
228    DroppedNewest,
229    Handoff(Box<Flow>),
230}
231
232/// Which of a mailbox's two bounds refused a hop.
233///
234/// Reported so an operator can tell "this flow is not draining its inbox"
235/// ([`Self::MessageLimit`]) from "this flow is being sent payloads too
236/// large for its budget" ([`Self::ByteLimit`]) without instrumenting the
237/// sender. Those have different fixes: raise capacity / speed up the
238/// receiver versus raise the byte budget / shrink the payload.
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub enum MailboxFullReason {
241    /// [`MailboxCapacity`] hops are already queued.
242    MessageLimit,
243    /// Accepting the hop would exceed the [`MailboxBytes`] budget. Also
244    /// reported when a single hop is larger than the entire budget, which
245    /// no eviction policy can make room for.
246    ByteLimit,
247    /// Inbox was closed by finalize — the flow is exiting. Delivery must
248    /// treat this like “target gone”, not like a capacity refusal.
249    Closed,
250}
251
252impl std::fmt::Display for MailboxFullReason {
253    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
254        match self {
255            MailboxFullReason::MessageLimit => write!(f, "hop count limit"),
256            MailboxFullReason::ByteLimit => write!(f, "byte budget"),
257            MailboxFullReason::Closed => write!(f, "mailbox closed"),
258        }
259    }
260}
261
262/// Inbox at one of its logical bounds under [`OverflowPolicy::Reject`].
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub struct MailboxFull {
265    reason: MailboxFullReason,
266}
267
268impl MailboxFull {
269    #[inline]
270    pub const fn reason(self) -> MailboxFullReason {
271        self.reason
272    }
273}
274
275impl std::fmt::Display for MailboxFull {
276    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
277        write!(f, "mailbox full ({})", self.reason)
278    }
279}
280
281impl std::error::Error for MailboxFull {}
282
283/// Identifies **one specific park** of a flow in its mailbox.
284///
285/// # Why a timeout needs a token
286///
287/// Cancellation of a `ReceiveTimeout` deadline is lazy: the timer thread
288/// does not remove its entry when a hop wakes the receiver early, it just
289/// finds nobody parked when it eventually fires. That reasoning only holds
290/// if the flow never parks *again* before the old deadline — and in a
291/// receive loop it always does:
292///
293/// ```text
294///   t=0    ReceiveTimeout(r5, 100ms)  -> park A, timer(100ms) armed
295///   t=20   hop arrives                -> handoff, park A over, flow runs
296///   t=30   Receive(r7)                -> park B  (no timeout)
297///   t=100  timer for park A fires     -> takes park B!
298///                                        writes Unit into r5, not r7
299/// ```
300///
301/// That is a spurious wake *and* a write to the previous wait's register.
302/// So [`Mailbox::park`] returns the epoch of the park it installed, the
303/// timer carries it, and [`Mailbox::take_parked_at`] only hands the flow
304/// over while that epoch is still current.
305///
306/// There is no public constructor: an epoch can only come from parking,
307/// so a timeout cannot present one for a wait that never happened.
308#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
309pub struct WaitEpoch(u64);
310
311impl WaitEpoch {
312    /// Raw counter value, for logs and metrics only. Never compare epochs
313    /// from two different mailboxes: the counter is per-inbox.
314    #[inline]
315    pub const fn get(self) -> u64 {
316        self.0
317    }
318}
319
320impl std::fmt::Display for WaitEpoch {
321    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322        write!(f, "wait#{}", self.0)
323    }
324}
325
326impl Mailbox {
327    pub fn new() -> Self {
328        Self::with_config(MailboxConfig::DEFAULT)
329    }
330
331    pub fn with_config(config: MailboxConfig) -> Self {
332        Mailbox {
333            inner: Mutex::new(MailboxInner {
334                queue: MailboxQueue::new(config.capacity().get(), config.bytes().get()),
335                parked: None,
336                parked_filter: WaitFilter::Any,
337                wait_epoch: 0,
338                stats: MailboxStats::default(),
339                waiting_senders: VecDeque::new(),
340                closed: false,
341            }),
342            config,
343        }
344    }
345
346    #[inline]
347    pub fn config(&self) -> MailboxConfig {
348        self.config
349    }
350
351    /// Snapshot of enqueue/dequeue/drop counters plus current occupancy
352    /// (taken under the mailbox lock, so the depth and the counters
353    /// describe the same instant).
354    pub fn stats(&self) -> Result<MailboxStats, RuntimeError> {
355        let inner = sync_lock::lock(&self.inner, "Mailbox::stats")?;
356        let mut stats = inner.stats;
357        stats.queued_messages = inner.queue.len();
358        stats.queued_bytes = inner.queue.bytes();
359        Ok(stats)
360    }
361
362    /// Push `value` under the mailbox config.
363    ///
364    /// 1. If a matching waiter is parked → [`Delivery::Handoff`] (does not
365    ///    consume a queue slot).
366    /// 2. Else enqueue / overflow according to [`OverflowPolicy`].
367    /// 3. [`MailboxFull`] only for Reject when the queue is already at one
368    ///    of its logical bounds (see [`MailboxFullReason`]) — plus the one
369    ///    case no policy can absorb: a hop larger than the whole byte
370    ///    budget.
371    ///
372    /// Mutex poison → [`RuntimeError`] (fail-closed).
373    pub fn push(&self, value: Value) -> Result<Result<Delivery, MailboxFull>, RuntimeError> {
374        // Reject before matching or sizing. Both used to recurse through the
375        // payload, so a long `Message` chain overflowed this thread.
376        if !value.within_nesting_limit() {
377            return Ok(Err(MailboxFull {
378                reason: MailboxFullReason::ByteLimit,
379            }));
380        }
381        let mut inner = sync_lock::lock(&self.inner, "Mailbox::push")?;
382        if inner.closed {
383            return Ok(Err(MailboxFull {
384                reason: MailboxFullReason::Closed,
385            }));
386        }
387        if let Some(flow) = inner.parked.take() {
388            if inner.parked_filter.matches(&value) {
389                inner.parked_filter = WaitFilter::Any;
390                inner.stats.dequeued = inner.stats.dequeued.saturating_add(1);
391                inner.stats.enqueued = inner.stats.enqueued.saturating_add(1);
392                return Ok(Ok(Delivery::Handoff(flow)));
393            }
394            inner.parked = Some(flow);
395            return Ok(enqueue_locked(&mut inner, value, self.config.overflow()));
396        }
397        Ok(enqueue_locked(&mut inner, value, self.config.overflow()))
398    }
399
400    /// Non-blocking pop of the front hop (classic `Receive`).
401    pub fn try_pop(&self) -> Result<Option<Value>, RuntimeError> {
402        self.try_pop_filter(WaitFilter::Any)
403    }
404
405    /// Non-blocking selective pop by application `tag` (`ReceiveMatch`).
406    pub fn try_pop_match(&self, tag: u16) -> Result<Option<Value>, RuntimeError> {
407        self.try_pop_filter(WaitFilter::Tag(tag))
408    }
409
410    /// Non-blocking pop under an arbitrary [`WaitFilter`] (FIFO skip).
411    pub(crate) fn try_pop_filter(&self, filter: WaitFilter) -> Result<Option<Value>, RuntimeError> {
412        let mut inner = sync_lock::lock(&self.inner, "Mailbox::try_pop_filter")?;
413        let got = inner.queue.take(filter);
414        if got.is_some() {
415            inner.stats.dequeued = inner.stats.dequeued.saturating_add(1);
416        }
417        Ok(got)
418    }
419
420    /// Atomically re-check the queue and, if still empty, store `flow`
421    /// as parked (classic `Receive` — any hop wakes).
422    ///
423    /// Outer `Result` is infrastructure (mutex poison). Inner `Result` is
424    /// the lost-wakeup race: `Err(flow)` means a message arrived between
425    /// the worker's `try_pop` and this call — resume immediately with the
426    /// stashed pending message rather than parking forever.
427    ///
428    /// `Ok(Ok(epoch))` identifies the park that was installed. A caller
429    /// arming a `ReceiveTimeout` deadline must carry that [`WaitEpoch`] to
430    /// [`Mailbox::take_parked_at`], or a late deadline will wake whatever
431    /// wait happens to be current instead.
432    pub fn park(&self, flow: Box<Flow>) -> Result<Result<WaitEpoch, Box<Flow>>, RuntimeError> {
433        self.park_filter(flow, WaitFilter::Any)
434            .map_err(|(e, _flow)| e)
435    }
436
437    /// Like [`park`](Self::park), but only a hop with `Message.tag == tag`
438    /// ends the wait. Non-matching hops already in the queue are left
439    /// untouched (FIFO skip).
440    pub fn park_match(
441        &self,
442        flow: Box<Flow>,
443        tag: u16,
444    ) -> Result<Result<WaitEpoch, Box<Flow>>, RuntimeError> {
445        self.park_filter(flow, WaitFilter::Tag(tag))
446            .map_err(|(e, _flow)| e)
447    }
448
449    /// Park under an arbitrary filter. Re-checks the queue under the same
450    /// mutex before installing the waiter (anti lost-wakeup).
451    pub(crate) fn park_filter(
452        &self,
453        flow: Box<Flow>,
454        filter: WaitFilter,
455    ) -> Result<Result<WaitEpoch, Box<Flow>>, (RuntimeError, Box<Flow>)> {
456        let mut inner = match sync_lock::lock(&self.inner, "Mailbox::park_filter") {
457            Ok(g) => g,
458            Err(e) => return Err((e, flow)),
459        };
460        if let Some(value) = inner.queue.take(filter.clone()) {
461            inner.stats.dequeued = inner.stats.dequeued.saturating_add(1);
462            drop(inner);
463            return Ok(Err(with_pending(flow, value)));
464        }
465        debug_assert!(
466            inner.parked.is_none(),
467            "park_filter would overwrite a parked Flow"
468        );
469        // Wrapping, not saturating: a saturated counter would make every
470        // later epoch compare equal, silently restoring the stale-deadline
471        // bug this exists to prevent. Reuse needs 2^64 parks on one inbox.
472        inner.wait_epoch = inner.wait_epoch.wrapping_add(1);
473        let epoch = WaitEpoch(inner.wait_epoch);
474        inner.parked_filter = filter;
475        inner.parked = Some(flow);
476        Ok(Ok(epoch))
477    }
478
479    /// Whether `value` can occupy this inbox when the queue is empty.
480    /// A hop larger than the byte budget must never enter `WAITING_SEND`.
481    #[inline]
482    pub(crate) fn hop_can_ever_fit(&self, value: &Value) -> bool {
483        value.memory_size() <= self.config.bytes().get()
484    }
485
486    /// Take the parked flow back out **only if** `epoch` is still the
487    /// current wait, used by the timer when a `ReceiveTimeout` deadline
488    /// fires.
489    ///
490    /// `None` means the deadline lost the race and must do nothing: either
491    /// a hop already woke that wait, or the flow has since parked on a
492    /// *different* `Receive` that this deadline does not own (see
493    /// [`WaitEpoch`]).
494    ///
495    /// The selective filter is reset only when the flow is actually taken.
496    /// Clearing it on a stale call would downgrade a live `ReceiveMatch` /
497    /// `Ask` waiter to "any hop wakes me".
498    pub fn take_parked_at(&self, epoch: WaitEpoch) -> Result<Option<Box<Flow>>, RuntimeError> {
499        let mut inner = sync_lock::lock(&self.inner, "Mailbox::take_parked_at")?;
500        if inner.wait_epoch != epoch.0 {
501            return Ok(None);
502        }
503        match inner.parked.take() {
504            Some(flow) => {
505                inner.parked_filter = WaitFilter::Any;
506                Ok(Some(flow))
507            }
508            None => Ok(None),
509        }
510    }
511
512    /// Take the current parked receiver regardless of epoch (lifecycle kill).
513    pub(crate) fn take_parked(&self) -> Result<Option<Box<Flow>>, RuntimeError> {
514        let mut inner = sync_lock::lock(&self.inner, "Mailbox::take_parked")?;
515        inner.parked_filter = WaitFilter::Any;
516        Ok(inner.parked.take())
517    }
518
519    /// Enqueue a hop even when the inbox is at a bound (system `DOWN` /
520    /// `TAG_SYS_EXIT` from `trap_exit` or orphaned Ask).
521    pub(crate) fn push_system(&self, value: Value) -> Result<Delivery, RuntimeError> {
522        let mut inner = sync_lock::lock(&self.inner, "Mailbox::push_system")?;
523        // System lifecycle hops may still target a live owner; if that owner
524        // is already closed, drop the hop (owner is exiting / gone).
525        if inner.closed {
526            return Ok(Delivery::Queued);
527        }
528        if let Some(flow) = inner.parked.take() {
529            if inner.parked_filter.matches(&value) {
530                inner.parked_filter = WaitFilter::Any;
531                inner.stats.dequeued = inner.stats.dequeued.saturating_add(1);
532                inner.stats.enqueued = inner.stats.enqueued.saturating_add(1);
533                return Ok(Delivery::Handoff(flow));
534            }
535            inner.parked = Some(flow);
536        }
537        inner.queue.force_push(value);
538        inner.stats.enqueued = inner.stats.enqueued.saturating_add(1);
539        Ok(Delivery::Queued)
540    }
541
542    /// Close the inbox for new `WAITING_SEND` parks, then drain waiters.
543    ///
544    /// Called from `finalize_flow` **before** unregistering the directory
545    /// so a sender that lost the Full/park race cannot park on a dead inbox.
546    pub(crate) fn close(&self) -> Result<Vec<Flow>, RuntimeError> {
547        let mut inner = sync_lock::lock(&self.inner, "Mailbox::close")?;
548        inner.closed = true;
549        Ok(inner.waiting_senders.drain(..).map(|w| *w.flow).collect())
550    }
551
552    /// Park a bytecode sender whose hop was refused (`WAITING_SEND`).
553    ///
554    /// A slot may have opened between the caller's `push` and this lock.
555    /// That hop is queued here ([`ParkSender::Delivered`]) instead of
556    /// sitting in `waiting_senders` while the inbox has room.
557    ///
558    /// Never drops `flow`: a closed or poisoned mailbox returns it in
559    /// [`ParkSender::Closed`] so the worker can finalize.
560    pub(crate) fn park_sender(&self, flow: Box<Flow>, message: Value) -> ParkSender {
561        if !self.hop_can_ever_fit(&message) {
562            return ParkSender::Undeliverable(flow);
563        }
564        match sync_lock::lock(&self.inner, "Mailbox::park_sender") {
565            Ok(inner) if inner.closed => ParkSender::Closed(flow),
566            Ok(mut inner) => match inner.queue.try_enqueue_reject(message) {
567                Ok(()) => {
568                    inner.stats.enqueued = inner.stats.enqueued.saturating_add(1);
569                    ParkSender::Delivered(flow)
570                }
571                Err(message) => {
572                    if inner.waiting_senders.len() >= self.config.capacity().get() {
573                        return ParkSender::WaitersFull(flow);
574                    }
575                    inner
576                        .waiting_senders
577                        .push_back(WaitingSender { flow, message });
578                    ParkSender::Parked
579                }
580            },
581            Err(e) => {
582                super::error::report_fault(e);
583                ParkSender::Closed(flow)
584            }
585        }
586    }
587
588    /// After a pop frees a slot, admit **one** waiting sender (no wake storm).
589    pub(crate) fn admit_waiting_sender(&self) -> Result<AdmitSender, RuntimeError> {
590        let mut inner = sync_lock::lock(&self.inner, "Mailbox::admit_waiting_sender")?;
591        if inner.closed {
592            return Ok(AdmitSender::Idle);
593        }
594        let Some(waiter) = inner.waiting_senders.pop_front() else {
595            return Ok(AdmitSender::Idle);
596        };
597        if !inner.queue.can_ever_fit(waiter.message.memory_size()) {
598            return Ok(AdmitSender::Undeliverable(waiter.flow));
599        }
600        match enqueue_locked(&mut inner, waiter.message.clone(), OverflowPolicy::Reject) {
601            Ok(_) => Ok(AdmitSender::Woken(waiter.flow)),
602            Err(_) => {
603                inner.waiting_senders.push_front(waiter);
604                Ok(AdmitSender::Idle)
605            }
606        }
607    }
608
609    /// Pull one parked sender out (link-kill of a flow blocked on `WAITING_SEND`).
610    pub(crate) fn take_waiting_sender(
611        &self,
612        sender: FlowId,
613    ) -> Result<Option<Box<Flow>>, RuntimeError> {
614        let mut inner = sync_lock::lock(&self.inner, "Mailbox::take_waiting_sender")?;
615        if let Some(pos) = inner
616            .waiting_senders
617            .iter()
618            .position(|w| w.flow.id == sender)
619        {
620            return Ok(inner.waiting_senders.remove(pos).map(|w| w.flow));
621        }
622        Ok(None)
623    }
624}
625
626/// Outcome of [`Mailbox::park_sender`].
627pub(crate) enum ParkSender {
628    Parked,
629    /// The inbox had room under this lock. The hop is queued and the
630    /// sender must keep running.
631    Delivered(Box<Flow>),
632    /// Inbox already closed (target finalizing) or lock poisoned.
633    Closed(Box<Flow>),
634    /// Too many senders are already parked. The target is still alive.
635    WaitersFull(Box<Flow>),
636    /// Hop is larger than the inbox byte budget — parking would never unblock.
637    Undeliverable(Box<Flow>),
638}
639
640/// Outcome of [`Mailbox::admit_waiting_sender`].
641pub(crate) enum AdmitSender {
642    Woken(Box<Flow>),
643    Idle,
644    /// Head waiter can never fit an empty inbox (oversized hop).
645    Undeliverable(Box<Flow>),
646}
647
648impl Default for Mailbox {
649    fn default() -> Self {
650        Self::new()
651    }
652}
653
654fn enqueue_locked(
655    inner: &mut MailboxInner,
656    value: Value,
657    policy: OverflowPolicy,
658) -> Result<Delivery, MailboxFull> {
659    match inner.queue.enqueue(value, policy) {
660        Ok(EnqueueEffect::Enqueued) => {
661            inner.stats.enqueued = inner.stats.enqueued.saturating_add(1);
662            Ok(Delivery::Queued)
663        }
664        Ok(EnqueueEffect::DroppedOldest) => {
665            inner.stats.dropped_oldest = inner.stats.dropped_oldest.saturating_add(1);
666            inner.stats.enqueued = inner.stats.enqueued.saturating_add(1);
667            Ok(Delivery::QueuedDropOldest)
668        }
669        Ok(EnqueueEffect::DroppedNewest) => {
670            inner.stats.dropped_newest = inner.stats.dropped_newest.saturating_add(1);
671            Ok(Delivery::DroppedNewest)
672        }
673        Err(reason) => {
674            inner.stats.rejected = inner.stats.rejected.saturating_add(1);
675            if reason == MailboxFullReason::ByteLimit {
676                inner.stats.rejected_byte_limit = inner.stats.rejected_byte_limit.saturating_add(1);
677            }
678            Err(MailboxFull { reason })
679        }
680    }
681}
682
683/// Stashes a message that arrived just as we were about to park, so the
684/// worker loop can resume the flow with it on the very next step
685/// without re-entering the mailbox. See [`Mailbox::park`].
686fn with_pending(mut flow: Box<Flow>, value: Value) -> Box<Flow> {
687    flow.pending_message = Some(value);
688    flow
689}
690
691#[cfg(test)]
692mod tests {
693    use super::*;
694    use crate::bytecode::builder::ChunkBuilder;
695    use crate::bytecode::Message;
696    use crate::bytecode::RestartPolicy;
697    use crate::scheduler::oneshot;
698    use crate::scheduler::process::next_flow_id;
699    use crate::vm::{NativeTable, Vm};
700    use std::sync::Arc;
701
702    type TestResult = Result<(), Box<dyn std::error::Error>>;
703
704    #[test]
705    fn a_long_message_chain_is_rejected_without_blowing_the_stack() -> TestResult {
706        let mb = Mailbox::new();
707        let mut value = Value::Int(1);
708        for _ in 0..10_000 {
709            value = Value::Message(Message::new(0, 1, 1, value));
710        }
711        match mb.push(value)? {
712            Ok(_) => Err("a chain past the decoder ceiling must not be queued".into()),
713            Err(full) => {
714                assert_eq!(full.reason(), MailboxFullReason::ByteLimit);
715                assert!(mb.try_pop()?.is_none());
716                Ok(())
717            }
718        }
719    }
720
721    #[test]
722    fn tag_cmp_skips_a_non_matching_int_and_a_non_int() {
723        let filter = WaitFilter::TagCmp {
724            tag: 1,
725            cmp: crate::bytecode::IntCmp::Lt,
726            bound: 10,
727        };
728        let high = Value::Message(Message::new(1, 1, 1, Value::Int(20)));
729        let text = Value::Message(Message::new(1, 2, 1, Value::str("no")));
730        let low = Value::Message(Message::new(1, 3, 1, Value::Int(3)));
731        let other_tag = Value::Message(Message::new(1, 4, 2, Value::Int(1)));
732        assert!(!filter.matches(&high));
733        assert!(!filter.matches(&text));
734        assert!(filter.matches(&low));
735        assert!(!filter.matches(&other_tag));
736        let min = Value::Message(Message::new(1, 5, 1, Value::Int(i64::MIN)));
737        assert!(filter.matches(&min));
738        let eq = WaitFilter::TagCmp {
739            tag: 1,
740            cmp: crate::bytecode::IntCmp::Eq,
741            bound: i64::MIN,
742        };
743        let le = WaitFilter::TagCmp {
744            tag: 1,
745            cmp: crate::bytecode::IntCmp::Le,
746            bound: 3,
747        };
748        assert!(eq.matches(&min));
749        assert!(!eq.matches(&low));
750        assert!(le.matches(&low));
751        assert!(!le.matches(&high));
752    }
753
754    fn dummy_flow() -> Result<Box<Flow>, Box<dyn std::error::Error>> {
755        let mut b = ChunkBuilder::new("mb");
756        b.begin_function("main", 0, 1);
757        b.emit_return(0);
758        let chunk = b.finish();
759        let vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
760        let (tx, _rx) = oneshot::channel();
761        Ok(Box::new(Flow::new(
762            next_flow_id(),
763            vm,
764            Arc::new(Mailbox::new()),
765            RestartPolicy::Never,
766            tx,
767        )))
768    }
769
770    fn hop_payload_int(msg: &Message) -> i64 {
771        match msg.payload.as_int() {
772            Some(n) => n,
773            None => 0,
774        }
775    }
776
777    fn hop(sender: u64, request_id: u64, tag: u16, payload: impl Into<Value>) -> Value {
778        Value::Message(Message::new(sender, request_id, tag, payload))
779    }
780
781    fn msg(tag: u16, payload: impl Into<Value>) -> Value {
782        hop(1, 1, tag, payload)
783    }
784
785    fn tiny_reject(n: u32) -> Result<Mailbox, Box<dyn std::error::Error>> {
786        let cap = MailboxCapacity::new(n).ok_or("invalid mailbox capacity")?;
787        Ok(Mailbox::with_config(MailboxConfig::new(
788            cap,
789            OverflowPolicy::Reject,
790        )))
791    }
792
793    fn hop_msg(value: &Value) -> Result<&Message, Box<dyn std::error::Error>> {
794        value
795            .as_message()
796            .ok_or_else(|| "expected Message hop".into())
797    }
798
799    #[test]
800    fn try_pop_match_skips_non_matching_fifo() -> TestResult {
801        let mb = Mailbox::new();
802        mb.push(msg(9, 1))??;
803        mb.push(msg(1, 42))??;
804        mb.push(msg(9, 2))??;
805        let got = mb.try_pop_match(1)?.ok_or("match")?;
806        assert_eq!(hop_payload_int(hop_msg(&got)?), 42);
807        assert_eq!(hop_msg(&mb.try_pop()?.ok_or("first leftover")?)?.tag, 9);
808        assert_eq!(
809            hop_payload_int(hop_msg(&mb.try_pop()?.ok_or("second leftover")?)?),
810            2
811        );
812        Ok(())
813    }
814
815    #[test]
816    fn push_while_park_match_queues_junk_keeps_waiter() -> TestResult {
817        let mb = Mailbox::new();
818        let flow = dummy_flow()?;
819        assert!(mb.park_match(flow, 1)?.is_ok());
820        assert!(matches!(mb.push(msg(9, 0))??, Delivery::Queued));
821        assert!(matches!(mb.push(msg(1, 7))??, Delivery::Handoff(_)));
822        assert_eq!(hop_msg(&mb.try_pop()?.ok_or("queued junk")?)?.tag, 9);
823        Ok(())
824    }
825
826    #[test]
827    fn ask_does_not_consume_reply_for_another_request() -> TestResult {
828        let mb = Mailbox::new();
829        mb.push(hop(10, 2, 2, 99))??;
830        mb.push(hop(10, 1, 2, 42))??;
831        let filter = WaitFilter::Correlation {
832            expect_request_id: 1,
833            expect_sender: Some(10),
834        };
835        let got = mb.try_pop_filter(filter)?.ok_or("id=1")?;
836        assert_eq!(hop_payload_int(hop_msg(&got)?), 42);
837        let left = mb.try_pop()?.ok_or("leftover")?;
838        assert_eq!(hop_msg(&left)?.request_id, 2);
839        Ok(())
840    }
841
842    #[test]
843    fn tagged_correlation_skips_wrong_id_and_tag() -> TestResult {
844        let mb = Mailbox::new();
845        mb.push(hop(10, 1, 1, 7))??;
846        mb.push(hop(10, 2, 2, 9))??;
847        mb.push(hop(10, 1, 2, 42))??;
848        assert!(mb
849            .try_pop_filter(WaitFilter::TaggedCorrelation {
850                tag: 99,
851                expect_request_id: 1,
852            })?
853            .is_none());
854        let got = mb
855            .try_pop_filter(WaitFilter::TaggedCorrelation {
856                tag: 2,
857                expect_request_id: 1,
858            })?
859            .ok_or("tag=2 id=1")?;
860        assert_eq!(hop_payload_int(hop_msg(&got)?), 42);
861        Ok(())
862    }
863
864    #[test]
865    fn ask_requires_reply_from_target() -> TestResult {
866        let mb = Mailbox::new();
867        let flow = dummy_flow()?;
868        let filter = WaitFilter::Correlation {
869            expect_request_id: 1,
870            expect_sender: Some(10),
871        };
872        assert!(mb.park_filter(flow, filter).map_err(|(e, _)| e)?.is_ok());
873        assert!(matches!(mb.push(hop(99, 1, 2, 0))??, Delivery::Queued));
874        assert!(matches!(mb.push(hop(10, 1, 2, 42))??, Delivery::Handoff(_)));
875        assert_eq!(
876            hop_msg(&mb.try_pop()?.ok_or("non-matching queued")?)?.sender,
877            99
878        );
879        Ok(())
880    }
881
882    #[test]
883    fn reject_when_full_without_waiter() -> TestResult {
884        let mb = tiny_reject(1)?;
885        assert!(matches!(mb.push(msg(1, 1))??, Delivery::Queued));
886        // Bind the error: `Err(MailboxFull)` would introduce a *variable*
887        // named MailboxFull now that the type carries a reason, matching
888        // every error and asserting nothing.
889        match mb.push(msg(1, 2))? {
890            Err(full) => assert_eq!(full.reason(), MailboxFullReason::MessageLimit),
891            Ok(_) => return Err("expected the hop count bound to refuse".into()),
892        }
893        let s = mb.stats()?;
894        assert_eq!(s.enqueued, 1);
895        assert_eq!(s.rejected, 1);
896        assert_eq!(s.rejected_byte_limit, 0);
897        assert_eq!(s.queued_messages, 1);
898        Ok(())
899    }
900
901    /// Park `flow`, requiring that it actually parked, and hand back the
902    /// epoch. Collapses the two-level `Result` the tests do not care about.
903    fn park_now(mb: &Mailbox, flow: Box<Flow>) -> Result<WaitEpoch, Box<dyn std::error::Error>> {
904        match mb.park(flow)? {
905            Ok(epoch) => Ok(epoch),
906            Err(_) => Err("an empty mailbox should have parked the flow".into()),
907        }
908    }
909
910    fn handoff(mb: &Mailbox, value: Value) -> Result<Box<Flow>, Box<dyn std::error::Error>> {
911        match mb.push(value)?? {
912            Delivery::Handoff(flow) => Ok(flow),
913            other => Err(format!("expected a handoff, got {}", delivery_name(&other)).into()),
914        }
915    }
916
917    fn delivery_name(d: &Delivery) -> &'static str {
918        match d {
919            Delivery::Queued => "Queued",
920            Delivery::QueuedDropOldest => "QueuedDropOldest",
921            Delivery::DroppedNewest => "DroppedNewest",
922            Delivery::Handoff(_) => "Handoff",
923        }
924    }
925
926    #[test]
927    fn a_stale_deadline_cannot_steal_a_later_wait() -> TestResult {
928        let mb = Mailbox::new();
929        let first = park_now(&mb, dummy_flow()?)?;
930        // A hop beats the deadline: the handoff ends *this* wait.
931        let woken = handoff(&mb, msg(1, 1))?;
932        // The same flow parks again on a fresh `Receive`.
933        let second = park_now(&mb, woken)?;
934        assert_ne!(first, second, "each park must get its own epoch");
935
936        // The deadline armed for the first wait fires late. Before the
937        // epoch check it took this second wait, resumed the flow, and
938        // wrote Unit into the *first* wait's register.
939        assert!(mb.take_parked_at(first)?.is_none());
940        // The live wait is untouched, so its own deadline still works.
941        assert!(mb.take_parked_at(second)?.is_some());
942        Ok(())
943    }
944
945    #[test]
946    fn a_stale_deadline_does_not_downgrade_a_selective_waiter() -> TestResult {
947        let mb = Mailbox::new();
948        let first = park_now(&mb, dummy_flow()?)?;
949        let woken = handoff(&mb, msg(1, 1))?;
950        // Second wait is selective: only tag 7 may wake it.
951        let second = match mb.park_match(woken, 7)? {
952            Ok(epoch) => epoch,
953            Err(_) => return Err("empty mailbox should have parked the flow".into()),
954        };
955        assert_ne!(first, second);
956
957        assert!(mb.take_parked_at(first)?.is_none());
958        // The filter must survive the stale call: a tag-9 hop is queued,
959        // not handed off.
960        assert!(matches!(mb.push(msg(9, 0))??, Delivery::Queued));
961        // ...and tag 7 still wakes it.
962        assert!(matches!(mb.push(msg(7, 0))??, Delivery::Handoff(_)));
963        Ok(())
964    }
965
966    #[test]
967    fn a_deadline_for_a_wait_that_a_hop_ended_does_nothing() -> TestResult {
968        let mb = Mailbox::new();
969        let epoch = park_now(&mb, dummy_flow()?)?;
970        let _woken = handoff(&mb, msg(1, 1))?;
971        // Nobody is parked now; the deadline must be a no-op rather than
972        // reporting a flow it does not have.
973        assert!(mb.take_parked_at(epoch)?.is_none());
974        Ok(())
975    }
976
977    #[test]
978    fn byte_budget_refuses_before_the_hop_count_and_says_so() -> TestResult {
979        // 64 hop slots but a 1 KiB budget: blobs exhaust bytes first.
980        let cap = MailboxCapacity::new(64).ok_or("cap")?;
981        let budget = MailboxBytes::new(MailboxBytes::MIN).ok_or("bytes")?;
982        let mb = Mailbox::with_config(
983            MailboxConfig::new(cap, OverflowPolicy::Reject).with_bytes(budget),
984        );
985        assert!(matches!(
986            mb.push(Value::bytes(vec![0u8; 900]))??,
987            Delivery::Queued
988        ));
989        match mb.push(Value::bytes(vec![0u8; 900]))? {
990            Err(full) => assert_eq!(full.reason(), MailboxFullReason::ByteLimit),
991            Ok(_) => return Err("expected the byte budget to refuse".into()),
992        }
993        let s = mb.stats()?;
994        assert_eq!(s.queued_messages, 1);
995        assert!(s.queued_bytes >= 900);
996        assert_eq!(s.rejected, 1);
997        assert_eq!(s.rejected_byte_limit, 1);
998        Ok(())
999    }
1000
1001    #[test]
1002    fn draining_a_hop_frees_its_byte_charge() -> TestResult {
1003        let cap = MailboxCapacity::new(64).ok_or("cap")?;
1004        let budget = MailboxBytes::new(MailboxBytes::MIN).ok_or("bytes")?;
1005        let mb = Mailbox::with_config(
1006            MailboxConfig::new(cap, OverflowPolicy::Reject).with_bytes(budget),
1007        );
1008        mb.push(Value::bytes(vec![0u8; 900]))??;
1009        mb.try_pop()?.ok_or("queued blob")?;
1010        assert_eq!(mb.stats()?.queued_bytes, 0);
1011        // A receiver that keeps up must not be permanently throttled by a
1012        // charge that was never refunded.
1013        assert!(matches!(
1014            mb.push(Value::bytes(vec![0u8; 900]))??,
1015            Delivery::Queued
1016        ));
1017        Ok(())
1018    }
1019
1020    #[test]
1021    fn matching_handoff_does_not_count_as_full() -> TestResult {
1022        let mb = tiny_reject(1)?;
1023        mb.push(msg(9, 0))??;
1024        let flow = dummy_flow()?;
1025        assert!(mb.park_match(flow, 1)?.is_ok());
1026        assert!(matches!(mb.push(msg(1, 7))??, Delivery::Handoff(_)));
1027        assert_eq!(hop_msg(&mb.try_pop()?.ok_or("queued")?)?.tag, 9);
1028        Ok(())
1029    }
1030
1031    #[test]
1032    fn waiting_send_admits_one_after_pop() -> TestResult {
1033        let mb = tiny_reject(1)?;
1034        assert!(matches!(mb.push(msg(1, 1))??, Delivery::Queued));
1035        assert!(matches!(
1036            mb.park_sender(dummy_flow()?, msg(1, 2)),
1037            ParkSender::Parked
1038        ));
1039        assert!(mb.try_pop()?.is_some());
1040        match mb.admit_waiting_sender()? {
1041            AdmitSender::Woken(woken) => drop(woken),
1042            AdmitSender::Idle => return Err("expected admitted sender, got Idle".into()),
1043            AdmitSender::Undeliverable(_) => {
1044                return Err("expected admitted sender, got Undeliverable".into())
1045            }
1046        }
1047        assert_eq!(
1048            hop_payload_int(hop_msg(&mb.try_pop()?.ok_or("second hop")?)?),
1049            2
1050        );
1051        assert!(matches!(mb.admit_waiting_sender()?, AdmitSender::Idle));
1052        Ok(())
1053    }
1054
1055    #[test]
1056    fn park_sender_delivers_when_a_slot_opened() -> TestResult {
1057        let mb = tiny_reject(1)?;
1058        assert!(matches!(mb.push(msg(1, 1))??, Delivery::Queued));
1059        mb.try_pop()?.ok_or("the slot must open before park")?;
1060        match mb.park_sender(dummy_flow()?, msg(1, 2)) {
1061            ParkSender::Delivered(_) => {}
1062            ParkSender::Parked => {
1063                return Err("a free inbox must deliver, not park the sender".into())
1064            }
1065            ParkSender::Closed(_) => return Err("live inbox reported Closed".into()),
1066            ParkSender::WaitersFull(_) => return Err("live inbox reported WaitersFull".into()),
1067            ParkSender::Undeliverable(_) => return Err("a fitting hop was Undeliverable".into()),
1068        }
1069        assert_eq!(
1070            hop_payload_int(hop_msg(&mb.try_pop()?.ok_or("delivered hop")?)?),
1071            2
1072        );
1073        assert!(matches!(mb.admit_waiting_sender()?, AdmitSender::Idle));
1074        Ok(())
1075    }
1076
1077    #[test]
1078    fn park_sender_reports_a_full_waiter_list() -> TestResult {
1079        let mb = tiny_reject(1)?;
1080        assert!(matches!(mb.push(msg(1, 1))??, Delivery::Queued));
1081        assert!(matches!(
1082            mb.park_sender(dummy_flow()?, msg(1, 2)),
1083            ParkSender::Parked
1084        ));
1085        match mb.park_sender(dummy_flow()?, msg(1, 3)) {
1086            ParkSender::WaitersFull(_) => {}
1087            ParkSender::Parked => return Err("the waiter list must refuse a second sender".into()),
1088            ParkSender::Delivered(_) => return Err("a full inbox must not deliver".into()),
1089            ParkSender::Closed(_) => return Err("a live inbox must not look closed".into()),
1090            ParkSender::Undeliverable(_) => return Err("a fitting hop was Undeliverable".into()),
1091        }
1092        assert_eq!(
1093            hop_payload_int(hop_msg(&mb.try_pop()?.ok_or("original hop")?)?),
1094            1
1095        );
1096        Ok(())
1097    }
1098
1099    #[test]
1100    fn close_rejects_late_park_sender() -> TestResult {
1101        let mb = tiny_reject(1)?;
1102        let leftover = mb.close()?;
1103        assert!(leftover.is_empty());
1104        match mb.park_sender(dummy_flow()?, msg(1, 1)) {
1105            ParkSender::Closed(_) => {}
1106            ParkSender::Parked => return Err("closed mailbox must not park a sender".into()),
1107            ParkSender::Delivered(_) => {
1108                return Err("closed mailbox must not accept a sender".into())
1109            }
1110            ParkSender::WaitersFull(_) => {
1111                return Err("closed mailbox should report Closed, not WaitersFull".into())
1112            }
1113            ParkSender::Undeliverable(_) => {
1114                return Err("closed mailbox should report Closed, not Undeliverable".into())
1115            }
1116        }
1117        Ok(())
1118    }
1119
1120    #[test]
1121    fn close_rejects_late_push() -> TestResult {
1122        let mb = tiny_reject(4)?;
1123        let _ = mb.close()?;
1124        match mb.push(msg(1, 1))? {
1125            Err(full) if full.reason() == MailboxFullReason::Closed => Ok(()),
1126            Err(full) => Err(format!("expected Closed, got {}", full.reason()).into()),
1127            Ok(_) => Err("closed mailbox must refuse push".into()),
1128        }
1129    }
1130
1131    #[test]
1132    fn oversized_hop_is_undeliverable_not_parked() -> TestResult {
1133        let cap = MailboxCapacity::new(8).ok_or("cap")?;
1134        let budget = MailboxBytes::new(MailboxBytes::MIN).ok_or("bytes")?;
1135        let mb = Mailbox::with_config(
1136            MailboxConfig::new(cap, OverflowPolicy::Reject).with_bytes(budget),
1137        );
1138        let huge = Value::bytes(vec![0u8; MailboxBytes::MIN + 64]);
1139        match mb.park_sender(dummy_flow()?, huge.clone()) {
1140            ParkSender::Undeliverable(_) => {}
1141            ParkSender::Parked => return Err("oversized hop must not park".into()),
1142            ParkSender::Delivered(_) => return Err("oversized hop must not be delivered".into()),
1143            ParkSender::WaitersFull(_) => {
1144                return Err("oversized hop must be Undeliverable, not WaitersFull".into())
1145            }
1146            ParkSender::Closed(_) => return Err("oversized hop must be Undeliverable".into()),
1147        }
1148        mb.push(msg(1, 1))??;
1149        mb.try_pop()?.ok_or("drain")?;
1150        // A hop that can never fit must not sit at the head of waiting_senders.
1151        match mb.admit_waiting_sender()? {
1152            AdmitSender::Idle => {}
1153            AdmitSender::Woken(_) => {
1154                return Err("expected Idle after refusing oversized hop, got Woken".into())
1155            }
1156            AdmitSender::Undeliverable(_) => {
1157                return Err("expected Idle after refusing oversized hop, got Undeliverable".into())
1158            }
1159        }
1160        let _ = huge;
1161        Ok(())
1162    }
1163
1164    #[test]
1165    fn drop_oldest_still_wakes_on_match() -> TestResult {
1166        let cap = MailboxCapacity::new(1).ok_or("cap")?;
1167        let mb = Mailbox::with_config(MailboxConfig::new(cap, OverflowPolicy::DropOldest));
1168        let flow = dummy_flow()?;
1169        assert!(mb.park_match(flow, 1)?.is_ok());
1170        mb.push(msg(9, 1))??;
1171        assert!(matches!(mb.push(msg(1, 2))??, Delivery::Handoff(_)));
1172        Ok(())
1173    }
1174}