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