byteflow-actors 0.9.14

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
//! Built-in demo chunks assembled with [`crate::Program`].
//!
//! Use these as runnable specs of the messaging contract (and as regression
//! tests). Prefer copying a sample over inventing hop register layouts from
//! scratch.
//!
//! | Sample | Shows |
//! |--------|--------|
//! | [`add_forty_two`] | Scalar VM path (no natives) |
//! | [`ping_pong`] | Cap spawn + Atomic Hop round-trip |
//! | [`atomic_request_reply`] | Tagged REQ/REP + correlated receive |
//! | [`atomic_actors`] | Server loop + two `Ask` clients + minted `request_id` |
//! | [`cap_in_payload`] | Cap in hop payload is reissued to the recipient |
//! | [`selective_receive`] | `ReceiveMatch` FIFO skip |
//! | [`selective_receive_timeout`] | BEAM `after`: `ReceiveMatchImmTimeout` → `Unit` |
//! | [`selective_receive_after`] | `after` still skips junk and hits the tag |
//! | [`process_alive`] | `IsAlive` (BEAM `is_process_alive/1`) |
//! | [`process_dict`] | process dictionary `put` / `get` / `erase` |
//! | [`receive_match_eq`] | term equality: tag + `Int` payload |
//! | [`exit_signal`] | BEAM `exit/2` → `DOWN` with `Fault` |
//! | [`supervised_tree`] | bytecode `StartChild` under a host supervisor |
//! | [`receive_match_kind`] | `ReceiveMatchKind` by payload wire-tag |
//! | [`ask_reply`] | `Ask` RPC hop |
//! | [`ask_timeout_expires`] | `AskTimeout` writes `Unit` when the server stays silent |
//! | [`ask_target_exits`] | `Ask` dest is `TAG_SYS_EXIT` when the server dies first |
//! | [`server_loop`] | BEAM-style receive → handle → reply loop |
//! | [`named_service`] | Bytecode `register_name` / `whereis` (Cap, not FlowId) |
//! | [`forged_sender_send`] / [`forged_sender_ask`] | S1: forged `make_msg` sender dies |
//! | [`boom`] | Immediate trap (supervisor demos) |
//! | [`monitor_down`] | Monitor → [`crate::TAG_SYS_DOWN`] on child exit |
//! | [`waiting_send`] | `WAITING_SEND`: second hop parks until the first is received |
//!
//! Lifecycle regression tests in this module (not demo samples) also cover
//! `trap_exit` / `SetTrapExit` and linked `TAG_SYS_EXIT` hops.
//!
//! Hop samples require [`crate::std_native_table`].

use crate::natives::std_native;
use crate::{Chunk, Program};

/// Native indices (must match [`crate::std_native_map`]).
const N_PRINT: u32 = std_native::PRINT;
const N_MAKE_MSG: u32 = std_native::MAKE_MSG;

/// Protocol tags for Atomic Hop samples.
pub const TAG_REQ: i32 = 1;
pub const TAG_REP: i32 = 2;
/// Client → parent completion hop in [`atomic_actors`] (not an RPC reply).
pub const TAG_DONE: i32 = 3;
/// Readiness handshake (e.g. `SetTrapExit` before link).
pub const TAG_READY: i32 = 4;
pub const TAG_PING: i32 = 10;
pub const TAG_PONG: i32 = 11;
/// Decoy hop for [`selective_receive`] — must be skipped by `ReceiveMatch`.
pub const TAG_JUNK: i32 = 99;

/// `41 + 1; return` — the 60-second sanity chunk.
pub fn add_forty_two() -> Chunk {
    let mut p = Program::new("add-forty-two");
    p.function("main", 0, |f| {
        let a = f.load_i32(41);
        let b = f.load_i32(1);
        let sum = f.add(a, b);
        f.return_(sum);
    });
    p.build()
}

/// Two flows, one **Atomic Hop** round-trip: `main` sends a `Message` to
/// `pong`, `pong` replies with payload+1 via `msg_reply_cap`, `main` returns
/// that payload (`2`).
pub fn ping_pong() -> Chunk {
    let mut p = Program::new("ping-pong");
    let pong = p.function("pong", 0, |f| {
        let msg = f.receive();
        let payload = f.hop_payload(msg);
        f.add_imm(payload, 1);
        f.send_reply(msg, TAG_PONG, payload);
        f.exit(payload);
    });
    p.function("main", 0, |f| {
        let child = f.spawn(pong, &[]);
        let payload = f.load_i32(1);
        let req = f.hop_fresh(TAG_PING, payload);
        let rid = f.hop_request_id(req);
        f.send(child, req);
        let reply = f.receive_match_corr_imm(TAG_PONG as u16, rid);
        let out = f.hop_payload(reply);
        f.return_(out);
    });
    p.build()
}

/// Atomic request-reply with [`crate::Value::Message`] (one envelope per hop).
pub fn atomic_request_reply() -> Chunk {
    let mut p = Program::new("atomic-request-reply");
    let server = p.function("server", 0, |f| {
        let msg = f.receive();
        f.native1_on(msg, N_PRINT);
        let payload = f.hop_payload(msg);
        f.add_imm(payload, 1);
        f.send_reply(msg, TAG_REP, payload);
        f.exit(payload);
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let payload = f.load_i32(41);
        let req = f.hop_fresh(TAG_REQ, payload);
        let rid = f.hop_request_id(req);
        f.native1_on(req, N_PRINT);
        f.send(server_cap, req);
        let reply = f.receive_match_corr_imm(TAG_REP as u16, rid);
        f.native1_on(reply, N_PRINT);
        let out = f.hop_payload(reply);
        f.return_(out);
    });
    p.build()
}

