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
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread::JoinHandle;

use crate::bytecode::{Cap, CapRights, CapTarget, Chunk, NativeMask, Value};
use crate::vm::{NativeGate, NativeTable, Vm};

use super::directory::Directory;
use super::error::{RuntimeError, SpawnError};
use super::finalize::finalize_flow;
use super::handle::FlowHandle;
use super::mailbox::{Delivery, Mailbox, MailboxConfig, MailboxFullReason};
use super::metrics::{RuntimeMetrics, RuntimeMetricsSnapshot, RuntimeSnapshot};
use super::monitor::FlowExitReason;
use super::process::{Flow, FlowId, FlowOutcome};
use super::runqueue::{Injector, Stealer, Worker as LocalDeque};
use super::supervisor::SupervisorLink;
use super::timer::TimerWheel;
use super::worker;
use crate::bytecode::RestartPolicy;

/// Default instruction budget per scheduling turn (design notes §10).
/// Chosen as a middle ground: large enough that the per-yield bookkeeping
/// cost is amortized over meaningful work, small enough that a
/// pathological `loop {}` in one flow can't visibly stall the others —
/// at 10k simple instructions/turn and even a conservative tens-of-millions
/// of instructions/sec per core, worst-case added latency for a sibling
/// flow is sub-millisecond.
pub const DEFAULT_QUANTUM: u32 = 10_000;

/// Tunables for [`Runtime::new`]. Everything has a sensible default via
/// [`RuntimeConfig::default`] so the common case is `Runtime::new(chunk)`.
#[derive(Clone, Debug)]
pub struct RuntimeConfig {
    /// Number of worker OS threads. Defaults to the number of logical CPUs
    /// — one worker per core is the right starting point for a CPU-bound
    /// M:N scheduler; embedders running alongside other CPU-heavy work on
    /// the same machine may want fewer. `0` is raised to `1`: a runtime
    /// with no worker cannot run a flow.
    pub workers: usize,
    /// Instructions a flow runs before being preempted back to the
    /// scheduler even if it never hits `Yield`. `0` is raised to `1`.
    /// A zero slice returns `Yield` without executing anything, and the
    /// worker would requeue that flow forever.
    pub quantum: u32,
    /// Memory + overflow contract applied to **every** flow mailbox
    /// spawned by this runtime (bytecode `Spawn` and host `spawn`).
    /// See [`MailboxConfig`] / `docs/mailbox.md`.
    pub mailbox: MailboxConfig,
    /// Hard cap on concurrently live flows (`0` = unlimited).
    /// Checked on every host and bytecode `spawn`.
    pub max_flows: u32,
    /// Hard cap on outstanding `Ask` / `AskTimeout` waiters process-wide
    /// (`0` = unlimited). Each asker holds at most one wait; this bounds the
    /// total index size when many flows park against a silent target.
    /// See [`crate::docs::security`] (DoS) and [`Self::sandbox`].
    pub max_ask_waits: u32,
    /// Hard cap on outstanding `HostAwait` parkers process-wide
    /// (`0` = unlimited). Each flow holds at most one await.
    pub max_host_awaits: u32,
    /// Hard cap on live process-wide links (`0` = unlimited).
    ///
    /// Accounting is performed by the link store itself, under
    /// the same synchronization that protects the link table.
    pub max_links: u32,
    /// Hard cap on live process-wide monitors (`0` = unlimited).
    ///
    /// Accounting is performed by the monitor store itself.
    pub max_monitors: u32,
    /// Hard cap on live process-wide registry names (`0` = unlimited).
    ///
    /// The registry store counts only successfully registered names.
    pub max_registry_names: u32,
    /// Host async bridge for [`crate::Opcode::HostAwait`]. `None` fails
    /// any `HostAwait` closed. Not a `CallNative` / std-native slot.
    pub host_await: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
    /// `0` = disabled. When set, [`Runtime::deliver_frame`] ignores duplicate
    /// `(sender, request_id)` pairs within the window (at-least-once wire).
    pub remote_dedup_window: u32,
    /// Host queue for [`crate::Opcode::SendRemote`]. `None` fails that opcode.
    /// Byteflow does not open sockets; the embedder drains the bridge.
    pub distribution: Option<Arc<super::distribution::DistributionBridge>>,
    /// Process-wide memory ceiling for heap charges (`Str` / `Bytes`
    /// register stores and shared [`crate::HeapStr`] / [`crate::HeapBytes`]).
    /// Independent of per-flow [`crate::QuotaConfig::mem_limit`] and mailbox
    /// byte budgets. Default: 256 MiB.
    pub max_runtime_bytes: usize,
    /// Constant-pool trust for [`crate::verify_with`] at runtime construction.
    /// Default is [`crate::TrustLevel::Untrusted`] (fail closed).
    pub trust: crate::bytecode::TrustLevel,
    /// Where bytecode `print` (native index 0) writes when using
    /// [`crate::std_native_table_with`]. Ignored if you supply your own table.
    pub output: Arc<dyn crate::OutputSink>,
    /// Scheduler diagnostics (`ask`, `finalize`, …). `None` keeps the
    /// `BYTEFLOW_LOG` stderr path and adds no collector. The sink is called
    /// inline and must not block or panic.
    pub log: Option<Arc<dyn crate::log::LogSink>>,
    /// Per-flow CPU / memory / spawn-send rate budgets.
    pub quota: super::quota::QuotaConfig,
    /// Optional security audit sink (capability / quota / module denials).
    /// Independent of [`Self::log`]; never receives full CapId tokens.
    pub security_audit: Option<Arc<dyn super::sandbox::SecurityAuditSink>>,
    /// Authority minted for host [`Runtime::spawn`] (not bytecode `Spawn`).
    ///
    /// Default [`RootAuthorityPolicy::TrustedHost`] preserves historical
    /// ROOT + full native mask. [`Self::sandbox`] does **not** change this —
    /// use [`Runtime::spawn_untrusted`] or set this field explicitly.
    pub root_authority: RootAuthorityPolicy,
    /// Trace JIT settings (`feature = "jit"`). Ignored when the feature is off.
    #[cfg(feature = "jit")]
    pub jit: JitConfig,
}

/// Initial Cap rights for host-spawned root flows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RootAuthorityPolicy {
    /// [`CapRights::ROOT`] + full native mask (historical host spawn).
    #[default]
    TrustedHost,
    /// Flow rights without [`CapRights::NATIVE`]; empty native mask.
    Restricted,
    /// [`CapRights::NONE`] + empty native mask (minimum authority).
    Untrusted,
}

impl RootAuthorityPolicy {
    fn mint(self, flow: u64, natives_len: usize, cell: &crate::bytecode::RevocationCell) -> Cap {
        match self {
            Self::TrustedHost => Cap::root(
                CapTarget::Flow(flow),
                CapRights::ROOT,
                Some(NativeMask::full(natives_len)),
                cell,
            ),
            Self::Restricted => Cap::root(
                CapTarget::Flow(flow),
                CapRights::from_bits(CapRights::FLOW.bits() & !CapRights::NATIVE.bits()),
                Some(NativeMask::empty(natives_len)),
                cell,
            ),
            Self::Untrusted => Cap::root(
                CapTarget::Flow(flow),
                CapRights::NONE,
                Some(NativeMask::empty(natives_len)),
                cell,
            ),
        }
    }
}

/// Trace JIT toggles for [`RuntimeConfig`] (`feature = "jit"`).
#[cfg(feature = "jit")]
#[derive(Clone, Debug)]
pub struct JitConfig {
    /// When true, workers attempt compiled traces before interpreting.
    pub enabled: bool,
    /// How many times a `(function, pc)` pair must run before compilation.
    pub hot_threshold: u32,
}

#[cfg(feature = "jit")]
impl Default for JitConfig {
    fn default() -> Self {
        JitConfig {
            enabled: false,
            hot_threshold: crate::jit::HOT_THRESHOLD,
        }
    }
}

/// Logical CPU count for [`RuntimeConfig::default`], via `std` only.
fn default_worker_count() -> usize {
    match std::thread::available_parallelism() {
        Ok(n) => n.get().max(1),
        Err(_) => 1,
    }
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        RuntimeConfig {
            workers: default_worker_count(),
            quantum: DEFAULT_QUANTUM,
            mailbox: MailboxConfig::DEFAULT,
            max_flows: 0,
            max_ask_waits: 0,
            max_host_awaits: 0,
            max_links: 0,
            max_monitors: 0,
            max_registry_names: 0,
            host_await: None,
            remote_dedup_window: 0,
            distribution: None,
            max_runtime_bytes: 256 * 1024 * 1024,
            trust: crate::bytecode::TrustLevel::Untrusted,
            output: Arc::new(crate::output::NullSink),
            log: None,
            quota: super::quota::QuotaConfig::default(),
            security_audit: None,
            root_authority: RootAuthorityPolicy::TrustedHost,
            #[cfg(feature = "jit")]
            jit: JitConfig::default(),
        }
    }
}

impl RuntimeConfig {
    /// Opt-in sandbox profile for untrusted modules.
    ///
    /// Default [`RuntimeConfig`] stays permissive (`max_* = 0` unlimited,
    /// [`QuotaConfig::permissive`](super::quota::QuotaConfig::permissive)).
    /// This profile enables fail-closed process-wide caps and tight
    /// per-flow budgets. Trust defaults to [`TrustLevel::Untrusted`]
    /// (inherited from [`Default`]) so Cap/Pid/Message constants are
    /// rejected at verify time.
    ///
    /// Does **not** change [`Self::root_authority`]: host [`Runtime::spawn`]
    /// still mints trusted ROOT unless you set the policy or call
    /// [`Runtime::spawn_untrusted`].
    ///
    /// Limits (starting point — tune under load):
    /// - `max_flows = 128` live flows
    /// - `max_ask_waits = 64`, `max_host_awaits = 128`
    /// - `max_runtime_bytes = 64 MiB` process heap accounting
    /// - mailbox: 256 hops / 4 MiB / Reject ( [`MailboxConfig::DEFAULT`] )
    /// - per-flow: [`QuotaConfig::sandbox`](super::quota::QuotaConfig::sandbox)
    pub fn sandbox() -> Self {
        RuntimeConfig {
            quota: super::quota::QuotaConfig::sandbox(),
            max_flows: 128,
            max_ask_waits: 64,
            max_host_awaits: 128,
            max_links: 1024,
            max_monitors: 1024,
            max_registry_names: 256,
            max_runtime_bytes: 64 * 1024 * 1024,
            trust: crate::bytecode::TrustLevel::Untrusted,
            ..Default::default()
        }
    }

