Skip to main content

byteflow/scheduler/mailbox/
mod.rs

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