byteflow-actors 0.9.23

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
//! Host ↔ flow async bridge (`Opcode::HostAwait`).
//!
//! The worker registers one ticket per operation and keeps running the flow.
//! The destination register receives that ticket as `Int`. Completion is an
//! authenticated host hop ([`crate::TAG_SYS_AWAIT`], `request_id` = ticket),
//! the same stamp and capability reissue as [`crate::Runtime::send`]. Bytecode
//! reads the result with `Receive`. A cap the table does not know fails the
//! flow instead of entering the mailbox.
//!
//! Several tickets may be outstanding for one flow. Finalize, kill, and
//! runtime shutdown cancel every ticket of that flow. A late `complete`
//! finds the ticket gone and returns [`HostAwaitError::Stale`]. The host
//! callback runs after the registry lock is released.
//!
//! The bridge itself must return quickly from [`HostAwaitBridge::submit`];
//! heavy work belongs on a host thread / Tokio task outside this crate.

use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Weak};

use crate::bytecode::{Message, Value, TAG_SYS_AWAIT};

use super::deterministic::{replay_label, StagedHostHop};
use super::error::{report_fault, RuntimeError};
use super::finalize::{extract_for_kill, finalize_flow, resume_handoff};
use super::mailbox::{Delivery, MailboxFullReason};
use super::monitor::FlowExitReason;
use super::process::{Flow, FlowId, FlowOutcome};
use super::runtime::Shared;
use super::sync_lock;

/// Opaque host discriminator passed as the `HostAwait` immediate.
pub type HostAwaitOp = u32;

/// Request handed to [`HostAwaitBridge::submit`].
#[derive(Debug, Clone)]
pub struct HostAwaitRequest {
    pub flow: FlowId,
    pub op: HostAwaitOp,
    pub args: Value,
}

/// Host-side async completion channel (one-shot).
///
/// Prefer calling [`Self::complete`] / [`Self::fail`] explicitly. If the
/// completer is dropped unused, the flow is failed closed (avoids a
/// permanent wait when the host forgets to settle the await).
///
/// Holds a [`Weak`] to the runtime shared state so a bridge that retains
/// completers cannot keep the runtime alive in a reference cycle
/// (`Shared` → bridge → completer → `Shared`).
pub struct HostAwaitCompleter {
    shared: Weak<Shared>,
    ticket: u64,
    cancelled: Arc<AtomicBool>,
    consumed: AtomicBool,
}

/// Errors from [`HostAwaitCompleter`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HostAwaitError {
    /// Ticket already used, flow finalized, or await cancelled.
    Stale,
    /// Infrastructure failure while completing.
    Runtime(RuntimeError),
    /// The completion value carried a capability the runtime would not grant.
    Rejected,
    /// The mailbox refused the completion hop. The flow is failed when it
    /// is still alive, so a later `Receive` does not wait for a hop that
    /// was never stored.
    Mailbox(MailboxFullReason),
    /// The test replay gate rejected this completion's recorded sequence.
    Replay(&'static str),
}

impl std::fmt::Display for HostAwaitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HostAwaitError::Stale => f.write_str("HostAwait completer is stale"),
            HostAwaitError::Runtime(e) => write!(f, "{e}"),
            HostAwaitError::Rejected => {
                f.write_str("HostAwait completion refused a capability grant")
            }
            HostAwaitError::Mailbox(reason) => {
                write!(f, "HostAwait mailbox refused the completion ({reason})")
            }
            HostAwaitError::Replay(reason) => {
                write!(f, "host replay rejected the sequence ({reason})")
            }
        }
    }
}

impl std::error::Error for HostAwaitError {}

impl HostAwaitCompleter {
    pub(crate) fn new(shared: Arc<Shared>, ticket: u64, cancelled: Arc<AtomicBool>) -> Self {
        Self {
            shared: Arc::downgrade(&shared),
            ticket,
            cancelled,
            consumed: AtomicBool::new(false),
        }
    }

    /// Ticket id written into the flow's destination register.
    pub fn ticket(&self) -> u64 {
        self.ticket
    }

    /// `true` after finalize, kill, or shutdown cancelled this operation.
    ///
    /// Cooperative: the host observes this or [`HostAwaitBridge::cancel`] and
    /// aborts the I/O it owns. The flag alone does not close a socket.
    pub fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::Acquire)
    }

    /// Deliver `value` as a [`crate::TAG_SYS_AWAIT`] hop to the awaiting flow.
    pub fn complete(self, value: Value) -> Result<(), HostAwaitError> {
        self.finish(Ok(value))
    }

    /// Fail the flow (`FlowOutcome::Failed`).
    pub fn fail(self, msg: impl Into<String>) -> Result<(), HostAwaitError> {
        self.finish(Err(msg.into()))
    }

    fn finish(self, result: Result<Value, String>) -> Result<(), HostAwaitError> {
        if self.consumed.swap(true, Ordering::SeqCst) {
            return Err(HostAwaitError::Stale);
        }
        settle(&self.shared, self.ticket, result)
    }
}

impl Drop for HostAwaitCompleter {
    fn drop(&mut self) {
        if self.consumed.swap(true, Ordering::SeqCst) {
            return;
        }
        let _ = settle(
            &self.shared,
            self.ticket,
            Err("HostAwait completer dropped".into()),
        );
    }
}

fn settle(
    shared: &Weak<Shared>,
    ticket: u64,
    result: Result<Value, String>,
) -> Result<(), HostAwaitError> {
    let Some(shared) = shared.upgrade() else {
        return Err(HostAwaitError::Stale);
    };
    let Some(flow_id) = shared
        .host_awaits
        .take_ticket(ticket)
        .map_err(HostAwaitError::Runtime)?
    else {
        return Err(HostAwaitError::Stale);
    };
    match result {
        Ok(value) => {
            let raw = Message::request(ticket, TAG_SYS_AWAIT, value);
            let stamped =
                match super::worker::authenticate_host_outgoing_message(&shared, flow_id, raw) {
                    Ok(message) => Value::Message(message),
                    Err(_) => {
                        fail_live(&shared, flow_id, "HostAwait: capability grant refused");
                        return Err(HostAwaitError::Rejected);
                    }
                };
            let ready = stage_completion(
                &shared,
                ticket,
                StagedHostHop {
                    flow: flow_id,
                    value: stamped,
                },
            )?;
            deliver_ready(&shared, ready)
        }
        Err(msg) => {
            if fail_live(&shared, flow_id, &msg) {
                Ok(())
            } else {
                Err(HostAwaitError::Stale)
            }
        }
    }
}