/// Selective Atomic Hop: server waits for `TAG_REQ` while a `TAG_JUNK` hop
/// sits ahead in the mailbox (FIFO skip, not drop).
pub fn selective_receive() -> Chunk {
    let mut p = Program::new("selective-receive");
    let server = p.function("server", 0, |f| {
        let msg = f.receive_match_imm(TAG_REQ as u16);
        let payload = f.hop_payload(msg);
        f.add_imm(payload, 1);
        f.send_reply(msg, TAG_REP, payload);
        let junk = f.receive();
        let tag = f.hop_tag(junk);
        let is_junk = f.eq_imm(tag, TAG_JUNK);
        let trap_lbl = f.label();
        f.branch_if_falsy(is_junk, trap_lbl);
        f.exit(payload);
        f.bind(trap_lbl);
        f.trap(2);
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let req_id = f.load_i32(1);
        let zero = f.load_i32(0);
        let junk = f.hop(req_id, TAG_JUNK, zero);
        f.send(server_cap, junk);
        let payload = f.load_i32(41);
        let req = f.hop(req_id, TAG_REQ, payload);
        f.send(server_cap, req);
        let reply = f.receive_match_imm(TAG_REP as u16);
        let out = f.hop_payload(reply);
        f.return_(out);
    });
    p.build()
}

/// BEAM `receive … after`: nobody sends `TAG_REQ`, so the wait writes `Unit`.
pub fn selective_receive_timeout() -> Chunk {
    let mut p = Program::new("selective-receive-timeout");
    p.function("main", 0, |f| {
        let ms = f.load_i32(40);
        let msg = f.receive_match_imm_timeout(TAG_REQ as u16, ms);
        f.return_(msg);
    });
    p.build()
}

/// Selective receive + `after`: junk stays queued, `TAG_REQ` arrives in time.
pub fn selective_receive_after() -> Chunk {
    let mut p = Program::new("selective-receive-after");
    let server = p.function("server", 0, |f| {
        let ms = f.load_i32(5_000);
        let msg = f.receive_match_imm_timeout(TAG_REQ as u16, ms);
        let payload = f.hop_payload(msg);
        f.add_imm(payload, 1);
        f.send_reply(msg, TAG_REP, payload);
        let junk = f.receive();
        let tag = f.hop_tag(junk);
        let is_junk = f.eq_imm(tag, TAG_JUNK);
        let trap_lbl = f.label();
        f.branch_if_falsy(is_junk, trap_lbl);
        f.exit(payload);
        f.bind(trap_lbl);
        f.trap(2);
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let req_id = f.load_i32(1);
        let zero = f.load_i32(0);
        let junk = f.hop(req_id, TAG_JUNK, zero);
        f.cast(server_cap, junk);
        let payload = f.load_i32(41);
        let req = f.hop(req_id, TAG_REQ, payload);
        f.cast(server_cap, req);
        let reply = f.receive_match_imm(TAG_REP as u16);
        let out = f.hop_payload(reply);
        f.return_(out);
    });
    p.build()
}

/// BEAM `is_process_alive/1`: a parked child is live; after `DOWN`, its Cap is not.
pub fn process_alive() -> Chunk {
    let mut p = Program::new("process-alive");
    let parked = p.function("parked", 0, |f| {
        let _msg = f.receive();
        let z = f.load_i32(0);
        f.return_(z);
    });
    p.function("main", 0, |f| {
        let live_cap = f.spawn(parked, &[]);
        let was_live = f.is_alive(live_cap);
        let _mon = f.monitor(live_cap);
        let rid = f.load_i32(1);
        let z = f.load_i32(0);
        let hop = f.hop(rid, TAG_REQ, z);
        f.cast(live_cap, hop);
        let _down = f.receive_match_imm(crate::TAG_SYS_DOWN);
        let now_dead = f.is_alive(live_cap);
        let bad = f.label();
        let ok = f.label();
        f.branch_if_falsy(was_live, bad);
        f.branch_if_falsy(now_dead, ok);
        f.bind(bad);
        f.trap(1);
        f.bind(ok);
        let one = f.load_i32(1);
        f.return_(one);
    });
    p.build()
}

/// Process dictionary (`put` / `get` / `erase`): store 41, add 1 in a
/// register, erase still yields the stored 41. Returns `42 + 41 = 83`.
pub fn process_dict() -> Chunk {
    let mut p = Program::new("process-dict");
    p.function("main", 0, |f| {
        let key = f.load_i32(1);
        let value = f.load_i32(41);
        let _prev = f.dict_put(key, value);
        let got = f.dict_get(key);
        f.add_imm(got, 1);
        let erased = f.dict_erase(key);
        let sum = f.add(got, erased);
        f.return_(sum);
    });
    p.build()
}

/// Term equality receive: skip a `TAG_REQ` whose payload is `0`, take `41`.
pub fn receive_match_eq() -> Chunk {
    let mut p = Program::new("receive-match-eq");
    let server = p.function("server", 0, |f| {
        let tag = f.load_i32(TAG_REQ);
        let want = f.load_i32(41);
        let msg = f.receive_match_eq(tag, want);
        let payload = f.hop_payload(msg);
        f.add_imm(payload, 1);
        f.send_reply(msg, TAG_REP, payload);
        let junk = f.receive();
        let got = f.hop_payload(junk);
        let zero = f.eq_imm(got, 0);
        let trap_lbl = f.label();
        f.branch_if_falsy(zero, trap_lbl);
        f.exit(payload);
        f.bind(trap_lbl);
        f.trap(2);
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let req_id = f.load_i32(1);
        let zero = f.load_i32(0);
        let junk = f.hop(req_id, TAG_REQ, zero);
        f.cast(server_cap, junk);
        let payload = f.load_i32(41);
        let req = f.hop(req_id, TAG_REQ, payload);
        f.cast(server_cap, req);
        let reply = f.receive_match_imm(TAG_REP as u16);
        let out = f.hop_payload(reply);
        f.return_(out);
    });
    p.build()
}

