Skip to main content

byteflow/scheduler/
host_await.rs

1//! Host ↔ flow async bridge (`Opcode::HostAwait`).
2//!
3//! The worker registers one ticket per operation and keeps running the flow.
4//! The destination register receives that ticket as `Int`. Completion is an
5//! authenticated host hop ([`crate::TAG_SYS_AWAIT`], `request_id` = ticket),
6//! the same stamp and capability reissue as [`crate::Runtime::send`]. Bytecode
7//! reads the result with `Receive`. A cap the table does not know fails the
8//! flow instead of entering the mailbox.
9//!
10//! Several tickets may be outstanding for one flow. Finalize, kill, and
11//! runtime shutdown cancel every ticket of that flow. A late `complete`
12//! finds the ticket gone and returns [`HostAwaitError::Stale`]. The host
13//! callback runs after the registry lock is released.
14//!
15//! The bridge itself must return quickly from [`HostAwaitBridge::submit`];
16//! heavy work belongs on a host thread / Tokio task outside this crate.
17
18use std::collections::HashMap;
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::{Arc, Mutex, Weak};
21
22use crate::bytecode::{Message, Value, TAG_SYS_AWAIT};
23
24use super::deterministic::{replay_label, StagedHostHop};
25use super::error::{report_fault, RuntimeError};
26use super::finalize::{extract_for_kill, finalize_flow, resume_handoff};
27use super::mailbox::{Delivery, MailboxFullReason};
28use super::monitor::FlowExitReason;
29use super::process::{Flow, FlowId, FlowOutcome};
30use super::runtime::Shared;
31use super::sync_lock;
32
33/// Opaque host discriminator passed as the `HostAwait` immediate.
34pub type HostAwaitOp = u32;
35
36/// Request handed to [`HostAwaitBridge::submit`].
37#[derive(Debug, Clone)]
38pub struct HostAwaitRequest {
39    pub flow: FlowId,
40    pub op: HostAwaitOp,
41    pub args: Value,
42}
43
44/// Host-side async completion channel (one-shot).
45///
46/// Prefer calling [`Self::complete`] / [`Self::fail`] explicitly. If the
47/// completer is dropped unused, the flow is failed closed (avoids a
48/// permanent wait when the host forgets to settle the await).
49///
50/// Holds a [`Weak`] to the runtime shared state so a bridge that retains
51/// completers cannot keep the runtime alive in a reference cycle
52/// (`Shared` → bridge → completer → `Shared`).
53pub struct HostAwaitCompleter {
54    shared: Weak<Shared>,
55    ticket: u64,
56    cancelled: Arc<AtomicBool>,
57    consumed: AtomicBool,
58}
59
60/// Errors from [`HostAwaitCompleter`].
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum HostAwaitError {
63    /// Ticket already used, flow finalized, or await cancelled.
64    Stale,
65    /// Infrastructure failure while completing.
66    Runtime(RuntimeError),
67    /// The completion value carried a capability the runtime would not grant.
68    Rejected,
69    /// The mailbox refused the completion hop. The flow is failed when it
70    /// is still alive, so a later `Receive` does not wait for a hop that
71    /// was never stored.
72    Mailbox(MailboxFullReason),
73    /// The test replay gate rejected this completion's recorded sequence.
74    Replay(&'static str),
75}
76
77impl std::fmt::Display for HostAwaitError {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        match self {
80            HostAwaitError::Stale => f.write_str("HostAwait completer is stale"),
81            HostAwaitError::Runtime(e) => write!(f, "{e}"),
82            HostAwaitError::Rejected => {
83                f.write_str("HostAwait completion refused a capability grant")
84            }
85            HostAwaitError::Mailbox(reason) => {
86                write!(f, "HostAwait mailbox refused the completion ({reason})")
87            }
88            HostAwaitError::Replay(reason) => {
89                write!(f, "host replay rejected the sequence ({reason})")
90            }
91        }
92    }
93}
94
95impl std::error::Error for HostAwaitError {}
96
97impl HostAwaitCompleter {
98    pub(crate) fn new(shared: Arc<Shared>, ticket: u64, cancelled: Arc<AtomicBool>) -> Self {
99        Self {
100            shared: Arc::downgrade(&shared),
101            ticket,
102            cancelled,
103            consumed: AtomicBool::new(false),
104        }
105    }
106
107    /// Ticket id written into the flow's destination register.
108    pub fn ticket(&self) -> u64 {
109        self.ticket
110    }
111
112    /// `true` after finalize, kill, or shutdown cancelled this operation.
113    ///
114    /// Cooperative: the host observes this or [`HostAwaitBridge::cancel`] and
115    /// aborts the I/O it owns. The flag alone does not close a socket.
116    pub fn is_cancelled(&self) -> bool {
117        self.cancelled.load(Ordering::Acquire)
118    }
119
120    /// Deliver `value` as a [`crate::TAG_SYS_AWAIT`] hop to the awaiting flow.
121    pub fn complete(self, value: Value) -> Result<(), HostAwaitError> {
122        self.finish(Ok(value))
123    }
124
125    /// Fail the flow (`FlowOutcome::Failed`).
126    pub fn fail(self, msg: impl Into<String>) -> Result<(), HostAwaitError> {
127        self.finish(Err(msg.into()))
128    }
129
130    fn finish(self, result: Result<Value, String>) -> Result<(), HostAwaitError> {
131        if self.consumed.swap(true, Ordering::SeqCst) {
132            return Err(HostAwaitError::Stale);
133        }
134        settle(&self.shared, self.ticket, result)
135    }
136}
137
138impl Drop for HostAwaitCompleter {
139    fn drop(&mut self) {
140        if self.consumed.swap(true, Ordering::SeqCst) {
141            return;
142        }
143        let _ = settle(
144            &self.shared,
145            self.ticket,
146            Err("HostAwait completer dropped".into()),
147        );
148    }
149}
150
151fn settle(
152    shared: &Weak<Shared>,
153    ticket: u64,
154    result: Result<Value, String>,
155) -> Result<(), HostAwaitError> {
156    let Some(shared) = shared.upgrade() else {
157        return Err(HostAwaitError::Stale);
158    };
159    let Some(flow_id) = shared
160        .host_awaits
161        .take_ticket(ticket)
162        .map_err(HostAwaitError::Runtime)?
163    else {
164        return Err(HostAwaitError::Stale);
165    };
166    match result {
167        Ok(value) => {
168            let raw = Message::request(ticket, TAG_SYS_AWAIT, value);
169            let stamped =
170                match super::worker::authenticate_host_outgoing_message(&shared, flow_id, raw) {
171                    Ok(message) => Value::Message(message),
172                    Err(_) => {
173                        fail_live(&shared, flow_id, "HostAwait: capability grant refused");
174                        return Err(HostAwaitError::Rejected);
175                    }
176                };
177            let ready = stage_completion(
178                &shared,
179                ticket,
180                StagedHostHop {
181                    flow: flow_id,
182                    value: stamped,
183                },
184            )?;
185            deliver_ready(&shared, ready)
186        }
187        Err(msg) => {
188            if fail_live(&shared, flow_id, &msg) {
189                Ok(())
190            } else {
191                Err(HostAwaitError::Stale)
192            }
193        }
194    }
195}
196
197/// Record `msg` and fail the flow with that text.
198///
199/// Returns `false` when the flow has already committed an outcome. A flow
200/// still on its worker keeps running only until the next result check,
201/// which reads this table before it can `return` successfully.
202fn fail_live(shared: &Shared, flow_id: FlowId, msg: &str) -> bool {
203    match shared.directory.lookup(flow_id) {
204        Ok(Some(_)) => {}
205        Ok(None) => return false,
206        Err(err) => {
207            report_fault(err);
208            return false;
209        }
210    }
211    match shared.host_await_failures.request(flow_id, msg) {
212        Ok(true) => {}
213        Ok(false) => return false,
214        Err(err) => {
215            report_fault(err);
216            return false;
217        }
218    }
219    if let Some(flow) = extract_for_kill(shared, flow_id, FlowExitReason::Fault) {
220        let text = match shared.host_await_failures.take(flow_id) {
221            Ok(Some(text)) => text,
222            _ => msg.to_string(),
223        };
224        finalize_flow(
225            shared,
226            flow,
227            FlowOutcome::Failed(text),
228            FlowExitReason::Fault,
229        );
230    }
231    true
232}
233
234/// `None` when `flow` was finalized with a pending host failure.
235pub(crate) fn park_flow_if_host_failed(shared: &Shared, flow: Box<Flow>) -> Option<Box<Flow>> {
236    match shared.host_await_failures.take(flow.id) {
237        Ok(Some(msg)) => {
238            let _ = shared.kill_signals.take(flow.id);
239            finalize_flow(
240                shared,
241                *flow,
242                FlowOutcome::Failed(msg),
243                FlowExitReason::Fault,
244            );
245            None
246        }
247        Ok(None) => Some(flow),
248        Err(err) => {
249            report_fault(err);
250            finalize_flow(
251                shared,
252                *flow,
253                FlowOutcome::Failed("HostAwait failure table unavailable".into()),
254                FlowExitReason::Fault,
255            );
256            None
257        }
258    }
259}
260
261/// Host text when a kill and a host failure name the same flow.
262pub(crate) fn message_or_kill(shared: &Shared, id: FlowId, reason: FlowExitReason) -> String {
263    match shared.host_await_failures.take(id) {
264        Ok(Some(msg)) => msg,
265        Ok(None) => super::finalize::kill_outcome_message(reason),
266        Err(err) => {
267            report_fault(err);
268            super::finalize::kill_outcome_message(reason)
269        }
270    }
271}
272
273fn stage_completion(
274    shared: &Shared,
275    ticket: u64,
276    hop: StagedHostHop,
277) -> Result<Vec<StagedHostHop>, HostAwaitError> {
278    let prepared = {
279        let mut gate = sync_lock::lock(&shared.host_replay, "HostAwait replay")
280            .map_err(HostAwaitError::Runtime)?;
281        match gate.as_mut() {
282            None => Ok(vec![hop]),
283            Some(replay) => {
284                let flow = hop.flow;
285                match replay.stage(ticket, hop) {
286                    Ok(()) => Ok(replay.drain_ready()),
287                    Err(err) => Err((flow, err)),
288                }
289            }
290        }
291    };
292    match prepared {
293        Ok(ready) => Ok(ready),
294        Err((flow, err)) => {
295            let _ = fail_live(shared, flow, "host replay rejected the sequence");
296            Err(HostAwaitError::Replay(replay_label(err)))
297        }
298    }
299}
300
301/// Deliver every hop already removed from the replay queue.
302///
303/// One refusal does not drop the rest: those flows are still waiting on
304/// `Receive`.
305pub(crate) fn deliver_ready(
306    shared: &Shared,
307    ready: Vec<StagedHostHop>,
308) -> Result<(), HostAwaitError> {
309    let mut first = None;
310    for hop in ready {
311        if let Err(err) = deliver_staged(shared, hop) {
312            if first.is_none() {
313                first = Some(err);
314            }
315        }
316    }
317    match first {
318        Some(err) => Err(err),
319        None => Ok(()),
320    }
321}
322
323/// Push one already-authenticated completion through [`crate::Runtime::send`]'s
324/// mailbox admission. A closed inbox is [`HostAwaitError::Stale`]. A full
325/// inbox fails the live flow and returns [`HostAwaitError::Mailbox`].
326pub(crate) fn deliver_staged(shared: &Shared, hop: StagedHostHop) -> Result<(), HostAwaitError> {
327    let mailbox = match shared.directory.lookup(hop.flow) {
328        Ok(Some(mailbox)) => mailbox,
329        Ok(None) => return Err(HostAwaitError::Stale),
330        Err(err) => return Err(HostAwaitError::Runtime(err)),
331    };
332    let flow_id = hop.flow;
333    match mailbox.push(hop.value.clone()) {
334        Ok(Ok(Delivery::Handoff(parked))) => {
335            resume_handoff(shared, parked, hop.value);
336            Ok(())
337        }
338        Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest)) => Ok(()),
339        Ok(Ok(Delivery::DroppedNewest)) => {
340            let _ = fail_live(shared, flow_id, "HostAwait mailbox dropped the completion");
341            Err(HostAwaitError::Mailbox(MailboxFullReason::MessageLimit))
342        }
343        Ok(Err(full)) if full.reason() == MailboxFullReason::Closed => Err(HostAwaitError::Stale),
344        Ok(Err(full)) => {
345            let reason = full.reason();
346            let _ = fail_live(shared, flow_id, "HostAwait mailbox refused the completion");
347            Err(HostAwaitError::Mailbox(reason))
348        }
349        Err(err) => Err(HostAwaitError::Runtime(err)),
350    }
351}
352
353/// Embedder hook: schedule host work for [`Opcode::HostAwait`](crate::Opcode::HostAwait).
354///
355/// `submit` must return promptly. Spawn a thread / enqueue a task for I/O.
356pub trait HostAwaitBridge: Send + Sync + std::fmt::Debug + 'static {
357    fn submit(&self, req: HostAwaitRequest, done: HostAwaitCompleter);
358
359    /// The flow was finalized or the runtime is shutting down.
360    ///
361    /// Called without the registry lock. Must return quickly and must not
362    /// take a lock the finalizer already holds. Aborting the socket or
363    /// future is the host's job; [`HostAwaitCompleter::is_cancelled`] is
364    /// already set. The default body does nothing.
365    fn cancel(&self, _flow: FlowId, _op: HostAwaitOp, _ticket: u64) {}
366}
367
368/// Tell the bridge about tickets removed by finalize, kill, or shutdown.
369pub(crate) fn notify_cancelled(shared: &Shared, notices: Vec<CancelledAwait>) {
370    let Some(bridge) = shared.host_await_bridge.as_ref() else {
371        return;
372    };
373    for notice in notices {
374        bridge.cancel(notice.flow, notice.op, notice.ticket);
375    }
376}
377
378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
379pub(crate) enum HostAwaitParkError {
380    LimitReached { current: usize, max: usize },
381    IdExhausted,
382}
383
384impl std::fmt::Display for HostAwaitParkError {
385    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386        match self {
387            HostAwaitParkError::LimitReached { current, max } => {
388                write!(f, "HostAwait limit reached ({current}/{max})")
389            }
390            HostAwaitParkError::IdExhausted => f.write_str("HostAwait ticket ids exhausted"),
391        }
392    }
393}
394
395pub(crate) struct RegisteredAwait {
396    pub id: u64,
397    pub cancelled: Arc<AtomicBool>,
398}
399
400pub(crate) struct CancelledAwait {
401    pub flow: FlowId,
402    pub op: HostAwaitOp,
403    pub ticket: u64,
404}
405
406struct AwaitEntry {
407    flow: FlowId,
408    op: HostAwaitOp,
409    cancelled: Arc<AtomicBool>,
410}
411
412/// Host `fail` text observed by the worker before a successful `return`.
413///
414/// `settled` is the commit bit: once the worker has chosen an outcome, a
415/// later `fail` is too late and does not invent a second one.
416pub(crate) struct HostAwaitFailures {
417    inner: Mutex<HashMap<FlowId, FailSlot>>,
418}
419
420#[derive(Default)]
421struct FailSlot {
422    message: Option<String>,
423    settled: bool,
424}
425
426impl HostAwaitFailures {
427    pub(crate) fn new() -> Self {
428        Self {
429            inner: Mutex::new(HashMap::new()),
430        }
431    }
432
433    /// `Ok(true)` stores `msg` for the worker. `Ok(false)` means the flow
434    /// already committed an outcome.
435    pub(crate) fn request(&self, id: FlowId, msg: &str) -> Result<bool, RuntimeError> {
436        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::request")?;
437        let slot = slots.entry(id).or_default();
438        if slot.settled {
439            return Ok(false);
440        }
441        if slot.message.is_none() {
442            slot.message = Some(msg.to_string());
443        }
444        Ok(true)
445    }
446
447    pub(crate) fn take(&self, id: FlowId) -> Result<Option<String>, RuntimeError> {
448        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::take")?;
449        let Some(slot) = slots.get_mut(&id) else {
450            return Ok(None);
451        };
452        let message = slot.message.take();
453        if message.is_none() && !slot.settled {
454            slots.remove(&id);
455        }
456        Ok(message)
457    }
458
459    /// Mark a successful outcome. `Some` is a host failure that won the race
460    /// and must replace that success.
461    pub(crate) fn commit_success(&self, id: FlowId) -> Result<Option<String>, RuntimeError> {
462        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::commit_success")?;
463        let slot = slots.entry(id).or_default();
464        slot.settled = true;
465        Ok(slot.message.take())
466    }
467
468    pub(crate) fn seal(&self, id: FlowId) -> Result<(), RuntimeError> {
469        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::seal")?;
470        let slot = slots.entry(id).or_default();
471        slot.settled = true;
472        slot.message = None;
473        Ok(())
474    }
475
476    pub(crate) fn clear(&self, id: FlowId) -> Result<(), RuntimeError> {
477        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::clear")?;
478        slots.remove(&id);
479        Ok(())
480    }
481}
482
483/// Process-wide table of in-flight `HostAwait` tickets.
484///
485/// The flow itself stays on a worker or in its mailbox. This table only
486/// records the ticket so completion and cancellation compete for one removal.
487pub struct HostAwaitIndex {
488    inner: Mutex<HostAwaitInner>,
489    max: usize,
490}
491
492struct HostAwaitInner {
493    by_ticket: HashMap<u64, AwaitEntry>,
494    by_flow: HashMap<FlowId, Vec<u64>>,
495    next_ticket: u64,
496}
497
498impl HostAwaitIndex {
499    /// `max_host_awaits == 0` → unlimited.
500    pub fn new(max_host_awaits: u32) -> Self {
501        Self::with_next(max_host_awaits, 1)
502    }
503
504    fn with_next(max_host_awaits: u32, next_ticket: u64) -> Self {
505        Self {
506            inner: Mutex::new(HostAwaitInner {
507                by_ticket: HashMap::new(),
508                by_flow: HashMap::new(),
509                next_ticket,
510            }),
511            max: max_host_awaits as usize,
512        }
513    }
514
515    pub fn register(
516        &self,
517        flow: FlowId,
518        op: HostAwaitOp,
519    ) -> Result<Result<RegisteredAwait, HostAwaitParkError>, RuntimeError> {
520        let mut entries = sync_lock::lock(&self.inner, "HostAwaitIndex::register")?;
521        if self.max != 0 && entries.by_ticket.len() >= self.max {
522            return Ok(Err(HostAwaitParkError::LimitReached {
523                current: entries.by_ticket.len(),
524                max: self.max,
525            }));
526        }
527        if entries.next_ticket == 0 || entries.next_ticket >= i64::MAX as u64 {
528            return Ok(Err(HostAwaitParkError::IdExhausted));
529        }
530        let id = entries.next_ticket;
531        entries.next_ticket += 1;
532        let cancelled = Arc::new(AtomicBool::new(false));
533        entries.by_flow.entry(flow).or_default().push(id);
534        entries.by_ticket.insert(
535            id,
536            AwaitEntry {
537                flow,
538                op,
539                cancelled: Arc::clone(&cancelled),
540            },
541        );
542        Ok(Ok(RegisteredAwait { id, cancelled }))
543    }
544
545    /// Removes the ticket once. `None` means it was already completed or cancelled.
546    pub fn take_ticket(&self, ticket: u64) -> Result<Option<FlowId>, RuntimeError> {
547        let mut entries = sync_lock::lock(&self.inner, "HostAwaitIndex::take_ticket")?;
548        let Some(entry) = entries.by_ticket.remove(&ticket) else {
549            return Ok(None);
550        };
551        unlink(&mut entries, entry.flow, ticket);
552        if entry.cancelled.load(Ordering::Acquire) {
553            return Ok(None);
554        }
555        Ok(Some(entry.flow))
556    }
557
558    /// Cancels every ticket of `flow`. The caller notifies the host after
559    /// this returns, so the bridge does not run under the registry lock.
560    pub fn cancel_flow(&self, flow: FlowId) -> Result<Vec<CancelledAwait>, RuntimeError> {
561        let mut entries = sync_lock::lock(&self.inner, "HostAwaitIndex::cancel_flow")?;
562        Ok(take_flow_ids(&mut entries, flow))
563    }
564
565    /// Cancels every outstanding ticket (runtime shutdown).
566    pub(crate) fn cancel_all(&self) -> Result<Vec<CancelledAwait>, RuntimeError> {
567        let mut entries = sync_lock::lock(&self.inner, "HostAwaitIndex::cancel_all")?;
568        entries.by_flow.clear();
569        let mut notices = Vec::with_capacity(entries.by_ticket.len());
570        for (ticket, entry) in entries.by_ticket.drain() {
571            entry.cancelled.store(true, Ordering::Release);
572            notices.push(CancelledAwait {
573                flow: entry.flow,
574                op: entry.op,
575                ticket,
576            });
577        }
578        Ok(notices)
579    }
580
581    #[cfg(test)]
582    pub fn outstanding(&self) -> Result<usize, RuntimeError> {
583        let entries = sync_lock::lock(&self.inner, "HostAwaitIndex::outstanding")?;
584        Ok(entries.by_ticket.len())
585    }
586}
587
588fn unlink(entries: &mut HostAwaitInner, flow: FlowId, ticket: u64) {
589    let Some(ids) = entries.by_flow.get_mut(&flow) else {
590        return;
591    };
592    ids.retain(|id| *id != ticket);
593    if ids.is_empty() {
594        entries.by_flow.remove(&flow);
595    }
596}
597
598fn take_flow_ids(entries: &mut HostAwaitInner, flow: FlowId) -> Vec<CancelledAwait> {
599    let Some(ids) = entries.by_flow.remove(&flow) else {
600        return Vec::new();
601    };
602    let mut notices = Vec::with_capacity(ids.len());
603    for ticket in ids {
604        if let Some(entry) = entries.by_ticket.remove(&ticket) {
605            entry.cancelled.store(true, Ordering::Release);
606            notices.push(CancelledAwait {
607                flow,
608                op: entry.op,
609                ticket,
610            });
611        }
612    }
613    notices
614}
615
616#[cfg(test)]
617mod tests {
618    use super::*;
619
620    #[test]
621    fn allows_multiple_operations_for_one_flow() -> Result<(), Box<dyn std::error::Error>> {
622        let index = HostAwaitIndex::new(0);
623        let first = registered(&index, FlowId(7), 1)?;
624        let second = registered(&index, FlowId(7), 2)?;
625
626        assert_ne!(first.id, second.id);
627        assert!(!first.cancelled.load(Ordering::Acquire));
628        assert!(!second.cancelled.load(Ordering::Acquire));
629        assert_eq!(index.outstanding()?, 2);
630
631        assert_eq!(index.take_ticket(first.id)?, Some(FlowId(7)));
632        assert_eq!(index.take_ticket(second.id)?, Some(FlowId(7)));
633        assert_eq!(index.outstanding()?, 0);
634        Ok(())
635    }
636
637    #[test]
638    fn cancel_flow_invalidates_all_its_operations() -> Result<(), Box<dyn std::error::Error>> {
639        let index = HostAwaitIndex::new(0);
640        let left = registered(&index, FlowId(10), 1)?;
641        let right = registered(&index, FlowId(10), 2)?;
642        let other = registered(&index, FlowId(20), 1)?;
643
644        let notices = index.cancel_flow(FlowId(10))?;
645        assert_eq!(notices.len(), 2);
646        assert!(left.cancelled.load(Ordering::Acquire));
647        assert!(right.cancelled.load(Ordering::Acquire));
648        assert!(!other.cancelled.load(Ordering::Acquire));
649
650        assert_eq!(index.take_ticket(left.id)?, None);
651        assert_eq!(index.take_ticket(right.id)?, None);
652        assert_eq!(index.take_ticket(other.id)?, Some(FlowId(20)));
653        assert_eq!(index.outstanding()?, 0);
654        Ok(())
655    }
656
657    #[test]
658    fn completion_is_consumed_only_once() -> Result<(), Box<dyn std::error::Error>> {
659        let index = HostAwaitIndex::new(0);
660        let registered = registered(&index, FlowId(42), 1)?;
661
662        assert_eq!(index.take_ticket(registered.id)?, Some(FlowId(42)));
663        assert_eq!(index.take_ticket(registered.id)?, None);
664        Ok(())
665    }
666
667    #[test]
668    fn shutdown_cancels_all_operations() -> Result<(), Box<dyn std::error::Error>> {
669        let index = HostAwaitIndex::new(0);
670        let left = registered(&index, FlowId(1), 1)?;
671        let right = registered(&index, FlowId(2), 1)?;
672
673        assert_eq!(index.cancel_all()?.len(), 2);
674        assert!(left.cancelled.load(Ordering::Acquire));
675        assert!(right.cancelled.load(Ordering::Acquire));
676        assert_eq!(index.take_ticket(left.id)?, None);
677        assert_eq!(index.take_ticket(right.id)?, None);
678        assert_eq!(index.outstanding()?, 0);
679        Ok(())
680    }
681
682    #[test]
683    fn register_hits_process_limit() -> Result<(), Box<dyn std::error::Error>> {
684        let index = HostAwaitIndex::new(1);
685        let _first = registered(&index, FlowId(1), 1)?;
686        match index.register(FlowId(2), 1)? {
687            Err(HostAwaitParkError::LimitReached { current: 1, max: 1 }) => Ok(()),
688            Ok(_) => Err("expected limit".into()),
689            Err(err) => Err(format!("wrong park error: {err}").into()),
690        }
691    }
692
693    #[test]
694    fn slot_is_free_after_take() -> Result<(), Box<dyn std::error::Error>> {
695        let index = HostAwaitIndex::new(1);
696        let first = registered(&index, FlowId(1), 1)?;
697        assert!(index.take_ticket(first.id)?.is_some());
698        let _second = registered(&index, FlowId(2), 1)?;
699        Ok(())
700    }
701
702    #[test]
703    fn commit_keeps_a_fail_that_arrives_after_the_poll() -> Result<(), RuntimeError> {
704        let failures = HostAwaitFailures::new();
705        assert!(failures.take(FlowId(1))?.is_none());
706        assert!(failures.request(FlowId(1), "host boom")?);
707        assert_eq!(
708            failures.commit_success(FlowId(1))?.as_deref(),
709            Some("host boom")
710        );
711        Ok(())
712    }
713
714    #[test]
715    fn request_after_commit_is_too_late() -> Result<(), RuntimeError> {
716        let failures = HostAwaitFailures::new();
717        assert!(failures.commit_success(FlowId(1))?.is_none());
718        assert!(!failures.request(FlowId(1), "late")?);
719        Ok(())
720    }
721
722    #[test]
723    fn ticket_ids_stop_before_i64_max() -> Result<(), Box<dyn std::error::Error>> {
724        let index = HostAwaitIndex::with_next(0, i64::MAX as u64);
725        match index.register(FlowId(1), 1)? {
726            Err(HostAwaitParkError::IdExhausted) => Ok(()),
727            Ok(_) => Err("expected exhausted ids".into()),
728            Err(err) => Err(format!("wrong park error: {err}").into()),
729        }
730    }
731
732    #[test]
733    fn complete_and_cancel_remove_the_ticket_once() -> Result<(), Box<dyn std::error::Error>> {
734        let index = Arc::new(HostAwaitIndex::new(0));
735        let registered = registered(&index, FlowId(3), 9)?;
736        let ticket = registered.id;
737        let taker = Arc::clone(&index);
738        let canceller = Arc::clone(&index);
739        let took = std::thread::spawn(move || taker.take_ticket(ticket));
740        let cancelled = std::thread::spawn(move || canceller.cancel_flow(FlowId(3)));
741        let took = match took.join() {
742            Ok(result) => result?,
743            Err(_) => return Err("take join".into()),
744        };
745        let cancelled = match cancelled.join() {
746            Ok(result) => result?,
747            Err(_) => return Err("cancel join".into()),
748        };
749        let won_take = took.is_some();
750        let won_cancel = !cancelled.is_empty();
751        assert!(won_take ^ won_cancel, "take={won_take} cancel={won_cancel}");
752        assert_eq!(index.outstanding()?, 0);
753        if won_cancel {
754            assert!(registered.cancelled.load(Ordering::Acquire));
755        }
756        Ok(())
757    }
758
759    fn registered(
760        index: &HostAwaitIndex,
761        flow: FlowId,
762        op: HostAwaitOp,
763    ) -> Result<RegisteredAwait, Box<dyn std::error::Error>> {
764        match index.register(flow, op)? {
765            Ok(registered) => Ok(registered),
766            Err(err) => Err(err.to_string().into()),
767        }
768    }
769}
770
771/// Runtime-level HostAwait coverage (bridge wiring, limits, lifecycle).
772#[cfg(test)]
773mod runtime_tests {
774    use super::*;
775    use crate::bytecode::{CapId, Message, Program};
776    use crate::scheduler::mailbox::{MailboxCapacity, MailboxConfig, OverflowPolicy};
777    use crate::scheduler::process::FlowOutcome;
778    use crate::scheduler::runtime::{Runtime, RuntimeConfig};
779    use std::sync::{Arc, Condvar, Mutex};
780    use std::time::Duration;
781
782    /// Causal hold: waits until `n` submits arrived (no sleep races).
783    struct HoldBridge {
784        state: Mutex<HoldState>,
785        cv: Condvar,
786    }
787
788    struct HoldState {
789        held: Vec<(FlowId, HostAwaitCompleter)>,
790        submitted: usize,
791    }
792
793    impl HoldBridge {
794        fn new() -> Self {
795            Self {
796                state: Mutex::new(HoldState {
797                    held: Vec::new(),
798                    submitted: 0,
799                }),
800                cv: Condvar::new(),
801            }
802        }
803
804        fn wait_for_submissions(&self, n: usize) -> Result<(), &'static str> {
805            let mut guard = match self.state.lock() {
806                Ok(guard) => guard,
807                Err(_) => return Err("HoldBridge lock"),
808            };
809            while guard.submitted < n {
810                guard = match self.cv.wait(guard) {
811                    Ok(guard) => guard,
812                    Err(_) => return Err("HoldBridge wait"),
813                };
814            }
815            Ok(())
816        }
817
818        fn take_all(&self) -> Result<Vec<(FlowId, HostAwaitCompleter)>, &'static str> {
819            let mut guard = match self.state.lock() {
820                Ok(guard) => guard,
821                Err(_) => return Err("HoldBridge lock"),
822            };
823            Ok(std::mem::take(&mut guard.held))
824        }
825
826        fn take_one(&self) -> Result<Option<(FlowId, HostAwaitCompleter)>, &'static str> {
827            let mut guard = match self.state.lock() {
828                Ok(guard) => guard,
829                Err(_) => return Err("HoldBridge lock"),
830            };
831            if guard.held.is_empty() {
832                Ok(None)
833            } else {
834                Ok(Some(guard.held.remove(0)))
835            }
836        }
837    }
838
839    impl std::fmt::Debug for HoldBridge {
840        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
841            f.write_str("HoldBridge")
842        }
843    }
844
845    impl HostAwaitBridge for HoldBridge {
846        fn submit(&self, req: HostAwaitRequest, done: HostAwaitCompleter) {
847            match self.state.lock() {
848                Ok(mut guard) => {
849                    guard.held.push((req.flow, done));
850                    guard.submitted += 1;
851                    self.cv.notify_all();
852                }
853                Err(_) => {
854                    let _ = done.fail("HoldBridge lock poisoned");
855                }
856            }
857        }
858    }
859
860    fn waiter_program() -> (Program, u32) {
861        let mut program = Program::new("ha-waiter");
862        let waiter = program.function("waiter", 0, |f| {
863            let args = f.load_i32(0);
864            let _ticket = f.host_await(1, args);
865            let msg = f.receive();
866            f.return_(msg);
867        });
868        (program, waiter)
869    }
870
871    fn payload_int(outcome: &FlowOutcome) -> Option<i64> {
872        match outcome {
873            FlowOutcome::Completed(Value::Message(msg)) => match msg.payload.as_ref() {
874                Value::Int(n) => Some(*n),
875                _ => None,
876            },
877            _ => None,
878        }
879    }
880
881    #[test]
882    fn host_await_without_bridge_fails() -> Result<(), Box<dyn std::error::Error>> {
883        let mut program = Program::new("ha-none");
884        program.function("main", 0, |f| {
885            let args = f.load_i32(1);
886            let out = f.host_await(1, args);
887            f.return_(out);
888        });
889        let rt = Runtime::with_config(
890            program.build(),
891            RuntimeConfig {
892                workers: 1,
893                quantum: 1_000,
894                mailbox: MailboxConfig::DEFAULT,
895                host_await: None,
896                ..Default::default()
897            },
898        )?;
899        let outcome = rt.spawn(0, &[])?.join();
900        rt.shutdown();
901        match outcome {
902            FlowOutcome::Failed(msg) if msg.contains("no bridge") => Ok(()),
903            other => Err(format!("expected no-bridge failure, got {other:?}").into()),
904        }
905    }
906
907    #[test]
908    fn host_await_thread_bridge_delivers_a_hop() -> Result<(), Box<dyn std::error::Error>> {
909        #[derive(Debug)]
910        struct EchoBridge;
911
912        impl HostAwaitBridge for EchoBridge {
913            fn submit(&self, req: HostAwaitRequest, done: HostAwaitCompleter) {
914                std::thread::spawn(move || {
915                    let value = match (req.op, &req.args) {
916                        (1, Value::Int(n)) => Value::Int(n + 1),
917                        _ => Value::Int(42),
918                    };
919                    let _ = done.complete(value);
920                });
921            }
922        }
923
924        let mut program = Program::new("ha-echo");
925        program.function("main", 0, |f| {
926            let args = f.load_i32(41);
927            let _ticket = f.host_await(1, args);
928            let msg = f.receive();
929            f.return_(msg);
930        });
931        let rt = Runtime::with_config(
932            program.build(),
933            RuntimeConfig {
934                workers: 1,
935                quantum: 1_000,
936                mailbox: MailboxConfig::DEFAULT,
937                host_await: Some(Arc::new(EchoBridge)),
938                ..Default::default()
939            },
940        )?;
941        let outcome = rt
942            .spawn(0, &[])?
943            .join_timeout(Duration::from_secs(2))
944            .ok_or("host_await timed out")?;
945        rt.shutdown();
946        match &outcome {
947            FlowOutcome::Completed(Value::Message(msg))
948                if msg.sender == FlowId::HOST.as_u64()
949                    && msg.reply_cap.is_none()
950                    && msg.tag == TAG_SYS_AWAIT
951                    && matches!(msg.payload.as_ref(), Value::Int(42)) =>
952            {
953                Ok(())
954            }
955            other => Err(format!("expected await hop 42, got {other:?}").into()),
956        }
957    }
958
959    #[test]
960    fn host_await_limit_rejects_second() -> Result<(), Box<dyn std::error::Error>> {
961        let bridge = Arc::new(HoldBridge::new());
962        let (program, waiter) = waiter_program();
963        let rt = Runtime::with_config(
964            program.build(),
965            RuntimeConfig {
966                workers: 2,
967                quantum: 1_000,
968                mailbox: MailboxConfig::DEFAULT,
969                max_host_awaits: 1,
970                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
971                ..Default::default()
972            },
973        )?;
974
975        let first = rt.spawn(waiter, &[])?;
976        bridge.wait_for_submissions(1)?;
977        let second = rt.spawn(waiter, &[])?;
978        let second_out = second
979            .join_timeout(Duration::from_secs(2))
980            .ok_or("second HostAwait did not finish")?;
981
982        for (_, done) in bridge.take_all()? {
983            let _ = done.complete(Value::Int(0));
984        }
985        let _ = first.join_timeout(Duration::from_secs(2));
986        rt.shutdown();
987
988        match second_out {
989            FlowOutcome::Failed(msg) if msg.contains("HostAwait limit") => Ok(()),
990            other => Err(format!("expected HostAwait limit failure, got {other:?}").into()),
991        }
992    }
993
994    #[test]
995    fn host_await_slot_reused_after_complete() -> Result<(), Box<dyn std::error::Error>> {
996        let bridge = Arc::new(HoldBridge::new());
997        let (program, waiter) = waiter_program();
998        let rt = Runtime::with_config(
999            program.build(),
1000            RuntimeConfig {
1001                workers: 2,
1002                quantum: 1_000,
1003                mailbox: MailboxConfig::DEFAULT,
1004                max_host_awaits: 1,
1005                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1006                ..Default::default()
1007            },
1008        )?;
1009
1010        let first = rt.spawn(waiter, &[])?;
1011        bridge.wait_for_submissions(1)?;
1012        let second = rt.spawn(waiter, &[])?;
1013        let second_out = second
1014            .join_timeout(Duration::from_secs(2))
1015            .ok_or("second should fail on limit")?;
1016        assert!(
1017            matches!(
1018                &second_out,
1019                FlowOutcome::Failed(msg) if msg.contains("HostAwait limit")
1020            ),
1021            "got {second_out:?}"
1022        );
1023
1024        let (_, done) = bridge.take_one()?.ok_or("missing first completer")?;
1025        done.complete(Value::Int(7))?;
1026        let first_out = first
1027            .join_timeout(Duration::from_secs(2))
1028            .ok_or("first hop timed out")?;
1029        assert_eq!(payload_int(&first_out), Some(7), "got {first_out:?}");
1030
1031        let third = rt.spawn(waiter, &[])?;
1032        bridge.wait_for_submissions(2)?;
1033        let (_, done3) = bridge.take_one()?.ok_or("missing third completer")?;
1034        done3.complete(Value::Int(9))?;
1035        let third_out = third
1036            .join_timeout(Duration::from_secs(2))
1037            .ok_or("third hop timed out")?;
1038        rt.shutdown();
1039
1040        match payload_int(&third_out) {
1041            Some(9) => Ok(()),
1042            _ => Err(format!("expected slot reuse hop, got {third_out:?}").into()),
1043        }
1044    }
1045
1046    #[test]
1047    fn host_await_max_zero_allows_concurrent() -> Result<(), Box<dyn std::error::Error>> {
1048        let bridge = Arc::new(HoldBridge::new());
1049        let (program, waiter) = waiter_program();
1050        let rt = Runtime::with_config(
1051            program.build(),
1052            RuntimeConfig {
1053                workers: 2,
1054                quantum: 1_000,
1055                mailbox: MailboxConfig::DEFAULT,
1056                max_host_awaits: 0,
1057                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1058                ..Default::default()
1059            },
1060        )?;
1061
1062        let a = rt.spawn(waiter, &[])?;
1063        let b = rt.spawn(waiter, &[])?;
1064        bridge.wait_for_submissions(2)?;
1065        for (_, done) in bridge.take_all()? {
1066            let _ = done.complete(Value::Int(1));
1067        }
1068        let a_out = a
1069            .join_timeout(Duration::from_secs(2))
1070            .ok_or("a timed out")?;
1071        let b_out = b
1072            .join_timeout(Duration::from_secs(2))
1073            .ok_or("b timed out")?;
1074        rt.shutdown();
1075
1076        match (payload_int(&a_out), payload_int(&b_out)) {
1077            (Some(1), Some(1)) => Ok(()),
1078            _ => Err(format!("expected both hops, got {a_out:?} {b_out:?}").into()),
1079        }
1080    }
1081
1082    #[test]
1083    fn two_awaits_on_one_flow_both_deliver() -> Result<(), Box<dyn std::error::Error>> {
1084        let bridge = Arc::new(HoldBridge::new());
1085        let mut program = Program::new("ha-two");
1086        program.function("main", 0, |f| {
1087            let left = f.load_i32(11);
1088            let right = f.load_i32(22);
1089            let _first = f.host_await(1, left);
1090            let _second = f.host_await(2, right);
1091            let first = f.receive();
1092            let _second_msg = f.receive();
1093            f.return_(first);
1094        });
1095        let rt = Runtime::with_config(
1096            program.build(),
1097            RuntimeConfig {
1098                workers: 1,
1099                quantum: 1_000,
1100                mailbox: MailboxConfig::DEFAULT,
1101                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1102                ..Default::default()
1103            },
1104        )?;
1105        let handle = rt.spawn(0, &[])?;
1106        bridge.wait_for_submissions(2)?;
1107        let mut held = bridge.take_all()?;
1108        assert_eq!(held.len(), 2);
1109        let (_, second) = held.pop().ok_or("second completer")?;
1110        let (_, first) = held.pop().ok_or("first completer")?;
1111        assert_ne!(first.ticket(), second.ticket());
1112        first.complete(Value::Int(11))?;
1113        second.complete(Value::Int(22))?;
1114        let outcome = handle
1115            .join_timeout(Duration::from_secs(2))
1116            .ok_or("two-await timed out")?;
1117        rt.shutdown();
1118        match payload_int(&outcome) {
1119            Some(11) => Ok(()),
1120            _ => Err(format!("expected first hop 11, got {outcome:?}").into()),
1121        }
1122    }
1123
1124    #[test]
1125    fn replay_delivers_completions_in_script_order() -> Result<(), Box<dyn std::error::Error>> {
1126        let bridge = Arc::new(HoldBridge::new());
1127        let mut program = Program::new("ha-replay");
1128        program.function("main", 0, |f| {
1129            let left = f.load_i32(11);
1130            let right = f.load_i32(22);
1131            let _first = f.host_await(1, left);
1132            let _second = f.host_await(2, right);
1133            let first = f.receive();
1134            let _second_msg = f.receive();
1135            f.return_(first);
1136        });
1137        let rt = Runtime::with_config(
1138            program.build(),
1139            RuntimeConfig {
1140                workers: 1,
1141                quantum: 1_000,
1142                mailbox: MailboxConfig::DEFAULT,
1143                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1144                ..Default::default()
1145            },
1146        )?;
1147        rt.enable_host_await_replay()?;
1148        let handle = rt.spawn(0, &[])?;
1149        bridge.wait_for_submissions(2)?;
1150        let mut held = bridge.take_all()?;
1151        let (_, second) = held.pop().ok_or("second completer")?;
1152        let (_, first) = held.pop().ok_or("first completer")?;
1153        rt.bind_host_await_replay(first.ticket(), 1)?;
1154        rt.bind_host_await_replay(second.ticket(), 0)?;
1155        first.complete(Value::Int(11))?;
1156        second.complete(Value::Int(22))?;
1157        let outcome = handle
1158            .join_timeout(Duration::from_secs(2))
1159            .ok_or("replay timed out")?;
1160        rt.shutdown();
1161        match payload_int(&outcome) {
1162            Some(22) => Ok(()),
1163            _ => Err(format!("expected script order 22 then 11, got {outcome:?}").into()),
1164        }
1165    }
1166
1167    #[test]
1168    fn kill_parked_host_await_then_complete_is_stale() -> Result<(), Box<dyn std::error::Error>> {
1169        let bridge = Arc::new(HoldBridge::new());
1170        let (program, waiter) = waiter_program();
1171        let rt = Runtime::with_config(
1172            program.build(),
1173            RuntimeConfig {
1174                workers: 1,
1175                quantum: 1_000,
1176                mailbox: MailboxConfig::DEFAULT,
1177                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1178                ..Default::default()
1179            },
1180        )?;
1181
1182        let handle = rt.spawn(waiter, &[])?;
1183        bridge.wait_for_submissions(1)?;
1184        let (flow_id, done) = bridge.take_one()?.ok_or("missing completer")?;
1185        assert_eq!(flow_id, handle.id());
1186        rt.kill(handle.id())?;
1187        let outcome = handle
1188            .join_timeout(Duration::from_secs(2))
1189            .ok_or("kill join timed out")?;
1190        assert!(
1191            matches!(outcome, FlowOutcome::Failed(_)),
1192            "kill must fail joiner, got {outcome:?}"
1193        );
1194        assert!(done.is_cancelled());
1195        let stale = done.complete(Value::Int(1));
1196        rt.shutdown();
1197        match stale {
1198            Err(HostAwaitError::Stale) => Ok(()),
1199            other => Err(format!("expected Stale after kill, got {other:?}").into()),
1200        }
1201    }
1202
1203    #[test]
1204    fn shutdown_with_parked_host_await_does_not_hang() -> Result<(), Box<dyn std::error::Error>> {
1205        let bridge = Arc::new(HoldBridge::new());
1206        let (program, waiter) = waiter_program();
1207        let rt = Runtime::with_config(
1208            program.build(),
1209            RuntimeConfig {
1210                workers: 1,
1211                quantum: 1_000,
1212                mailbox: MailboxConfig::DEFAULT,
1213                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1214                ..Default::default()
1215            },
1216        )?;
1217
1218        let handle = rt.spawn(waiter, &[])?;
1219        bridge.wait_for_submissions(1)?;
1220        rt.shutdown();
1221        let outcome = handle
1222            .join_timeout(Duration::from_secs(2))
1223            .ok_or("joiner stuck after shutdown")?;
1224        for (_, done) in bridge.take_all()? {
1225            assert!(done.is_cancelled());
1226            assert!(matches!(
1227                done.complete(Value::Int(1)),
1228                Err(HostAwaitError::Stale)
1229            ));
1230        }
1231        match outcome {
1232            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
1233            other => Err(format!("expected shutdown failure, got {other:?}").into()),
1234        }
1235    }
1236
1237    #[test]
1238    fn unknown_cap_in_completion_rejects_and_fails_the_flow(
1239    ) -> Result<(), Box<dyn std::error::Error>> {
1240        let bridge = Arc::new(HoldBridge::new());
1241        let (program, waiter) = waiter_program();
1242        let rt = Runtime::with_config(
1243            program.build(),
1244            RuntimeConfig {
1245                workers: 1,
1246                quantum: 1_000,
1247                mailbox: MailboxConfig::DEFAULT,
1248                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1249                ..Default::default()
1250            },
1251        )?;
1252        let handle = rt.spawn(waiter, &[])?;
1253        bridge.wait_for_submissions(1)?;
1254        let (_, done) = bridge.take_one()?.ok_or("missing completer")?;
1255        let rejected = done.complete(Value::Cap(CapId::from_raw(1)));
1256        let outcome = handle
1257            .join_timeout(Duration::from_secs(2))
1258            .ok_or("cap rejection timed out")?;
1259        rt.shutdown();
1260        match rejected {
1261            Err(HostAwaitError::Rejected) => {}
1262            other => return Err(format!("expected Rejected, got {other:?}").into()),
1263        }
1264        match outcome {
1265            FlowOutcome::Failed(msg) if msg.contains("capability") => Ok(()),
1266            other => Err(format!("expected capability failure, got {other:?}").into()),
1267        }
1268    }
1269
1270    #[test]
1271    fn fail_during_submit_uses_the_host_message() -> Result<(), Box<dyn std::error::Error>> {
1272        #[derive(Debug)]
1273        struct Boom;
1274        impl HostAwaitBridge for Boom {
1275            fn submit(&self, _req: HostAwaitRequest, done: HostAwaitCompleter) {
1276                let _ = done.fail("host boom");
1277            }
1278        }
1279        let mut program = Program::new("ha-boom");
1280        program.function("main", 0, |f| {
1281            let args = f.load_i32(1);
1282            let _ticket = f.host_await(1, args);
1283            f.return_(args);
1284        });
1285        let rt = Runtime::with_config(
1286            program.build(),
1287            RuntimeConfig {
1288                workers: 1,
1289                quantum: 1_000,
1290                mailbox: MailboxConfig::DEFAULT,
1291                host_await: Some(Arc::new(Boom)),
1292                ..Default::default()
1293            },
1294        )?;
1295        let outcome = rt
1296            .spawn(0, &[])?
1297            .join_timeout(Duration::from_secs(2))
1298            .ok_or("fail join timed out")?;
1299        rt.shutdown();
1300        match outcome {
1301            FlowOutcome::Failed(msg) if msg.contains("host boom") => Ok(()),
1302            other => Err(format!("expected host boom, got {other:?}").into()),
1303        }
1304    }
1305
1306    #[test]
1307    fn fail_after_the_flow_commits_is_stale() -> Result<(), Box<dyn std::error::Error>> {
1308        let bridge = Arc::new(HoldBridge::new());
1309        let mut program = Program::new("ha-late-fail");
1310        program.function("main", 0, |f| {
1311            let args = f.load_i32(1);
1312            let _ticket = f.host_await(1, args);
1313            f.return_(args);
1314        });
1315        let rt = Runtime::with_config(
1316            program.build(),
1317            RuntimeConfig {
1318                workers: 1,
1319                quantum: 1_000,
1320                mailbox: MailboxConfig::DEFAULT,
1321                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1322                ..Default::default()
1323            },
1324        )?;
1325        let handle = rt.spawn(0, &[])?;
1326        bridge.wait_for_submissions(1)?;
1327        let (_, done) = bridge.take_one()?.ok_or("missing completer")?;
1328        let outcome = handle
1329            .join_timeout(Duration::from_secs(2))
1330            .ok_or("commit timed out")?;
1331        let late = done.fail("too late");
1332        rt.shutdown();
1333        match outcome {
1334            FlowOutcome::Completed(Value::Int(1)) => {}
1335            other => return Err(format!("expected completed 1, got {other:?}").into()),
1336        }
1337        match late {
1338            Err(HostAwaitError::Stale) => Ok(()),
1339            other => Err(format!("expected stale fail, got {other:?}").into()),
1340        }
1341    }
1342
1343    #[test]
1344    fn replay_keeps_delivering_after_a_full_mailbox() -> Result<(), Box<dyn std::error::Error>> {
1345        let bridge = Arc::new(HoldBridge::new());
1346        let capacity = MailboxCapacity::new(1).ok_or("capacity")?;
1347        let mut program = Program::new("ha-replay-full");
1348        let blocked = program.function("blocked", 0, |f| {
1349            let args = f.load_i32(1);
1350            let _ticket = f.host_await(1, args);
1351            let _ignored = f.receive_match_imm(1);
1352            f.return_(args);
1353        });
1354        let open = program.function("open", 0, |f| {
1355            let args = f.load_i32(22);
1356            let _ticket = f.host_await(2, args);
1357            let msg = f.receive();
1358            f.return_(msg);
1359        });
1360        let gate = program.function("gate", 0, |f| {
1361            let n = f.load_i32(1);
1362            f.return_(n);
1363        });
1364        let rt = Runtime::with_config(
1365            program.build(),
1366            RuntimeConfig {
1367                workers: 1,
1368                quantum: 1_000,
1369                mailbox: MailboxConfig::new(capacity, OverflowPolicy::Reject),
1370                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1371                ..Default::default()
1372            },
1373        )?;
1374        rt.enable_host_await_replay()?;
1375        let blocked_handle = rt.spawn(blocked, &[])?;
1376        let open_handle = rt.spawn(open, &[])?;
1377        let blocked_id = blocked_handle.id();
1378        let open_id = open_handle.id();
1379        bridge.wait_for_submissions(2)?;
1380        let parked = rt.spawn(gate, &[])?;
1381        let parked_out = parked
1382            .join_timeout(Duration::from_secs(2))
1383            .ok_or("worker did not become free")?;
1384        match parked_out {
1385            FlowOutcome::Completed(Value::Int(1)) => {}
1386            other => return Err(format!("worker did not become free, got {other:?}").into()),
1387        }
1388        let mut blocked_done = None;
1389        let mut open_done = None;
1390        for (id, done) in bridge.take_all()? {
1391            if id == blocked_id {
1392                blocked_done = Some(done);
1393            } else if id == open_id {
1394                open_done = Some(done);
1395            }
1396        }
1397        let blocked_done = blocked_done.ok_or("blocked completer")?;
1398        let open_done = open_done.ok_or("open completer")?;
1399        rt.send(
1400            blocked_id,
1401            Value::Message(Message::request(9, 2, Value::Int(0))),
1402        )?;
1403        rt.bind_host_await_replay(open_done.ticket(), 1)?;
1404        rt.bind_host_await_replay(blocked_done.ticket(), 0)?;
1405        open_done.complete(Value::Int(22))?;
1406        let blocked_result = blocked_done.complete(Value::Int(7));
1407        let open_out = open_handle
1408            .join_timeout(Duration::from_secs(2))
1409            .ok_or("open hop timed out")?;
1410        let _ = blocked_handle.join_timeout(Duration::from_secs(2));
1411        rt.shutdown();
1412        match blocked_result {
1413            Err(HostAwaitError::Mailbox(crate::scheduler::MailboxFullReason::MessageLimit)) => {}
1414            other => return Err(format!("expected a full mailbox, got {other:?}").into()),
1415        }
1416        match payload_int(&open_out) {
1417            Some(22) => Ok(()),
1418            _ => Err(format!("expected the later hop to arrive, got {open_out:?}").into()),
1419        }
1420    }
1421}