/// Record `msg` and fail the flow with that text.
///
/// Returns `false` when the flow has already committed an outcome. A flow
/// still on its worker keeps running only until the next result check,
/// which reads this table before it can `return` successfully.
fn fail_live(shared: &Shared, flow_id: FlowId, msg: &str) -> bool {
    match shared.directory.lookup(flow_id) {
        Ok(Some(_)) => {}
        Ok(None) => return false,
        Err(err) => {
            report_fault(err);
            return false;
        }
    }
    match shared.host_await_failures.request(flow_id, msg) {
        Ok(true) => {}
        Ok(false) => return false,
        Err(err) => {
            report_fault(err);
            return false;
        }
    }
    if let Some(flow) = extract_for_kill(shared, flow_id, FlowExitReason::Fault) {
        let text = match shared.host_await_failures.take(flow_id) {
            Ok(Some(text)) => text,
            _ => msg.to_string(),
        };
        finalize_flow(
            shared,
            flow,
            FlowOutcome::Failed(text),
            FlowExitReason::Fault,
        );
    }
    true
}

/// `None` when `flow` was finalized with a pending host failure.
pub(crate) fn park_flow_if_host_failed(shared: &Shared, flow: Box<Flow>) -> Option<Box<Flow>> {
    match shared.host_await_failures.take(flow.id) {
        Ok(Some(msg)) => {
            let _ = shared.kill_signals.take(flow.id);
            finalize_flow(
                shared,
                *flow,
                FlowOutcome::Failed(msg),
                FlowExitReason::Fault,
            );
            None
        }
        Ok(None) => Some(flow),
        Err(err) => {
            report_fault(err);
            finalize_flow(
                shared,
                *flow,
                FlowOutcome::Failed("HostAwait failure table unavailable".into()),
                FlowExitReason::Fault,
            );
            None
        }
    }
}

/// Host text when a kill and a host failure name the same flow.
pub(crate) fn message_or_kill(shared: &Shared, id: FlowId, reason: FlowExitReason) -> String {
    match shared.host_await_failures.take(id) {
        Ok(Some(msg)) => msg,
        Ok(None) => super::finalize::kill_outcome_message(reason),
        Err(err) => {
            report_fault(err);
            super::finalize::kill_outcome_message(reason)
        }
    }
}

fn stage_completion(
    shared: &Shared,
    ticket: u64,
    hop: StagedHostHop,
) -> Result<Vec<StagedHostHop>, HostAwaitError> {
    let prepared = {
        let mut gate = sync_lock::lock(&shared.host_replay, "HostAwait replay")
            .map_err(HostAwaitError::Runtime)?;
        match gate.as_mut() {
            None => Ok(vec![hop]),
            Some(replay) => {
                let flow = hop.flow;
                match replay.stage(ticket, hop) {
                    Ok(()) => Ok(replay.drain_ready()),
                    Err(err) => Err((flow, err)),
                }
            }
        }
    };
    match prepared {
        Ok(ready) => Ok(ready),
        Err((flow, err)) => {
            let _ = fail_live(shared, flow, "host replay rejected the sequence");
            Err(HostAwaitError::Replay(replay_label(err)))
        }
    }
}

/// Deliver every hop already removed from the replay queue.
///
/// One refusal does not drop the rest: those flows are still waiting on
/// `Receive`.
pub(crate) fn deliver_ready(
    shared: &Shared,
    ready: Vec<StagedHostHop>,
) -> Result<(), HostAwaitError> {
    let mut first = None;
    for hop in ready {
        if let Err(err) = deliver_staged(shared, hop) {
            if first.is_none() {
                first = Some(err);
            }
        }
    }
    match first {
        Some(err) => Err(err),
        None => Ok(()),
    }
}

/// Push one already-authenticated completion through [`crate::Runtime::send`]'s
/// mailbox admission. A closed inbox is [`HostAwaitError::Stale`]. A full
/// inbox fails the live flow and returns [`HostAwaitError::Mailbox`].
pub(crate) fn deliver_staged(shared: &Shared, hop: StagedHostHop) -> Result<(), HostAwaitError> {
    let mailbox = match shared.directory.lookup(hop.flow) {
        Ok(Some(mailbox)) => mailbox,
        Ok(None) => return Err(HostAwaitError::Stale),
        Err(err) => return Err(HostAwaitError::Runtime(err)),
    };
    let flow_id = hop.flow;
    match mailbox.push(hop.value.clone()) {
        Ok(Ok(Delivery::Handoff(parked))) => {
            resume_handoff(shared, parked, hop.value);
            Ok(())
        }
        Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest)) => Ok(()),
        Ok(Ok(Delivery::DroppedNewest)) => {
            let _ = fail_live(shared, flow_id, "HostAwait mailbox dropped the completion");
            Err(HostAwaitError::Mailbox(MailboxFullReason::MessageLimit))
        }
        Ok(Err(full)) if full.reason() == MailboxFullReason::Closed => Err(HostAwaitError::Stale),
        Ok(Err(full)) => {
            let reason = full.reason();
            let _ = fail_live(shared, flow_id, "HostAwait mailbox refused the completion");
            Err(HostAwaitError::Mailbox(reason))
        }
        Err(err) => Err(HostAwaitError::Runtime(err)),
    }
}

/// Embedder hook: schedule host work for [`Opcode::HostAwait`](crate::Opcode::HostAwait).
///
/// `submit` must return promptly. Spawn a thread / enqueue a task for I/O.
pub trait HostAwaitBridge: Send + Sync + std::fmt::Debug + 'static {
    fn submit(&self, req: HostAwaitRequest, done: HostAwaitCompleter);

    /// The flow was finalized or the runtime is shutting down.
    ///
    /// Called without the registry lock. Must return quickly and must not
    /// take a lock the finalizer already holds. Aborting the socket or
    /// future is the host's job; [`HostAwaitCompleter::is_cancelled`] is
    /// already set. The default body does nothing.
    fn cancel(&self, _flow: FlowId, _op: HostAwaitOp, _ticket: u64) {}
}

/// Settle `done` from a host thread.
///
/// A ticket already removed by cancel, shutdown, or finalize returns
/// [`HostAwaitError::Stale`] and does not write a hop. `Err` from the host
/// work fails the flow only while the ticket is still live.
pub fn finish_host_await(
    done: HostAwaitCompleter,
    result: Result<Value, String>,
) -> Result<(), HostAwaitError> {
    if done.is_cancelled() {
        return done.complete(Value::Unit);
    }
    match result {
        Ok(value) => done.complete(value),
        Err(err) => done.fail(err),
    }
}

type HostAwaitWork =
    dyn Fn(&HostAwaitRequest, &dyn Fn() -> bool) -> Result<Value, String> + Send + Sync;

/// Runs [`HostAwaitBridge::submit`] on a fresh `std` thread.
///
/// `submit` returns after the thread is spawned. The closure sees a
/// cancellation probe and must not block the worker itself. Tokio is not
/// required. If the ticket is cancelled before delivery, the result is
/// dropped and [`finish_host_await`] returns [`HostAwaitError::Stale`].
pub struct ThreadedHostAwait {
    work: Arc<HostAwaitWork>,
}

impl std::fmt::Debug for ThreadedHostAwait {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("ThreadedHostAwait")
    }
}

impl ThreadedHostAwait {
    pub fn new<F>(work: F) -> Self
    where
        F: Fn(&HostAwaitRequest, &dyn Fn() -> bool) -> Result<Value, String>
            + Send
            + Sync
            + 'static,
    {
        Self {
            work: Arc::new(work),
        }
    }
}