/// BEAM `exit/2`: child parked on receive dies with `Fault`; monitor payload is `3`.
pub fn exit_signal() -> Chunk {
    let mut p = Program::new("exit-signal");
    let parked = p.function("parked", 0, |f| {
        let _msg = f.receive();
        let z = f.load_i32(0);
        f.return_(z);
    });
    p.function("main", 0, |f| {
        let cap = f.spawn(parked, &[]);
        let _mon = f.monitor(cap);
        let reason = f.load_i32(crate::FlowExitReason::Fault as i32);
        f.exit_signal(cap, reason);
        let down = f.receive_match_imm(crate::TAG_SYS_DOWN);
        let payload = f.hop_payload(down);
        f.return_(payload);
    });
    p.build()
}

/// Root (started by a host [`crate::Supervisor`]) starts a parked worker,
/// then `exit/2`s it. Returns `1` when the worker was alive and `DOWN` is `Fault`.
pub fn supervised_tree() -> Chunk {
    let mut p = Program::new("supervised-tree");
    let worker = p.function("worker", 0, |f| {
        let _msg = f.receive();
        let z = f.load_i32(0);
        f.return_(z);
    });
    p.function("root", 0, |f| {
        let cap = f.start_child(worker, crate::RestartPolicy::Never);
        let alive = f.is_alive(cap);
        let _mon = f.monitor(cap);
        let reason = f.load_i32(crate::FlowExitReason::Fault as i32);
        f.exit_signal(cap, reason);
        let down = f.receive_match_imm(crate::TAG_SYS_DOWN);
        let payload = f.hop_payload(down);
        let fault = f.eq_imm(payload, crate::FlowExitReason::Fault as i32);
        let bad = f.label();
        let ok = f.label();
        f.branch_if_falsy(alive, bad);
        f.branch_if_falsy(fault, bad);
        f.jump(ok);
        f.bind(bad);
        f.trap(1);
        f.bind(ok);
        let one = f.load_i32(1);
        f.return_(one);
    });
    p.build()
}

/// Selective receive by payload wire-tag (`ReceiveMatchKind`): skip hops
/// whose payload is not `Int` (tag 2), then reply with that payload.
pub fn receive_match_kind() -> Chunk {
    let mut p = Program::new("receive-match-kind");
    let server = p.function("server", 0, |f| {
        // BFV0 Int = 2
        let msg = f.receive_match_kind(2);
        let payload = f.hop_payload(msg);
        f.send_reply(msg, TAG_REP, payload);
        let _junk = f.receive();
        f.exit(payload);
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let req_id = f.load_i32(1);
        let decoy = f.load_str("skip-me");
        let junk = f.hop(req_id, TAG_JUNK, decoy);
        f.send(server_cap, junk);
        let payload = f.load_i32(42);
        let req = f.hop(req_id, TAG_REQ, payload);
        f.send(server_cap, req);
        let reply = f.receive_match_imm(TAG_REP as u16);
        let out = f.hop_payload(reply);
        f.return_(out);
    });
    p.build()
}

/// Atomic request/reply via `Ask` (RPC hop).
pub fn ask_reply() -> Chunk {
    let mut p = Program::new("ask-reply");
    let server = p.function("server", 0, |f| {
        let msg = f.receive_match_imm(TAG_REQ as u16);
        let payload = f.hop_payload(msg);
        f.add_imm(payload, 1);
        f.send_reply(msg, TAG_REP, payload);
        f.exit(payload);
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let payload = f.load_i32(41);
        let req = f.hop_fresh(TAG_REQ, payload);
        let reply = f.ask(server_cap, req);
        let out = f.hop_payload(reply);
        f.return_(out);
    });
    p.build()
}

/// `AskTimeout` against a server that never replies → `Unit`.
pub fn ask_timeout_expires() -> Chunk {
    let mut p = Program::new("ask-timeout");
    let server = p.function("server", 0, |f| {
        let _msg = f.receive();
        let ms = f.load_i32(10_000);
        f.sleep(ms);
        let zero = f.load_i32(0);
        f.return_(zero);
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let req_id = f.load_i32(1);
        let payload = f.load_i32(0);
        let req = f.hop(req_id, TAG_REQ, payload);
        let ms = f.load_i32(40);
        let reply = f.ask_timeout(server_cap, req, ms);
        f.return_(reply);
    });
    p.build()
}

/// Server takes the request and exits; client `Ask` must not hang.
pub fn ask_target_exits() -> Chunk {
    let mut p = Program::new("ask-target-exits");
    let server = p.function("server", 0, |f| {
        let _msg = f.receive();
        let z = f.load_i32(0);
        f.return_(z);
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let req_id = f.load_i32(1);
        let payload = f.load_i32(0);
        let req = f.hop(req_id, TAG_REQ, payload);
        let reply = f.ask(server_cap, req);
        let tag = f.hop_tag(reply);
        f.return_(tag);
    });
    p.build()
}

/// BEAM-style server loop: `receive_match` → handle → `send_reply` → repeat.
pub fn server_loop() -> Chunk {
    let mut p = Program::new("server-loop");
    let server = p.function("server", 0, |f| {
        f.actor_loop(TAG_REQ as u16, |f, req| {
            let payload = f.hop_payload(req);
            f.add_imm(payload, 1);
            f.send_reply(req, TAG_REP, payload);
        });
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let payload = f.load_i32(41);
        let req = f.hop_fresh(TAG_REQ, payload);
        f.send(server_cap, req);
        let reply = f.receive_match_imm(TAG_REP as u16);
        let out = f.hop_payload(reply);
        f.return_(out);
    });
    p.build()
}