    /// Same process-wide caps as [`Self::sandbox`], but
    /// [`TrustLevel::Restricted`]: still no Cap/Pid/Message in the constant
    /// pool; host may grant Caps / natives after admission.
    pub fn sandbox_restricted() -> Self {
        RuntimeConfig {
            trust: crate::bytecode::TrustLevel::Restricted,
            ..Self::sandbox()
        }
    }

    /// Stable identity of the security-relevant knobs on this config.
    pub fn policy_fingerprint(&self) -> super::sandbox::PolicyFingerprint {
        super::sandbox::policy_fingerprint(self)
    }

    /// True when at least one process-wide sandbox ceiling is armed
    /// (`max_flows` / ask / host-await / runtime bytes tighter than the
    /// permissive defaults). Does not imply the chunk was verified as
    /// Untrusted — check [`Self::trust`] separately.
    pub fn applies_sandbox_caps(&self) -> bool {
        self.max_flows != 0
            || self.max_ask_waits != 0
            || self.max_host_awaits != 0
            || self.max_links != 0
            || self.max_monitors != 0
            || self.max_registry_names != 0
            || self.max_runtime_bytes < 256 * 1024 * 1024
            || self.quota.cpu_budget < super::quota::QuotaConfig::permissive().cpu_budget
    }
}

/// State shared by every worker thread and the timer thread. Everything in
/// here is either internally synchronized (`Injector`, `Directory`,
/// `CapTable`, `TimerWheel`, the `RuntimeMetrics` atomics) or immutable after
/// construction (`stealers`, `quantum`) — there is no top-level lock
/// covering the whole runtime, by design: a global lock is exactly what an
/// M:N scheduler exists to avoid.
pub struct Shared {
    pub(crate) injector: Injector<Box<Flow>>,
    pub(crate) stealers: Vec<Stealer<Box<Flow>>>,
    /// FlowId → mailbox (delivery after Cap resolution).
    pub(crate) directory: Directory,
    /// CapId → { holder, target, rights, native_mask, epoch } (FlowCap).
    pub(crate) caps: super::capability::CapTable,
    pub(crate) timer: Arc<TimerWheel>,
    pub(crate) notify: (Mutex<()>, Condvar),
    pub(crate) metrics: RuntimeMetrics,
    pub(crate) shutdown: AtomicBool,
    pub(crate) quantum: u32,
    pub(crate) mailbox: MailboxConfig,
    /// Atomic live-flow budget (`max_flows == 0` → unlimited).
    pub(crate) flow_limit: super::flow_limit::FlowLimit,
    pub(crate) memory: Arc<crate::MemoryBudget>,
    pub(crate) quota: super::quota::QuotaConfig,
    pub(crate) quotas: super::quota::QuotaTable,
    pub(crate) monitors: super::monitor::MonitorStore,
    pub(crate) links: super::link::LinkStore,
    pub(crate) registry: super::registry::RegistryStore,
    pub(crate) kill_signals: super::finalize::KillSignals,
    pub(crate) trap_exits: super::finalize::TrapExitFlags,
    pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
    pub(crate) ask_waits: super::finalize::AskWaitIndex,
    /// In-flight `Opcode::HostAwait` tickets. The flow stays on a worker
    /// or in its mailbox; completion arrives as a host hop.
    pub(crate) host_awaits: super::host_await::HostAwaitIndex,
    /// Host async bridge (`None` ⇒ HostAwait fails closed).
    pub(crate) host_await_bridge: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
    /// Recorded order for host completions. `None` delivers immediately.
    pub(crate) host_replay: Mutex<Option<super::deterministic::HostReplayGate>>,
    /// Host `fail` text the worker reads before committing a success.
    pub(crate) host_await_failures: super::host_await::HostAwaitFailures,
    /// `SendRemote` queue. `None` fails the opcode.
    pub(crate) distribution: Option<Arc<super::distribution::DistributionBridge>>,
    /// Optional replay filter for inbound remote frames.
    pub(crate) remote_dedup: Option<Arc<super::distribution::RemoteFrameDedup>>,
    /// Embedder copy of scheduler diagnostics. `None` leaves stderr gating
    /// in [`crate::log`] unchanged.
    pub(crate) log_sink: Option<Arc<dyn crate::log::LogSink>>,
    /// One named table per flow. Empty until `TableOpen`.
    pub(crate) tables: super::table::FlowTables,
    /// Supervisors started by bytecode `StartSupervisor`. Joined from
    /// [`Runtime::shutdown`] after workers stop.
    pub(crate) flow_supervisors: Mutex<Vec<super::supervisor::Supervisor>>,
    /// Correlation ids for host `Runtime::send` when `request_id == 0`.
    /// Starts at 1; `0` stays the unset sentinel.
    pub(crate) host_next_request_id: AtomicU64,
    /// Shared trace JIT state (`feature = "jit"`).
    #[cfg(feature = "jit")]
    pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
    /// Sandbox observability (host-only; bytecode cannot mutate).
    pub(crate) security: Arc<super::sandbox::SecurityCounters>,
    pub(crate) security_audit: Option<Arc<dyn super::sandbox::SecurityAuditSink>>,
    pub(crate) policy: super::sandbox::PolicyFingerprint,
    pub(crate) trust: crate::bytecode::TrustLevel,
    pub(crate) root_authority: RootAuthorityPolicy,
}

/// A running Byteflow runtime: worker pool + timer thread over one shared
/// [`Chunk`].
///
/// Owns M:N scheduling for **flows** (spawn, yield, sleep, mailboxes,
/// FlowCap resolution, supervised restarts). Optional trace JIT when built
/// with `feature = "jit"` and enabled in `RuntimeConfig`'s `jit` field.
///
/// Construct with [`Runtime::new`] (no natives) or
/// [`Runtime::with_natives`] when the chunk uses `CallNative` /
/// [`crate::std_native_table`].
pub struct Runtime {
    shared: Arc<Shared>,
    chunk: Arc<Chunk>,
    natives: Arc<NativeTable>,
    workers: Vec<JoinHandle<()>>,
    timer_thread: Option<JoinHandle<()>>,
    trust: crate::bytecode::TrustLevel,
}