impl HostAwaitBridge for ThreadedHostAwait {
    fn submit(&self, req: HostAwaitRequest, done: HostAwaitCompleter) {
        let work = Arc::clone(&self.work);
        // A failed spawn drops `done` with the closure. That Drop fails the
        // flow closed; `submit` itself does not wait for `work`.
        if std::thread::Builder::new()
            .name("byteflow-host-await".into())
            .spawn(move || {
                let result = work(&req, &|| done.is_cancelled());
                let _ = finish_host_await(done, result);
            })
            .is_err()
        {}
    }
}

/// Tell the bridge about tickets removed by finalize, kill, or shutdown.
pub(crate) fn notify_cancelled(shared: &Shared, notices: Vec<CancelledAwait>) {
    let Some(bridge) = shared.host_await_bridge.as_ref() else {
        return;
    };
    for notice in notices {
        bridge.cancel(notice.flow, notice.op, notice.ticket);
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HostAwaitParkError {
    LimitReached { current: usize, max: usize },
    IdExhausted,
}

impl std::fmt::Display for HostAwaitParkError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HostAwaitParkError::LimitReached { current, max } => {
                write!(f, "HostAwait limit reached ({current}/{max})")
            }
            HostAwaitParkError::IdExhausted => f.write_str("HostAwait ticket ids exhausted"),
        }
    }
}

pub(crate) struct RegisteredAwait {
    pub id: u64,
    pub cancelled: Arc<AtomicBool>,
}

pub(crate) struct CancelledAwait {
    pub flow: FlowId,
    pub op: HostAwaitOp,
    pub ticket: u64,
}

struct AwaitEntry {
    flow: FlowId,
    op: HostAwaitOp,
    cancelled: Arc<AtomicBool>,
}

/// Host `fail` text observed by the worker before a successful `return`.
///
/// `settled` is the commit bit: once the worker has chosen an outcome, a
/// later `fail` is too late and does not invent a second one.
pub(crate) struct HostAwaitFailures {
    inner: Mutex<HashMap<FlowId, FailSlot>>,
}

#[derive(Default)]
struct FailSlot {
    message: Option<String>,
    settled: bool,
}

impl HostAwaitFailures {
    pub(crate) fn new() -> Self {
        Self {
            inner: Mutex::new(HashMap::new()),
        }
    }

    /// `Ok(true)` stores `msg` for the worker. `Ok(false)` means the flow
    /// already committed an outcome.
    pub(crate) fn request(&self, id: FlowId, msg: &str) -> Result<bool, RuntimeError> {
        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::request")?;
        let slot = slots.entry(id).or_default();
        if slot.settled {
            return Ok(false);
        }
        if slot.message.is_none() {
            slot.message = Some(msg.to_string());
        }
        Ok(true)
    }

    pub(crate) fn take(&self, id: FlowId) -> Result<Option<String>, RuntimeError> {
        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::take")?;
        let Some(slot) = slots.get_mut(&id) else {
            return Ok(None);
        };
        let message = slot.message.take();
        if message.is_none() && !slot.settled {
            slots.remove(&id);
        }
        Ok(message)
    }

    /// Mark a successful outcome. `Some` is a host failure that won the race
    /// and must replace that success.
    pub(crate) fn commit_success(&self, id: FlowId) -> Result<Option<String>, RuntimeError> {
        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::commit_success")?;
        let slot = slots.entry(id).or_default();
        slot.settled = true;
        Ok(slot.message.take())
    }

    pub(crate) fn seal(&self, id: FlowId) -> Result<(), RuntimeError> {
        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::seal")?;
        let slot = slots.entry(id).or_default();
        slot.settled = true;
        slot.message = None;
        Ok(())
    }

    pub(crate) fn clear(&self, id: FlowId) -> Result<(), RuntimeError> {
        let mut slots = sync_lock::lock(&self.inner, "HostAwaitFailures::clear")?;
        slots.remove(&id);
        Ok(())
    }
}

/// Process-wide table of in-flight `HostAwait` tickets.
///
/// The flow itself stays on a worker or in its mailbox. This table only
/// records the ticket so completion and cancellation compete for one removal.
pub struct HostAwaitIndex {
    inner: Mutex<HostAwaitInner>,
    max: usize,
}

struct HostAwaitInner {
    by_ticket: HashMap<u64, AwaitEntry>,
    by_flow: HashMap<FlowId, Vec<u64>>,
    next_ticket: u64,
}

impl HostAwaitIndex {
    /// `max_host_awaits == 0` → unlimited.
    pub fn new(max_host_awaits: u32) -> Self {
        Self::with_next(max_host_awaits, 1)
    }

    fn with_next(max_host_awaits: u32, next_ticket: u64) -> Self {
        Self {
            inner: Mutex::new(HostAwaitInner {
                by_ticket: HashMap::new(),
                by_flow: HashMap::new(),
                next_ticket,
            }),
            max: max_host_awaits as usize,
        }
    }

    pub fn register(
        &self,
        flow: FlowId,
        op: HostAwaitOp,
    ) -> Result<Result<RegisteredAwait, HostAwaitParkError>, RuntimeError> {
        let mut entries = sync_lock::lock(&self.inner, "HostAwaitIndex::register")?;
        if self.max != 0 && entries.by_ticket.len() >= self.max {
            return Ok(Err(HostAwaitParkError::LimitReached {
                current: entries.by_ticket.len(),
                max: self.max,
            }));
        }
        if entries.next_ticket == 0 || entries.next_ticket >= i64::MAX as u64 {
            return Ok(Err(HostAwaitParkError::IdExhausted));
        }
        let id = entries.next_ticket;
        entries.next_ticket += 1;
        let cancelled = Arc::new(AtomicBool::new(false));
        entries.by_flow.entry(flow).or_default().push(id);
        entries.by_ticket.insert(
            id,
            AwaitEntry {
                flow,
                op,
                cancelled: Arc::clone(&cancelled),
            },
        );
        Ok(Ok(RegisteredAwait { id, cancelled }))
    }

    /// Removes the ticket once. `None` means it was already completed or cancelled.
    pub fn take_ticket(&self, ticket: u64) -> Result<Option<FlowId>, RuntimeError> {
        let mut entries = sync_lock::lock(&self.inner, "HostAwaitIndex::take_ticket")?;
        let Some(entry) = entries.by_ticket.remove(&ticket) else {
            return Ok(None);
        };
        unlink(&mut entries, entry.flow, ticket);
        if entry.cancelled.load(Ordering::Acquire) {
            return Ok(None);
        }
        Ok(Some(entry.flow))
    }

    /// Cancels every ticket of `flow`. The caller notifies the host after
    /// this returns, so the bridge does not run under the registry lock.
    pub fn cancel_flow(&self, flow: FlowId) -> Result<Vec<CancelledAwait>, RuntimeError> {
        let mut entries = sync_lock::lock(&self.inner, "HostAwaitIndex::cancel_flow")?;
        Ok(take_flow_ids(&mut entries, flow))
    }