/// Server publishes `"svc"`; client loops `whereis` until it gets a SEND Cap
/// (not ASK — use `Send` + `Receive`, not `Ask`). Returns `42` (41 + 1).
/// Discovery never exposes a raw FlowId.
pub fn named_service() -> Chunk {
    let mut p = Program::new("named-service");
    let server = p.function("server", 0, |f| {
        let name = f.load_str("svc");
        f.register_name(name);
        f.actor_loop(TAG_REQ as u16, |f, req| {
            let payload = f.hop_payload(req);
            f.add_imm(payload, 1);
            f.send_reply(req, TAG_REP, payload);
        });
    });
    p.function("main", 0, |f| {
        let _server = f.spawn(server, &[]);
        let name = f.load_str("svc");
        let retry = f.label();
        let miss = f.label();
        f.bind(retry);
        let cap = f.whereis(name);
        f.branch_if_falsy(cap, miss);
        let payload = f.load_i32(41);
        let req = f.hop_fresh(TAG_REQ, payload);
        f.send(cap, req);
        let reply = f.receive_match_imm(TAG_REP as u16);
        let out = f.hop_payload(reply);
        f.return_(out);
        f.bind(miss);
        // Sleep (not Yield): Yield re-queues on the local worker deque and
        // can starve the injector, so the server would never register.
        let ms = f.load_i32(1);
        f.sleep(ms);
        f.jump(retry);
    });
    p.build()
}

/// Canonical Atomic Hop actor demo: one server loop, two clients, each
/// doing `N` `Ask`s with minted `request_id`s. Each client asserts that the
/// reply echoes the request's `request_id` before accumulating. Main waits
/// for both DONE hops and returns the sum (`2 * 36 = 72`).
pub fn atomic_actors() -> Chunk {
    const N: i32 = 8;
    let mut p = Program::new("atomic-actors");
    let server = p.function("server", 0, |f| {
        f.actor_loop(TAG_REQ as u16, |f, req| {
            let payload = f.hop_payload(req);
            f.add_imm(payload, 1);
            f.send_reply(req, TAG_REP, payload);
        });
    });
    let client = p.function("client", 2, |f| {
        let server_cap = f.reg(0);
        let parent_cap = f.reg(1);
        let acc = f.load_i32(0);
        let i = f.load_i32(0);
        let n = f.load_i32(N);
        f.while_lt(i, n, |f| {
            let req = f.hop_fresh(TAG_REQ, i);
            let expect = f.hop_request_id(req);
            let reply = f.ask(server_cap, req);
            let got_id = f.hop_request_id(reply);
            let same = f.eq(expect, got_id);
            let bad = f.label();
            f.branch_if_falsy(same, bad);
            let got = f.hop_payload(reply);
            let sum = f.add(acc, got);
            f.mov(acc, sum);
            f.add_imm(i, 1);
            let cont = f.label();
            f.jump(cont);
            f.bind(bad);
            f.trap(1);
            f.bind(cont);
        });
        let done = f.hop_fresh(TAG_DONE, acc);
        f.send(parent_cap, done);
        f.return_(acc);
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let me = f.self_cap();
        let w1 = f.window(3);
        f.mov(w1.at(1), server_cap);
        f.mov(w1.at(2), me);
        f.spawn_at(w1.at(0), client, 2);
        let w2 = f.window(3);
        f.mov(w2.at(1), server_cap);
        f.mov(w2.at(2), me);
        f.spawn_at(w2.at(0), client, 2);
        let a = f.receive_match_imm(TAG_DONE as u16);
        let b = f.receive_match_imm(TAG_DONE as u16);
        let pa = f.hop_payload(a);
        let pb = f.hop_payload(b);
        let out = f.add(pa, pb);
        f.return_(out);
    });
    p.build()
}

/// Server receives a Cap in the payload and sends `42` back through it.
/// Exercises hop-time reissue (holder becomes the recipient).
pub fn cap_in_payload() -> Chunk {
    let mut p = Program::new("cap-in-payload");
    let server = p.function("server", 0, |f| {
        let msg = f.receive();
        let dest = f.hop_payload(msg);
        let payload = f.load_i32(42);
        let reply = f.hop_fresh(TAG_REP, payload);
        f.send(dest, reply);
        f.exit(payload);
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let me = f.self_cap();
        let req = f.hop_fresh(TAG_REQ, me);
        f.send(server_cap, req);
        let reply = f.receive_match_imm(TAG_REP as u16);
        let out = f.hop_payload(reply);
        f.return_(out);
    });
    p.build()
}

/// Security regression: forged `make_msg` sender must not survive `Send`.
pub fn forged_sender_send() -> Chunk {
    let mut p = Program::new("forged-sender-send");
    let server = p.function("server", 0, |f| {
        let msg = f.receive();
        let sender = f.hop_sender(msg);
        f.send_reply(msg, TAG_REP, sender);
        f.exit(sender);
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let forged = f.load_i32(999);
        let req_id = f.load_i32(1);
        let zero = f.load_i32(0);
        let req = f.make_msg_legacy_sender(N_MAKE_MSG, forged, req_id, TAG_REQ, zero);
        f.send(server_cap, req);
        let reply = f.receive();
        let out = f.hop_payload(reply);
        f.return_(out);
    });
    p.build()
}

/// Same security property as [`forged_sender_send`], via `Ask`.
pub fn forged_sender_ask() -> Chunk {
    let mut p = Program::new("forged-sender-ask");
    let server = p.function("server", 0, |f| {
        let msg = f.receive_match_imm(TAG_REQ as u16);
        let sender = f.hop_sender(msg);
        f.send_reply(msg, TAG_REP, sender);
        f.exit(sender);
    });
    p.function("main", 0, |f| {
        let server_cap = f.spawn(server, &[]);
        let forged = f.load_i32(999);
        let req_id = f.load_i32(1);
        let zero = f.load_i32(0);
        let req = f.make_msg_legacy_sender(N_MAKE_MSG, forged, req_id, TAG_REQ, zero);
        let reply = f.ask(server_cap, req);
        let out = f.hop_payload(reply);
        f.return_(out);
    });
    p.build()
}

