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