    /// Cancels every outstanding ticket (runtime shutdown).
    pub(crate) fn cancel_all(&self) -> Result<Vec<CancelledAwait>, RuntimeError> {
        let mut entries = sync_lock::lock(&self.inner, "HostAwaitIndex::cancel_all")?;
        entries.by_flow.clear();
        let mut notices = Vec::with_capacity(entries.by_ticket.len());
        for (ticket, entry) in entries.by_ticket.drain() {
            entry.cancelled.store(true, Ordering::Release);
            notices.push(CancelledAwait {
                flow: entry.flow,
                op: entry.op,
                ticket,
            });
        }
        Ok(notices)
    }

    #[cfg(test)]
    pub fn outstanding(&self) -> Result<usize, RuntimeError> {
        let entries = sync_lock::lock(&self.inner, "HostAwaitIndex::outstanding")?;
        Ok(entries.by_ticket.len())
    }
}

fn unlink(entries: &mut HostAwaitInner, flow: FlowId, ticket: u64) {
    let Some(ids) = entries.by_flow.get_mut(&flow) else {
        return;
    };
    ids.retain(|id| *id != ticket);
    if ids.is_empty() {
        entries.by_flow.remove(&flow);
    }
}

fn take_flow_ids(entries: &mut HostAwaitInner, flow: FlowId) -> Vec<CancelledAwait> {
    let Some(ids) = entries.by_flow.remove(&flow) else {
        return Vec::new();
    };
    let mut notices = Vec::with_capacity(ids.len());
    for ticket in ids {
        if let Some(entry) = entries.by_ticket.remove(&ticket) {
            entry.cancelled.store(true, Ordering::Release);
            notices.push(CancelledAwait {
                flow,
                op: entry.op,
                ticket,
            });
        }
    }
    notices
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn allows_multiple_operations_for_one_flow() -> Result<(), Box<dyn std::error::Error>> {
        let index = HostAwaitIndex::new(0);
        let first = registered(&index, FlowId(7), 1)?;
        let second = registered(&index, FlowId(7), 2)?;

        assert_ne!(first.id, second.id);
        assert!(!first.cancelled.load(Ordering::Acquire));
        assert!(!second.cancelled.load(Ordering::Acquire));
        assert_eq!(index.outstanding()?, 2);

        assert_eq!(index.take_ticket(first.id)?, Some(FlowId(7)));
        assert_eq!(index.take_ticket(second.id)?, Some(FlowId(7)));
        assert_eq!(index.outstanding()?, 0);
        Ok(())
    }

    #[test]
    fn cancel_flow_invalidates_all_its_operations() -> Result<(), Box<dyn std::error::Error>> {
        let index = HostAwaitIndex::new(0);
        let left = registered(&index, FlowId(10), 1)?;
        let right = registered(&index, FlowId(10), 2)?;
        let other = registered(&index, FlowId(20), 1)?;

        let notices = index.cancel_flow(FlowId(10))?;
        assert_eq!(notices.len(), 2);
        assert!(left.cancelled.load(Ordering::Acquire));
        assert!(right.cancelled.load(Ordering::Acquire));
        assert!(!other.cancelled.load(Ordering::Acquire));

        assert_eq!(index.take_ticket(left.id)?, None);
        assert_eq!(index.take_ticket(right.id)?, None);
        assert_eq!(index.take_ticket(other.id)?, Some(FlowId(20)));
        assert_eq!(index.outstanding()?, 0);
        Ok(())
    }

    #[test]
    fn completion_is_consumed_only_once() -> Result<(), Box<dyn std::error::Error>> {
        let index = HostAwaitIndex::new(0);
        let registered = registered(&index, FlowId(42), 1)?;

        assert_eq!(index.take_ticket(registered.id)?, Some(FlowId(42)));
        assert_eq!(index.take_ticket(registered.id)?, None);
        Ok(())
    }

    #[test]
    fn shutdown_cancels_all_operations() -> Result<(), Box<dyn std::error::Error>> {
        let index = HostAwaitIndex::new(0);
        let left = registered(&index, FlowId(1), 1)?;
        let right = registered(&index, FlowId(2), 1)?;

        assert_eq!(index.cancel_all()?.len(), 2);
        assert!(left.cancelled.load(Ordering::Acquire));
        assert!(right.cancelled.load(Ordering::Acquire));
        assert_eq!(index.take_ticket(left.id)?, None);
        assert_eq!(index.take_ticket(right.id)?, None);
        assert_eq!(index.outstanding()?, 0);
        Ok(())
    }

    #[test]
    fn register_hits_process_limit() -> Result<(), Box<dyn std::error::Error>> {
        let index = HostAwaitIndex::new(1);
        let _first = registered(&index, FlowId(1), 1)?;
        match index.register(FlowId(2), 1)? {
            Err(HostAwaitParkError::LimitReached { current: 1, max: 1 }) => Ok(()),
            Ok(_) => Err("expected limit".into()),
            Err(err) => Err(format!("wrong park error: {err}").into()),
        }
    }

    #[test]
    fn slot_is_free_after_take() -> Result<(), Box<dyn std::error::Error>> {
        let index = HostAwaitIndex::new(1);
        let first = registered(&index, FlowId(1), 1)?;
        assert!(index.take_ticket(first.id)?.is_some());
        let _second = registered(&index, FlowId(2), 1)?;
        Ok(())
    }

    #[test]
    fn commit_keeps_a_fail_that_arrives_after_the_poll() -> Result<(), RuntimeError> {
        let failures = HostAwaitFailures::new();
        assert!(failures.take(FlowId(1))?.is_none());
        assert!(failures.request(FlowId(1), "host boom")?);
        assert_eq!(
            failures.commit_success(FlowId(1))?.as_deref(),
            Some("host boom")
        );
        Ok(())
    }

    #[test]
    fn request_after_commit_is_too_late() -> Result<(), RuntimeError> {
        let failures = HostAwaitFailures::new();
        assert!(failures.commit_success(FlowId(1))?.is_none());
        assert!(!failures.request(FlowId(1), "late")?);
        Ok(())
    }

    #[test]
    fn ticket_ids_stop_before_i64_max() -> Result<(), Box<dyn std::error::Error>> {
        let index = HostAwaitIndex::with_next(0, i64::MAX as u64);
        match index.register(FlowId(1), 1)? {
            Err(HostAwaitParkError::IdExhausted) => Ok(()),
            Ok(_) => Err("expected exhausted ids".into()),
            Err(err) => Err(format!("wrong park error: {err}").into()),
        }
    }

    #[test]
    fn complete_and_cancel_remove_the_ticket_once() -> Result<(), Box<dyn std::error::Error>> {
        let index = Arc::new(HostAwaitIndex::new(0));
        let registered = registered(&index, FlowId(3), 9)?;
        let ticket = registered.id;
        let taker = Arc::clone(&index);
        let canceller = Arc::clone(&index);
        let took = std::thread::spawn(move || taker.take_ticket(ticket));
        let cancelled = std::thread::spawn(move || canceller.cancel_flow(FlowId(3)));
        let took = match took.join() {
            Ok(result) => result?,
            Err(_) => return Err("take join".into()),
        };
        let cancelled = match cancelled.join() {
            Ok(result) => result?,
            Err(_) => return Err("cancel join".into()),
        };
        let won_take = took.is_some();
        let won_cancel = !cancelled.is_empty();
        assert!(won_take ^ won_cancel, "take={won_take} cancel={won_cancel}");
        assert_eq!(index.outstanding()?, 0);
        if won_cancel {
            assert!(registered.cancelled.load(Ordering::Acquire));
        }
        Ok(())
    }

    fn registered(
        index: &HostAwaitIndex,
        flow: FlowId,
        op: HostAwaitOp,
    ) -> Result<RegisteredAwait, Box<dyn std::error::Error>> {
        match index.register(flow, op)? {
            Ok(registered) => Ok(registered),
            Err(err) => Err(err.to_string().into()),
        }
    }
}

