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