/// Child sleeps then exits; parent monitors and returns the `DOWN` reason (`0` = normal).
pub fn monitor_down() -> Chunk {
    let mut p = Program::new("monitor-down");
    let child = p.function("child", 0, |f| {
        let ms = f.load_i32(40);
        f.sleep(ms);
        let z = f.load_i32(0);
        f.return_(z);
    });
    p.function("main", 0, |f| {
        let cap = f.spawn(child, &[]);
        let mon = f.monitor(cap);
        let msg = f.receive_match_imm(crate::TAG_SYS_DOWN);
        let id = f.hop_request_id(msg);
        let ok = f.eq(id, mon);
        let trap = f.label();
        f.branch_if_falsy(ok, trap);
        let out = f.hop_payload(msg);
        f.return_(out);
        f.bind(trap);
        f.trap(3);
    });
    p.build()
}

/// Client arity 1 (`r0` = server Cap) sends two hops; server drains both.
/// With mailbox capacity 1 the second send parks (`WAITING_SEND`).
pub fn waiting_send() -> Chunk {
    let mut p = Program::new("waiting-send");
    p.function("server", 0, |f| {
        let ms = f.load_i32(50);
        f.sleep(ms);
        let _first = f.receive();
        let second = f.receive();
        let out = f.hop_payload(second);
        f.return_(out);
    });
    p.function("client", 1, |f| {
        let server = f.reg(0);
        let req_id = f.load_i32(1);
        let one = f.load_i32(1);
        let first = f.hop(req_id, TAG_REQ, one);
        f.send(server, first);
        let forty_two = f.load_i32(42);
        let second = f.hop(req_id, TAG_REQ, forty_two);
        f.send(server, second);
        f.exit(second);
    });
    p.build()
}