/// Runtime-level HostAwait coverage (bridge wiring, limits, lifecycle).
#[cfg(test)]
mod runtime_tests {
    use super::*;
    use crate::bytecode::{CapId, Message, Program};
    use crate::scheduler::mailbox::{MailboxCapacity, MailboxConfig, OverflowPolicy};
    use crate::scheduler::process::FlowOutcome;
    use crate::scheduler::runtime::{Runtime, RuntimeConfig};
    use std::sync::{Arc, Condvar, Mutex};
    use std::time::Duration;

    /// Causal hold: waits until `n` submits arrived (no sleep races).
    struct HoldBridge {
        state: Mutex<HoldState>,
        cv: Condvar,
    }

    struct HoldState {
        held: Vec<(FlowId, HostAwaitCompleter)>,
        submitted: usize,
    }

    impl HoldBridge {
        fn new() -> Self {
            Self {
                state: Mutex::new(HoldState {
                    held: Vec::new(),
                    submitted: 0,
                }),
                cv: Condvar::new(),
            }
        }

        fn wait_for_submissions(&self, n: usize) -> Result<(), &'static str> {
            let mut guard = match self.state.lock() {
                Ok(guard) => guard,
                Err(_) => return Err("HoldBridge lock"),
            };
            while guard.submitted < n {
                guard = match self.cv.wait(guard) {
                    Ok(guard) => guard,
                    Err(_) => return Err("HoldBridge wait"),
                };
            }
            Ok(())
        }

