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