impl Runtime {
    /// Convenience constructor for chunks that never call out through
    /// `Opcode::CallNative`. Equivalent to
    /// `Runtime::with_natives(chunk, NativeTable::empty())`.
    ///
    /// Returns [`SpawnError`] instead of panicking: verify failures and OS
    /// thread-spawn refusals are category-A errors (see
    /// [`docs::error_model`](crate::docs::error_model)).
    pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
        Self::with_config(chunk, RuntimeConfig::default())
    }

    /// Construct a runtime whose flows can call into `natives` via
    /// `Opcode::CallNative` — the host FFI boundary.
    pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
        Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
    }

    pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
        Self::with_natives_and_config(chunk, NativeTable::empty(), config)
    }

    /// Decode a `.bf` buffer only if its integrity fingerprint matches
    /// `expected_digest`, then verify and start the runtime.
    ///
    /// Digest mismatch / decode failure → [`SpawnError::Attestation`].
    /// Semantic verify failure → [`SpawnError::VerifyFailed`].
    pub fn with_attested(
        bytes: &[u8],
        expected_digest: [u8; 32],
        natives: Arc<NativeTable>,
        config: RuntimeConfig,
    ) -> Result<Self, SpawnError> {
        let chunk =
            crate::decode_attested(bytes, &expected_digest).map_err(SpawnError::Attestation)?;
        Self::with_natives_and_config(chunk, natives, config)
    }

    /// Like [`Runtime::with_config`] but wires [`crate::std_native_table_with`]
    /// using [`RuntimeConfig::output`] for the `print` native.
    pub fn with_std_natives_and_config(
        chunk: Chunk,
        config: RuntimeConfig,
    ) -> Result<Self, SpawnError> {
        Self::with_natives_and_config(
            chunk,
            crate::std_native_table_with(Arc::clone(&config.output)),
            config,
        )
    }

    /// Verify `chunk`, spawn the worker pool + timer thread, and return a
    /// live [`Runtime`].
    ///
    /// Failures here mean the runtime was **never** started (no orphan
    /// threads): either the bytecode is invalid
    /// ([`SpawnError::VerifyFailed`]) or the OS refused a thread
    /// ([`SpawnError::ThreadSpawnFailed`]). Partial spawn failure rolls
    /// back: already-started workers/timer are shut down and joined before
    /// the error is returned.
    pub fn with_natives_and_config(
        chunk: Chunk,
        natives: Arc<NativeTable>,
        config: RuntimeConfig,
    ) -> Result<Self, SpawnError> {
        if let Err(err) = crate::bytecode::verify_with(
            &chunk,
            crate::bytecode::VerifyConfig {
                trust: config.trust,
            },
        ) {
            if let Some(sink) = config.security_audit.as_ref() {
                sink.record(&super::sandbox::SecurityEvent::ModuleRejected {
                    reason: "verify_failed",
                });
            }
            return Err(SpawnError::VerifyFailed(err));
        }
        let chunk = Arc::new(chunk);
        let workers_n = config.workers.max(1);
        let quantum = config.quantum.max(1);

        let locals: Vec<LocalDeque<Box<Flow>>> =
            (0..workers_n).map(|_| LocalDeque::new()).collect();
        let stealers: Vec<Stealer<Box<Flow>>> = locals.iter().map(|l| l.stealer()).collect();

        #[cfg(feature = "jit")]
        let jit = if config.jit.enabled {
            Some(super::jit::new_runtime(
                chunk.clone(),
                config.jit.hot_threshold,
            ))
        } else {
            None
        };

        let shared = Arc::new(Shared {
            injector: Injector::new(),
            stealers,
            directory: Directory::new(),
            caps: super::capability::CapTable::new(),
            timer: TimerWheel::new(),
            notify: (Mutex::new(()), Condvar::new()),
            metrics: RuntimeMetrics::default(),
            shutdown: AtomicBool::new(false),
            quantum,
            mailbox: config.mailbox,
            flow_limit: super::flow_limit::FlowLimit::new(config.max_flows),
            memory: Arc::new(crate::MemoryBudget::new(config.max_runtime_bytes)),
            quota: config.quota,
            quotas: super::quota::QuotaTable::new(),
            monitors: super::monitor::MonitorStore::new(config.max_monitors),
            links: super::link::LinkStore::new(config.max_links),
            registry: super::registry::RegistryStore::new(config.max_registry_names),
            kill_signals: super::finalize::KillSignals::new(),
            trap_exits: super::finalize::TrapExitFlags::new(),
            waiting_send_at: super::finalize::WaitingSendIndex::new(),
            ask_waits: super::finalize::AskWaitIndex::new(config.max_ask_waits),
            host_awaits: super::host_await::HostAwaitIndex::new(config.max_host_awaits),
            host_await_bridge: config.host_await.clone(),
            host_replay: Mutex::new(None),
            host_await_failures: super::host_await::HostAwaitFailures::new(),
            distribution: config.distribution.clone(),
            remote_dedup: if config.remote_dedup_window == 0 {
                None
            } else {
                Some(super::distribution::RemoteFrameDedup::new(
                    config.remote_dedup_window as usize,
                ))
            },
            log_sink: config.log.clone(),
            tables: super::table::FlowTables::new(),
            flow_supervisors: Mutex::new(Vec::new()),
            host_next_request_id: AtomicU64::new(1),
            #[cfg(feature = "jit")]
            jit,
            security: Arc::new(super::sandbox::SecurityCounters::default()),
            security_audit: config.security_audit.clone(),
            policy: config.policy_fingerprint(),
            trust: config.trust,
            root_authority: config.root_authority,
        });

        let mut workers = Vec::with_capacity(workers_n);
        for local in locals {
            let shared_w = shared.clone();
            match std::thread::Builder::new()
                .name("byteflow-worker".into())
                .spawn(move || worker::run_worker(shared_w, local))
            {
                Ok(handle) => workers.push(handle),
                Err(e) => {
                    abort_startup(&shared, workers, None);
                    return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
                }
            }
        }

        let shared_timer = shared.clone();
        let timer_thread = match std::thread::Builder::new()
            .name("byteflow-timer".into())
            .spawn(move || shared_timer.timer.clone().drive(&shared_timer))
        {
            Ok(handle) => handle,
            Err(e) => {
                abort_startup(&shared, workers, None);
                return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
            }
        };

        Ok(Runtime {
            shared,
            chunk,
            natives,
            workers,
            timer_thread: Some(timer_thread),
            trust: config.trust,
        })
    }

    /// Spawn a top-level flow starting at `function` in this runtime's
    /// chunk, returning a [`FlowHandle`] the caller can `.join()`.
    ///
    /// Host authority follows [`RuntimeConfig::root_authority`] (default
    /// trusted ROOT). For untrusted admission see [`Self::spawn_untrusted`].
    ///
    /// Returns [`SpawnError::BadFunction`] if `function` is out of range.
    pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
        spawn_on(
            &self.shared,
            &self.chunk,
            &self.natives,
            function,
            args,
            RestartPolicy::Never,
            None,
            None,
            None,
            None,
        )
    }

    /// Like [`Self::spawn`], but forces [`RootAuthorityPolicy::Untrusted`]
    /// (no Cap rights, empty native mask) regardless of config.
    pub fn spawn_untrusted(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
        spawn_on(
            &self.shared,
            &self.chunk,
            &self.natives,
            function,
            args,
            RestartPolicy::Never,
            None,
            None,
            None,
            Some(RootAuthorityPolicy::Untrusted),
        )
    }

    /// A cheap, `Send + Sync` handle that can spawn flows into this
    /// runtime from any thread, independent of `Runtime`'s own lifetime
    /// bookkeeping (worker `JoinHandle`s). Used by [`super::supervisor::Supervisor`].
    pub fn spawner(&self) -> RuntimeSpawner {
        RuntimeSpawner {
            shared: self.shared.clone(),
            chunk: self.chunk.clone(),
            natives: self.natives.clone(),
        }
    }

    /// A [`super::supervisor::Supervisor`] bound to this runtime, ready to
    /// take supervised children (design notes §15).
    pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
        super::supervisor::Supervisor::new(self.spawner())
    }

    /// Look up a function by name in the runtime's chunk — convenience for
    /// callers that built their chunk with [`crate::Program`]
    /// and don't want to thread raw indices through their own code.
    pub fn function_index(&self, name: &str) -> Option<u32> {
        self.chunk
            .functions
            .iter()
            .position(|f| f.name == name)
            .map(|i| i as u32)
    }

    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
        self.shared.metrics.snapshot()
    }

    /// Sandbox security counters (host-only).
    pub fn security_counters(&self) -> super::sandbox::SecurityCountersSnapshot {
        self.shared.security.snapshot()
    }

    /// Policy fingerprint recorded at construction.
    pub fn policy_fingerprint(&self) -> super::sandbox::PolicyFingerprint {
        self.shared.policy
    }

    /// Trust level used for constant-pool verification at construction.
    pub fn trust_level(&self) -> crate::bytecode::TrustLevel {
        self.trust
    }

    /// Host attestation of Caps currently held by `flow`.
    pub fn attest_capabilities(
        &self,
        flow: FlowId,
    ) -> Result<super::sandbox::CapabilityAttestation, RuntimeError> {
        super::sandbox::CapabilityAttestation::from_table(
            &self.shared.caps,
            flow,
            self.trust,
            self.shared.policy,
        )
    }

    /// Point-in-time view for dashboards and debug tooling.
    pub fn snapshot(&self) -> RuntimeSnapshot {
        RuntimeSnapshot {
            metrics: self.metrics(),
            live_flows: self.live_flows(),
            flow_limit_live: self.shared.flow_limit.reserved_live(),
            max_flows: self.shared.flow_limit.max_flows(),
            distribution_pending: self
                .shared
                .distribution
                .as_ref()
                .and_then(|b| b.outbound_pending().ok()),
            memory: self.memory_snapshot(),
            workers: self.worker_count(),
        }
    }

    /// Approximate number of flows currently registered in the directory.
    ///
    /// Sharded sum without a global snapshot — fine for dashboards
    /// ([`Self::metrics`]), **not** for admission control (see
    /// the flow limit / `max_flows`).
    pub fn live_flows(&self) -> usize {
        self.shared.directory.len()
    }

    /// Process-wide heap accounting snapshot (`max_runtime_bytes` ceiling).
    pub fn memory_snapshot(&self) -> crate::MemorySnapshot {
        self.shared.memory.snapshot()
    }

    pub fn worker_count(&self) -> usize {
        self.workers.len()
    }

    /// Deliver an **Atomic Hop** (`Value::Message`) to `target` from the
    /// embedder (not from bytecode).
    ///
    /// # Host trust boundary
    ///
    /// This path takes a [`FlowId`] directly — **no Cap required**. The host
    /// is trusted; bytecode must use `Value::Cap` via `Opcode::Send` /
    /// `Ask`. The hop still goes through the same authentication choke-point
    /// as bytecode: `sender` is stamped [`FlowId::HOST`] (`0`), `request_id`
    /// is minted when unset, and payload Caps are reissued to the recipient.
    /// The host has no mailbox, so `reply_cap` is [`crate::bytecode::CapId::NONE`].
    /// Bare scalars are rejected ([`SendError::NotAHop`]).
    pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
        let Some(msg) = message.as_message().cloned() else {
            return Err(SendError::NotAHop {
                got: message.type_name(),
            });
        };
        let mailbox = match self.shared.directory.lookup(target) {
            Ok(Some(m)) => m,
            Ok(None) => return Err(SendError::NoSuchFlow(target)),
            Err(e) => {
                super::error::report_fault(e);
                return Err(SendError::Unavailable);
            }
        };
        let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
            Ok(m) => Value::Message(m),
            Err(_) => return Err(SendError::Capability),
        };
        match mailbox.push(stamped.clone()) {
            // Host `send` is fire-and-forget: DropNewest means the hop was
            // intentionally discarded under policy, not an infrastructure
            // error. Bytecode `Ask` treats DropNewest as hard failure in
            // `worker::deliver` (must not park waiting for a reply).
            Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
                Ok(())
            }
            Ok(Ok(Delivery::Handoff(flow))) => {
                let _ = self.shared.ask_waits.remove_asker(flow.id);
                match flow.last_receive_dest {
                    Some(dest) => {
                        let Some(flow) =
                            super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
                        else {
                            return Err(SendError::Unavailable);
                        };
                        enqueue_flow(&self.shared, flow);
                        wake_workers(&self.shared);
                        Ok(())
                    }
                    None => {
                        super::error::report_fault(super::error::RuntimeError::PoisonedLock(
                            "Runtime::send handoff missing dest register",
                        ));
                        finalize_flow(
                            &self.shared,
                            *flow,
                            FlowOutcome::Failed("handoff missing dest register".into()),
                            FlowExitReason::Fault,
                        );
                        Err(SendError::Unavailable)
                    }
                }
            }
            Ok(Err(full)) => {
                if full.reason() == MailboxFullReason::Closed {
                    return Err(SendError::NoSuchFlow(target));
                }
                Err(SendError::MailboxFull {
                    flow: target,
                    reason: full.reason(),
                })
            }
            Err(e) => {
                super::error::report_fault(e);
                Err(SendError::Unavailable)
            }
        }
    }

    /// Deliver a hop the host read off its own socket.
    ///
    /// The frame's sender is kept. This path does not restamp it as the local
    /// host (`0`). A `Cap` or `Pid` in the frame is refused. The name must
    /// already be registered on this node; the host still owns the socket.
    ///
    /// When [`RuntimeConfig::remote_dedup_window`] is set, acceptance is
    /// transactional: a failed delivery (unknown name, full mailbox) rolls
    /// back the reservation so the host may retransmit the same
    /// `(sender, request_id)`.
    pub fn deliver_frame(&self, bytes: &[u8]) -> Result<(), super::distribution::RemoteFrameError> {
        let hop = super::distribution::decode_frame(bytes)?;
        let reservation = if hop.message.request_id != 0 {
            if let Some(dedup) = self.shared.remote_dedup.as_ref() {
                match dedup
                    .reserve(hop.sender.as_u64(), hop.message.request_id)
                    .map_err(|_| super::distribution::RemoteFrameError::Unavailable)?
                {
                    super::distribution::DedupTicket::Duplicate => return Ok(()),
                    super::distribution::DedupTicket::Fresh { sender, request_id } => {
                        Some((sender, request_id))
                    }
                }
            } else {
                None
            }
        } else {
            None
        };

        let outcome = self.deliver_frame_after_dedup(hop);
        if let Some((sender, request_id)) = reservation {
            if let Some(dedup) = self.shared.remote_dedup.as_ref() {
                match &outcome {
                    // Mailbox accepted the hop (queued or handoff taken).
                    Ok(()) | Err(DeliverAcceptError::AfterAccept(_)) => {
                        let _ = dedup.commit(sender, request_id);
                    }
                    Err(DeliverAcceptError::BeforeAccept(_)) => {
                        let _ = dedup.rollback(sender, request_id);
                    }
                }
            }
        }
        match outcome {
            Ok(()) => Ok(()),
            Err(DeliverAcceptError::BeforeAccept(e) | DeliverAcceptError::AfterAccept(e)) => Err(e),
        }
    }

    fn deliver_frame_after_dedup(
        &self,
        hop: super::distribution::OutboundHop,
    ) -> Result<(), DeliverAcceptError> {
        let cap = match self.shared.registry.whereis(hop.name.as_ref()) {
            Ok(Some(cap)) => cap,
            Ok(None) => {
                return Err(DeliverAcceptError::BeforeAccept(
                    super::distribution::RemoteFrameError::NoSuchName,
                ))
            }
            Err(err) => {
                super::error::report_fault(err);
                return Err(DeliverAcceptError::BeforeAccept(
                    super::distribution::RemoteFrameError::Unavailable,
                ));
            }
        };
        let target = match self.shared.caps.lookup(cap) {
            Ok(Some(entry)) => match entry.target() {
                Some(id) => id,
                None => {
                    return Err(DeliverAcceptError::BeforeAccept(
                        super::distribution::RemoteFrameError::NoSuchName,
                    ))
                }
            },
            Ok(None) => {
                return Err(DeliverAcceptError::BeforeAccept(
                    super::distribution::RemoteFrameError::NoSuchName,
                ))
            }
            Err(err) => {
                super::error::report_fault(err);
                return Err(DeliverAcceptError::BeforeAccept(
                    super::distribution::RemoteFrameError::Unavailable,
                ));
            }
        };
        let mailbox = match self.shared.directory.lookup(target) {
            Ok(Some(mailbox)) => mailbox,
            Ok(None) => {
                return Err(DeliverAcceptError::BeforeAccept(
                    super::distribution::RemoteFrameError::NoSuchName,
                ))
            }
            Err(err) => {
                super::error::report_fault(err);
                return Err(DeliverAcceptError::BeforeAccept(
                    super::distribution::RemoteFrameError::Unavailable,
                ));
            }
        };
        let stamped = Value::Message(hop.message);
        match mailbox.push(stamped.clone()) {
            Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
                Ok(())
            }
            Ok(Ok(Delivery::Handoff(flow))) => {
                let _ = self.shared.ask_waits.remove_asker(flow.id);
                match flow.last_receive_dest {
                    Some(dest) => {
                        let Some(flow) =
                            super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
                        else {
                            return Err(DeliverAcceptError::AfterAccept(
                                super::distribution::RemoteFrameError::Unavailable,
                            ));
                        };
                        enqueue_flow(&self.shared, flow);
                        wake_workers(&self.shared);
                        Ok(())
                    }
                    None => {
                        super::finalize::finalize_flow(
                            &self.shared,
                            *flow,
                            FlowOutcome::Failed("handoff missing dest register".into()),
                            FlowExitReason::Fault,
                        );
                        Err(DeliverAcceptError::AfterAccept(
                            super::distribution::RemoteFrameError::Unavailable,
                        ))
                    }
                }
            }
            Ok(Err(full)) => Err(DeliverAcceptError::BeforeAccept(
                super::distribution::RemoteFrameError::Mailbox(full.reason()),
            )),
            Err(err) => {
                super::error::report_fault(err);
                Err(DeliverAcceptError::BeforeAccept(
                    super::distribution::RemoteFrameError::Unavailable,
                ))
            }
        }
    }
}

