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