/// Immediate `Trap` — used to show [`crate::Supervisor`] restart.
pub fn boom() -> Chunk {
    let mut p = Program::new("boom");
    p.function("boom", 0, |f| f.trap(1));
    p.build()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        bytecode::CapId, decode, encode, std_native_table, verify, FlowOutcome, Message,
        QuotaConfig, Runtime, RuntimeConfig, Value,
    };

    fn tiny(chunk: Chunk) -> Result<Runtime, crate::SpawnError> {
        Runtime::with_config(
            chunk,
            RuntimeConfig {
                workers: 1,
                quantum: 10_000,
                mailbox: crate::MailboxConfig::DEFAULT,
                ..Default::default()
            },
        )
    }

    fn tiny_natives(chunk: Chunk) -> Result<Runtime, crate::SpawnError> {
        Runtime::with_natives_and_config(
            chunk,
            std_native_table(),
            RuntimeConfig {
                workers: 1,
                quantum: 10_000,
                mailbox: crate::MailboxConfig::DEFAULT,
                ..Default::default()
            },
        )
    }

    #[test]
    fn add_forty_two_joins_42() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny(add_forty_two())?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(matches!(outcome, FlowOutcome::Completed(Value::Int(42))));
        Ok(())
    }

    #[test]
    fn ping_pong_joins_2() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = ping_pong();
        assert!(verify(&chunk).is_ok());
        let bytes = encode(&chunk);
        let chunk = decode(&bytes)?;
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        let sent = rt.metrics().messages_sent;
        rt.shutdown();
        assert!(matches!(outcome, FlowOutcome::Completed(Value::Int(2))));
        assert!(sent >= 2);
        Ok(())
    }

    #[test]
    fn atomic_request_reply_joins_42() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = atomic_request_reply();
        assert!(verify(&chunk).is_ok());
        let bytes = encode(&chunk);
        let chunk = decode(&bytes)?;
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        let sent = rt.metrics().messages_sent;
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "got {outcome:?}"
        );
        assert!(sent >= 1);
        Ok(())
    }

    #[test]
    fn atomic_actors_two_clients_sum_72() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = atomic_actors();
        assert!(verify(&chunk).is_ok());
        let bytes = encode(&chunk);
        let chunk = decode(&bytes)?;
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        let sent = rt.metrics().messages_sent;
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(72))),
            "got {outcome:?}"
        );
        // 8 Ask + 8 reply per client, plus 2 DONE hops.
        assert!(sent >= 34);
        Ok(())
    }

    #[test]
    fn cap_in_payload_reissues_holder() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = cap_in_payload();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn selective_receive_timeout_writes_unit() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = selective_receive_timeout();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Unit)),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn selective_receive_after_hits_tag() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = selective_receive_after();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn process_alive_tracks_live_then_down() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = process_alive();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(1))),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn process_dict_put_get_erase() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = process_dict();
        assert!(verify(&chunk).is_ok());
        let rt = tiny(chunk)?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(83))),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn receive_match_eq_skips_other_payload() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = receive_match_eq();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn exit_signal_down_is_fault() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = exit_signal();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(
                outcome,
                FlowOutcome::Completed(Value::Int(n))
                    if n == i64::from(crate::FlowExitReason::Fault as u8)
            ),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn supervised_tree_start_child_then_exit() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = supervised_tree();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let root = rt.function_index("root").ok_or("root")?;
        let sup = rt.supervisor()?;
        let outcome = sup
            .start_child(crate::ChildSpec::new("root", root).restart(crate::RestartPolicy::Never))?
            .join();
        sup.shutdown();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(1))),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn selective_receive_skips_junk_tag() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = selective_receive();
        assert!(verify(&chunk).is_ok());
        let bytes = encode(&chunk);
        let chunk = decode(&bytes)?;
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn receive_match_kind_skips_non_int_payload() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = receive_match_kind();
        assert!(verify(&chunk).is_ok());
        let bytes = encode(&chunk);
        let chunk = decode(&bytes)?;
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn ask_reply_joins_42() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = ask_reply();
        assert!(verify(&chunk).is_ok());
        let bytes = encode(&chunk);
        let chunk = decode(&bytes)?;
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        let sent = rt.metrics().messages_sent;
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "got {outcome:?}"
        );
        assert!(sent >= 2);
        Ok(())
    }

    #[test]
    fn ask_timeout_writes_unit() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = ask_timeout_expires();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Unit)),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn ask_target_exit_writes_sys_exit() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = ask_target_exits();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(
                outcome,
                FlowOutcome::Completed(Value::Int(n)) if n == i64::from(crate::TAG_SYS_EXIT)
            ),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn server_loop_joins_42() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = server_loop();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn send_overwrites_forged_sender() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = forged_sender_send();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        match outcome {
            FlowOutcome::Completed(Value::Pid(n)) => {
                assert_ne!(n, 999, "forged make_msg sender must not survive Send");
                assert!(n >= 1, "authenticated sender must be a live flow id");
                Ok(())
            }
            other => Err(format!("expected Completed(Pid), got {other:?}").into()),
        }
    }

    #[test]
    fn ask_overwrites_forged_request_sender() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = forged_sender_ask();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        match outcome {
            FlowOutcome::Completed(Value::Pid(n)) => {
                assert_ne!(n, 999, "forged make_msg sender must not survive Ask");
                assert!(n >= 1, "authenticated sender must be a live flow id");
                Ok(())
            }
            other => Err(format!("expected Completed(Pid), got {other:?}").into()),
        }
    }

    #[test]
    fn send_scalar_target_traps() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("bad-cap-target");
        p.function("main", 0, |f| {
            let bad_cap = f.load_i32(99);
            let req_id = f.load_i32(1);
            let payload = f.load_i32(1);
            let msg = f.hop(req_id, TAG_PING, payload);
            f.send(bad_cap, msg);
            f.return_(msg);
        });
        let rt = tiny_natives(p.build())?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Failed(_)),
            "non-Cap Send target must fail, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn send_scalar_is_not_an_atomic_hop() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("bad-hop");
        p.function("main", 0, |f| {
            let cap = f.self_cap();
            let scalar = f.load_i32(99);
            f.send(cap, scalar);
            f.return_(scalar);
        });
        let rt = tiny(p.build())?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Failed(_)),
            "scalar Send must trap, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn monitor_down_joins_normal_reason() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = monitor_down();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(0))),
            "DOWN reason should be Normal (0), got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn waiting_send_second_hop_arrives() -> Result<(), Box<dyn std::error::Error>> {
        let cap = crate::MailboxCapacity::new(1).ok_or("cap")?;
        let rt = Runtime::with_natives_and_config(
            waiting_send(),
            std_native_table(),
            RuntimeConfig {
                workers: 1,
                quantum: 10_000,
                mailbox: crate::MailboxConfig::new(cap, crate::OverflowPolicy::Reject),
                ..Default::default()
            },
        )?;
        let server = rt.function_index("server").ok_or("server")?;
        let client = rt.function_index("client").ok_or("client")?;
        let server_h = rt.spawn(server, &[])?;
        let server_cap = rt.mint_cap(server_h.id())?;
        rt.spawn(client, &[Value::Cap(server_cap)])?;
        let outcome = server_h.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "second hop should be admitted after the first pop, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn link_kills_peer_on_fault() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("link-kill");
        p.function("park", 0, |f| {
            let _ = f.receive();
            f.trap(9);
        });
        p.function("boom", 0, |f| f.trap(1));
        let rt = tiny(p.build())?;
        let park = rt.function_index("park").ok_or("park")?;
        let boom = rt.function_index("boom").ok_or("boom")?;
        let parked = rt.spawn(park, &[])?;
        let killer = rt.spawn(boom, &[])?;
        rt.link(parked.id(), killer.id())?;
        let boom_out = killer.join();
        let park_out = parked.join();
        rt.shutdown();
        assert!(matches!(boom_out, FlowOutcome::Failed(_)), "{boom_out:?}");
        assert!(
            matches!(park_out, FlowOutcome::Failed(_)),
            "linked peer must die on fault, got {park_out:?}"
        );
        Ok(())
    }

    #[test]
    fn trap_exit_converts_link_kill_to_exit_hop() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("trap-exit");
        p.function("trapper", 0, |f| {
            let msg = f.receive_match_imm(crate::TAG_SYS_EXIT);
            let out = f.hop_payload(msg);
            f.return_(out);
        });
        p.function("boom", 0, |f| {
            let ms = f.load_i32(30);
            f.sleep(ms);
            f.trap(1);
        });
        let rt = tiny_natives(p.build())?;
        let trapper = rt.spawn(rt.function_index("trapper").ok_or("trapper")?, &[])?;
        let killer = rt.spawn(rt.function_index("boom").ok_or("boom")?, &[])?;
        rt.set_trap_exit(trapper.id(), true)?;
        rt.link(trapper.id(), killer.id())?;
        let boom_out = killer.join();
        let trap_out = trapper.join();
        rt.shutdown();
        assert!(matches!(boom_out, FlowOutcome::Failed(_)), "{boom_out:?}");
        assert!(
            matches!(
                trap_out,
                FlowOutcome::Completed(Value::Int(n))
                    if n == crate::FlowExitReason::Fault.as_u64() as i64
            ),
            "trap_exit peer must receive EXIT with Fault reason, got {trap_out:?}"
        );
        Ok(())
    }

    #[test]
    fn trap_exit_receives_normal_exit_signal() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("trap-exit-normal");
        p.function("trapper", 0, |f| {
            let msg = f.receive_match_imm(crate::TAG_SYS_EXIT);
            let out = f.hop_payload(msg);
            f.return_(out);
        });
        p.function("done", 0, |f| {
            let ms = f.load_i32(30);
            f.sleep(ms);
            let z = f.load_i32(0);
            f.return_(z);
        });
        let rt = tiny_natives(p.build())?;
        let trapper = rt.spawn(rt.function_index("trapper").ok_or("trapper")?, &[])?;
        let peer = rt.spawn(rt.function_index("done").ok_or("done")?, &[])?;
        rt.set_trap_exit(trapper.id(), true)?;
        rt.link(trapper.id(), peer.id())?;
        let _ = peer.join();
        let trap_out = trapper.join();
        rt.shutdown();
        assert!(
            matches!(
                trap_out,
                FlowOutcome::Completed(Value::Int(n))
                    if n == crate::FlowExitReason::Normal.as_u64() as i64
            ),
            "trap_exit must surface Normal as EXIT hop, got {trap_out:?}"
        );
        Ok(())
    }

    #[test]
    fn set_trap_exit_opcode_enables_trapping() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("trap-exit-opcode");
        // Parent waits for READY so SetTrapExit is known to have run before link.
        p.function("parent", 0, |f| {
            let msg = f.receive_match_imm(TAG_READY as u16);
            let out = f.hop_payload(msg);
            f.return_(out);
        });
        p.function("trapper", 1, |f| {
            let parent = f.reg(0);
            let on = f.load_i32(1);
            f.set_trap_exit(on);
            let z = f.load_i32(1);
            let ready = f.hop_fresh(TAG_READY, z);
            f.send(parent, ready);
            let msg = f.receive_match_imm(crate::TAG_SYS_EXIT);
            let out = f.hop_payload(msg);
            f.return_(out);
        });
        p.function("boom", 0, |f| {
            // Stay parked until the host wakes us *after* the link is installed.
            let _wake = f.receive();
            f.trap(1);
        });
        let rt = tiny_natives(p.build())?;
        let parent = rt.spawn(rt.function_index("parent").ok_or("parent")?, &[])?;
        let parent_cap = rt.mint_cap(parent.id())?;
        let trapper = rt.spawn(
            rt.function_index("trapper").ok_or("trapper")?,
            &[Value::Cap(parent_cap)],
        )?;
        let killer = rt.spawn(rt.function_index("boom").ok_or("boom")?, &[])?;
        let ready = parent.join();
        assert!(
            matches!(ready, FlowOutcome::Completed(Value::Int(1))),
            "trapper must signal READY after SetTrapExit, got {ready:?}"
        );
        rt.link(trapper.id(), killer.id())?;
        rt.send(
            killer.id(),
            Value::Message(Message::request(0, TAG_REQ as u16, 0)),
        )?;
        let boom_out = killer.join();
        let trap_out = trapper.join();
        rt.shutdown();
        assert!(matches!(boom_out, FlowOutcome::Failed(_)), "{boom_out:?}");
        assert!(
            matches!(
                trap_out,
                FlowOutcome::Completed(Value::Int(n))
                    if n == crate::FlowExitReason::Fault.as_u64() as i64
            ),
            "bytecode SetTrapExit must receive EXIT with Fault reason, got {trap_out:?}"
        );
        Ok(())
    }

    #[test]
    fn linked_exit_down_carries_link_reason() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("link-down-reason");
        p.function("watcher", 0, |f| {
            let msg = f.receive_match_imm(crate::TAG_SYS_DOWN);
            let out = f.hop_payload(msg);
            f.return_(out);
        });
        p.function("park", 0, |f| {
            let _ = f.receive();
            f.trap(9);
        });
        p.function("boom", 0, |f| f.trap(1));
        let rt = tiny_natives(p.build())?;
        let watcher = rt.spawn(rt.function_index("watcher").ok_or("watcher")?, &[])?;
        let parked = rt.spawn(rt.function_index("park").ok_or("park")?, &[])?;
        let killer = rt.spawn(rt.function_index("boom").ok_or("boom")?, &[])?;
        rt.monitor(watcher.id(), parked.id())?;
        rt.link(parked.id(), killer.id())?;
        let _ = killer.join();
        let watched = watcher.join();
        let _ = parked.join();
        rt.shutdown();
        assert!(
            matches!(
                watched,
                FlowOutcome::Completed(Value::Int(n)) if n == crate::FlowExitReason::Link.as_u64() as i64
            ),
            "DOWN payload must be Link, got {watched:?}"
        );
        Ok(())
    }

    #[test]
    fn monitor_dead_owner_is_rejected() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny(add_forty_two())?;
        let first = rt.spawn(0, &[])?;
        let dead = first.id();
        let done = first.join();
        assert!(matches!(done, FlowOutcome::Completed(_)));
        let live = rt.spawn(0, &[])?;
        let err = rt.monitor(dead, live.id());
        live.join();
        rt.shutdown();
        assert!(
            matches!(err, Err(crate::LifecycleError::NoSuchFlow(_))),
            "{err:?}"
        );
        Ok(())
    }

    #[test]
    fn forged_cap_cannot_be_registered() -> Result<(), Box<dyn std::error::Error>> {
        let rt = tiny(add_forty_two())?;
        let err = rt.register_name("svc", CapId::from_raw(99_999));
        rt.shutdown();
        assert_eq!(err, Err(crate::LifecycleError::InvalidCapability));
        Ok(())
    }

    #[test]
    fn bytecode_register_name_joins() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("reg-self");
        p.function("main", 0, |f| {
            let name = f.load_str("svc");
            f.register_name(name);
            let z = f.load_i32(1);
            f.return_(z);
        });
        let rt = tiny(p.build())?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(1))),
            "host-spawned flow must be able to register_name, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn named_service_whereis_returns_cap() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = named_service();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt
            .spawn(idx, &[])?
            .join_timeout(std::time::Duration::from_secs(2))
            .ok_or("named_service timed out")?;
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "named whereis should yield a usable SEND Cap, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn confined_spawn_cannot_register_name() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("confined-reg");
        let child = p.function("child", 0, |f| {
            let name = f.load_str("stolen");
            f.register_name(name);
            // Stay alive so a successful register would remain visible.
            // Sleep does not require RECV (a confined child has no RECV).
            let ms = f.load_i32(5_000);
            f.sleep(ms);
            let z = f.load_i32(1);
            f.return_(z);
        });
        p.function("main", 0, |f| {
            let _c = f.spawn_confined(child, &[]);
            let ms = f.load_i32(80);
            f.sleep(ms);
            let name = f.load_str("stolen");
            let cap = f.whereis(name);
            let ok = f.label();
            f.branch_if_falsy(cap, ok);
            let one = f.load_i32(1);
            f.return_(one);
            f.bind(ok);
            let zero = f.load_i32(0);
            f.return_(zero);
        });
        let rt = tiny(p.build())?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt.spawn(idx, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(0))),
            "confined child must not publish a name, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn heap_quota_rejects_oversized_str() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("heap-str");
        p.function("main", 0, |f| {
            let s = f.load_str("x".repeat(200));
            f.return_(s);
        });
        let mut quota = QuotaConfig::permissive();
        quota.mem_limit = 64;
        let rt = Runtime::with_config(
            p.build(),
            RuntimeConfig {
                workers: 1,
                quantum: 10_000,
                mailbox: crate::MailboxConfig::DEFAULT,
                quota,
                ..Default::default()
            },
        )?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Failed(_)),
            "200-byte Str must exceed 64-byte heap quota, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn heap_quota_rejects_oversized_bytes() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("heap-bytes");
        p.function("main", 0, |f| {
            let b = f.load_bytes(vec![0u8; 200]);
            f.return_(b);
        });
        let mut quota = QuotaConfig::permissive();
        quota.mem_limit = 64;
        let rt = Runtime::with_config(
            p.build(),
            RuntimeConfig {
                workers: 1,
                quantum: 10_000,
                mailbox: crate::MailboxConfig::DEFAULT,
                quota,
                ..Default::default()
            },
        )?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Failed(_)),
            "200-byte Bytes must exceed 64-byte heap quota, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn host_send_stamps_sender_zero() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("host-send-sender");
        p.function("main", 0, |f| {
            let msg = f.receive();
            let sender = f.hop_sender(msg);
            f.return_(sender);
        });
        let rt = tiny_natives(p.build())?;
        let h = rt.spawn(0, &[])?;
        // Non-zero request_id so minting is not under test here.
        rt.send(h.id(), Value::Message(Message::request(7, 1, 0)))?;
        let outcome = h.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Pid(0))),
            "host send must stamp sender=0 (Pid), got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn host_send_mints_request_id() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("host-send-rid");
        p.function("main", 0, |f| {
            let msg = f.receive();
            let rid = f.hop_request_id(msg);
            f.return_(rid);
        });
        let rt = tiny_natives(p.build())?;
        let h = rt.spawn(0, &[])?;
        rt.send(h.id(), Value::Message(Message::request(0, 1, 0)))?;
        let outcome = h.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(n)) if n > 0),
            "host send must mint a non-zero request_id when unset, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn hop_fresh_mints_distinct_request_ids() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("fresh-ids");
        p.function("main", 0, |f| {
            let z = f.load_i32(0);
            let a = f.hop_fresh(TAG_REQ, z);
            let b = f.hop_fresh(TAG_REQ, z);
            let ida = f.hop_request_id(a);
            let idb = f.hop_request_id(b);
            let same = f.eq(ida, idb);
            let ok = f.label();
            let miss = f.label();
            // Distinct ids → eq is falsy → branch to ok.
            f.branch_if_falsy(same, ok);
            f.trap(1);
            f.bind(ok);
            f.branch_if_falsy(ida, miss);
            f.branch_if_falsy(idb, miss);
            f.return_(ida);
            f.bind(miss);
            let neg = f.load_i32(-1);
            f.return_(neg);
        });
        let rt = tiny_natives(p.build())?;
        let outcome = rt.spawn(0, &[])?.join();
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(n)) if n > 0),
            "hop_fresh must mint two distinct non-zero request_ids, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn ask_reply_preserves_request_id() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("ask-corr");
        let server = p.function("server", 0, |f| {
            let msg = f.receive_match_imm(TAG_REQ as u16);
            let payload = f.hop_payload(msg);
            f.add_imm(payload, 1);
            f.send_reply(msg, TAG_REP, payload);
            f.exit(payload);
        });
        p.function("main", 0, |f| {
            let server_cap = f.spawn(server, &[]);
            let payload = f.load_i32(41);
            let req = f.hop_fresh(TAG_REQ, payload);
            let expect = f.hop_request_id(req);
            let reply = f.ask(server_cap, req);
            // Correlate explicitly: wait would have already matched by Ask;
            // assert the delivered reply carries the same request_id.
            let got = f.hop_request_id(reply);
            let same = f.eq(expect, got);
            let bad = f.label();
            f.branch_if_falsy(same, bad);
            let out = f.hop_payload(reply);
            f.return_(out);
            f.bind(bad);
            let neg = f.load_i32(-1);
            f.return_(neg);
        });
        let rt = tiny_natives(p.build())?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt
            .spawn(idx, &[])?
            .join_timeout(std::time::Duration::from_secs(2))
            .ok_or("ask_reply_preserves_request_id timed out")?;
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "Ask reply must echo request_id and payload+1, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn send_receive_match_corr_binds_request_id() -> Result<(), Box<dyn std::error::Error>> {
        let chunk = atomic_request_reply();
        assert!(verify(&chunk).is_ok());
        let rt = tiny_natives(chunk)?;
        let idx = rt.function_index("main").ok_or("main")?;
        let outcome = rt
            .spawn(idx, &[])?
            .join_timeout(std::time::Duration::from_secs(2))
            .ok_or("atomic_request_reply timed out")?;
        rt.shutdown();
        assert!(
            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
            "ReceiveMatchCorr must bind the minted request_id, got {outcome:?}"
        );
        Ok(())
    }

    #[test]
    fn registry_clears_on_exit() -> Result<(), Box<dyn std::error::Error>> {
        let mut p = Program::new("reg");
        p.function("main", 0, |f| {
            let ms = f.load_i32(80);
            f.sleep(ms);
            let z = f.load_i32(1);
            f.return_(z);
        });
        let rt = tiny(p.build())?;
        let h = rt.spawn(0, &[])?;
        let cap = rt.mint_cap(h.id())?;
        rt.register_name("svc", cap)?;
        assert_eq!(rt.whereis("svc")?, Some(cap));
        let _ = h.join();
        assert_eq!(rt.whereis("svc")?, None);
        rt.shutdown();
        Ok(())
    }
}