/// Internal split for remote dedup: rollback only when the mailbox never
/// accepted the hop.
enum DeliverAcceptError {
    BeforeAccept(super::distribution::RemoteFrameError),
    AfterAccept(super::distribution::RemoteFrameError),
}

impl Runtime {
    fn require_live(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
        match self.shared.directory.lookup(id) {
            Ok(Some(_)) => Ok(()),
            Ok(None) => Err(super::error::LifecycleError::NoSuchFlow(id)),
            Err(e) => Err(self.unavailable(e)),
        }
    }

    fn unavailable(&self, err: super::error::RuntimeError) -> super::error::LifecycleError {
        super::error::report_fault(err);
        super::error::LifecycleError::Unavailable
    }

    /// Mint an addressing Cap ([`CapRights::ADDRESSING`]) for a live flow
    /// (host equivalent of `SelfPid`).
    pub fn mint_cap(
        &self,
        flow: FlowId,
    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
        self.require_live(flow)?;
        self.shared
            .caps
            .mint(flow, flow, super::capability::CapRights::ADDRESSING)
            .map_err(|e| self.unavailable(e))
    }

    /// Mint a Cap held by `holder` targeting `target` (host introduction).
    pub fn grant_cap(
        &self,
        holder: FlowId,
        target: FlowId,
    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
        self.require_live(holder)?;
        self.require_live(target)?;
        self.shared
            .caps
            .mint(holder, target, super::capability::CapRights::ADDRESSING)
            .map_err(|e| self.unavailable(e))
    }

    /// Watch `target`; when it exits, `owner` receives a [`crate::TAG_SYS_DOWN`] hop.
    ///
    /// Both flows must be live. `owner == target` is `LifecycleError::SelfRelation`.
    pub fn monitor(
        &self,
        owner: FlowId,
        target: FlowId,
    ) -> Result<super::monitor::MonitorRef, super::error::LifecycleError> {
        if owner == target {
            return Err(super::error::LifecycleError::SelfRelation);
        }
        self.require_live(owner)?;
        self.require_live(target)?;
        let mon = self
            .shared
            .monitors
            .create(owner, target)
            .map_err(|e| self.unavailable(e))??;
        // Target may have finalized between the live check and insert.
        // Synthesize DOWN and drop the now-useless relation (owner still live).
        if self.require_live(target).is_err() {
            let _ = self.shared.monitors.remove_owned(owner, mon);
            super::finalize::deliver_down(
                &self.shared,
                super::monitor::DownEvent {
                    monitor: mon,
                    owner,
                    target,
                    reason: super::monitor::FlowExitReason::Fault,
                },
            );
        }
        Ok(mon)
    }

    /// Drop `monitor` if `owner` still owns it.
    pub fn demonitor(
        &self,
        owner: FlowId,
        monitor: super::monitor::MonitorRef,
    ) -> Result<(), super::error::LifecycleError> {
        self.require_live(owner)?;
        match self.shared.monitors.remove_owned(owner, monitor) {
            Ok(inner) => inner,
            Err(e) => Err(self.unavailable(e)),
        }
    }

    /// Bidirectional link. Without `trap_exit`, abnormal exit of either side
    /// kills the peer (`Normal` only drops the link). With
    /// [`Self::set_trap_exit`] on a peer, that peer receives a
    /// [`crate::TAG_SYS_EXIT`] hop for every linked exit (including `Normal`).
    pub fn link(
        &self,
        a: FlowId,
        b: FlowId,
    ) -> Result<super::link::LinkId, super::error::LifecycleError> {
        if a == b {
            return Err(super::error::LifecycleError::SelfRelation);
        }
        self.require_live(a)?;
        self.require_live(b)?;
        match self.shared.links.link_if_live(a, b, |id| {
            self.shared.directory.lookup(id).map(|m| m.is_some())
        }) {
            Ok(Ok(super::link::LinkOutcome::Linked(id))) => Ok(id),
            Ok(Ok(super::link::LinkOutcome::Consumed { dead })) => {
                Err(super::error::LifecycleError::NoSuchFlow(dead))
            }
            Ok(Err(error)) => Err(error),
            Err(e) => Err(self.unavailable(e)),
        }
    }