        fn take_all(&self) -> Result<Vec<(FlowId, HostAwaitCompleter)>, &'static str> {
            let mut guard = match self.state.lock() {
                Ok(guard) => guard,
                Err(_) => return Err("HoldBridge lock"),
            };
            Ok(std::mem::take(&mut guard.held))
        }

        fn take_one(&self) -> Result<Option<(FlowId, HostAwaitCompleter)>, &'static str> {
            let mut guard = match self.state.lock() {
                Ok(guard) => guard,
                Err(_) => return Err("HoldBridge lock"),
            };
            if guard.held.is_empty() {
                Ok(None)
            } else {
                Ok(Some(guard.held.remove(0)))
            }
        }
    }

    impl std::fmt::Debug for HoldBridge {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("HoldBridge")
        }
    }

    impl HostAwaitBridge for HoldBridge {
        fn submit(&self, req: HostAwaitRequest, done: HostAwaitCompleter) {
            match self.state.lock() {
                Ok(mut guard) => {
                    guard.held.push((req.flow, done));
                    guard.submitted += 1;
                    self.cv.notify_all();
                }
                Err(_) => {
                    let _ = done.fail("HoldBridge lock poisoned");
                }
            }
        }
    }

    fn waiter_program() -> (Program, u32) {
        let mut program = Program::new("ha-waiter");
        let waiter = program.function("waiter", 0, |f| {
            let args = f.load_i32(0);
            let _ticket = f.host_await(1, args);
            let msg = f.receive();
            f.return_(msg);
        });
        (program, waiter)
    }

    fn payload_int(outcome: &FlowOutcome) -> Option<i64> {
        match outcome {
            FlowOutcome::Completed(Value::Message(msg)) => match msg.payload.as_ref() {
                Value::Int(n) => Some(*n),
                _ => None,
            },
            _ => None,
        }
    }

    #[test]
    fn host_await_without_bridge_fails() -> Result<(), Box<dyn std::error::Error>> {
        let mut program = Program::new("ha-none");
        program.function("main", 0, |f| {
            let args = f.load_i32(1);
            let out = f.host_await(1, args);
            f.return_(out);
        });
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                host_await: None,
                ..Default::default()
            },
        )?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();
        match outcome {
            FlowOutcome::Failed(msg) if msg.contains("no bridge") => Ok(()),
            other => Err(format!("expected no-bridge failure, got {other:?}").into()),
        }
    }

    #[test]
    fn host_await_thread_bridge_delivers_a_hop() -> Result<(), Box<dyn std::error::Error>> {
        #[derive(Debug)]
        struct EchoBridge;

        impl HostAwaitBridge for EchoBridge {
            fn submit(&self, req: HostAwaitRequest, done: HostAwaitCompleter) {
                std::thread::spawn(move || {
                    let value = match (req.op, &req.args) {
                        (1, Value::Int(n)) => Value::Int(n + 1),
                        _ => Value::Int(42),
                    };
                    let _ = done.complete(value);
                });
            }
        }

        let mut program = Program::new("ha-echo");
        program.function("main", 0, |f| {
            let args = f.load_i32(41);
            let _ticket = f.host_await(1, args);
            let msg = f.receive();
            f.return_(msg);
        });
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                host_await: Some(Arc::new(EchoBridge)),
                ..Default::default()
            },
        )?;
        let outcome = rt
            .spawn(0, &[])?
            .join_timeout(Duration::from_secs(2))
            .ok_or("host_await timed out")?;
        rt.shutdown();
        match &outcome {
            FlowOutcome::Completed(Value::Message(msg))
                if msg.sender == FlowId::HOST.as_u64()
                    && msg.reply_cap.is_none()
                    && msg.tag == TAG_SYS_AWAIT
                    && matches!(msg.payload.as_ref(), Value::Int(42)) =>
            {
                Ok(())
            }
            other => Err(format!("expected await hop 42, got {other:?}").into()),
        }
    }

    #[test]
    fn host_await_limit_rejects_second() -> Result<(), Box<dyn std::error::Error>> {
        let bridge = Arc::new(HoldBridge::new());
        let (program, waiter) = waiter_program();
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 2,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                max_host_awaits: 1,
                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
                ..Default::default()
            },
        )?;

        let first = rt.spawn(waiter, &[])?;
        bridge.wait_for_submissions(1)?;
        let second = rt.spawn(waiter, &[])?;
        let second_out = second
            .join_timeout(Duration::from_secs(2))
            .ok_or("second HostAwait did not finish")?;

        for (_, done) in bridge.take_all()? {
            let _ = done.complete(Value::Int(0));
        }
        let _ = first.join_timeout(Duration::from_secs(2));
        rt.shutdown();

        match second_out {
            FlowOutcome::Failed(msg) if msg.contains("HostAwait limit") => Ok(()),
            other => Err(format!("expected HostAwait limit failure, got {other:?}").into()),
        }
    }

    #[test]
    fn host_await_slot_reused_after_complete() -> Result<(), Box<dyn std::error::Error>> {
        let bridge = Arc::new(HoldBridge::new());
        let (program, waiter) = waiter_program();
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 2,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                max_host_awaits: 1,
                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
                ..Default::default()
            },
        )?;

        let first = rt.spawn(waiter, &[])?;
        bridge.wait_for_submissions(1)?;
        let second = rt.spawn(waiter, &[])?;
        let second_out = second
            .join_timeout(Duration::from_secs(2))
            .ok_or("second should fail on limit")?;
        assert!(
            matches!(
                &second_out,
                FlowOutcome::Failed(msg) if msg.contains("HostAwait limit")
            ),
            "got {second_out:?}"
        );

        let (_, done) = bridge.take_one()?.ok_or("missing first completer")?;
        done.complete(Value::Int(7))?;
        let first_out = first
            .join_timeout(Duration::from_secs(2))
            .ok_or("first hop timed out")?;
        assert_eq!(payload_int(&first_out), Some(7), "got {first_out:?}");

        let third = rt.spawn(waiter, &[])?;
        bridge.wait_for_submissions(2)?;
        let (_, done3) = bridge.take_one()?.ok_or("missing third completer")?;
        done3.complete(Value::Int(9))?;
        let third_out = third
            .join_timeout(Duration::from_secs(2))
            .ok_or("third hop timed out")?;
        rt.shutdown();

        match payload_int(&third_out) {
            Some(9) => Ok(()),
            _ => Err(format!("expected slot reuse hop, got {third_out:?}").into()),
        }
    }

    #[test]
    fn host_await_max_zero_allows_concurrent() -> Result<(), Box<dyn std::error::Error>> {
        let bridge = Arc::new(HoldBridge::new());
        let (program, waiter) = waiter_program();
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 2,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                max_host_awaits: 0,
                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
                ..Default::default()
            },
        )?;

        let a = rt.spawn(waiter, &[])?;
        let b = rt.spawn(waiter, &[])?;
        bridge.wait_for_submissions(2)?;
        for (_, done) in bridge.take_all()? {
            let _ = done.complete(Value::Int(1));
        }
        let a_out = a
            .join_timeout(Duration::from_secs(2))
            .ok_or("a timed out")?;
        let b_out = b
            .join_timeout(Duration::from_secs(2))
            .ok_or("b timed out")?;
        rt.shutdown();

        match (payload_int(&a_out), payload_int(&b_out)) {
            (Some(1), Some(1)) => Ok(()),
            _ => Err(format!("expected both hops, got {a_out:?} {b_out:?}").into()),
        }
    }

    #[test]
    fn two_awaits_on_one_flow_both_deliver() -> Result<(), Box<dyn std::error::Error>> {
        let bridge = Arc::new(HoldBridge::new());
        let mut program = Program::new("ha-two");
        program.function("main", 0, |f| {
            let left = f.load_i32(11);
            let right = f.load_i32(22);
            let _first = f.host_await(1, left);
            let _second = f.host_await(2, right);
            let first = f.receive();
            let _second_msg = f.receive();
            f.return_(first);
        });
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
                ..Default::default()
            },
        )?;
        let handle = rt.spawn(0, &[])?;
        bridge.wait_for_submissions(2)?;
        let mut held = bridge.take_all()?;
        assert_eq!(held.len(), 2);
        let (_, second) = held.pop().ok_or("second completer")?;
        let (_, first) = held.pop().ok_or("first completer")?;
        assert_ne!(first.ticket(), second.ticket());
        first.complete(Value::Int(11))?;
        second.complete(Value::Int(22))?;
        let outcome = handle
            .join_timeout(Duration::from_secs(2))
            .ok_or("two-await timed out")?;
        rt.shutdown();
        match payload_int(&outcome) {
            Some(11) => Ok(()),
            _ => Err(format!("expected first hop 11, got {outcome:?}").into()),
        }
    }

    #[test]
    fn replay_delivers_completions_in_script_order() -> Result<(), Box<dyn std::error::Error>> {
        let bridge = Arc::new(HoldBridge::new());
        let mut program = Program::new("ha-replay");
        program.function("main", 0, |f| {
            let left = f.load_i32(11);
            let right = f.load_i32(22);
            let _first = f.host_await(1, left);
            let _second = f.host_await(2, right);
            let first = f.receive();
            let _second_msg = f.receive();
            f.return_(first);
        });
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
                ..Default::default()
            },
        )?;
        rt.enable_host_await_replay()?;
        let handle = rt.spawn(0, &[])?;
        bridge.wait_for_submissions(2)?;
        let mut held = bridge.take_all()?;
        let (_, second) = held.pop().ok_or("second completer")?;
        let (_, first) = held.pop().ok_or("first completer")?;
        rt.bind_host_await_replay(first.ticket(), 1)?;
        rt.bind_host_await_replay(second.ticket(), 0)?;
        first.complete(Value::Int(11))?;
        second.complete(Value::Int(22))?;
        let outcome = handle
            .join_timeout(Duration::from_secs(2))
            .ok_or("replay timed out")?;
        rt.shutdown();
        match payload_int(&outcome) {
            Some(22) => Ok(()),
            _ => Err(format!("expected script order 22 then 11, got {outcome:?}").into()),
        }
    }

    #[test]
    fn kill_parked_host_await_then_complete_is_stale() -> Result<(), Box<dyn std::error::Error>> {
        let bridge = Arc::new(HoldBridge::new());
        let (program, waiter) = waiter_program();
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
                ..Default::default()
            },
        )?;

        let handle = rt.spawn(waiter, &[])?;
        bridge.wait_for_submissions(1)?;
        let (flow_id, done) = bridge.take_one()?.ok_or("missing completer")?;
        assert_eq!(flow_id, handle.id());
        rt.kill(handle.id())?;
        let outcome = handle
            .join_timeout(Duration::from_secs(2))
            .ok_or("kill join timed out")?;
        assert!(
            matches!(outcome, FlowOutcome::Failed(_)),
            "kill must fail joiner, got {outcome:?}"
        );
        assert!(done.is_cancelled());
        let stale = done.complete(Value::Int(1));
        rt.shutdown();
        match stale {
            Err(HostAwaitError::Stale) => Ok(()),
            other => Err(format!("expected Stale after kill, got {other:?}").into()),
        }
    }

    #[test]
    fn shutdown_with_parked_host_await_does_not_hang() -> Result<(), Box<dyn std::error::Error>> {
        let bridge = Arc::new(HoldBridge::new());
        let (program, waiter) = waiter_program();
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
                ..Default::default()
            },
        )?;

        let handle = rt.spawn(waiter, &[])?;
        bridge.wait_for_submissions(1)?;
        rt.shutdown();
        let outcome = handle
            .join_timeout(Duration::from_secs(2))
            .ok_or("joiner stuck after shutdown")?;
        for (_, done) in bridge.take_all()? {
            assert!(done.is_cancelled());
            assert!(matches!(
                done.complete(Value::Int(1)),
                Err(HostAwaitError::Stale)
            ));
        }
        match outcome {
            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
            other => Err(format!("expected shutdown failure, got {other:?}").into()),
        }
    }

    #[test]
    fn unknown_cap_in_completion_rejects_and_fails_the_flow(
    ) -> Result<(), Box<dyn std::error::Error>> {
        let bridge = Arc::new(HoldBridge::new());
        let (program, waiter) = waiter_program();
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
                ..Default::default()
            },
        )?;
        let handle = rt.spawn(waiter, &[])?;
        bridge.wait_for_submissions(1)?;
        let (_, done) = bridge.take_one()?.ok_or("missing completer")?;
        let rejected = done.complete(Value::Cap(CapId::from_raw(1)));
        let outcome = handle
            .join_timeout(Duration::from_secs(2))
            .ok_or("cap rejection timed out")?;
        rt.shutdown();
        match rejected {
            Err(HostAwaitError::Rejected) => {}
            other => return Err(format!("expected Rejected, got {other:?}").into()),
        }
        match outcome {
            FlowOutcome::Failed(msg) if msg.contains("capability") => Ok(()),
            other => Err(format!("expected capability failure, got {other:?}").into()),
        }
    }

    #[test]
    fn fail_during_submit_uses_the_host_message() -> Result<(), Box<dyn std::error::Error>> {
        #[derive(Debug)]
        struct Boom;
        impl HostAwaitBridge for Boom {
            fn submit(&self, _req: HostAwaitRequest, done: HostAwaitCompleter) {
                let _ = done.fail("host boom");
            }
        }
        let mut program = Program::new("ha-boom");
        program.function("main", 0, |f| {
            let args = f.load_i32(1);
            let _ticket = f.host_await(1, args);
            f.return_(args);
        });
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                host_await: Some(Arc::new(Boom)),
                ..Default::default()
            },
        )?;
        let outcome = rt
            .spawn(0, &[])?
            .join_timeout(Duration::from_secs(2))
            .ok_or("fail join timed out")?;
        rt.shutdown();
        match outcome {
            FlowOutcome::Failed(msg) if msg.contains("host boom") => Ok(()),
            other => Err(format!("expected host boom, got {other:?}").into()),
        }
    }

    #[test]
    fn fail_after_the_flow_commits_is_stale() -> Result<(), Box<dyn std::error::Error>> {
        let bridge = Arc::new(HoldBridge::new());
        let mut program = Program::new("ha-late-fail");
        program.function("main", 0, |f| {
            let args = f.load_i32(1);
            let _ticket = f.host_await(1, args);
            f.return_(args);
        });
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
                ..Default::default()
            },
        )?;
        let handle = rt.spawn(0, &[])?;
        bridge.wait_for_submissions(1)?;
        let (_, done) = bridge.take_one()?.ok_or("missing completer")?;
        let outcome = handle
            .join_timeout(Duration::from_secs(2))
            .ok_or("commit timed out")?;
        let late = done.fail("too late");
        rt.shutdown();
        match outcome {
            FlowOutcome::Completed(Value::Int(1)) => {}
            other => return Err(format!("expected completed 1, got {other:?}").into()),
        }
        match late {
            Err(HostAwaitError::Stale) => Ok(()),
            other => Err(format!("expected stale fail, got {other:?}").into()),
        }
    }

    #[test]
    fn replay_keeps_delivering_after_a_full_mailbox() -> Result<(), Box<dyn std::error::Error>> {
        let bridge = Arc::new(HoldBridge::new());
        let capacity = MailboxCapacity::new(1).ok_or("capacity")?;
        let mut program = Program::new("ha-replay-full");
        let blocked = program.function("blocked", 0, |f| {
            let args = f.load_i32(1);
            let _ticket = f.host_await(1, args);
            let _ignored = f.receive_match_imm(1);
            f.return_(args);
        });
        let open = program.function("open", 0, |f| {
            let args = f.load_i32(22);
            let _ticket = f.host_await(2, args);
            let msg = f.receive();
            f.return_(msg);
        });
        let gate = program.function("gate", 0, |f| {
            let n = f.load_i32(1);
            f.return_(n);
        });
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::new(capacity, OverflowPolicy::Reject),
                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
                ..Default::default()
            },
        )?;
        rt.enable_host_await_replay()?;
        let blocked_handle = rt.spawn(blocked, &[])?;
        let open_handle = rt.spawn(open, &[])?;
        let blocked_id = blocked_handle.id();
        let open_id = open_handle.id();
        bridge.wait_for_submissions(2)?;
        let parked = rt.spawn(gate, &[])?;
        let parked_out = parked
            .join_timeout(Duration::from_secs(2))
            .ok_or("worker did not become free")?;
        match parked_out {
            FlowOutcome::Completed(Value::Int(1)) => {}
            other => return Err(format!("worker did not become free, got {other:?}").into()),
        }
        let mut blocked_done = None;
        let mut open_done = None;
        for (id, done) in bridge.take_all()? {
            if id == blocked_id {
                blocked_done = Some(done);
            } else if id == open_id {
                open_done = Some(done);
            }
        }
        let blocked_done = blocked_done.ok_or("blocked completer")?;
        let open_done = open_done.ok_or("open completer")?;
        rt.send(
            blocked_id,
            Value::Message(Message::request(9, 2, Value::Int(0))),
        )?;
        rt.bind_host_await_replay(open_done.ticket(), 1)?;
        rt.bind_host_await_replay(blocked_done.ticket(), 0)?;
        open_done.complete(Value::Int(22))?;
        let blocked_result = blocked_done.complete(Value::Int(7));
        let open_out = open_handle
            .join_timeout(Duration::from_secs(2))
            .ok_or("open hop timed out")?;
        let _ = blocked_handle.join_timeout(Duration::from_secs(2));
        rt.shutdown();
        match blocked_result {
            Err(HostAwaitError::Mailbox(crate::scheduler::MailboxFullReason::MessageLimit)) => {}
            other => return Err(format!("expected a full mailbox, got {other:?}").into()),
        }
        match payload_int(&open_out) {
            Some(22) => Ok(()),
            _ => Err(format!("expected the later hop to arrive, got {open_out:?}").into()),
        }
    }

    #[test]
    fn threaded_host_await_delivers_sys_await() -> Result<(), Box<dyn std::error::Error>> {
        let bridge = ThreadedHostAwait::new(|req, _cancelled| match req.args {
            Value::Int(n) => Ok(Value::Int(n + 1)),
            _ => Err("host args".into()),
        });
        let mut program = Program::new("ha-thread");
        program.function("main", 0, |f| {
            let args = f.load_i32(41);
            let _ticket = f.host_await(1, args);
            let msg = f.receive();
            f.return_(msg);
        });
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                host_await: Some(Arc::new(bridge)),
                ..RuntimeConfig::default()
            },
        )?;
        let outcome = rt
            .spawn(0, &[])?
            .join_timeout(Duration::from_secs(2))
            .ok_or("threaded host await timed out")?;
        rt.shutdown();
        match &outcome {
            FlowOutcome::Completed(Value::Message(msg))
                if msg.tag == TAG_SYS_AWAIT && matches!(msg.payload.as_ref(), Value::Int(42)) =>
            {
                Ok(())
            }
            other => Err(format!("expected TAG_SYS_AWAIT 42, got {other:?}").into()),
        }
    }

    #[test]
    fn threaded_submit_returns_while_host_work_is_blocked() -> Result<(), Box<dyn std::error::Error>>
    {
        let gate = Arc::new((Mutex::new(false), Condvar::new()));
        let started = Arc::new((Mutex::new(false), Condvar::new()));
        let gate_work = Arc::clone(&gate);
        let started_work = Arc::clone(&started);
        let bridge = ThreadedHostAwait::new(move |req, cancelled| {
            if let Ok(mut flag) = started_work.0.lock() {
                *flag = true;
                started_work.1.notify_all();
            }
            let (lock, cv) = &*gate_work;
            let mut guard = lock.lock().map_err(|_| "gate".to_string())?;
            while !*guard {
                if cancelled() {
                    return Err("cancelled".into());
                }
                let (next, _) = cv
                    .wait_timeout(guard, Duration::from_millis(20))
                    .map_err(|_| "gate wait".to_string())?;
                guard = next;
            }
            match req.args {
                Value::Int(n) => Ok(Value::Int(n)),
                _ => Ok(Value::Int(0)),
            }
        });
        let mut program = Program::new("ha-block");
        program.function("main", 0, |f| {
            let args = f.load_i32(7);
            let _ticket = f.host_await(1, args);
            let msg = f.receive();
            f.return_(msg);
        });
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                host_await: Some(Arc::new(bridge)),
                ..RuntimeConfig::default()
            },
        )?;
        let handle = rt.spawn(0, &[])?;
        let mut flag = started.0.lock().map_err(|_| "started lock")?;
        let deadline = std::time::Instant::now() + Duration::from_secs(2);
        while !*flag {
            let (next, timeout) = started
                .1
                .wait_timeout(flag, Duration::from_millis(50))
                .map_err(|_| "started wait")?;
            flag = next;
            if timeout.timed_out() && std::time::Instant::now() > deadline {
                return Err("host work did not start".into());
            }
        }
        drop(flag);
        if handle.join_timeout(Duration::from_millis(80)).is_some() {
            return Err("submit blocked the flow until the host work finished".into());
        }
        if let Ok(mut release) = gate.0.lock() {
            *release = true;
            gate.1.notify_all();
        }
        let outcome = handle
            .join_timeout(Duration::from_secs(2))
            .ok_or("blocked host work did not finish")?;
        rt.shutdown();
        match payload_int(&outcome) {
            Some(7) => Ok(()),
            _ => Err(format!("expected 7 after release, got {outcome:?}").into()),
        }
    }

    #[test]
    fn threaded_cancel_drops_the_late_result() -> Result<(), Box<dyn std::error::Error>> {
        let gate = Arc::new((Mutex::new(false), Condvar::new()));
        let started = Arc::new((Mutex::new(false), Condvar::new()));
        let gate_work = Arc::clone(&gate);
        let started_work = Arc::clone(&started);
        let bridge = ThreadedHostAwait::new(move |_req, cancelled| {
            if let Ok(mut flag) = started_work.0.lock() {
                *flag = true;
                started_work.1.notify_all();
            }
            let (lock, cv) = &*gate_work;
            let mut guard = lock.lock().map_err(|_| "gate".to_string())?;
            while !cancelled() && !*guard {
                let (next, _) = cv
                    .wait_timeout(guard, Duration::from_millis(20))
                    .map_err(|_| "gate wait".to_string())?;
                guard = next;
            }
            Ok(Value::Int(99))
        });
        let (program, waiter) = waiter_program();
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                host_await: Some(Arc::new(bridge)),
                ..RuntimeConfig::default()
            },
        )?;
        let handle = rt.spawn(waiter, &[])?;
        let mut flag = started.0.lock().map_err(|_| "started lock")?;
        while !*flag {
            flag = started.1.wait(flag).map_err(|_| "started wait")?;
        }
        drop(flag);
        rt.kill(handle.id())?;
        let outcome = handle
            .join_timeout(Duration::from_secs(2))
            .ok_or("kill did not finish")?;
        if let Ok(mut release) = gate.0.lock() {
            *release = true;
            gate.1.notify_all();
        }
        std::thread::sleep(Duration::from_millis(50));
        rt.shutdown();
        match outcome {
            FlowOutcome::Failed(_) => Ok(()),
            FlowOutcome::Completed(Value::Message(msg))
                if matches!(msg.payload.as_ref(), Value::Int(99)) =>
            {
                Err("late host result resurrected the flow".into())
            }
            other => Err(format!("expected the kill outcome, got {other:?}").into()),
        }
    }

    #[test]
    fn finish_after_cancel_is_stale() -> Result<(), Box<dyn std::error::Error>> {
        let bridge = Arc::new(HoldBridge::new());
        let (program, waiter) = waiter_program();
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                host_await: Some(Arc::clone(&bridge) as Arc<dyn HostAwaitBridge>),
                ..RuntimeConfig::default()
            },
        )?;
        let handle = rt.spawn(waiter, &[])?;
        bridge.wait_for_submissions(1)?;
        let (_flow, done) = bridge.take_one()?.ok_or("missing completer")?;
        rt.kill(handle.id())?;
        let outcome = handle
            .join_timeout(Duration::from_secs(2))
            .ok_or("kill join timed out")?;
        let stale = finish_host_await(done, Ok(Value::Int(1)));
        rt.shutdown();
        if !matches!(outcome, FlowOutcome::Failed(_)) {
            return Err(format!("kill outcome changed, got {outcome:?}").into());
        }
        match stale {
            Err(HostAwaitError::Stale) => Ok(()),
            other => Err(format!("expected Stale, got {other:?}").into()),
        }
    }

    #[test]
    fn threaded_host_error_fails_the_flow() -> Result<(), Box<dyn std::error::Error>> {
        let bridge = ThreadedHostAwait::new(|_req, _cancelled| Err("host broke".into()));
        let mut program = Program::new("ha-err");
        program.function("main", 0, |f| {
            let args = f.load_i32(1);
            let _ticket = f.host_await(1, args);
            let msg = f.receive();
            f.return_(msg);
        });
        let rt = Runtime::with_config(
            program.build(),
            RuntimeConfig {
                workers: 1,
                host_await: Some(Arc::new(bridge)),
                ..RuntimeConfig::default()
            },
        )?;
        let outcome = rt
            .spawn(0, &[])?
            .join_timeout(Duration::from_secs(2))
            .ok_or("host error timed out")?;
        rt.shutdown();
        match outcome {
            FlowOutcome::Failed(msg) if msg.contains("host broke") => Ok(()),
            other => Err(format!("expected host broke, got {other:?}").into()),
        }
    }
}