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