    /// BEAM-style `process_flag(trap_exit, …)`.
    ///
    /// When `enabled`, linked exits deliver a [`crate::TAG_SYS_EXIT`] hop
    /// (including `Normal`) instead of killing this flow.
    pub fn set_trap_exit(
        &self,
        id: FlowId,
        enabled: bool,
    ) -> Result<(), super::error::LifecycleError> {
        self.require_live(id)?;
        self.shared
            .trap_exits
            .set(id, enabled)
            .map_err(|e| self.unavailable(e))
    }

    /// Drop `link` if `owner` is one of the endpoints.
    pub fn unlink(
        &self,
        owner: FlowId,
        link: super::link::LinkId,
    ) -> Result<(), super::error::LifecycleError> {
        self.require_live(owner)?;
        match self.shared.links.unlink_owned(owner, link) {
            Ok(inner) => inner,
            Err(e) => Err(self.unavailable(e)),
        }
    }

    /// Bind `name` to a live Cap (address). Names are swept when that flow exits.
    pub fn register_name(
        &self,
        name: &str,
        cap: crate::bytecode::CapId,
    ) -> Result<(), super::error::LifecycleError> {
        let entry = match self.shared.caps.lookup(cap) {
            Ok(Some(e)) => e,
            Ok(None) => return Err(super::error::LifecycleError::InvalidCapability),
            Err(e) => return Err(self.unavailable(e)),
        };
        let target = match entry.target() {
            Some(id) => id,
            None => return Err(super::error::LifecycleError::InvalidCapability),
        };
        self.require_live(target)?;
        match self
            .shared
            .registry
            .register(super::registry::RegistryName::from(name), cap, target)
        {
            Ok(inner) => inner,
            Err(e) => Err(self.unavailable(e)),
        }
    }

    /// Look up a registered Cap, or `None` if the name is free / was swept.
    pub fn whereis(
        &self,
        name: &str,
    ) -> Result<Option<crate::bytecode::CapId>, super::error::LifecycleError> {
        self.shared
            .registry
            .whereis(name)
            .map_err(|e| self.unavailable(e))
    }

    /// Cooperative abort. Parked flows finalize immediately; a running flow
    /// dies at the next quantum with [`super::monitor::FlowExitReason::Killed`].
    pub fn kill(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
        self.require_live(id)?;
        super::finalize::request_kill(&self.shared, id, super::monitor::FlowExitReason::Killed);
        Ok(())
    }

    /// Mint a scheduler ADMIN cap for a live flow (host introduction).
    pub fn mint_admin_cap(
        &self,
        holder: FlowId,
    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
        self.require_live(holder)?;
        let cap = crate::bytecode::Cap::root(
            crate::bytecode::CapTarget::Scheduler,
            CapRights::ADMIN,
            None,
            self.shared.caps.scheduler_cell().as_ref(),
        );
        self.shared
            .caps
            .grant(holder, cap)
            .map_err(|e| self.unavailable(e))
    }

    /// Kill `target` only if `holder` presents a live ADMIN scheduler cap.
    pub fn admin_kill(
        &self,
        holder: FlowId,
        cap: crate::bytecode::CapId,
        target: FlowId,
    ) -> Result<(), super::error::LifecycleError> {
        self.require_admin(holder, cap)?;
        self.kill(target)
    }

    /// Top up `target`'s CPU budget. Requires a live ADMIN scheduler cap.
    pub fn admin_top_up_cpu(
        &self,
        holder: FlowId,
        cap: crate::bytecode::CapId,
        target: FlowId,
        extra: i64,
    ) -> Result<(), super::error::LifecycleError> {
        self.require_admin(holder, cap)?;
        let quota = match self.shared.quotas.get(target) {
            Ok(Some(q)) => q,
            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
            Err(e) => return Err(self.unavailable(e)),
        };
        quota.top_up_cpu(extra);
        Ok(())
    }

    /// Raise `target`'s heap limit. Requires a live ADMIN scheduler cap.
    pub fn admin_top_up_mem(
        &self,
        holder: FlowId,
        cap: crate::bytecode::CapId,
        target: FlowId,
        extra: usize,
    ) -> Result<(), super::error::LifecycleError> {
        self.require_admin(holder, cap)?;
        let quota = match self.shared.quotas.get(target) {
            Ok(Some(q)) => q,
            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
            Err(e) => return Err(self.unavailable(e)),
        };
        quota.top_up_mem(extra);
        Ok(())
    }

    /// Credit `target`'s send bucket. Requires a live ADMIN scheduler cap.
    pub fn admin_top_up_send(
        &self,
        holder: FlowId,
        cap: crate::bytecode::CapId,
        target: FlowId,
        extra: i64,
    ) -> Result<(), super::error::LifecycleError> {
        self.require_admin(holder, cap)?;
        let quota = match self.shared.quotas.get(target) {
            Ok(Some(q)) => q,
            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
            Err(e) => return Err(self.unavailable(e)),
        };
        quota.top_up_send(extra);
        Ok(())
    }

    fn require_admin(
        &self,
        holder: FlowId,
        cap: crate::bytecode::CapId,
    ) -> Result<(), super::error::LifecycleError> {
        let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
            Ok(e) => e,
            Err(_) => return Err(super::error::LifecycleError::InvalidCapability),
        };
        super::link_admin::check_admin(&entry.cap, self.shared.caps.scheduler_cell().as_ref())
            .map_err(|_| super::error::LifecycleError::InvalidCapability)
    }

    /// Remove a name without waiting for the flow to exit. `false` if unknown.
    pub fn unregister_name(&self, name: &str) -> Result<bool, super::error::LifecycleError> {
        self.shared
            .registry
            .unregister(name)
            .map_err(|e| self.unavailable(e))
    }

    /// Replace the image used by **new host** [`Self::spawn`] calls and
    /// drop JIT traces. Live flows and bytecode `Spawn` keep the parent's
    /// existing `Vm` chunk.
    pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
        crate::bytecode::verify_with(&chunk, crate::bytecode::VerifyConfig { trust: self.trust })
            .map_err(SpawnError::VerifyFailed)?;
        let chunk = Arc::new(chunk);
        self.chunk = chunk.clone();
        #[cfg(feature = "jit")]
        if let Some(jit) = &self.shared.jit {
            jit.reload(chunk);
        }
        Ok(())
    }

    /// Signal workers and the timer to stop. Does **not** join those threads.
    /// [`Self::finish`] joins them and finalizes flows still parked.
    fn request_shutdown(&self) {
        self.shared.shutdown.store(true, Ordering::Release);
        // Settle parked HostAwaits before joining workers: otherwise a bridge
        // holding Completers could leave joiners blocked after OS threads exit.
        finalize_host_awaits(&self.shared);
        self.shared.timer.shutdown();
        let (lock, cvar) = &self.shared.notify;
        match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
            Ok(_g) => cvar.notify_all(),
            Err(e) => super::error::report_fault(e),
        }
    }

    /// Install the test-only host-completion replay gate.
    ///
    /// Production leaves the gate unset and delivers each completion at once.
    /// Sequence numbers come from the test, not from arrival order.
    #[cfg(test)]
    pub(crate) fn enable_host_await_replay(&self) -> Result<(), super::error::RuntimeError> {
        let mut gate = super::sync_lock::lock(
            &self.shared.host_replay,
            "Runtime::enable_host_await_replay",
        )?;
        *gate = Some(super::deterministic::HostReplayGate::default());
        Ok(())
    }

    /// Bind a host-await ticket to a recorded sequence and deliver every
    /// completion that is now the next event.
    #[cfg(test)]
    pub(crate) fn bind_host_await_replay(
        &self,
        ticket: u64,
        sequence: u64,
    ) -> Result<(), super::host_await::HostAwaitError> {
        let ready = {
            let mut gate =
                super::sync_lock::lock(&self.shared.host_replay, "Runtime::bind_host_await_replay")
                    .map_err(super::host_await::HostAwaitError::Runtime)?;
            let Some(replay) = gate.as_mut() else {
                return Err(super::host_await::HostAwaitError::Replay(
                    "replay gate is not enabled",
                ));
            };
            replay.bind(ticket, sequence).map_err(|err| {
                super::host_await::HostAwaitError::Replay(super::deterministic::replay_label(err))
            })?;
            replay.drain_ready()
        };
        super::host_await::deliver_ready(&self.shared, ready)
    }

    /// Stop accepting new scheduling work, join every worker + the timer
    /// thread, then finalize any flow still parked (mailbox, timer, injector,
    /// worker deques). Joiners see [`FlowOutcome::Failed`] (`runtime shutdown`)
    /// instead of [`super::error::RuntimeError::Abandoned`].
    ///
    /// Mid-quantum bytecode is not aborted mid-instruction — the worker
    /// finalizes at the next loop check (cooperative preemption).
    ///
    /// [`Drop`] does the same work when it runs off a worker thread. On a
    /// worker thread it only signals: joining that thread from itself would
    /// deadlock the pool.
    /// Register a process-wide (global) table under `name`.
    ///
    /// A flow that calls `TableOpen(name)` afterwards receives a Cap to this
    /// table instead of opening its own per-flow table. The table survives
    /// any single flow's exit; each opener's Cap is revoked when that flow
    /// exits. Names must be 1..=256 bytes and unique.
    pub fn register_table(&self, name: &str) -> Result<(), super::error::RuntimeError> {
        self.shared
            .tables
            .register_global(&self.shared, name)
            .map_err(super::error::RuntimeError::from)
    }

    /// Drop a previously registered global table and revoke every Cap that
    /// still references it.
    pub fn unregister_table(&self, name: &str) -> Result<(), super::error::RuntimeError> {
        self.shared
            .tables
            .unregister_global(&self.shared, name)
            .map_err(super::error::RuntimeError::from)
    }

    /// Names of the currently registered global tables.
    pub fn global_tables(&self) -> Vec<String> {
        self.shared.tables.list_global()
    }

    pub fn shutdown(mut self) {
        self.finish();
    }

    /// Join the threads started by [`Self::with_natives_and_config`] and
    /// finalize every flow they did not finish. Safe to call again after
    /// [`Self::shutdown`]: the handles are already taken and the second
    /// sweep finds an empty directory.
    fn finish(&mut self) {
        if !self.shared.shutdown.load(Ordering::Acquire) {
            self.request_shutdown();
        }
        for worker in self.workers.drain(..) {
            let _ = worker.join();
        }
        super::flow_supervisor::shutdown_all(&self.shared.flow_supervisors);
        if let Some(timer) = self.timer_thread.take() {
            let _ = timer.join();
        }
        finalize_stranded(&self.shared);
    }
}

