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