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/// Settle `done` from a host thread.
369///
370/// A ticket already removed by cancel, shutdown, or finalize returns
371/// [`HostAwaitError::Stale`] and does not write a hop. `Err` from the host
372/// work fails the flow only while the ticket is still live.
373pub fn finish_host_await(
374    done: HostAwaitCompleter,
375    result: Result<Value, String>,
376) -> Result<(), HostAwaitError> {
377    if done.is_cancelled() {
378        return done.complete(Value::Unit);
379    }
380    match result {
381        Ok(value) => done.complete(value),
382        Err(err) => done.fail(err),
383    }
384}
385
386type HostAwaitWork =
387    dyn Fn(&HostAwaitRequest, &dyn Fn() -> bool) -> Result<Value, String> + Send + Sync;
388
389/// Runs [`HostAwaitBridge::submit`] on a fresh `std` thread.
390///
391/// `submit` returns after the thread is spawned. The closure sees a
392/// cancellation probe and must not block the worker itself. Tokio is not
393/// required. If the ticket is cancelled before delivery, the result is
394/// dropped and [`finish_host_await`] returns [`HostAwaitError::Stale`].
395pub struct ThreadedHostAwait {
396    work: Arc<HostAwaitWork>,
397}
398
399impl std::fmt::Debug for ThreadedHostAwait {
400    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
401        f.write_str("ThreadedHostAwait")
402    }
403}
404
405impl ThreadedHostAwait {
406    pub fn new<F>(work: F) -> Self
407    where
408        F: Fn(&HostAwaitRequest, &dyn Fn() -> bool) -> Result<Value, String>
409            + Send
410            + Sync
411            + 'static,
412    {
413        Self {
414            work: Arc::new(work),
415        }
416    }
417}
418
419impl HostAwaitBridge for ThreadedHostAwait {
420    fn submit(&self, req: HostAwaitRequest, done: HostAwaitCompleter) {
421        let work = Arc::clone(&self.work);
422        // A failed spawn drops `done` with the closure. That Drop fails the
423        // flow closed; `submit` itself does not wait for `work`.
424        if std::thread::Builder::new()
425            .name("byteflow-host-await".into())
426            .spawn(move || {
427                let result = work(&req, &|| done.is_cancelled());
428                let _ = finish_host_await(done, result);
429            })
430            .is_err()
431        {}
432    }
433}
434
435/// Tell the bridge about tickets removed by finalize, kill, or shutdown.
436pub(crate) fn notify_cancelled(shared: &Shared, notices: Vec<CancelledAwait>) {
437    let Some(bridge) = shared.host_await_bridge.as_ref() else {
438        return;
439    };
440    for notice in notices {
441        bridge.cancel(notice.flow, notice.op, notice.ticket);
442    }
443}
444
445#[derive(Debug, Clone, Copy, PartialEq, Eq)]
446pub(crate) enum HostAwaitParkError {
447    LimitReached { current: usize, max: usize },
448    IdExhausted,
449}
450
451impl std::fmt::Display for HostAwaitParkError {
452    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453        match self {
454            HostAwaitParkError::LimitReached { current, max } => {
455                write!(f, "HostAwait limit reached ({current}/{max})")
456            }
457            HostAwaitParkError::IdExhausted => f.write_str("HostAwait ticket ids exhausted"),
458        }
459    }
460}
461
462pub(crate) struct RegisteredAwait {
463    pub id: u64,
464    pub cancelled: Arc<AtomicBool>,
465}
466
467pub(crate) struct CancelledAwait {
468    pub flow: FlowId,
469    pub op: HostAwaitOp,
470    pub ticket: u64,
471}
472
473struct AwaitEntry {
474    flow: FlowId,
475    op: HostAwaitOp,
476    cancelled: Arc<AtomicBool>,
477}
478
479/// Host `fail` text observed by the worker before a successful `return`.
480///
481/// `settled` is the commit bit: once the worker has chosen an outcome, a
482/// later `fail` is too late and does not invent a second one.
483pub(crate) struct HostAwaitFailures {
484    inner: Mutex<HashMap<FlowId, FailSlot>>,
485}
486
487#[derive(Default)]
488struct FailSlot {
489    message: Option<String>,
490    settled: bool,
491}
492
493impl HostAwaitFailures {
494    pub(crate) fn new() -> Self {
495        Self {
496            inner: Mutex::new(HashMap::new()),
497        }
498    }
499
500    /// `Ok(true)` stores `msg` for the worker. `Ok(false)` means the flow
501    /// already committed an outcome.
502    pub(crate) fn request(&self, id: FlowId, msg: &str) -> Result<bool, RuntimeError> {
503        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::request")?;
504        let slot = slots.entry(id).or_default();
505        if slot.settled {
506            return Ok(false);
507        }
508        if slot.message.is_none() {
509            slot.message = Some(msg.to_string());
510        }
511        Ok(true)
512    }
513
514    pub(crate) fn take(&self, id: FlowId) -> Result<Option<String>, RuntimeError> {
515        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::take")?;
516        let Some(slot) = slots.get_mut(&id) else {
517            return Ok(None);
518        };
519        let message = slot.message.take();
520        if message.is_none() && !slot.settled {
521            slots.remove(&id);
522        }
523        Ok(message)
524    }
525
526    /// Mark a successful outcome. `Some` is a host failure that won the race
527    /// and must replace that success.
528    pub(crate) fn commit_success(&self, id: FlowId) -> Result<Option<String>, RuntimeError> {
529        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::commit_success")?;
530        let slot = slots.entry(id).or_default();
531        slot.settled = true;
532        Ok(slot.message.take())
533    }
534
535    pub(crate) fn seal(&self, id: FlowId) -> Result<(), RuntimeError> {
536        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::seal")?;
537        let slot = slots.entry(id).or_default();
538        slot.settled = true;
539        slot.message = None;
540        Ok(())
541    }
542
543    pub(crate) fn clear(&self, id: FlowId) -> Result<(), RuntimeError> {
544        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::clear")?;
545        slots.remove(&id);
546        Ok(())
547    }
548}
549
550/// Process-wide table of in-flight `HostAwait` tickets.
551///
552/// The flow itself stays on a worker or in its mailbox. This table only
553/// records the ticket so completion and cancellation compete for one removal.
554pub struct HostAwaitIndex {
555    inner: Mutex<HostAwaitInner>,
556    max: usize,
557}
558
559struct HostAwaitInner {
560    by_ticket: HashMap<u64, AwaitEntry>,
561    by_flow: HashMap<FlowId, Vec<u64>>,
562    next_ticket: u64,
563}
564
565impl HostAwaitIndex {
566    /// `max_host_awaits == 0` → unlimited.
567    pub fn new(max_host_awaits: u32) -> Self {
568        Self::with_next(max_host_awaits, 1)
569    }
570
571    fn with_next(max_host_awaits: u32, next_ticket: u64) -> Self {
572        Self {
573            inner: Mutex::new(HostAwaitInner {
574                by_ticket: HashMap::new(),
575                by_flow: HashMap::new(),
576                next_ticket,
577            }),
578            max: max_host_awaits as usize,
579        }
580    }
581
582    pub fn register(
583        &self,
584        flow: FlowId,
585        op: HostAwaitOp,
586    ) -> Result<Result<RegisteredAwait, HostAwaitParkError>, RuntimeError> {
587        let mut entries = sync_lock::lock(&self.inner, "HostAwaitIndex::register")?;
588        if self.max != 0 && entries.by_ticket.len() >= self.max {
589            return Ok(Err(HostAwaitParkError::LimitReached {
590                current: entries.by_ticket.len(),
591                max: self.max,
592            }));
593        }
594        if entries.next_ticket == 0 || entries.next_ticket >= i64::MAX as u64 {
595            return Ok(Err(HostAwaitParkError::IdExhausted));
596        }
597        let id = entries.next_ticket;
598        entries.next_ticket += 1;
599        let cancelled = Arc::new(AtomicBool::new(false));
600        entries.by_flow.entry(flow).or_default().push(id);
601        entries.by_ticket.insert(
602            id,
603            AwaitEntry {
604                flow,
605                op,
606                cancelled: Arc::clone(&cancelled),
607            },
608        );
609        Ok(Ok(RegisteredAwait { id, cancelled }))
610    }
611
612    /// Removes the ticket once. `None` means it was already completed or cancelled.
613    pub fn take_ticket(&self, ticket: u64) -> Result<Option<FlowId>, RuntimeError> {
614        let mut entries = sync_lock::lock(&self.inner, "HostAwaitIndex::take_ticket")?;
615        let Some(entry) = entries.by_ticket.remove(&ticket) else {
616            return Ok(None);
617        };
618        unlink(&mut entries, entry.flow, ticket);
619        if entry.cancelled.load(Ordering::Acquire) {
620            return Ok(None);
621        }
622        Ok(Some(entry.flow))
623    }
624
625    /// Cancels every ticket of `flow`. The caller notifies the host after
626    /// this returns, so the bridge does not run under the registry lock.
627    pub fn cancel_flow(&self, flow: FlowId) -> Result<Vec<CancelledAwait>, RuntimeError> {
628        let mut entries = sync_lock::lock(&self.inner, "HostAwaitIndex::cancel_flow")?;
629        Ok(take_flow_ids(&mut entries, flow))
630    }
631
632    /// Cancels every outstanding ticket (runtime shutdown).
633    pub(crate) fn cancel_all(&self) -> Result<Vec<CancelledAwait>, RuntimeError> {
634        let mut entries = sync_lock::lock(&self.inner, "HostAwaitIndex::cancel_all")?;
635        entries.by_flow.clear();
636        let mut notices = Vec::with_capacity(entries.by_ticket.len());
637        for (ticket, entry) in entries.by_ticket.drain() {
638            entry.cancelled.store(true, Ordering::Release);
639            notices.push(CancelledAwait {
640                flow: entry.flow,
641                op: entry.op,
642                ticket,
643            });
644        }
645        Ok(notices)
646    }
647
648    #[cfg(test)]
649    pub fn outstanding(&self) -> Result<usize, RuntimeError> {
650        let entries = sync_lock::lock(&self.inner, "HostAwaitIndex::outstanding")?;
651        Ok(entries.by_ticket.len())
652    }
653}
654
655fn unlink(entries: &mut HostAwaitInner, flow: FlowId, ticket: u64) {
656    let Some(ids) = entries.by_flow.get_mut(&flow) else {
657        return;
658    };
659    ids.retain(|id| *id != ticket);
660    if ids.is_empty() {
661        entries.by_flow.remove(&flow);
662    }
663}
664
665fn take_flow_ids(entries: &mut HostAwaitInner, flow: FlowId) -> Vec<CancelledAwait> {
666    let Some(ids) = entries.by_flow.remove(&flow) else {
667        return Vec::new();
668    };
669    let mut notices = Vec::with_capacity(ids.len());
670    for ticket in ids {
671        if let Some(entry) = entries.by_ticket.remove(&ticket) {
672            entry.cancelled.store(true, Ordering::Release);
673            notices.push(CancelledAwait {
674                flow,
675                op: entry.op,
676                ticket,
677            });
678        }
679    }
680    notices
681}
682
683#[cfg(test)]
684mod tests {
685    use super::*;
686
687    #[test]
688    fn allows_multiple_operations_for_one_flow() -> Result<(), Box<dyn std::error::Error>> {
689        let index = HostAwaitIndex::new(0);
690        let first = registered(&index, FlowId(7), 1)?;
691        let second = registered(&index, FlowId(7), 2)?;
692
693        assert_ne!(first.id, second.id);
694        assert!(!first.cancelled.load(Ordering::Acquire));
695        assert!(!second.cancelled.load(Ordering::Acquire));
696        assert_eq!(index.outstanding()?, 2);
697
698        assert_eq!(index.take_ticket(first.id)?, Some(FlowId(7)));
699        assert_eq!(index.take_ticket(second.id)?, Some(FlowId(7)));
700        assert_eq!(index.outstanding()?, 0);
701        Ok(())
702    }
703
704    #[test]
705    fn cancel_flow_invalidates_all_its_operations() -> Result<(), Box<dyn std::error::Error>> {
706        let index = HostAwaitIndex::new(0);
707        let left = registered(&index, FlowId(10), 1)?;
708        let right = registered(&index, FlowId(10), 2)?;
709        let other = registered(&index, FlowId(20), 1)?;
710
711        let notices = index.cancel_flow(FlowId(10))?;
712        assert_eq!(notices.len(), 2);
713        assert!(left.cancelled.load(Ordering::Acquire));
714        assert!(right.cancelled.load(Ordering::Acquire));
715        assert!(!other.cancelled.load(Ordering::Acquire));
716
717        assert_eq!(index.take_ticket(left.id)?, None);
718        assert_eq!(index.take_ticket(right.id)?, None);
719        assert_eq!(index.take_ticket(other.id)?, Some(FlowId(20)));
720        assert_eq!(index.outstanding()?, 0);
721        Ok(())
722    }
723
724    #[test]
725    fn completion_is_consumed_only_once() -> Result<(), Box<dyn std::error::Error>> {
726        let index = HostAwaitIndex::new(0);
727        let registered = registered(&index, FlowId(42), 1)?;
728
729        assert_eq!(index.take_ticket(registered.id)?, Some(FlowId(42)));
730        assert_eq!(index.take_ticket(registered.id)?, None);
731        Ok(())
732    }
733
734    #[test]
735    fn shutdown_cancels_all_operations() -> Result<(), Box<dyn std::error::Error>> {
736        let index = HostAwaitIndex::new(0);
737        let left = registered(&index, FlowId(1), 1)?;
738        let right = registered(&index, FlowId(2), 1)?;
739
740        assert_eq!(index.cancel_all()?.len(), 2);
741        assert!(left.cancelled.load(Ordering::Acquire));
742        assert!(right.cancelled.load(Ordering::Acquire));
743        assert_eq!(index.take_ticket(left.id)?, None);
744        assert_eq!(index.take_ticket(right.id)?, None);
745        assert_eq!(index.outstanding()?, 0);
746        Ok(())
747    }
748
749    #[test]
750    fn register_hits_process_limit() -> Result<(), Box<dyn std::error::Error>> {
751        let index = HostAwaitIndex::new(1);
752        let _first = registered(&index, FlowId(1), 1)?;
753        match index.register(FlowId(2), 1)? {
754            Err(HostAwaitParkError::LimitReached { current: 1, max: 1 }) => Ok(()),
755            Ok(_) => Err("expected limit".into()),
756            Err(err) => Err(format!("wrong park error: {err}").into()),
757        }
758    }
759
760    #[test]
761    fn slot_is_free_after_take() -> Result<(), Box<dyn std::error::Error>> {
762        let index = HostAwaitIndex::new(1);
763        let first = registered(&index, FlowId(1), 1)?;
764        assert!(index.take_ticket(first.id)?.is_some());
765        let _second = registered(&index, FlowId(2), 1)?;
766        Ok(())
767    }
768
769    #[test]
770    fn commit_keeps_a_fail_that_arrives_after_the_poll() -> Result<(), RuntimeError> {
771        let failures = HostAwaitFailures::new();
772        assert!(failures.take(FlowId(1))?.is_none());
773        assert!(failures.request(FlowId(1), "host boom")?);
774        assert_eq!(
775            failures.commit_success(FlowId(1))?.as_deref(),
776            Some("host boom")
777        );
778        Ok(())
779    }
780
781    #[test]
782    fn request_after_commit_is_too_late() -> Result<(), RuntimeError> {
783        let failures = HostAwaitFailures::new();
784        assert!(failures.commit_success(FlowId(1))?.is_none());
785        assert!(!failures.request(FlowId(1), "late")?);
786        Ok(())
787    }
788
789    #[test]
790    fn ticket_ids_stop_before_i64_max() -> Result<(), Box<dyn std::error::Error>> {
791        let index = HostAwaitIndex::with_next(0, i64::MAX as u64);
792        match index.register(FlowId(1), 1)? {
793            Err(HostAwaitParkError::IdExhausted) => Ok(()),
794            Ok(_) => Err("expected exhausted ids".into()),
795            Err(err) => Err(format!("wrong park error: {err}").into()),
796        }
797    }
798
799    #[test]
800    fn complete_and_cancel_remove_the_ticket_once() -> Result<(), Box<dyn std::error::Error>> {
801        let index = Arc::new(HostAwaitIndex::new(0));
802        let registered = registered(&index, FlowId(3), 9)?;
803        let ticket = registered.id;
804        let taker = Arc::clone(&index);
805        let canceller = Arc::clone(&index);
806        let took = std::thread::spawn(move || taker.take_ticket(ticket));
807        let cancelled = std::thread::spawn(move || canceller.cancel_flow(FlowId(3)));
808        let took = match took.join() {
809            Ok(result) => result?,
810            Err(_) => return Err("take join".into()),
811        };
812        let cancelled = match cancelled.join() {
813            Ok(result) => result?,
814            Err(_) => return Err("cancel join".into()),
815        };
816        let won_take = took.is_some();
817        let won_cancel = !cancelled.is_empty();
818        assert!(won_take ^ won_cancel, "take={won_take} cancel={won_cancel}");
819        assert_eq!(index.outstanding()?, 0);
820        if won_cancel {
821            assert!(registered.cancelled.load(Ordering::Acquire));
822        }
823        Ok(())
824    }
825
826    fn registered(
827        index: &HostAwaitIndex,
828        flow: FlowId,
829        op: HostAwaitOp,
830    ) -> Result<RegisteredAwait, Box<dyn std::error::Error>> {
831        match index.register(flow, op)? {
832            Ok(registered) => Ok(registered),
833            Err(err) => Err(err.to_string().into()),
834        }
835    }
836}
837
838/// Runtime-level HostAwait coverage (bridge wiring, limits, lifecycle).
839#[cfg(test)]
840mod runtime_tests {
841    use super::*;
842    use crate::bytecode::{CapId, Message, Program};
843    use crate::scheduler::mailbox::{MailboxCapacity, MailboxConfig, OverflowPolicy};
844    use crate::scheduler::process::FlowOutcome;
845    use crate::scheduler::runtime::{Runtime, RuntimeConfig};
846    use std::sync::{Arc, Condvar, Mutex};
847    use std::time::Duration;
848
849    /// Causal hold: waits until `n` submits arrived (no sleep races).
850    struct HoldBridge {
851        state: Mutex<HoldState>,
852        cv: Condvar,
853    }
854
855    struct HoldState {
856        held: Vec<(FlowId, HostAwaitCompleter)>,
857        submitted: usize,
858    }
859
860    impl HoldBridge {
861        fn new() -> Self {
862            Self {
863                state: Mutex::new(HoldState {
864                    held: Vec::new(),
865                    submitted: 0,
866                }),
867                cv: Condvar::new(),
868            }
869        }
870
871        fn wait_for_submissions(&self, n: usize) -> Result<(), &'static str> {
872            let mut guard = match self.state.lock() {
873                Ok(guard) => guard,
874                Err(_) => return Err("HoldBridge lock"),
875            };
876            while guard.submitted < n {
877                guard = match self.cv.wait(guard) {
878                    Ok(guard) => guard,
879                    Err(_) => return Err("HoldBridge wait"),
880                };
881            }
882            Ok(())
883        }
884
885        fn take_all(&self) -> Result<Vec<(FlowId, HostAwaitCompleter)>, &'static str> {
886            let mut guard = match self.state.lock() {
887                Ok(guard) => guard,
888                Err(_) => return Err("HoldBridge lock"),
889            };
890            Ok(std::mem::take(&mut guard.held))
891        }
892
893        fn take_one(&self) -> Result<Option<(FlowId, HostAwaitCompleter)>, &'static str> {
894            let mut guard = match self.state.lock() {
895                Ok(guard) => guard,
896                Err(_) => return Err("HoldBridge lock"),
897            };
898            if guard.held.is_empty() {
899                Ok(None)
900            } else {
901                Ok(Some(guard.held.remove(0)))
902            }
903        }
904    }
905
906    impl std::fmt::Debug for HoldBridge {
907        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
908            f.write_str("HoldBridge")
909        }
910    }
911
912    impl HostAwaitBridge for HoldBridge {
913        fn submit(&self, req: HostAwaitRequest, done: HostAwaitCompleter) {
914            match self.state.lock() {
915                Ok(mut guard) => {
916                    guard.held.push((req.flow, done));
917                    guard.submitted += 1;
918                    self.cv.notify_all();
919                }
920                Err(_) => {
921                    let _ = done.fail("HoldBridge lock poisoned");
922                }
923            }
924        }
925    }
926
927    fn waiter_program() -> (Program, u32) {
928        let mut program = Program::new("ha-waiter");
929        let waiter = program.function("waiter", 0, |f| {
930            let args = f.load_i32(0);
931            let _ticket = f.host_await(1, args);
932            let msg = f.receive();
933            f.return_(msg);
934        });
935        (program, waiter)
936    }
937
938    fn payload_int(outcome: &FlowOutcome) -> Option<i64> {
939        match outcome {
940            FlowOutcome::Completed(Value::Message(msg)) => match msg.payload.as_ref() {
941                Value::Int(n) => Some(*n),
942                _ => None,
943            },
944            _ => None,
945        }
946    }
947
948    #[test]
949    fn host_await_without_bridge_fails() -> Result<(), Box<dyn std::error::Error>> {
950        let mut program = Program::new("ha-none");
951        program.function("main", 0, |f| {
952            let args = f.load_i32(1);
953            let out = f.host_await(1, args);
954            f.return_(out);
955        });
956        let rt = Runtime::with_config(
957            program.build(),
958            RuntimeConfig {
959                workers: 1,
960                quantum: 1_000,
961                mailbox: MailboxConfig::DEFAULT,
962                host_await: None,
963                ..Default::default()
964            },
965        )?;
966        let outcome = rt.spawn(0, &[])?.join();
967        rt.shutdown();
968        match outcome {
969            FlowOutcome::Failed(msg) if msg.contains("no bridge") => Ok(()),
970            other => Err(format!("expected no-bridge failure, got {other:?}").into()),
971        }
972    }
973
974    #[test]
975    fn host_await_thread_bridge_delivers_a_hop() -> Result<(), Box<dyn std::error::Error>> {
976        #[derive(Debug)]
977        struct EchoBridge;
978
979        impl HostAwaitBridge for EchoBridge {
980            fn submit(&self, req: HostAwaitRequest, done: HostAwaitCompleter) {
981                std::thread::spawn(move || {
982                    let value = match (req.op, &req.args) {
983                        (1, Value::Int(n)) => Value::Int(n + 1),
984                        _ => Value::Int(42),
985                    };
986                    let _ = done.complete(value);
987                });
988            }
989        }
990
991        let mut program = Program::new("ha-echo");
992        program.function("main", 0, |f| {
993            let args = f.load_i32(41);
994            let _ticket = f.host_await(1, args);
995            let msg = f.receive();
996            f.return_(msg);
997        });
998        let rt = Runtime::with_config(
999            program.build(),
1000            RuntimeConfig {
1001                workers: 1,
1002                quantum: 1_000,
1003                mailbox: MailboxConfig::DEFAULT,
1004                host_await: Some(Arc::new(EchoBridge)),
1005                ..Default::default()
1006            },
1007        )?;
1008        let outcome = rt
1009            .spawn(0, &[])?
1010            .join_timeout(Duration::from_secs(2))
1011            .ok_or("host_await timed out")?;
1012        rt.shutdown();
1013        match &outcome {
1014            FlowOutcome::Completed(Value::Message(msg))
1015                if msg.sender == FlowId::HOST.as_u64()
1016                    && msg.reply_cap.is_none()
1017                    && msg.tag == TAG_SYS_AWAIT
1018                    && matches!(msg.payload.as_ref(), Value::Int(42)) =>
1019            {
1020                Ok(())
1021            }
1022            other => Err(format!("expected await hop 42, got {other:?}").into()),
1023        }
1024    }
1025
1026    #[test]
1027    fn host_await_limit_rejects_second() -> Result<(), Box<dyn std::error::Error>> {
1028        let bridge = Arc::new(HoldBridge::new());
1029        let (program, waiter) = waiter_program();
1030        let rt = Runtime::with_config(
1031            program.build(),
1032            RuntimeConfig {
1033                workers: 2,
1034                quantum: 1_000,
1035                mailbox: MailboxConfig::DEFAULT,
1036                max_host_awaits: 1,
1037                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1038                ..Default::default()
1039            },
1040        )?;
1041
1042        let first = rt.spawn(waiter, &[])?;
1043        bridge.wait_for_submissions(1)?;
1044        let second = rt.spawn(waiter, &[])?;
1045        let second_out = second
1046            .join_timeout(Duration::from_secs(2))
1047            .ok_or("second HostAwait did not finish")?;
1048
1049        for (_, done) in bridge.take_all()? {
1050            let _ = done.complete(Value::Int(0));
1051        }
1052        let _ = first.join_timeout(Duration::from_secs(2));
1053        rt.shutdown();
1054
1055        match second_out {
1056            FlowOutcome::Failed(msg) if msg.contains("HostAwait limit") => Ok(()),
1057            other => Err(format!("expected HostAwait limit failure, got {other:?}").into()),
1058        }
1059    }
1060
1061    #[test]
1062    fn host_await_slot_reused_after_complete() -> Result<(), Box<dyn std::error::Error>> {
1063        let bridge = Arc::new(HoldBridge::new());
1064        let (program, waiter) = waiter_program();
1065        let rt = Runtime::with_config(
1066            program.build(),
1067            RuntimeConfig {
1068                workers: 2,
1069                quantum: 1_000,
1070                mailbox: MailboxConfig::DEFAULT,
1071                max_host_awaits: 1,
1072                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1073                ..Default::default()
1074            },
1075        )?;
1076
1077        let first = rt.spawn(waiter, &[])?;
1078        bridge.wait_for_submissions(1)?;
1079        let second = rt.spawn(waiter, &[])?;
1080        let second_out = second
1081            .join_timeout(Duration::from_secs(2))
1082            .ok_or("second should fail on limit")?;
1083        assert!(
1084            matches!(
1085                &second_out,
1086                FlowOutcome::Failed(msg) if msg.contains("HostAwait limit")
1087            ),
1088            "got {second_out:?}"
1089        );
1090
1091        let (_, done) = bridge.take_one()?.ok_or("missing first completer")?;
1092        done.complete(Value::Int(7))?;
1093        let first_out = first
1094            .join_timeout(Duration::from_secs(2))
1095            .ok_or("first hop timed out")?;
1096        assert_eq!(payload_int(&first_out), Some(7), "got {first_out:?}");
1097
1098        let third = rt.spawn(waiter, &[])?;
1099        bridge.wait_for_submissions(2)?;
1100        let (_, done3) = bridge.take_one()?.ok_or("missing third completer")?;
1101        done3.complete(Value::Int(9))?;
1102        let third_out = third
1103            .join_timeout(Duration::from_secs(2))
1104            .ok_or("third hop timed out")?;
1105        rt.shutdown();
1106
1107        match payload_int(&third_out) {
1108            Some(9) => Ok(()),
1109            _ => Err(format!("expected slot reuse hop, got {third_out:?}").into()),
1110        }
1111    }
1112
1113    #[test]
1114    fn host_await_max_zero_allows_concurrent() -> Result<(), Box<dyn std::error::Error>> {
1115        let bridge = Arc::new(HoldBridge::new());
1116        let (program, waiter) = waiter_program();
1117        let rt = Runtime::with_config(
1118            program.build(),
1119            RuntimeConfig {
1120                workers: 2,
1121                quantum: 1_000,
1122                mailbox: MailboxConfig::DEFAULT,
1123                max_host_awaits: 0,
1124                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1125                ..Default::default()
1126            },
1127        )?;
1128
1129        let a = rt.spawn(waiter, &[])?;
1130        let b = rt.spawn(waiter, &[])?;
1131        bridge.wait_for_submissions(2)?;
1132        for (_, done) in bridge.take_all()? {
1133            let _ = done.complete(Value::Int(1));
1134        }
1135        let a_out = a
1136            .join_timeout(Duration::from_secs(2))
1137            .ok_or("a timed out")?;
1138        let b_out = b
1139            .join_timeout(Duration::from_secs(2))
1140            .ok_or("b timed out")?;
1141        rt.shutdown();
1142
1143        match (payload_int(&a_out), payload_int(&b_out)) {
1144            (Some(1), Some(1)) => Ok(()),
1145            _ => Err(format!("expected both hops, got {a_out:?} {b_out:?}").into()),
1146        }
1147    }
1148
1149    #[test]
1150    fn two_awaits_on_one_flow_both_deliver() -> Result<(), Box<dyn std::error::Error>> {
1151        let bridge = Arc::new(HoldBridge::new());
1152        let mut program = Program::new("ha-two");
1153        program.function("main", 0, |f| {
1154            let left = f.load_i32(11);
1155            let right = f.load_i32(22);
1156            let _first = f.host_await(1, left);
1157            let _second = f.host_await(2, right);
1158            let first = f.receive();
1159            let _second_msg = f.receive();
1160            f.return_(first);
1161        });
1162        let rt = Runtime::with_config(
1163            program.build(),
1164            RuntimeConfig {
1165                workers: 1,
1166                quantum: 1_000,
1167                mailbox: MailboxConfig::DEFAULT,
1168                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1169                ..Default::default()
1170            },
1171        )?;
1172        let handle = rt.spawn(0, &[])?;
1173        bridge.wait_for_submissions(2)?;
1174        let mut held = bridge.take_all()?;
1175        assert_eq!(held.len(), 2);
1176        let (_, second) = held.pop().ok_or("second completer")?;
1177        let (_, first) = held.pop().ok_or("first completer")?;
1178        assert_ne!(first.ticket(), second.ticket());
1179        first.complete(Value::Int(11))?;
1180        second.complete(Value::Int(22))?;
1181        let outcome = handle
1182            .join_timeout(Duration::from_secs(2))
1183            .ok_or("two-await timed out")?;
1184        rt.shutdown();
1185        match payload_int(&outcome) {
1186            Some(11) => Ok(()),
1187            _ => Err(format!("expected first hop 11, got {outcome:?}").into()),
1188        }
1189    }
1190
1191    #[test]
1192    fn replay_delivers_completions_in_script_order() -> Result<(), Box<dyn std::error::Error>> {
1193        let bridge = Arc::new(HoldBridge::new());
1194        let mut program = Program::new("ha-replay");
1195        program.function("main", 0, |f| {
1196            let left = f.load_i32(11);
1197            let right = f.load_i32(22);
1198            let _first = f.host_await(1, left);
1199            let _second = f.host_await(2, right);
1200            let first = f.receive();
1201            let _second_msg = f.receive();
1202            f.return_(first);
1203        });
1204        let rt = Runtime::with_config(
1205            program.build(),
1206            RuntimeConfig {
1207                workers: 1,
1208                quantum: 1_000,
1209                mailbox: MailboxConfig::DEFAULT,
1210                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1211                ..Default::default()
1212            },
1213        )?;
1214        rt.enable_host_await_replay()?;
1215        let handle = rt.spawn(0, &[])?;
1216        bridge.wait_for_submissions(2)?;
1217        let mut held = bridge.take_all()?;
1218        let (_, second) = held.pop().ok_or("second completer")?;
1219        let (_, first) = held.pop().ok_or("first completer")?;
1220        rt.bind_host_await_replay(first.ticket(), 1)?;
1221        rt.bind_host_await_replay(second.ticket(), 0)?;
1222        first.complete(Value::Int(11))?;
1223        second.complete(Value::Int(22))?;
1224        let outcome = handle
1225            .join_timeout(Duration::from_secs(2))
1226            .ok_or("replay timed out")?;
1227        rt.shutdown();
1228        match payload_int(&outcome) {
1229            Some(22) => Ok(()),
1230            _ => Err(format!("expected script order 22 then 11, got {outcome:?}").into()),
1231        }
1232    }
1233
1234    #[test]
1235    fn kill_parked_host_await_then_complete_is_stale() -> Result<(), Box<dyn std::error::Error>> {
1236        let bridge = Arc::new(HoldBridge::new());
1237        let (program, waiter) = waiter_program();
1238        let rt = Runtime::with_config(
1239            program.build(),
1240            RuntimeConfig {
1241                workers: 1,
1242                quantum: 1_000,
1243                mailbox: MailboxConfig::DEFAULT,
1244                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1245                ..Default::default()
1246            },
1247        )?;
1248
1249        let handle = rt.spawn(waiter, &[])?;
1250        bridge.wait_for_submissions(1)?;
1251        let (flow_id, done) = bridge.take_one()?.ok_or("missing completer")?;
1252        assert_eq!(flow_id, handle.id());
1253        rt.kill(handle.id())?;
1254        let outcome = handle
1255            .join_timeout(Duration::from_secs(2))
1256            .ok_or("kill join timed out")?;
1257        assert!(
1258            matches!(outcome, FlowOutcome::Failed(_)),
1259            "kill must fail joiner, got {outcome:?}"
1260        );
1261        assert!(done.is_cancelled());
1262        let stale = done.complete(Value::Int(1));
1263        rt.shutdown();
1264        match stale {
1265            Err(HostAwaitError::Stale) => Ok(()),
1266            other => Err(format!("expected Stale after kill, got {other:?}").into()),
1267        }
1268    }
1269
1270    #[test]
1271    fn shutdown_with_parked_host_await_does_not_hang() -> Result<(), Box<dyn std::error::Error>> {
1272        let bridge = Arc::new(HoldBridge::new());
1273        let (program, waiter) = waiter_program();
1274        let rt = Runtime::with_config(
1275            program.build(),
1276            RuntimeConfig {
1277                workers: 1,
1278                quantum: 1_000,
1279                mailbox: MailboxConfig::DEFAULT,
1280                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1281                ..Default::default()
1282            },
1283        )?;
1284
1285        let handle = rt.spawn(waiter, &[])?;
1286        bridge.wait_for_submissions(1)?;
1287        rt.shutdown();
1288        let outcome = handle
1289            .join_timeout(Duration::from_secs(2))
1290            .ok_or("joiner stuck after shutdown")?;
1291        for (_, done) in bridge.take_all()? {
1292            assert!(done.is_cancelled());
1293            assert!(matches!(
1294                done.complete(Value::Int(1)),
1295                Err(HostAwaitError::Stale)
1296            ));
1297        }
1298        match outcome {
1299            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
1300            other => Err(format!("expected shutdown failure, got {other:?}").into()),
1301        }
1302    }
1303
1304    #[test]
1305    fn unknown_cap_in_completion_rejects_and_fails_the_flow(
1306    ) -> Result<(), Box<dyn std::error::Error>> {
1307        let bridge = Arc::new(HoldBridge::new());
1308        let (program, waiter) = waiter_program();
1309        let rt = Runtime::with_config(
1310            program.build(),
1311            RuntimeConfig {
1312                workers: 1,
1313                quantum: 1_000,
1314                mailbox: MailboxConfig::DEFAULT,
1315                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1316                ..Default::default()
1317            },
1318        )?;
1319        let handle = rt.spawn(waiter, &[])?;
1320        bridge.wait_for_submissions(1)?;
1321        let (_, done) = bridge.take_one()?.ok_or("missing completer")?;
1322        let rejected = done.complete(Value::Cap(CapId::from_raw(1)));
1323        let outcome = handle
1324            .join_timeout(Duration::from_secs(2))
1325            .ok_or("cap rejection timed out")?;
1326        rt.shutdown();
1327        match rejected {
1328            Err(HostAwaitError::Rejected) => {}
1329            other => return Err(format!("expected Rejected, got {other:?}").into()),
1330        }
1331        match outcome {
1332            FlowOutcome::Failed(msg) if msg.contains("capability") => Ok(()),
1333            other => Err(format!("expected capability failure, got {other:?}").into()),
1334        }
1335    }
1336
1337    #[test]
1338    fn fail_during_submit_uses_the_host_message() -> Result<(), Box<dyn std::error::Error>> {
1339        #[derive(Debug)]
1340        struct Boom;
1341        impl HostAwaitBridge for Boom {
1342            fn submit(&self, _req: HostAwaitRequest, done: HostAwaitCompleter) {
1343                let _ = done.fail("host boom");
1344            }
1345        }
1346        let mut program = Program::new("ha-boom");
1347        program.function("main", 0, |f| {
1348            let args = f.load_i32(1);
1349            let _ticket = f.host_await(1, args);
1350            f.return_(args);
1351        });
1352        let rt = Runtime::with_config(
1353            program.build(),
1354            RuntimeConfig {
1355                workers: 1,
1356                quantum: 1_000,
1357                mailbox: MailboxConfig::DEFAULT,
1358                host_await: Some(Arc::new(Boom)),
1359                ..Default::default()
1360            },
1361        )?;
1362        let outcome = rt
1363            .spawn(0, &[])?
1364            .join_timeout(Duration::from_secs(2))
1365            .ok_or("fail join timed out")?;
1366        rt.shutdown();
1367        match outcome {
1368            FlowOutcome::Failed(msg) if msg.contains("host boom") => Ok(()),
1369            other => Err(format!("expected host boom, got {other:?}").into()),
1370        }
1371    }
1372
1373    #[test]
1374    fn fail_after_the_flow_commits_is_stale() -> Result<(), Box<dyn std::error::Error>> {
1375        let bridge = Arc::new(HoldBridge::new());
1376        let mut program = Program::new("ha-late-fail");
1377        program.function("main", 0, |f| {
1378            let args = f.load_i32(1);
1379            let _ticket = f.host_await(1, args);
1380            f.return_(args);
1381        });
1382        let rt = Runtime::with_config(
1383            program.build(),
1384            RuntimeConfig {
1385                workers: 1,
1386                quantum: 1_000,
1387                mailbox: MailboxConfig::DEFAULT,
1388                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1389                ..Default::default()
1390            },
1391        )?;
1392        let handle = rt.spawn(0, &[])?;
1393        bridge.wait_for_submissions(1)?;
1394        let (_, done) = bridge.take_one()?.ok_or("missing completer")?;
1395        let outcome = handle
1396            .join_timeout(Duration::from_secs(2))
1397            .ok_or("commit timed out")?;
1398        let late = done.fail("too late");
1399        rt.shutdown();
1400        match outcome {
1401            FlowOutcome::Completed(Value::Int(1)) => {}
1402            other => return Err(format!("expected completed 1, got {other:?}").into()),
1403        }
1404        match late {
1405            Err(HostAwaitError::Stale) => Ok(()),
1406            other => Err(format!("expected stale fail, got {other:?}").into()),
1407        }
1408    }
1409
1410    #[test]
1411    fn replay_keeps_delivering_after_a_full_mailbox() -> Result<(), Box<dyn std::error::Error>> {
1412        let bridge = Arc::new(HoldBridge::new());
1413        let capacity = MailboxCapacity::new(1).ok_or("capacity")?;
1414        let mut program = Program::new("ha-replay-full");
1415        let blocked = program.function("blocked", 0, |f| {
1416            let args = f.load_i32(1);
1417            let _ticket = f.host_await(1, args);
1418            let _ignored = f.receive_match_imm(1);
1419            f.return_(args);
1420        });
1421        let open = program.function("open", 0, |f| {
1422            let args = f.load_i32(22);
1423            let _ticket = f.host_await(2, args);
1424            let msg = f.receive();
1425            f.return_(msg);
1426        });
1427        let gate = program.function("gate", 0, |f| {
1428            let n = f.load_i32(1);
1429            f.return_(n);
1430        });
1431        let rt = Runtime::with_config(
1432            program.build(),
1433            RuntimeConfig {
1434                workers: 1,
1435                quantum: 1_000,
1436                mailbox: MailboxConfig::new(capacity, OverflowPolicy::Reject),
1437                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1438                ..Default::default()
1439            },
1440        )?;
1441        rt.enable_host_await_replay()?;
1442        let blocked_handle = rt.spawn(blocked, &[])?;
1443        let open_handle = rt.spawn(open, &[])?;
1444        let blocked_id = blocked_handle.id();
1445        let open_id = open_handle.id();
1446        bridge.wait_for_submissions(2)?;
1447        let parked = rt.spawn(gate, &[])?;
1448        let parked_out = parked
1449            .join_timeout(Duration::from_secs(2))
1450            .ok_or("worker did not become free")?;
1451        match parked_out {
1452            FlowOutcome::Completed(Value::Int(1)) => {}
1453            other => return Err(format!("worker did not become free, got {other:?}").into()),
1454        }
1455        let mut blocked_done = None;
1456        let mut open_done = None;
1457        for (id, done) in bridge.take_all()? {
1458            if id == blocked_id {
1459                blocked_done = Some(done);
1460            } else if id == open_id {
1461                open_done = Some(done);
1462            }
1463        }
1464        let blocked_done = blocked_done.ok_or("blocked completer")?;
1465        let open_done = open_done.ok_or("open completer")?;
1466        rt.send(
1467            blocked_id,
1468            Value::Message(Message::request(9, 2, Value::Int(0))),
1469        )?;
1470        rt.bind_host_await_replay(open_done.ticket(), 1)?;
1471        rt.bind_host_await_replay(blocked_done.ticket(), 0)?;
1472        open_done.complete(Value::Int(22))?;
1473        let blocked_result = blocked_done.complete(Value::Int(7));
1474        let open_out = open_handle
1475            .join_timeout(Duration::from_secs(2))
1476            .ok_or("open hop timed out")?;
1477        let _ = blocked_handle.join_timeout(Duration::from_secs(2));
1478        rt.shutdown();
1479        match blocked_result {
1480            Err(HostAwaitError::Mailbox(crate::scheduler::MailboxFullReason::MessageLimit)) => {}
1481            other => return Err(format!("expected a full mailbox, got {other:?}").into()),
1482        }
1483        match payload_int(&open_out) {
1484            Some(22) => Ok(()),
1485            _ => Err(format!("expected the later hop to arrive, got {open_out:?}").into()),
1486        }
1487    }
1488
1489    #[test]
1490    fn threaded_host_await_delivers_sys_await() -> Result<(), Box<dyn std::error::Error>> {
1491        let bridge = ThreadedHostAwait::new(|req, _cancelled| match req.args {
1492            Value::Int(n) => Ok(Value::Int(n + 1)),
1493            _ => Err("host args".into()),
1494        });
1495        let mut program = Program::new("ha-thread");
1496        program.function("main", 0, |f| {
1497            let args = f.load_i32(41);
1498            let _ticket = f.host_await(1, args);
1499            let msg = f.receive();
1500            f.return_(msg);
1501        });
1502        let rt = Runtime::with_config(
1503            program.build(),
1504            RuntimeConfig {
1505                workers: 1,
1506                host_await: Some(Arc::new(bridge)),
1507                ..RuntimeConfig::default()
1508            },
1509        )?;
1510        let outcome = rt
1511            .spawn(0, &[])?
1512            .join_timeout(Duration::from_secs(2))
1513            .ok_or("threaded host await timed out")?;
1514        rt.shutdown();
1515        match &outcome {
1516            FlowOutcome::Completed(Value::Message(msg))
1517                if msg.tag == TAG_SYS_AWAIT && matches!(msg.payload.as_ref(), Value::Int(42)) =>
1518            {
1519                Ok(())
1520            }
1521            other => Err(format!("expected TAG_SYS_AWAIT 42, got {other:?}").into()),
1522        }
1523    }
1524
1525    #[test]
1526    fn threaded_submit_returns_while_host_work_is_blocked() -> Result<(), Box<dyn std::error::Error>>
1527    {
1528        let gate = Arc::new((Mutex::new(false), Condvar::new()));
1529        let started = Arc::new((Mutex::new(false), Condvar::new()));
1530        let gate_work = Arc::clone(&gate);
1531        let started_work = Arc::clone(&started);
1532        let bridge = ThreadedHostAwait::new(move |req, cancelled| {
1533            if let Ok(mut flag) = started_work.0.lock() {
1534                *flag = true;
1535                started_work.1.notify_all();
1536            }
1537            let (lock, cv) = &*gate_work;
1538            let mut guard = lock.lock().map_err(|_| "gate".to_string())?;
1539            while !*guard {
1540                if cancelled() {
1541                    return Err("cancelled".into());
1542                }
1543                let (next, _) = cv
1544                    .wait_timeout(guard, Duration::from_millis(20))
1545                    .map_err(|_| "gate wait".to_string())?;
1546                guard = next;
1547            }
1548            match req.args {
1549                Value::Int(n) => Ok(Value::Int(n)),
1550                _ => Ok(Value::Int(0)),
1551            }
1552        });
1553        let mut program = Program::new("ha-block");
1554        program.function("main", 0, |f| {
1555            let args = f.load_i32(7);
1556            let _ticket = f.host_await(1, args);
1557            let msg = f.receive();
1558            f.return_(msg);
1559        });
1560        let rt = Runtime::with_config(
1561            program.build(),
1562            RuntimeConfig {
1563                workers: 1,
1564                host_await: Some(Arc::new(bridge)),
1565                ..RuntimeConfig::default()
1566            },
1567        )?;
1568        let handle = rt.spawn(0, &[])?;
1569        let mut flag = started.0.lock().map_err(|_| "started lock")?;
1570        let deadline = std::time::Instant::now() + Duration::from_secs(2);
1571        while !*flag {
1572            let (next, timeout) = started
1573                .1
1574                .wait_timeout(flag, Duration::from_millis(50))
1575                .map_err(|_| "started wait")?;
1576            flag = next;
1577            if timeout.timed_out() && std::time::Instant::now() > deadline {
1578                return Err("host work did not start".into());
1579            }
1580        }
1581        drop(flag);
1582        if handle.join_timeout(Duration::from_millis(80)).is_some() {
1583            return Err("submit blocked the flow until the host work finished".into());
1584        }
1585        if let Ok(mut release) = gate.0.lock() {
1586            *release = true;
1587            gate.1.notify_all();
1588        }
1589        let outcome = handle
1590            .join_timeout(Duration::from_secs(2))
1591            .ok_or("blocked host work did not finish")?;
1592        rt.shutdown();
1593        match payload_int(&outcome) {
1594            Some(7) => Ok(()),
1595            _ => Err(format!("expected 7 after release, got {outcome:?}").into()),
1596        }
1597    }
1598
1599    #[test]
1600    fn threaded_cancel_drops_the_late_result() -> Result<(), Box<dyn std::error::Error>> {
1601        let gate = Arc::new((Mutex::new(false), Condvar::new()));
1602        let started = Arc::new((Mutex::new(false), Condvar::new()));
1603        let gate_work = Arc::clone(&gate);
1604        let started_work = Arc::clone(&started);
1605        let bridge = ThreadedHostAwait::new(move |_req, cancelled| {
1606            if let Ok(mut flag) = started_work.0.lock() {
1607                *flag = true;
1608                started_work.1.notify_all();
1609            }
1610            let (lock, cv) = &*gate_work;
1611            let mut guard = lock.lock().map_err(|_| "gate".to_string())?;
1612            while !cancelled() && !*guard {
1613                let (next, _) = cv
1614                    .wait_timeout(guard, Duration::from_millis(20))
1615                    .map_err(|_| "gate wait".to_string())?;
1616                guard = next;
1617            }
1618            Ok(Value::Int(99))
1619        });
1620        let (program, waiter) = waiter_program();
1621        let rt = Runtime::with_config(
1622            program.build(),
1623            RuntimeConfig {
1624                workers: 1,
1625                host_await: Some(Arc::new(bridge)),
1626                ..RuntimeConfig::default()
1627            },
1628        )?;
1629        let handle = rt.spawn(waiter, &[])?;
1630        let mut flag = started.0.lock().map_err(|_| "started lock")?;
1631        while !*flag {
1632            flag = started.1.wait(flag).map_err(|_| "started wait")?;
1633        }
1634        drop(flag);
1635        rt.kill(handle.id())?;
1636        let outcome = handle
1637            .join_timeout(Duration::from_secs(2))
1638            .ok_or("kill did not finish")?;
1639        if let Ok(mut release) = gate.0.lock() {
1640            *release = true;
1641            gate.1.notify_all();
1642        }
1643        std::thread::sleep(Duration::from_millis(50));
1644        rt.shutdown();
1645        match outcome {
1646            FlowOutcome::Failed(_) => Ok(()),
1647            FlowOutcome::Completed(Value::Message(msg))
1648                if matches!(msg.payload.as_ref(), Value::Int(99)) =>
1649            {
1650                Err("late host result resurrected the flow".into())
1651            }
1652            other => Err(format!("expected the kill outcome, got {other:?}").into()),
1653        }
1654    }
1655
1656    #[test]
1657    fn finish_after_cancel_is_stale() -> Result<(), Box<dyn std::error::Error>> {
1658        let bridge = Arc::new(HoldBridge::new());
1659        let (program, waiter) = waiter_program();
1660        let rt = Runtime::with_config(
1661            program.build(),
1662            RuntimeConfig {
1663                workers: 1,
1664                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
1665                ..RuntimeConfig::default()
1666            },
1667        )?;
1668        let handle = rt.spawn(waiter, &[])?;
1669        bridge.wait_for_submissions(1)?;
1670        let (_flow, done) = bridge.take_one()?.ok_or("missing completer")?;
1671        rt.kill(handle.id())?;
1672        let outcome = handle
1673            .join_timeout(Duration::from_secs(2))
1674            .ok_or("kill join timed out")?;
1675        let stale = finish_host_await(done, Ok(Value::Int(1)));
1676        rt.shutdown();
1677        if !matches!(outcome, FlowOutcome::Failed(_)) {
1678            return Err(format!("kill outcome changed, got {outcome:?}").into());
1679        }
1680        match stale {
1681            Err(HostAwaitError::Stale) => Ok(()),
1682            other => Err(format!("expected Stale, got {other:?}").into()),
1683        }
1684    }
1685
1686    #[test]
1687    fn threaded_host_error_fails_the_flow() -> Result<(), Box<dyn std::error::Error>> {
1688        let bridge = ThreadedHostAwait::new(|_req, _cancelled| Err("host broke".into()));
1689        let mut program = Program::new("ha-err");
1690        program.function("main", 0, |f| {
1691            let args = f.load_i32(1);
1692            let _ticket = f.host_await(1, args);
1693            let msg = f.receive();
1694            f.return_(msg);
1695        });
1696        let rt = Runtime::with_config(
1697            program.build(),
1698            RuntimeConfig {
1699                workers: 1,
1700                host_await: Some(Arc::new(bridge)),
1701                ..RuntimeConfig::default()
1702            },
1703        )?;
1704        let outcome = rt
1705            .spawn(0, &[])?
1706            .join_timeout(Duration::from_secs(2))
1707            .ok_or("host error timed out")?;
1708        rt.shutdown();
1709        match outcome {
1710            FlowOutcome::Failed(msg) if msg.contains("host broke") => Ok(()),
1711            other => Err(format!("expected host broke, got {other:?}").into()),
1712        }
1713    }
1714}