fn finalize_shutdown_flow(shared: &Shared, flow: Flow) {
    finalize_flow(
        shared,
        flow,
        FlowOutcome::Failed("runtime shutdown".into()),
        FlowExitReason::Shutdown,
    );
}

fn finalize_host_awaits(shared: &Shared) {
    match shared.host_awaits.cancel_all() {
        Ok(notices) => super::host_await::notify_cancelled(shared, notices),
        Err(e) => super::error::report_fault(e),
    }
}

/// After workers and the timer have stopped, take every remaining flow
/// and run it through [`finalize_flow`] so links, monitors and joiners fire.
///
/// A few passes: finalize can hand off a `trap_exit` peer onto the injector.
fn finalize_stranded(shared: &Shared) {
    finalize_host_awaits(shared);
    for flow in shared.timer.drain() {
        finalize_shutdown_flow(shared, flow);
    }
    for _ in 0..8 {
        let mut n = 0usize;
        for flow in shared.injector.drain() {
            finalize_shutdown_flow(shared, *flow);
            n += 1;
        }
        for stealer in &shared.stealers {
            for flow in stealer.drain() {
                finalize_shutdown_flow(shared, *flow);
                n += 1;
            }
        }
        for (_id, mailbox) in shared.directory.snapshot() {
            match mailbox.take_parked() {
                Ok(Some(flow)) => {
                    finalize_shutdown_flow(shared, *flow);
                    n += 1;
                }
                Ok(None) => {}
                Err(e) => super::error::report_fault(e),
            }
            match mailbox.close() {
                Ok(senders) => {
                    for sender in senders {
                        if let Err(e) = shared.waiting_send_at.remove(sender.id) {
                            super::error::report_fault(e);
                        }
                        finalize_shutdown_flow(shared, sender);
                        n += 1;
                    }
                }
                Err(e) => super::error::report_fault(e),
            }
        }
        if n == 0 {
            break;
        }
    }
}

impl Drop for Runtime {
    fn drop(&mut self) {
        if super::worker::is_on_worker() {
            if !self.shared.shutdown.load(Ordering::Acquire) {
                self.request_shutdown();
            }
            super::flow_supervisor::shutdown_all(&self.shared.flow_supervisors);
            return;
        }
        self.finish();
    }
}

/// A convenience Pid constructor for embedders that stored a raw `u64`
/// (e.g. round-tripped through `Value::Pid`) and need a [`FlowId`] to
/// call APIs that take one.
pub fn flow_id_from_u64(raw: u64) -> FlowId {
    FlowId(raw)
}

/// Why [`Runtime::send`] could not deliver a hop.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SendError {
    NoSuchFlow(FlowId),
    /// Atomic Hop rule: only [`crate::Value::Message`] may cross `Send`.
    NotAHop {
        got: &'static str,
    },
    /// Target inbox is at one of its logical bounds
    /// ([`OverflowPolicy::Reject`](crate::OverflowPolicy::Reject)). `reason` says which — see
    /// [`MailboxFullReason`].
    MailboxFull {
        flow: FlowId,
        reason: MailboxFullReason,
    },
    /// Host hop authentication failed (payload Cap reissue).
    Capability,
    /// Directory / mailbox mutex poisoned — not "no such flow".
    Unavailable,
}

impl std::fmt::Display for SendError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
            SendError::NotAHop { got } => {
                write!(f, "atomic hop requires Value::Message, got {got}")
            }
            SendError::MailboxFull { flow, reason } => {
                write!(f, "mailbox full for {flow} ({reason})")
            }
            SendError::Capability => {
                write!(f, "host send could not reissue a capability in the hop")
            }
            SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
        }
    }
}

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

/// Context for a bytecode `Spawn`: parent self-authority is attenuated into
/// the child. Host spawn passes `None` and mints a trusted root instead.
pub(crate) struct BytecodeSpawn<'a> {
    pub authority: &'a Cap,
    pub cell: &'a crate::bytecode::RevocationCell,
    pub quota: &'a super::quota::FlowQuota,
    pub requested_rights: CapRights,
}

