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