Skip to main content

byteflow/scheduler/mailbox/
mod.rs

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