/// Shared machinery behind `Runtime::spawn` and `RuntimeSpawner::spawn`
/// (and, transitively, `Supervisor`): build a fresh `Flow` (VM +
/// mailbox + completion channel), register it in the directory, and push
/// it onto the global injector for any worker to pick up.
///
/// Returns [`SpawnError`] on bad function index / VM init / directory
/// poison — never panics. Bytecode `Opcode::Spawn` that fails here turns
/// into `FlowOutcome::Failed` for the *parent* (see `worker`).
/// Bytecode `Spawn` must pass exactly the callee's arity. Host spawn is not
/// checked here.
pub(crate) fn bytecode_spawn_arity(arity: u8, argc: usize) -> Result<(), crate::vm::Fault> {
    if argc != usize::from(arity) {
        Err(crate::vm::Fault::BadArity {
            passed: argc,
            expected: arity,
        })
    } else {
        Ok(())
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn spawn_on(
    shared: &Arc<Shared>,
    chunk: &Arc<Chunk>,
    natives: &Arc<NativeTable>,
    function: u32,
    args: &[Value],
    restart_policy: RestartPolicy,
    supervisor: Option<SupervisorLink>,
    parent: Option<FlowId>,
    bytecode: Option<BytecodeSpawn<'_>>,
    // When `bytecode` is `None`, overrides `Shared::root_authority`.
    host_authority: Option<RootAuthorityPolicy>,
) -> Result<FlowHandle, SpawnError> {
    // Bytecode `Spawn` encodes argc. Host `Runtime::spawn` does not: a short
    // host argument list still fills the rest with `Unit`. Only the bytecode
    // path is rejected here, matching `VerifyError::CallArity` / `Fault::BadArity`.
    if bytecode.is_some() {
        match chunk.function(function) {
            Some(def) => {
                if let Err(fault) = bytecode_spawn_arity(def.arity, args.len()) {
                    return Err(fault.into());
                }
            }
            None => {
                return Err(SpawnError::BadFunction {
                    index: function,
                    table_size: chunk.functions.len() as u32,
                });
            }
        }
    }
    shared.flow_limit.try_reserve()?;
    let id = match super::process::try_next_flow_id() {
        Ok(id) => id,
        Err(super::error::RuntimeError::FlowIdExhausted) => {
            shared.flow_limit.release();
            return Err(SpawnError::FlowIdExhausted);
        }
        Err(_) => {
            shared.flow_limit.release();
            return Err(SpawnError::Unavailable);
        }
    };
    let cell = match shared.caps.bind_flow(id) {
        Ok(c) => c,
        Err(_) => {
            shared.flow_limit.release();
            return Err(SpawnError::Unavailable);
        }
    };
    let authority = match bytecode {
        None => {
            let policy = host_authority.unwrap_or(shared.root_authority);
            policy.mint(id.as_u64(), natives.len(), cell.as_ref())
        }
        Some(ctx) => match super::spawn::exec_spawn_authority(
            ctx.authority,
            ctx.cell,
            ctx.quota,
            id.as_u64(),
            ctx.requested_rights,
            None,
            cell.as_ref(),
        ) {
            Ok(cap) => cap,
            Err(e) => {
                shared.flow_limit.release();
                let _ = shared.caps.revoke_flow(id);
                return Err(SpawnError::from(e));
            }
        },
    };
    let args = match grant_caps_in_args(shared, parent, id, args) {
        Ok(a) => a,
        Err(e) => {
            shared.flow_limit.release();
            let _ = shared.caps.revoke_flow(id);
            return Err(e);
        }
    };
    let gate = NativeGate::from_authority(
        &authority,
        Arc::clone(&cell),
        shared.caps.native_cell(),
        natives.len(),
    );
    let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
    let mut vm = match Vm::with_native_gate(
        chunk.clone(),
        natives.clone(),
        gate,
        function,
        args.as_slice(),
    ) {
        Ok(vm) => vm,
        Err(e) => {
            shared.flow_limit.release();
            let _ = shared.caps.revoke_flow(id);
            return Err(e.into());
        }
    };
    vm.set_memory_budget(Arc::clone(&shared.memory));
    if let Err(e) = vm.set_quota(Arc::clone(&quota)) {
        shared.flow_limit.release();
        let _ = shared.caps.revoke_flow(id);
        return Err(e.into());
    }
    let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
    if let Err(e) = shared.directory.register(id, mailbox.clone()) {
        super::error::report_fault(e);
        shared.flow_limit.release();
        let _ = shared.caps.revoke_flow(id);
        return Err(SpawnError::Unavailable);
    }
    if let Err(e) = shared.quotas.insert(id, Arc::clone(&quota)) {
        super::error::report_fault(e);
        let _ = shared.directory.unregister(id);
        shared.flow_limit.release();
        let _ = shared.caps.revoke_flow(id);
        return Err(SpawnError::Unavailable);
    }
    let (tx, rx) = super::oneshot::channel();
    let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
    flow.authority = authority;
    flow.cell = cell;
    flow.quota = quota;
    flow.supervisor = supervisor;
    RuntimeMetrics::inc(&shared.metrics.processes_spawned);
    record_security_event(
        shared,
        &super::sandbox::SecurityEvent::CapabilityCreated {
            holder: id.as_u64(),
        },
    );
    if matches!(
        shared.trust,
        crate::bytecode::TrustLevel::Untrusted | crate::bytecode::TrustLevel::Restricted
    ) {
        super::sandbox::SecurityCounters::inc(&shared.security.active_untrusted_flows);
    }
    enqueue_flow(shared, flow);
    wake_workers(shared);
    Ok(FlowHandle { id, receiver: rx })
}

fn grant_caps_in_args(
    shared: &Shared,
    parent: Option<FlowId>,
    child: FlowId,
    args: &[Value],
) -> Result<Vec<Value>, SpawnError> {
    let mut out = Vec::with_capacity(args.len());
    for arg in args {
        if !arg.within_nesting_limit() {
            return Err(SpawnError::InvalidCapability);
        }
        let granted = arg.map_caps(
            0,
            &SpawnError::InvalidCapability,
            &mut |id| {
                let next = match parent {
                    None => shared.caps.reissue_for(id, child),
                    Some(holder) => shared.caps.delegate(id, holder, child),
                };
                next.map_err(|_| SpawnError::InvalidCapability)
            },
            &mut |message| {
                if let Some(holder) = parent {
                    if message.sender == 0 {
                        message.sender = holder.as_u64();
                    }
                }
                if message.request_id == 0 {
                    message.request_id =
                        super::worker::mint_host_request_id(&shared.host_next_request_id)
                            .ok_or(SpawnError::RequestIdsExhausted)?;
                }
                if !message.reply_cap.is_none() {
                    message.reply_cap = match parent {
                        None => shared.caps.reissue_for(message.reply_cap, child),
                        Some(holder) => shared.caps.delegate(message.reply_cap, holder, child),
                    }
                    .map_err(|_| SpawnError::InvalidCapability)?;
                }
                Ok(())
            },
        )?;
        out.push(granted);
    }
    Ok(out)
}

/// Park `flow` on the global injector.
///
/// A poisoned injector is cleared inside [`Injector::push`]. The flow stays
/// queued with whatever was already there.
pub(crate) fn enqueue_flow(shared: &Shared, flow: Box<Flow>) {
    shared.injector.push(flow);
}

pub(crate) fn wake_workers(shared: &Shared) {
    let (lock, cvar) = &shared.notify;
    match super::sync_lock::lock(lock, "wake_workers") {
        Ok(_g) => cvar.notify_one(),
        Err(e) => super::error::report_fault(e),
    }
}

/// Signal shutdown and join any threads already started during construction
/// failure — keeps the "no orphan threads" contract of
/// [`Runtime::with_natives_and_config`].
pub(crate) fn record_security_event(shared: &Shared, event: &super::sandbox::SecurityEvent) {
    use super::sandbox::{SecurityCounters, SecurityEvent};
    match event {
        SecurityEvent::AccessDenied { .. } => {
            SecurityCounters::inc(&shared.security.denied_operations);
        }
        SecurityEvent::QuotaExceeded { .. } => {
            SecurityCounters::inc(&shared.security.quota_exceeded);
        }
        SecurityEvent::CapabilityCreated { .. } => {
            SecurityCounters::inc(&shared.security.capabilities_created);
        }
        SecurityEvent::CapabilityRevoked { .. } => {
            SecurityCounters::inc(&shared.security.capabilities_revoked);
        }
        SecurityEvent::ModuleRejected { .. } => {
            SecurityCounters::inc(&shared.security.invalid_modules);
        }
        SecurityEvent::NativeDenied { .. } => {
            SecurityCounters::inc(&shared.security.native_denied);
        }
        SecurityEvent::CapabilityDelegated { .. } | SecurityEvent::FlowFinalized { .. } => {}
    }
    if let Some(sink) = shared.security_audit.as_ref() {
        sink.record(event);
    }
}

fn abort_startup(
    shared: &Arc<Shared>,
    workers: Vec<std::thread::JoinHandle<()>>,
    timer: Option<std::thread::JoinHandle<()>>,
) {
    shared.shutdown.store(true, Ordering::Release);
    shared.timer.shutdown();
    let (lock, cvar) = &shared.notify;
    match super::sync_lock::lock(lock, "abort_startup") {
        Ok(_g) => cvar.notify_all(),
        Err(e) => super::error::report_fault(e),
    }
    for w in workers {
        let _ = w.join();
    }
    if let Some(t) = timer {
        let _ = t.join();
    }
}

/// A `Send + Sync`, freely cloneable capability to spawn flows into a
/// [`Runtime`], detached from the `Runtime` value itself. Exists because
/// [`super::supervisor::Supervisor`] needs to respawn flows from a
/// background monitor thread whose lifetime isn't tied to the `Runtime`
/// object's own (which owns non-`Sync` `JoinHandle`s for its workers).
#[derive(Clone)]
pub struct RuntimeSpawner {
    pub(crate) shared: Arc<Shared>,
    pub(crate) chunk: Arc<Chunk>,
    pub(crate) natives: Arc<NativeTable>,
}

impl RuntimeSpawner {
    pub fn spawn(
        &self,
        function: u32,
        args: &[Value],
        restart_policy: RestartPolicy,
    ) -> Result<FlowHandle, SpawnError> {
        spawn_on(
            &self.shared,
            &self.chunk,
            &self.natives,
            function,
            args,
            restart_policy,
            None,
            None,
            None,
            None,
        )
    }

    /// Host spawn with [`RootAuthorityPolicy::Untrusted`].
    pub fn spawn_untrusted(
        &self,
        function: u32,
        args: &[Value],
        restart_policy: RestartPolicy,
    ) -> Result<FlowHandle, SpawnError> {
        spawn_on(
            &self.shared,
            &self.chunk,
            &self.natives,
            function,
            args,
            restart_policy,
            None,
            None,
            None,
            Some(RootAuthorityPolicy::Untrusted),
        )
    }

    pub(crate) fn spawn_linked(
        &self,
        function: u32,
        args: &[Value],
        restart_policy: RestartPolicy,
        supervisor: SupervisorLink,
    ) -> Result<FlowHandle, SpawnError> {
        spawn_on(
            &self.shared,
            &self.chunk,
            &self.natives,
            function,
            args,
            restart_policy,
            Some(supervisor),
            None,
            None,
            None,
        )
    }

    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
        self.shared.metrics.snapshot()
    }

    pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
        super::finalize::request_kill(&self.shared, id, reason);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
    use crate::scheduler::FlowOutcome;
    use std::time::Duration;

    #[test]
    fn bytecode_spawn_rejects_an_argc_the_callee_did_not_declare() {
        assert!(super::bytecode_spawn_arity(2, 2).is_ok());
        assert!(matches!(
            super::bytecode_spawn_arity(2, 1),
            Err(crate::vm::Fault::BadArity {
                passed: 1,
                expected: 2,
            })
        ));
    }

    fn add_chunk() -> Chunk {
        let mut b = ChunkBuilder::new("test");
        b.begin_function("main", 0, 2);
        b.emit_load_imm(0, 41);
        b.emit_load_imm(1, 1);
        b.emit_binop(Opcode::Add, 0, 0, 1);
        b.emit_return(0);
        b.finish()
    }

    /// Sleeps `millis` inside the flow, then returns 7. The sleep is what
    /// makes "still running" an observable state from the host thread.
    fn sleep_then_return_chunk(millis: i32) -> Chunk {
        let mut b = ChunkBuilder::new("test");
        b.begin_function("main", 0, 2);
        b.emit_load_imm(0, millis);
        b.emit_sleep(0);
        b.emit_load_imm(0, 7);
        b.emit_return(0);
        b.finish()
    }

    /// The host thread must be able to ask "done yet?" and to wait under a
    /// bound *it* chooses, instead of surrendering itself to `join` for
    /// however long the bytecode decides to take.
    #[test]
    fn polling_and_bounded_waits_never_commit_the_host_thread(
    ) -> Result<(), Box<dyn std::error::Error>> {
        const FLOW_SLEEP: i32 = 150;
        let rt = Runtime::with_config(
            sleep_then_return_chunk(FLOW_SLEEP),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                ..Default::default()
            },
        )?;
        let handle = rt.spawn(0, &[])?;

        // The flow cannot possibly be finished yet: it has to be picked up
        // and then sleep. A poll must say so without waiting.
        if let Some(outcome) = handle.try_join() {
            rt.shutdown();
            return Err(format!("try_join answered too early: {outcome:?}").into());
        }

        // A bound well below the flow's sleep must expire and hand control
        // back, not block until the flow happens to finish.
        if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
            rt.shutdown();
            return Err(format!("join_timeout answered too early: {outcome:?}").into());
        }

        // A generous bound collects the real outcome through the same
        // (non-consuming) handle.
        let outcome = handle.join_timeout(Duration::from_secs(10));
        rt.shutdown();
        match outcome {
            Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
            other => Err(format!("unexpected outcome: {other:?}").into()),
        }
    }

    #[test]
    fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
        let rt = Runtime::with_config(
            add_chunk(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                ..Default::default()
            },
        )?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();
        match outcome {
            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
            other => Err(format!("unexpected outcome: {other:?}").into()),
        }
    }

    fn receive_forever_chunk() -> Chunk {
        let mut b = ChunkBuilder::new("recv");
        b.begin_function("main", 0, 1);
        b.emit_receive(0);
        b.emit_return(0);
        b.finish()
    }

    #[test]
    fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
        let rt = Runtime::with_config(
            receive_forever_chunk(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                ..Default::default()
            },
        )?;
        let handle = rt.spawn(0, &[])?;
        rt.kill(handle.id())?;
        let outcome = handle.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Failed(_)),
            "kill must fail the joiner, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn shutdown_finalizes_parked_receive() -> Result<(), Box<dyn std::error::Error>> {
        let rt = Runtime::with_config(
            receive_forever_chunk(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                ..Default::default()
            },
        )?;
        let handle = rt.spawn(0, &[])?;
        std::thread::sleep(Duration::from_millis(30));
        rt.shutdown();
        match handle.join() {
            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
            other => Err(format!("expected shutdown finalize, got {other:?}").into()),
        }
    }

    #[test]
    fn shutdown_finalizes_sleeper() -> Result<(), Box<dyn std::error::Error>> {
        let rt = Runtime::with_config(
            sleep_then_return_chunk(60_000),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                ..Default::default()
            },
        )?;
        let handle = rt.spawn(0, &[])?;
        std::thread::sleep(Duration::from_millis(30));
        rt.shutdown();
        match handle.join() {
            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
            other => Err(format!("expected sleeper shutdown, got {other:?}").into()),
        }
    }

    #[test]
    fn drop_finalizes_a_parked_sleeper() -> Result<(), Box<dyn std::error::Error>> {
        let rt = Runtime::with_config(
            sleep_then_return_chunk(60_000),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                ..Default::default()
            },
        )?;
        let handle = rt.spawn(0, &[])?;
        std::thread::sleep(Duration::from_millis(30));
        drop(rt);
        match handle.join() {
            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
            other => Err(format!("expected drop to finalize the sleeper, got {other:?}").into()),
        }
    }

    #[test]
    fn zero_quantum_still_runs_the_flow() -> Result<(), Box<dyn std::error::Error>> {
        let rt = Runtime::with_config(
            add_chunk(),
            RuntimeConfig {
                workers: 1,
                quantum: 0,
                mailbox: MailboxConfig::DEFAULT,
                ..Default::default()
            },
        )?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
        let rt = Runtime::with_config(
            receive_forever_chunk(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                max_flows: 1,
                ..Default::default()
            },
        )?;
        let first = rt.spawn(0, &[])?;
        let second = rt.spawn(0, &[]);
        rt.kill(first.id())?;
        let _ = first.join();
        // After finalize, the reserved slot must be free again.
        let third = rt.spawn(0, &[])?;
        rt.kill(third.id())?;
        let _ = third.join();
        rt.shutdown();
        match second {
            Err(SpawnError::FlowLimit { current, max }) => {
                assert_eq!(current, 1);
                assert_eq!(max, 1);
                Ok(())
            }
            other => Err(format!(
                "expected FlowLimit, got {}",
                match &other {
                    Ok(_) => "Ok(handle)".into(),
                    Err(e) => format!("Err({e})"),
                }
            )
            .into()),
        }
    }

    /// Ask must not park waiting for a reply when DropNewest discarded the request.
    #[test]
    fn ask_drop_newest_fails_closed() -> Result<(), Box<dyn std::error::Error>> {
        use crate::bytecode::{Message, Program};
        use crate::scheduler::mailbox::{MailboxCapacity, OverflowPolicy};

        let mut program = Program::new("ask-drop-newest");
        let busy = program.function("busy", 0, |f| {
            // Stay alive without spinning the worker: sleep loop.
            let loop_lbl = f.label();
            f.bind(loop_lbl);
            let ms = f.load_i32(50);
            f.sleep(ms);
            f.jump(loop_lbl);
        });
        let asker = program.function("asker", 1, |f| {
            let server = f.reg(0);
            let z = f.load_i32(0);
            let req = f.hop_fresh(1, z);
            let reply = f.ask(server, req);
            f.return_(reply);
        });
        let chunk = program.build();

        let cap = MailboxCapacity::new(1).ok_or("cap")?;
        let rt = Runtime::with_natives_and_config(
            chunk,
            crate::std_native_table(),
            RuntimeConfig {
                // Busy target must not monopolize scheduling or Ask never runs.
                workers: 2,
                quantum: 1_000,
                mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
                ..Default::default()
            },
        )?;

        let server = rt.spawn(busy, &[])?;
        // Fill the only slot so the subsequent Ask is DropNewest'd.
        rt.send(
            server.id(),
            Value::Message(Message::request(1, 9, Value::Int(1))),
        )?;
        let server_cap = rt.mint_cap(server.id())?;
        let ask = rt.spawn(asker, &[Value::Cap(server_cap)])?;
        let outcome = ask.join_timeout(Duration::from_secs(3));
        rt.kill(server.id())?;
        let _ = server.join_timeout(Duration::from_millis(500));
        rt.shutdown();

        match outcome {
            Some(FlowOutcome::Failed(msg)) if msg.contains("DropNewest") => Ok(()),
            other => Err(format!("expected Ask DropNewest failure, got {other:?}").into()),
        }
    }

    #[test]
    fn max_ask_waits_rejects_extra_park() -> Result<(), Box<dyn std::error::Error>> {
        use crate::bytecode::Program;

        let mut program = Program::new("ask-limit");
        let silent = program.function("silent", 0, |f| {
            // Accept the request hop but never reply.
            let _req = f.receive();
            let loop_lbl = f.label();
            f.bind(loop_lbl);
            let ms = f.load_i32(50);
            f.sleep(ms);
            f.jump(loop_lbl);
        });
        let asker = program.function("asker", 1, |f| {
            let server = f.reg(0);
            let z = f.load_i32(0);
            let req = f.hop_fresh(1, z);
            let reply = f.ask(server, req);
            f.return_(reply);
        });
        let chunk = program.build();

        let rt = Runtime::with_natives_and_config(
            chunk,
            crate::std_native_table(),
            RuntimeConfig {
                workers: 2,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                max_ask_waits: 1,
                ..Default::default()
            },
        )?;

        let server = rt.spawn(silent, &[])?;
        let server_cap = rt.mint_cap(server.id())?;
        let first = rt.spawn(asker, &[Value::Cap(server_cap)])?;
        // Give the first Ask time to park before the second tries.
        std::thread::sleep(Duration::from_millis(30));
        let second = rt.spawn(asker, &[Value::Cap(server_cap)])?;
        let second_out = second.join_timeout(Duration::from_secs(2));
        rt.kill(server.id())?;
        let _ = first.join_timeout(Duration::from_millis(500));
        let _ = server.join_timeout(Duration::from_millis(500));
        rt.shutdown();

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

    // HostAwait E2E coverage lives in `host_await::runtime_tests`.

    #[cfg(feature = "jit")]
    #[test]
    fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
        use crate::JitConfig;

        let rt = Runtime::with_config(
            add_chunk(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                jit: JitConfig {
                    enabled: true,
                    hot_threshold: 1,
                },
                ..Default::default()
            },
        )?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();
        match outcome {
            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
            other => Err(format!("unexpected outcome: {other:?}").into()),
        }
    }

    #[test]
    fn sandbox_enables_process_wide_relation_caps() {
        let config = RuntimeConfig::sandbox();
        assert_eq!(config.max_flows, 128);
        assert_eq!(config.max_ask_waits, 64);
        assert_eq!(config.max_host_awaits, 128);
        assert_eq!(config.trust, crate::bytecode::TrustLevel::Untrusted);
        assert_ne!(
            config.policy_fingerprint(),
            RuntimeConfig::default().policy_fingerprint()
        );
        assert_eq!(config.max_links, 1024);
        assert_eq!(config.max_monitors, 1024);
        assert_eq!(config.max_registry_names, 256);
        assert_eq!(config.max_runtime_bytes, 64 * 1024 * 1024);
    }

    #[test]
    fn default_remains_unlimited_for_relation_caps() {
        let config = RuntimeConfig::default();
        assert_eq!(config.max_links, 0);
        assert_eq!(config.max_monitors, 0);
        assert_eq!(config.max_registry_names, 0);
    }

    #[test]
    fn with_attested_mismatch_is_attestation_error() -> Result<(), Box<dyn std::error::Error>> {
        use crate::bytecode::encode;
        use crate::{fingerprint_bf, AttestError};

        let bytes = encode(&add_chunk());
        let mut bad = fingerprint_bf(&bytes);
        bad[0] ^= 0xff;
        match Runtime::with_attested(&bytes, bad, NativeTable::empty(), RuntimeConfig::default()) {
            Err(SpawnError::Attestation(AttestError::DigestMismatch { .. })) => Ok(()),
            Ok(_) => Err("expected Attestation error, got Ok(Runtime)".into()),
            Err(e) => Err(format!("expected Attestation(DigestMismatch), got Err({e})").into()),
        }
    }

    #[test]
    fn with_attested_match_runs() -> Result<(), Box<dyn std::error::Error>> {
        use crate::bytecode::encode;
        use crate::fingerprint_bf;

        let chunk = add_chunk();
        let bytes = encode(&chunk);
        let digest = fingerprint_bf(&bytes);
        let rt = Runtime::with_attested(
            &bytes,
            digest,
            NativeTable::empty(),
            RuntimeConfig {
                workers: 1,
                quantum: 1_000,
                mailbox: MailboxConfig::DEFAULT,
                ..Default::default()
            },
        )?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();
        match outcome {
            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
            other => Err(format!("expected 42, got {other:?}").into()),
        }
    }

    #[test]
    fn poisoned_injector_still_runs_the_flow() -> Result<(), Box<dyn std::error::Error>> {
        let rt = Runtime::new(add_chunk())?;
        rt.shared.injector.poison_for_test();
        let outcome = rt.spawn(0, &[])?.join_timeout(Duration::from_secs(2));
        rt.shutdown();
        match outcome {
            Some(FlowOutcome::Completed(Value::Int(42))) => Ok(()),
            other => Err(format!("expected 42 after a poisoned injector, got {other:?}").into()),
        }
    }
}