dactor 0.3.0

An abstract framework for distributed actors in Rust
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
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
//! V2 test runtime for the `Actor` / `Handler<M>` / `ActorRef<A>` API.
//!
//! Provides a lightweight, in-process actor runtime suitable for unit tests.
//! Actors are spawned on the Tokio runtime and process messages sequentially
//! via an unbounded channel.

#[allow(unused_imports)]
use std::any::Any;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

#[allow(unused_imports)]
use async_trait::async_trait;
use futures::FutureExt;
use tokio::sync::mpsc;

use crate::actor::{
    Actor, ActorContext, ActorError, ActorRef, AskReply, ReduceHandler, Handler, ExpandHandler,
    TransformHandler,
};
use crate::dead_letter::{DeadLetterEvent, DeadLetterHandler, DeadLetterReason};
#[allow(unused_imports)]
use crate::dispatch::DispatchResult;
use crate::dispatch::{AskDispatch, BoxedDispatch, ReduceDispatch, ExpandDispatch, TransformDispatch, TypedDispatch};
use crate::errors::{ActorSendError, ErrorAction, RuntimeError};
#[allow(unused_imports)]
use crate::interceptor::OutboundContext;
use crate::interceptor::{
    Disposition, DropObserver, InboundContext, InboundInterceptor, OutboundInterceptor, Outcome,
    SendMode,
};
use crate::mailbox::{MailboxConfig, OverflowStrategy};
use crate::message::{Headers, Message, RuntimeHeaders};
use crate::node::{ActorId, NodeId};
use crate::registry::ActorRegistry;
use crate::stream::{
    BatchConfig, BatchReader, BatchWriter, BoxStream, StreamReceiver, StreamSender,
};
use crate::supervision::ChildTerminated;
use tokio_util::sync::CancellationToken;

// ---------------------------------------------------------------------------
// Mailbox channel wrappers
// ---------------------------------------------------------------------------

/// Unified sender that wraps both bounded and unbounded mpsc senders.
enum MailboxSender<A: Actor> {
    Unbounded(mpsc::UnboundedSender<Option<BoxedDispatch<A>>>),
    Bounded {
        sender: mpsc::Sender<Option<BoxedDispatch<A>>>,
        overflow: OverflowStrategy,
    },
}

impl<A: Actor> MailboxSender<A> {
    fn send(&self, msg: Option<BoxedDispatch<A>>) -> Result<(), ActorSendError> {
        match self {
            Self::Unbounded(tx) => tx
                .send(msg)
                .map_err(|_| ActorSendError("actor stopped".into())),
            Self::Bounded { sender, overflow } => match overflow {
                OverflowStrategy::RejectWithError => sender.try_send(msg).map_err(|e| match e {
                    mpsc::error::TrySendError::Full(_) => ActorSendError("mailbox full".into()),
                    mpsc::error::TrySendError::Closed(_) => ActorSendError("actor stopped".into()),
                }),
                OverflowStrategy::DropNewest => match sender.try_send(msg) {
                    Ok(()) => Ok(()),
                    Err(mpsc::error::TrySendError::Full(_)) => Ok(()), // silently drop
                    Err(mpsc::error::TrySendError::Closed(_)) => {
                        Err(ActorSendError("actor stopped".into()))
                    }
                },
                OverflowStrategy::Block => {
                    // Block is not supported in sync tell(). Treat as RejectWithError.
                    sender.try_send(msg).map_err(|e| match e {
                        mpsc::error::TrySendError::Full(_) => {
                            ActorSendError("mailbox full (Block not supported in sync tell)".into())
                        }
                        mpsc::error::TrySendError::Closed(_) => {
                            ActorSendError("actor stopped".into())
                        }
                    })
                }
            },
        }
    }

    /// Force-send a control signal bypassing overflow strategy.
    /// Used for stop signals that must not be dropped.
    fn force_send(&self, msg: Option<BoxedDispatch<A>>) {
        match self {
            Self::Unbounded(tx) => {
                let _ = tx.send(msg);
            }
            Self::Bounded { sender, .. } => {
                // For control signals, use regular send (not try_send).
                // This may block briefly but guarantees delivery.
                // If the channel is closed, the signal is moot (actor already stopped).
                let _ = sender.try_send(msg);
                // If full, the actor will stop naturally when all senders are dropped.
            }
        }
    }

    fn is_closed(&self) -> bool {
        match self {
            Self::Unbounded(tx) => tx.is_closed(),
            Self::Bounded { sender, .. } => sender.is_closed(),
        }
    }

    /// Approximate number of messages pending in the mailbox.
    fn pending(&self) -> usize {
        match self {
            Self::Unbounded(_) => 0, // unbounded channels don't expose length
            Self::Bounded { sender, .. } => sender.max_capacity() - sender.capacity(),
        }
    }
}

impl<A: Actor> Clone for MailboxSender<A> {
    fn clone(&self) -> Self {
        match self {
            Self::Unbounded(tx) => Self::Unbounded(tx.clone()),
            Self::Bounded { sender, overflow } => Self::Bounded {
                sender: sender.clone(),
                overflow: *overflow,
            },
        }
    }
}

/// Unified receiver that wraps both bounded and unbounded mpsc receivers.
enum MailboxReceiver<A: Actor> {
    Unbounded(mpsc::UnboundedReceiver<Option<BoxedDispatch<A>>>),
    Bounded(mpsc::Receiver<Option<BoxedDispatch<A>>>),
}

impl<A: Actor> MailboxReceiver<A> {
    async fn recv(&mut self) -> Option<Option<BoxedDispatch<A>>> {
        match self {
            Self::Unbounded(rx) => rx.recv().await,
            Self::Bounded(rx) => rx.recv().await,
        }
    }
}

// ---------------------------------------------------------------------------
// SpawnOptions
// ---------------------------------------------------------------------------

/// Options for spawning an actor, including the inbound interceptor pipeline.
pub struct SpawnOptions {
    pub interceptors: Vec<Box<dyn InboundInterceptor>>,
    /// Mailbox configuration (unbounded by default).
    pub mailbox: MailboxConfig,
}

impl Default for SpawnOptions {
    fn default() -> Self {
        Self {
            interceptors: Vec::new(),
            mailbox: MailboxConfig::Unbounded,
        }
    }
}

// ---------------------------------------------------------------------------
// TestActorRef
// ---------------------------------------------------------------------------

/// A test actor reference implementing `ActorRef<A>`.
pub struct TestActorRef<A: Actor> {
    id: ActorId,
    name: String,
    sender: MailboxSender<A>,
    alive: Arc<AtomicBool>,
    outbound_interceptors: Arc<Vec<Box<dyn OutboundInterceptor>>>,
    drop_observer: Option<Arc<dyn DropObserver>>,
    dead_letter_handler: Arc<Option<Arc<dyn DeadLetterHandler>>>,
}

impl<A: Actor> Clone for TestActorRef<A> {
    fn clone(&self) -> Self {
        Self {
            id: self.id.clone(),
            name: self.name.clone(),
            sender: self.sender.clone(),
            alive: self.alive.clone(),
            outbound_interceptors: self.outbound_interceptors.clone(),
            drop_observer: self.drop_observer.clone(),
            dead_letter_handler: self.dead_letter_handler.clone(),
        }
    }
}

impl<A: Actor> TestActorRef<A> {
    fn outbound_pipeline(&self) -> crate::runtime_support::OutboundPipeline {
        crate::runtime_support::OutboundPipeline {
            interceptors: self.outbound_interceptors.clone(),
            drop_observer: self.drop_observer.clone(),
            target_id: self.id.clone(),
            target_name: self.name.clone(),
        }
    }

    fn notify_dead_letter(
        &self,
        message_type: &'static str,
        send_mode: SendMode,
        reason: DeadLetterReason,
    ) {
        if let Some(ref handler) = *self.dead_letter_handler {
            let event = DeadLetterEvent {
                target_id: self.id.clone(),
                target_name: Some(self.name.clone()),
                message_type,
                send_mode,
                reason,
                message: None,
            };
            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                handler.on_dead_letter(event);
            }));
        }
    }
}

impl<A: Actor> ActorRef<A> for TestActorRef<A> {
    fn id(&self) -> ActorId {
        self.id.clone()
    }

    fn name(&self) -> String {
        self.name.clone()
    }

    fn is_alive(&self) -> bool {
        self.alive.load(Ordering::Acquire) && !self.sender.is_closed()
    }

    fn pending_messages(&self) -> usize {
        self.sender.pending()
    }

    fn stop(&self) {
        // Mark as not alive immediately so is_alive() returns false
        self.alive.store(false, Ordering::SeqCst);
        // Send stop signal bypassing overflow strategy
        self.sender.force_send(None);
    }

    fn tell<M>(&self, msg: M) -> Result<(), ActorSendError>
    where
        A: Handler<M>,
        M: Message<Reply = ()>,
    {
        let pipeline = self.outbound_pipeline();
        let result = pipeline.run_on_send(SendMode::Tell, &msg);
        match result.disposition {
            Disposition::Continue => {}
            Disposition::Delay(_) => {}
            Disposition::Drop | Disposition::Reject(_) | Disposition::Retry(_) => return Ok(()),
        }

        let dispatch: BoxedDispatch<A> = Box::new(TypedDispatch { msg });
        self.sender.send(Some(dispatch)).map_err(|e| {
            let reason = if e.0.contains("mailbox full") {
                DeadLetterReason::MailboxFull
            } else {
                DeadLetterReason::ActorStopped
            };
            self.notify_dead_letter(std::any::type_name::<M>(), SendMode::Tell, reason);
            e
        })
    }

    fn ask<M>(
        &self,
        msg: M,
        cancel: Option<CancellationToken>,
    ) -> Result<AskReply<M::Reply>, ActorSendError>
    where
        A: Handler<M>,
        M: Message,
    {
        let pipeline = self.outbound_pipeline();
        let result = pipeline.run_on_send(SendMode::Ask, &msg);
        match result.disposition {
            Disposition::Continue => {}
            Disposition::Delay(_) => {}
            Disposition::Drop => {
                let (tx, rx) = tokio::sync::oneshot::channel();
                let _ = tx.send(Err(RuntimeError::ActorNotFound(
                    "message dropped by outbound interceptor".into(),
                )));
                return Ok(AskReply::new(rx));
            }
            Disposition::Reject(reason) => {
                let (tx, rx) = tokio::sync::oneshot::channel();
                let _ = tx.send(Err(RuntimeError::Rejected {
                    interceptor: result.interceptor_name.to_string(),
                    reason,
                }));
                return Ok(AskReply::new(rx));
            }
            Disposition::Retry(retry_after) => {
                let (tx, rx) = tokio::sync::oneshot::channel();
                let _ = tx.send(Err(RuntimeError::RetryAfter {
                    interceptor: result.interceptor_name.to_string(),
                    retry_after,
                }));
                return Ok(AskReply::new(rx));
            }
        }

        let (tx, rx) = tokio::sync::oneshot::channel();
        let dispatch: BoxedDispatch<A> = Box::new(AskDispatch {
            msg,
            reply_tx: tx,
            cancel,
        });
        self.sender.send(Some(dispatch)).map_err(|e| {
            let reason = if e.0.contains("mailbox full") {
                DeadLetterReason::MailboxFull
            } else {
                DeadLetterReason::ActorStopped
            };
            self.notify_dead_letter(std::any::type_name::<M>(), SendMode::Ask, reason);
            e
        })?;

        // Wrap the reply channel so that outbound interceptors' on_reply()
        // is called when the reply arrives on the sender side.
        if self.outbound_interceptors.is_empty() {
            Ok(AskReply::new(rx))
        } else {
            let message_type = std::any::type_name::<M>();
            let (wrapped_tx, wrapped_rx) = tokio::sync::oneshot::channel();
            tokio::spawn(async move {
                match rx.await {
                    Ok(Ok(reply)) => {
                        pipeline.run_on_reply(
                            message_type,
                            &Outcome::AskSuccess {
                                reply: &reply as &dyn std::any::Any,
                            },
                        );
                        let _ = wrapped_tx.send(Ok(reply));
                    }
                    Ok(Err(e)) => {
                        let _ = wrapped_tx.send(Err(e));
                    }
                    Err(_) => {
                        let _ = wrapped_tx.send(Err(RuntimeError::ActorNotFound(
                            "reply channel closed".into(),
                        )));
                    }
                }
            });
            Ok(AskReply::new(wrapped_rx))
        }
    }

    fn expand<M, OutputItem>(
        &self,
        msg: M,
        buffer: usize,
        batch_config: Option<BatchConfig>,
        cancel: Option<CancellationToken>,
    ) -> Result<BoxStream<OutputItem>, ActorSendError>
    where
        A: ExpandHandler<M, OutputItem>,
        M: Send + 'static,
        OutputItem: Send + 'static,
    {
        let buffer = buffer.max(1);
        let pipeline = self.outbound_pipeline();

        let result = pipeline.run_on_send(SendMode::Expand, &msg);
        match result.disposition {
            Disposition::Continue => {}
            Disposition::Delay(_) => {}
            Disposition::Drop => {
                return Err(ActorSendError(
                    "stream dropped by outbound interceptor".into(),
                ));
            }
            Disposition::Reject(reason) => {
                return Err(ActorSendError(format!("stream rejected: {}", reason)));
            }
            Disposition::Retry(_) => {
                return Err(ActorSendError(
                    "stream retry requested by interceptor".into(),
                ));
            }
        }

        let (tx, mut rx) = tokio::sync::mpsc::channel(buffer);
        let sender = StreamSender::new(tx);
        let dispatch: BoxedDispatch<A> = Box::new(ExpandDispatch {
            msg,
            sender,
            cancel,
        });
        self.sender.send(Some(dispatch))?;

        match batch_config {
            Some(batch_config) => {
                // Batched: handler → batch writer → batch reader → interception → caller
                let (batch_tx, batch_rx) = tokio::sync::mpsc::channel::<Vec<OutputItem>>(buffer);
                let reader = BatchReader::new(batch_rx);
                tokio::spawn(async move {
                    let mut writer = BatchWriter::new(batch_tx, batch_config);
                    loop {
                        if writer.buffered_count() > 0 {
                            let delay = writer.max_delay();
                            tokio::select! {
                                biased;
                                item = rx.recv() => match item {
                                    Some(item) => {
                                        if writer.push(item).await.is_err() { break; }
                                    }
                                    None => break,
                                },
                                _ = tokio::time::sleep(delay) => {
                                    if writer.check_deadline().await.is_err() { break; }
                                }
                            }
                        } else {
                            match rx.recv().await {
                                Some(item) => {
                                    if writer.push(item).await.is_err() {
                                        break;
                                    }
                                }
                                None => break,
                            }
                        }
                    }
                    let _ = writer.flush().await;
                });
                Ok(
                    crate::runtime_support::wrap_batched_stream_with_interception(
                        reader,
                        buffer,
                        pipeline,
                        std::any::type_name::<M>(),
                        SendMode::Expand,
                    ),
                )
            }
            None => {
                // Unbatched: handler → interception → caller
                Ok(crate::runtime_support::wrap_stream_with_interception(
                    rx,
                    buffer,
                    pipeline,
                    std::any::type_name::<M>(),
                    SendMode::Expand,
                ))
            }
        }
    }

    fn reduce<InputItem, Reply>(
        &self,
        input: BoxStream<InputItem>,
        buffer: usize,
        batch_config: Option<BatchConfig>,
        cancel: Option<CancellationToken>,
    ) -> Result<AskReply<Reply>, ActorSendError>
    where
        A: ReduceHandler<InputItem, Reply>,
        InputItem: Send + 'static,
        Reply: Send + 'static,
    {
        let buffer = buffer.max(1);
        let pipeline = self.outbound_pipeline();

        let (item_tx, item_rx) = tokio::sync::mpsc::channel(buffer);
        let receiver = StreamReceiver::new(item_rx);
        let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
        let dispatch: BoxedDispatch<A> = Box::new(ReduceDispatch {
            receiver,
            reply_tx,
            cancel: cancel.clone(),
        });
        self.sender.send(Some(dispatch))?;

        match batch_config {
            Some(batch_config) => {
                crate::runtime_support::spawn_reduce_batched_drain(
                    input,
                    item_tx,
                    buffer,
                    batch_config,
                    cancel,
                    pipeline,
                    std::any::type_name::<InputItem>(),
                );
            }
            None => {
                crate::runtime_support::spawn_reduce_drain(
                    input,
                    item_tx,
                    cancel,
                    pipeline,
                    std::any::type_name::<InputItem>(),
                );
            }
        }

        Ok(AskReply::new(reply_rx))
    }

    fn transform<InputItem, OutputItem>(
        &self,
        input: BoxStream<InputItem>,
        buffer: usize,
        batch_config: Option<BatchConfig>,
        cancel: Option<CancellationToken>,
    ) -> Result<BoxStream<OutputItem>, ActorSendError>
    where
        A: TransformHandler<InputItem, OutputItem>,
        InputItem: Send + 'static,
        OutputItem: Send + 'static,
    {
        let buffer = buffer.max(1);
        let pipeline = self.outbound_pipeline();

        let (item_tx, item_rx) = tokio::sync::mpsc::channel(buffer);
        let (output_tx, mut output_rx) = tokio::sync::mpsc::channel(buffer);
        let receiver = StreamReceiver::new(item_rx);
        let sender = StreamSender::new(output_tx);
        let dispatch: BoxedDispatch<A> = Box::new(TransformDispatch::new(
            receiver,
            sender,
            cancel.clone(),
        ));
        self.sender.send(Some(dispatch))?;

        crate::runtime_support::spawn_transform_drain(
            input,
            item_tx,
            cancel,
            pipeline.clone(),
            std::any::type_name::<InputItem>(),
        );

        match batch_config {
            Some(batch_config) => {
                // Batched: handler → batch writer → batch reader → interception → caller
                let (batch_tx, batch_rx) =
                    tokio::sync::mpsc::channel::<Vec<OutputItem>>(buffer);
                let reader = BatchReader::new(batch_rx);
                tokio::spawn(async move {
                    let mut writer = BatchWriter::new(batch_tx, batch_config);
                    loop {
                        if writer.buffered_count() > 0 {
                            let delay = writer.max_delay();
                            tokio::select! {
                                biased;
                                item = output_rx.recv() => match item {
                                    Some(item) => {
                                        if writer.push(item).await.is_err() { break; }
                                    }
                                    None => break,
                                },
                                _ = tokio::time::sleep(delay) => {
                                    if writer.check_deadline().await.is_err() { break; }
                                }
                            }
                        } else {
                            match output_rx.recv().await {
                                Some(item) => {
                                    if writer.push(item).await.is_err() {
                                        break;
                                    }
                                }
                                None => break,
                            }
                        }
                    }
                    let _ = writer.flush().await;
                });
                Ok(
                    crate::runtime_support::wrap_batched_stream_with_interception(
                        reader,
                        buffer,
                        pipeline,
                        std::any::type_name::<OutputItem>(),
                        SendMode::Transform,
                    ),
                )
            }
            None => Ok(crate::runtime_support::wrap_stream_with_interception(
                output_rx,
                buffer,
                pipeline,
                std::any::type_name::<OutputItem>(),
                SendMode::Transform,
            )),
        }
    }
}

/// A type-erased entry in the watch registry.
struct WatchEntry {
    watcher_id: ActorId,
    /// Closure that delivers a [`ChildTerminated`] to the watcher actor.
    notify: Box<dyn Fn(ChildTerminated) + Send + Sync>,
}

// ---------------------------------------------------------------------------
// TestRuntime
// ---------------------------------------------------------------------------

/// A lightweight test runtime that spawns v0.2 actors on the Tokio runtime.
pub struct TestRuntime {
    node_id: NodeId,
    next_local: AtomicU64,
    outbound_interceptors: Arc<Vec<Box<dyn OutboundInterceptor>>>,
    drop_observer: Arc<Option<Arc<dyn DropObserver>>>,
    dead_letter_handler: Arc<Option<Arc<dyn DeadLetterHandler>>>,
    /// Watch registry — maps watched actor ID to list of watcher entries.
    watchers: Arc<Mutex<HashMap<ActorId, Vec<WatchEntry>>>>,
    /// Actor name registry for looking up actors by name.
    registry: Arc<ActorRegistry>,
    /// Stop notification receivers for await_stop(), keyed by ActorId.
    #[allow(clippy::type_complexity)]
    stop_receivers: Arc<Mutex<HashMap<ActorId, tokio::sync::oneshot::Receiver<Result<(), String>>>>>,
    /// Optional shared metrics registry. When set, a [`MetricsInterceptor`] is
    /// automatically prepended to every spawned actor's inbound interceptor list.
    #[cfg(feature = "metrics")]
    metrics_registry: Option<crate::metrics::MetricsRegistry>,
}

impl TestRuntime {
    pub fn new() -> Self {
        Self {
            node_id: NodeId("test-node".into()),
            next_local: AtomicU64::new(1),
            outbound_interceptors: Arc::new(Vec::new()),
            drop_observer: Arc::new(None),
            dead_letter_handler: Arc::new(None),
            watchers: Arc::new(Mutex::new(HashMap::new())),
            registry: Arc::new(ActorRegistry::new()),
            stop_receivers: Arc::new(Mutex::new(HashMap::new())),
            #[cfg(feature = "metrics")]
            metrics_registry: None,
        }
    }

    /// Create a new runtime with a custom node identity.
    pub fn with_node_id(node_id: NodeId) -> Self {
        Self {
            node_id,
            next_local: AtomicU64::new(1),
            outbound_interceptors: Arc::new(Vec::new()),
            drop_observer: Arc::new(None),
            dead_letter_handler: Arc::new(None),
            watchers: Arc::new(Mutex::new(HashMap::new())),
            registry: Arc::new(ActorRegistry::new()),
            stop_receivers: Arc::new(Mutex::new(HashMap::new())),
            #[cfg(feature = "metrics")]
            metrics_registry: None,
        }
    }

    /// Return a reference to the actor name registry.
    pub fn registry(&self) -> &ActorRegistry {
        &self.registry
    }

    /// Enable built-in metrics collection.
    ///
    /// Creates a shared [`MetricsRegistry`](crate::metrics::MetricsRegistry) and
    /// automatically prepends a [`MetricsInterceptor`](crate::metrics::MetricsInterceptor)
    /// to every subsequently spawned actor's inbound interceptor pipeline.
    ///
    /// **Must be called before any actors are spawned.**
    /// Requires the `metrics` feature.
    #[cfg(feature = "metrics")]
    pub fn enable_metrics(&mut self) {
        self.metrics_registry = Some(crate::metrics::MetricsRegistry::default());
    }

    /// Return a reference to the shared [`MetricsRegistry`](crate::metrics::MetricsRegistry),
    /// or `None` if metrics have not been enabled.
    /// Requires the `metrics` feature.
    #[cfg(feature = "metrics")]
    pub fn metrics(&self) -> Option<&crate::metrics::MetricsRegistry> {
        self.metrics_registry.as_ref()
    }

    /// Add a global outbound interceptor.
    ///
    /// **Must be called before any actors are spawned.** Panics if actors
    /// already hold references to the interceptor list (i.e., after `spawn()`).
    /// This constraint ensures interceptor lists are immutable during actor lifetime.
    pub fn add_outbound_interceptor(&mut self, interceptor: Box<dyn OutboundInterceptor>) {
        Arc::get_mut(&mut self.outbound_interceptors)
            .expect("cannot add interceptors after actors are spawned")
            .push(interceptor);
    }

    /// Set a global drop observer. Called whenever any interceptor returns
    /// `Disposition::Drop` for a message or stream item.
    ///
    /// **Must be called before any actors are spawned.**
    pub fn set_drop_observer(&mut self, observer: Arc<dyn DropObserver>) {
        self.drop_observer = Arc::new(Some(observer));
    }

    /// Set a global dead letter handler. Called whenever a message cannot be
    /// delivered (actor stopped, mailbox full, dropped by inbound interceptor).
    ///
    /// **Must be called before any actors are spawned.**
    pub fn set_dead_letter_handler(&mut self, handler: Arc<dyn DeadLetterHandler>) {
        self.dead_letter_handler = Arc::new(Some(handler));
    }

    /// Spawn a v0.2 actor whose `Deps` type is `()`. Returns a `TestActorRef<A>`.
    pub async fn spawn<A>(&self, name: &str, args: A::Args) -> Result<TestActorRef<A>, crate::errors::RuntimeError>
    where
        A: Actor<Deps = ()> + 'static,
    {
        Ok(self.spawn_internal(name, args, (), Vec::new(), MailboxConfig::Unbounded))
    }

    /// Spawn a v0.2 actor with explicit dependencies.
    pub async fn spawn_with_deps<A>(&self, name: &str, args: A::Args, deps: A::Deps) -> Result<TestActorRef<A>, crate::errors::RuntimeError>
    where
        A: Actor + 'static,
    {
        Ok(self.spawn_internal(name, args, deps, Vec::new(), MailboxConfig::Unbounded))
    }

    /// Spawn a v0.2 actor with spawn options (including interceptors and mailbox config).
    pub async fn spawn_with_options<A>(
        &self,
        name: &str,
        args: A::Args,
        options: SpawnOptions,
    ) -> Result<TestActorRef<A>, crate::errors::RuntimeError>
    where
        A: Actor<Deps = ()> + 'static,
    {
        Ok(self.spawn_internal(name, args, (), options.interceptors, options.mailbox))
    }

    /// Register actor `watcher` to be notified when `target` terminates.
    ///
    /// The watcher must implement `Handler<ChildTerminated>`. When the target
    /// actor stops (gracefully or due to panic), the runtime will deliver a
    /// [`ChildTerminated`] message to the watcher.
    pub fn watch<W>(&self, watcher: &TestActorRef<W>, target_id: ActorId)
    where
        W: Actor + Handler<ChildTerminated> + 'static,
    {
        let watcher_id = watcher.id();
        let watcher_sender = watcher.sender.clone();

        let entry = WatchEntry {
            watcher_id,
            notify: Box::new(move |msg: ChildTerminated| {
                let dispatch: BoxedDispatch<W> = Box::new(TypedDispatch { msg });
                let _ = watcher_sender.send(Some(dispatch));
            }),
        };

        let mut watchers = self.watchers.lock().unwrap();
        watchers.entry(target_id).or_default().push(entry);
    }

    /// Unregister `watcher_id` from notifications about `target_id`.
    pub fn unwatch(&self, watcher_id: &ActorId, target_id: &ActorId) {
        let mut watchers = self.watchers.lock().unwrap();
        if let Some(entries) = watchers.get_mut(target_id) {
            entries.retain(|e| &e.watcher_id != watcher_id);
            if entries.is_empty() {
                watchers.remove(target_id);
            }
        }
    }

    pub(crate) fn spawn_internal<A>(
        &self,
        name: &str,
        args: A::Args,
        deps: A::Deps,
        interceptors: Vec<Box<dyn InboundInterceptor>>,
        mailbox: MailboxConfig,
    ) -> TestActorRef<A>
    where
        A: Actor + 'static,
    {
        // Generate actor ID first so we can register with the metrics registry.
        let local = self.next_local.fetch_add(1, Ordering::SeqCst);
        let actor_id = ActorId {
            node: self.node_id.clone(),
            local,
        };

        // Prepend a MetricsInterceptor when metrics are enabled so it sees
        // every message regardless of what the caller passes in SpawnOptions.
        #[cfg(feature = "metrics")]
        let interceptors = if let Some(ref registry) = self.metrics_registry {
            let handle = registry.register(actor_id.clone());
            let mut combined = Vec::with_capacity(1 + interceptors.len());
            combined.push(Box::new(crate::metrics::MetricsInterceptor::new(handle))
                as Box<dyn InboundInterceptor>);
            combined.extend(interceptors);
            combined
        } else {
            interceptors
        };

        let actor_name = name.to_string();
        let alive = Arc::new(AtomicBool::new(true));
        let alive_task = alive.clone();

        let (tx, mut rx) = match &mailbox {
            MailboxConfig::Unbounded => {
                let (tx, rx) = mpsc::unbounded_channel::<Option<BoxedDispatch<A>>>();
                (MailboxSender::Unbounded(tx), MailboxReceiver::Unbounded(rx))
            }
            MailboxConfig::Bounded { capacity, overflow } => {
                let (tx, rx) = mpsc::channel::<Option<BoxedDispatch<A>>>(*capacity);
                (
                    MailboxSender::Bounded {
                        sender: tx,
                        overflow: *overflow,
                    },
                    MailboxReceiver::Bounded(rx),
                )
            }
        };

        let id_task = actor_id.clone();
        let name_task = actor_name.clone();
        let watchers_ref = self.watchers.clone();
        let dead_letter_handler_task = self.dead_letter_handler.clone();
        let registry_task = self.registry.clone();
        let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
        self.stop_receivers.lock().unwrap().insert(actor_id.clone(), stop_rx);

        tokio::spawn(async move {
            let mut actor = A::create(args, deps);
            let mut ctx = ActorContext {
                actor_id: id_task,
                actor_name: name_task,
                send_mode: None,
                headers: Headers::new(),
                cancellation_token: None,
            };

            actor.on_start(&mut ctx).await;

            let mut stop_reason: Option<String> = None;

            while let Some(msg) = rx.recv().await {
                let dispatch = match msg {
                    None => break, // stop signal
                    Some(d) => d,
                };

                // Capture metadata before dispatch consumes the message
                let send_mode = dispatch.send_mode();
                let message_type = dispatch.message_type_name();

                // Set context fields for this message
                ctx.send_mode = Some(send_mode);
                ctx.headers = Headers::new();

                // Run inbound interceptor pipeline
                let runtime_headers = RuntimeHeaders::new();
                let mut headers = Headers::new();
                let mut total_delay = Duration::ZERO;
                let mut rejection: Option<(String, Disposition)> = None; // (interceptor_name, disposition)

                {
                    let ictx = InboundContext {
                        actor_id: ctx.actor_id.clone(),
                        actor_name: &ctx.actor_name,
                        message_type,
                        send_mode,
                        remote: false,
                        origin_node: None,
                    };

                    for interceptor in &interceptors {
                        match interceptor.on_receive(
                            &ictx,
                            &runtime_headers,
                            &mut headers,
                            dispatch.message_any(),
                        ) {
                            Disposition::Continue => {}
                            Disposition::Delay(d) => {
                                total_delay += d;
                            }
                            disp @ (Disposition::Drop
                            | Disposition::Reject(_)
                            | Disposition::Retry(_)) => {
                                rejection = Some((interceptor.name().to_string(), disp));
                                break;
                            }
                        }
                    }
                }

                // If rejected/dropped/retry, propagate proper error to caller
                if let Some((interceptor_name, disposition)) = rejection {
                    if matches!(disposition, Disposition::Drop) {
                        if let Some(ref handler) = *dead_letter_handler_task {
                            let event = DeadLetterEvent {
                                target_id: ctx.actor_id.clone(),
                                target_name: Some(ctx.actor_name.clone()),
                                message_type,
                                send_mode,
                                reason: DeadLetterReason::DroppedByInterceptor {
                                    interceptor: interceptor_name.clone(),
                                },
                                message: None,
                            };
                            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                handler.on_dead_letter(event);
                            }));
                        }
                    }
                    dispatch.reject(disposition, &interceptor_name);
                    continue;
                }

                if !total_delay.is_zero() {
                    tokio::time::sleep(total_delay).await;
                }

                // Copy interceptor-populated headers to ActorContext so handler can access them
                ctx.headers = headers;

                // Set the cancellation token on the context
                let cancel_token = dispatch.cancel_token();
                ctx.cancellation_token = cancel_token.clone();

                // Check if already cancelled before dispatching
                if let Some(ref token) = cancel_token {
                    if token.is_cancelled() {
                        // Send RuntimeError::Cancelled to the caller
                        dispatch.cancel();
                        ctx.cancellation_token = None;
                        continue;
                    }
                }

                // Dispatch the message (with cancellation racing if token is set)
                // For cooperative cancellation: the handler can use ctx.cancelled() internally.
                // For non-cooperative handlers: the select! will drop the handler future on cancel.
                // biased; with dispatch first ensures that if the handler completes at the same
                // moment the token fires, the handler's result takes priority.
                let result = if let Some(ref token) = cancel_token {
                    let dispatch_fut =
                        std::panic::AssertUnwindSafe(dispatch.dispatch(&mut actor, &mut ctx))
                            .catch_unwind();
                    tokio::select! {
                        biased;
                        r = dispatch_fut => r,
                        _ = token.cancelled() => {
                            // Cancelled during handler execution.
                            // The handler is NOT interrupted — select! drops the future.
                            ctx.cancellation_token = None;
                            continue;
                        }
                    }
                } else {
                    std::panic::AssertUnwindSafe(dispatch.dispatch(&mut actor, &mut ctx))
                        .catch_unwind()
                        .await
                };

                // Clear the cancellation token
                ctx.cancellation_token = None;

                // Build context for on_complete (reuse headers from on_receive)
                let ictx = InboundContext {
                    actor_id: ctx.actor_id.clone(),
                    actor_name: &ctx.actor_name,
                    message_type,
                    send_mode,
                    remote: false,
                    origin_node: None,
                };

                match result {
                    Ok(dispatch_result) => {
                        let outcome = match (&dispatch_result.reply, send_mode) {
                            (Some(reply), SendMode::Ask) => Outcome::AskSuccess {
                                reply: reply.as_ref(),
                            },
                            _ => Outcome::TellSuccess,
                        };

                        for interceptor in &interceptors {
                            interceptor.on_complete(
                                &ictx,
                                &runtime_headers,
                                &ctx.headers,
                                &outcome,
                            );
                        }

                        // Send reply to caller AFTER interceptors have seen it
                        dispatch_result.send_reply();
                    }
                    Err(_panic) => {
                        let error = ActorError::internal("handler panicked");
                        let action = actor.on_error(&error);

                        let outcome = Outcome::HandlerError { error };
                        for interceptor in &interceptors {
                            interceptor.on_complete(
                                &ictx,
                                &runtime_headers,
                                &ctx.headers,
                                &outcome,
                            );
                        }

                        match action {
                            ErrorAction::Resume => {
                                continue;
                            }
                            ErrorAction::Stop | ErrorAction::Escalate => {
                                tracing::error!(
                                    "handler panicked in actor {}, stopping",
                                    ctx.actor_name
                                );
                                stop_reason = Some("handler panicked".into());
                                break;
                            }
                            ErrorAction::Restart => {
                                // Full restart with Args/Deps recreation is adapter-specific.
                                // TestRuntime treats Restart as Resume (documented limitation).
                                tracing::warn!(
                                    "Restart not fully implemented for actor {}, treating as Resume",
                                    ctx.actor_name
                                );
                                continue;
                            }
                        }
                    }
                }
            }

            // Set alive=false BEFORE on_stop to avoid is_alive race condition
            alive_task.store(false, Ordering::SeqCst);
            // Reset context for on_stop (no message being processed)
            ctx.send_mode = None;
            ctx.headers = Headers::new();

            // Run on_stop with panic catching so we can propagate errors
            let stop_result =
                std::panic::AssertUnwindSafe(actor.on_stop())
                    .catch_unwind()
                    .await;
            let stop_err = match stop_result {
                Ok(()) => None,
                Err(_panic) => Some("actor panicked in on_stop".to_string()),
            };

            // Notify all watchers that this actor has terminated.
            // Clone entries and release lock before calling notify closures
            // to avoid holding the mutex during potentially blocking sends.
            let actor_id = ctx.actor_id.clone();
            let actor_name = ctx.actor_name.clone();
            let entries = {
                let mut watchers = watchers_ref.lock().unwrap();
                watchers.remove(&actor_id).unwrap_or_default()
            };
            if !entries.is_empty() {
                let notification = ChildTerminated {
                    child_id: actor_id,
                    child_name: actor_name.clone(),
                    reason: stop_reason,
                };
                for entry in &entries {
                    (entry.notify)(notification.clone());
                }
            }

            // Notify await_stop() waiters with the result
            let result = match stop_err {
                Some(e) => Err(e),
                None => Ok(()),
            };
            let _ = stop_tx.send(result);

            // Auto-unregister from the name registry on stop.
            registry_task.unregister(&actor_name);
        });

        let actor_ref = TestActorRef {
            id: actor_id,
            name: actor_name,
            sender: tx,
            alive,
            outbound_interceptors: self.outbound_interceptors.clone(),
            drop_observer: (*self.drop_observer).clone(),
            dead_letter_handler: self.dead_letter_handler.clone(),
        };

        self.registry.register(name, actor_ref.clone());

        actor_ref
    }

    // -----------------------------------------------------------------------
    // Actor lifecycle handles
    // -----------------------------------------------------------------------

    /// Wait for an actor to stop.
    ///
    /// Returns `Ok(())` when the actor finishes cleanly, or `Err` if the
    /// actor panicked in `on_stop`. The stop receiver is consumed and removed
    /// from the map.
    ///
    /// Returns `Ok(())` immediately if no stop receiver is stored for this ID.
    pub async fn await_stop(&self, actor_id: &ActorId) -> Result<(), String> {
        let rx = {
            let mut receivers = self.stop_receivers.lock().unwrap();
            receivers.remove(actor_id)
        };
        match rx {
            Some(rx) => rx
                .await
                .map_err(|_| "stop notifier dropped".to_string())
                .and_then(|r| r),
            None => Ok(()),
        }
    }

    /// Wait for all spawned actors to stop.
    ///
    /// Drains all stored stop receivers and awaits them all. Returns the first
    /// error encountered, but always waits for every actor to finish.
    pub async fn await_all(&self) -> Result<(), String> {
        let receivers: Vec<_> = {
            let mut map = self.stop_receivers.lock().unwrap();
            map.drain().collect()
        };
        let mut first_error = None;
        for (_, rx) in receivers {
            let result = rx.await.map_err(|e| format!("stop notifier dropped: {e}")).and_then(|r| r);
            if let Err(e) = result {
                if first_error.is_none() {
                    first_error = Some(e);
                }
            }
        }
        match first_error {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }

    /// Remove completed stop receivers from the map.
    ///
    /// Call periodically to prevent stale entries from accumulating
    /// for actors that stopped without being awaited.
    pub fn cleanup_finished(&self) {
        let mut receivers = self.stop_receivers.lock().unwrap();
        receivers.retain(|_, rx| {
            matches!(
                rx.try_recv(),
                Err(tokio::sync::oneshot::error::TryRecvError::Empty)
            )
        });
    }

    /// Number of actors with stored stop receivers.
    ///
    /// Note: includes receivers for actors that have already stopped but
    /// haven't been awaited or cleaned up. Call `cleanup_finished()` first
    /// for an accurate count of running actors.
    pub fn active_handle_count(&self) -> usize {
        self.stop_receivers.lock().unwrap().len()
    }
}

impl Default for TestRuntime {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::actor::ActorContext;
    use crate::actor::{ReduceHandler, ExpandHandler, TransformHandler};
    use crate::message::Message;
    use crate::node::NodeId;
    use crate::stream::{StreamReceiver, StreamSender};

    // -- Shared test actor: Counter -----------------------------------------

    struct Increment(u64);
    impl Message for Increment {
        type Reply = ();
    }

    struct Counter {
        count: u64,
    }

    impl Actor for Counter {
        type Args = Self;
        type Deps = ();
        fn create(args: Self, _deps: ()) -> Self {
            args
        }
    }

    #[async_trait]
    impl Handler<Increment> for Counter {
        async fn handle(&mut self, msg: Increment, _ctx: &mut ActorContext) {
            self.count += msg.0;
        }
    }

    struct GetCount;
    impl Message for GetCount {
        type Reply = u64;
    }

    #[async_trait]
    impl Handler<GetCount> for Counter {
        async fn handle(&mut self, _msg: GetCount, _ctx: &mut ActorContext) -> u64 {
            self.count
        }
    }

    struct Reset;
    impl Message for Reset {
        type Reply = u64;
    }

    #[async_trait]
    impl Handler<Reset> for Counter {
        async fn handle(&mut self, _msg: Reset, _ctx: &mut ActorContext) -> u64 {
            let old = self.count;
            self.count = 0;
            old
        }
    }

    // -- Shared test actor: Greeter (for registry type-mismatch tests) ------

    struct Greet(String);
    impl Message for Greet {
        type Reply = String;
    }

    struct Greeter;

    impl Actor for Greeter {
        type Args = ();
        type Deps = ();
        fn create(_args: (), _deps: ()) -> Self {
            Greeter
        }
    }

    #[async_trait]
    impl Handler<Greet> for Greeter {
        async fn handle(&mut self, msg: Greet, _ctx: &mut ActorContext) -> String {
            format!("Hello, {}!", msg.0)
        }
    }

    // -- Tests --------------------------------------------------------------

    #[tokio::test]
    async fn test_spawn_and_tell() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        counter.tell(Increment(5)).unwrap();
        counter.tell(Increment(3)).unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        assert!(counter.is_alive());
    }

    #[tokio::test]
    async fn test_tell_returns_actor_id() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("my-counter", Counter { count: 0 }).await.unwrap();

        assert_eq!(counter.name(), "my-counter");
        assert_eq!(counter.id().node, NodeId("test-node".into()));
        assert!(counter.id().local > 0);
    }

    #[tokio::test]
    async fn test_tell_100_messages_in_order() {
        use std::sync::Arc;
        use tokio::sync::Mutex;

        struct OrderTracker {
            received: Arc<Mutex<Vec<u64>>>,
        }

        impl Actor for OrderTracker {
            type Args = Arc<Mutex<Vec<u64>>>;
            type Deps = ();
            fn create(args: Arc<Mutex<Vec<u64>>>, _deps: ()) -> Self {
                OrderTracker { received: args }
            }
        }

        struct TrackMsg(u64);
        impl Message for TrackMsg {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<TrackMsg> for OrderTracker {
            async fn handle(&mut self, msg: TrackMsg, _ctx: &mut ActorContext) {
                self.received.lock().await.push(msg.0);
            }
        }

        let received = Arc::new(Mutex::new(Vec::new()));
        let runtime = TestRuntime::new();
        let tracker = runtime.spawn::<OrderTracker>("tracker", received.clone()).await.unwrap();

        for i in 0..100 {
            tracker.tell(TrackMsg(i)).unwrap();
        }

        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        let result = received.lock().await;
        assert_eq!(result.len(), 100);
        for (i, val) in result.iter().enumerate() {
            assert_eq!(*val, i as u64, "message {} out of order", i);
        }
    }

    #[tokio::test]
    async fn test_multiple_actor_refs() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        let ref1 = counter.clone();
        let ref2 = counter.clone();

        ref1.tell(Increment(10)).unwrap();
        ref2.tell(Increment(20)).unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        assert!(ref1.is_alive());
        assert!(ref2.is_alive());
    }

    #[tokio::test]
    async fn test_on_start_called_before_messages() {
        use std::sync::Arc;
        use tokio::sync::Mutex;

        struct StartTracker {
            log: Arc<Mutex<Vec<String>>>,
        }

        struct StartTrackerArgs(Arc<Mutex<Vec<String>>>);

        #[async_trait]
        impl Actor for StartTracker {
            type Args = StartTrackerArgs;
            type Deps = ();
            fn create(args: StartTrackerArgs, _deps: ()) -> Self {
                StartTracker { log: args.0 }
            }
            async fn on_start(&mut self, _ctx: &mut ActorContext) {
                self.log.lock().await.push("on_start".into());
            }
        }

        struct Ping;
        impl Message for Ping {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<Ping> for StartTracker {
            async fn handle(&mut self, _msg: Ping, _ctx: &mut ActorContext) {
                self.log.lock().await.push("handle".into());
            }
        }

        let log = Arc::new(Mutex::new(Vec::new()));
        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<StartTracker>("tracker", StartTrackerArgs(log.clone())).await.unwrap();

        actor.tell(Ping).unwrap();

        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        let entries = log.lock().await;
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0], "on_start");
        assert_eq!(entries[1], "handle");
    }

    #[tokio::test]
    async fn test_tell_to_stopped_actor() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        // Drop the original to close the channel
        let counter2 = counter.clone();
        drop(counter);

        // counter2 still holds a sender, so the actor is alive
        assert!(counter2.tell(Increment(1)).is_ok());
    }

    #[tokio::test]
    async fn test_unique_actor_ids() {
        let runtime = TestRuntime::new();
        let a = runtime.spawn::<Counter>("a", Counter { count: 0 }).await.unwrap();
        let b = runtime.spawn::<Counter>("b", Counter { count: 0 }).await.unwrap();

        assert_ne!(a.id(), b.id());
        assert!(a.id().local < b.id().local);
    }

    // -- Ask tests ----------------------------------------------------------

    #[tokio::test]
    async fn test_ask_get_count() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 42 }).await.unwrap();

        let count = counter.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(count, 42);
    }

    #[tokio::test]
    async fn test_ask_after_tell() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        counter.tell(Increment(10)).unwrap();
        counter.tell(Increment(20)).unwrap();

        let count = counter.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(count, 30);
    }

    #[tokio::test]
    async fn test_ask_reset_returns_old_value() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 100 }).await.unwrap();

        let old = counter.ask(Reset, None).unwrap().await.unwrap();
        assert_eq!(old, 100);

        let count = counter.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(count, 0);
    }

    #[tokio::test]
    async fn test_concurrent_asks() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        counter.tell(Increment(100)).unwrap();

        // Ensure the tell is processed before asking
        let _ = counter.ask(GetCount, None).unwrap().await.unwrap();

        let ref1 = counter.clone();
        let ref2 = counter.clone();

        let (r1, r2) = tokio::join!(
            async { ref1.ask(GetCount, None).unwrap().await.unwrap() },
            async { ref2.ask(GetCount, None).unwrap().await.unwrap() },
        );

        assert_eq!(r1, 100);
        assert_eq!(r2, 100);
    }

    #[tokio::test]
    async fn test_interleaved_tell_ask() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        counter.tell(Increment(5)).unwrap();
        let c1 = counter.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(c1, 5);

        counter.tell(Increment(3)).unwrap();
        let c2 = counter.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(c2, 8);

        let old = counter.ask(Reset, None).unwrap().await.unwrap();
        assert_eq!(old, 8);

        let c3 = counter.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(c3, 0);
    }

    // -- Interceptor tests --------------------------------------------------

    use std::sync::Mutex;

    struct LogInterceptor {
        log: Arc<Mutex<Vec<String>>>,
    }

    impl InboundInterceptor for LogInterceptor {
        fn name(&self) -> &'static str {
            "log"
        }

        fn on_receive(
            &self,
            ctx: &InboundContext<'_>,
            _rh: &RuntimeHeaders,
            _h: &mut Headers,
            _msg: &dyn Any,
        ) -> Disposition {
            self.log
                .lock()
                .unwrap()
                .push(format!("on_receive:{}", ctx.message_type));
            Disposition::Continue
        }

        fn on_complete(
            &self,
            _ctx: &InboundContext<'_>,
            _rh: &RuntimeHeaders,
            _h: &Headers,
            outcome: &Outcome<'_>,
        ) {
            self.log
                .lock()
                .unwrap()
                .push(format!("on_complete:{:?}", outcome));
        }
    }

    #[tokio::test]
    async fn test_interceptor_on_receive_and_on_complete_called() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let runtime = TestRuntime::new();
        let counter = runtime.spawn_with_options::<Counter>(
            "counter",
            Counter { count: 0 },
            SpawnOptions {
                interceptors: vec![Box::new(LogInterceptor { log: log.clone() })],
                ..Default::default()
            },
        ).await.unwrap();

        counter.tell(Increment(5)).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        let entries = log.lock().unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries[0].starts_with("on_receive:"));
        assert!(entries[1].starts_with("on_complete:TellSuccess"));
    }

    #[tokio::test]
    async fn test_interceptor_on_complete_replied_for_ask() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let runtime = TestRuntime::new();
        let counter = runtime.spawn_with_options::<Counter>(
            "counter",
            Counter { count: 42 },
            SpawnOptions {
                interceptors: vec![Box::new(LogInterceptor { log: log.clone() })],
                ..Default::default()
            },
        ).await.unwrap();

        let count = counter.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(count, 42);

        let entries = log.lock().unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries[0].starts_with("on_receive:"));
        assert!(entries[1].starts_with("on_complete:AskSuccess"));
    }

    struct DropInterceptor;

    impl InboundInterceptor for DropInterceptor {
        fn name(&self) -> &'static str {
            "drop-all"
        }

        fn on_receive(
            &self,
            _ctx: &InboundContext<'_>,
            _rh: &RuntimeHeaders,
            _h: &mut Headers,
            _msg: &dyn Any,
        ) -> Disposition {
            Disposition::Drop
        }
    }

    #[tokio::test]
    async fn test_disposition_drop_prevents_handler() {
        // Use a shared counter to verify the handler was never called
        let handle_count = Arc::new(AtomicU64::new(0));
        let handle_count_clone = handle_count.clone();

        struct CountingActor {
            handle_count: Arc<AtomicU64>,
        }

        impl Actor for CountingActor {
            type Args = Arc<AtomicU64>;
            type Deps = ();
            fn create(args: Arc<AtomicU64>, _deps: ()) -> Self {
                CountingActor { handle_count: args }
            }
        }

        struct Ping;
        impl Message for Ping {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<Ping> for CountingActor {
            async fn handle(&mut self, _msg: Ping, _ctx: &mut ActorContext) {
                self.handle_count.fetch_add(1, Ordering::SeqCst);
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn_with_options::<CountingActor>(
            "counting",
            handle_count_clone,
            SpawnOptions {
                interceptors: vec![Box::new(DropInterceptor)],
                ..Default::default()
            },
        ).await.unwrap();

        actor.tell(Ping).unwrap();
        actor.tell(Ping).unwrap();
        actor.tell(Ping).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        assert_eq!(
            handle_count.load(Ordering::SeqCst),
            0,
            "handler should not have been called"
        );
        assert!(actor.is_alive(), "actor should still be alive after drops");
    }

    struct RejectInterceptor;

    impl InboundInterceptor for RejectInterceptor {
        fn name(&self) -> &'static str {
            "reject-all"
        }

        fn on_receive(
            &self,
            _ctx: &InboundContext<'_>,
            _rh: &RuntimeHeaders,
            _h: &mut Headers,
            _msg: &dyn Any,
        ) -> Disposition {
            Disposition::Reject("forbidden".into())
        }
    }

    #[tokio::test]
    async fn test_disposition_reject_ask_returns_error() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn_with_options::<Counter>(
            "counter",
            Counter { count: 42 },
            SpawnOptions {
                interceptors: vec![Box::new(RejectInterceptor)],
                ..Default::default()
            },
        ).await.unwrap();

        let result = counter.ask(GetCount, None).unwrap().await;
        assert!(result.is_err(), "rejected ask should return Err");
        match result.unwrap_err() {
            RuntimeError::Rejected {
                interceptor,
                reason,
            } => {
                assert_eq!(interceptor, "reject-all");
                assert_eq!(reason, "forbidden");
            }
            other => panic!("expected Rejected, got: {:?}", other),
        }
    }

    // ── Disposition::Retry tests ─────────────────────────────

    struct RetryInterceptor;
    impl InboundInterceptor for RetryInterceptor {
        fn name(&self) -> &'static str {
            "retry-later"
        }
        fn on_receive(
            &self,
            _ctx: &InboundContext<'_>,
            _rh: &RuntimeHeaders,
            _h: &mut Headers,
            _msg: &dyn Any,
        ) -> Disposition {
            Disposition::Retry(Duration::from_millis(500))
        }
    }

    #[tokio::test]
    async fn test_disposition_retry_ask_returns_retry_after() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn_with_options::<Counter>(
            "counter",
            Counter { count: 42 },
            SpawnOptions {
                interceptors: vec![Box::new(RetryInterceptor)],
                ..Default::default()
            },
        ).await.unwrap();

        let result = counter.ask(GetCount, None).unwrap().await;
        assert!(result.is_err());
        match result.unwrap_err() {
            RuntimeError::RetryAfter {
                interceptor,
                retry_after,
            } => {
                assert_eq!(interceptor, "retry-later");
                assert_eq!(retry_after, Duration::from_millis(500));
            }
            other => panic!("expected RetryAfter, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_disposition_retry_tell_silently_drops() {
        let handler_count = Arc::new(AtomicU64::new(0));
        let count_clone = handler_count.clone();

        struct TrackActor {
            count: Arc<AtomicU64>,
        }
        impl Actor for TrackActor {
            type Args = Arc<AtomicU64>;
            type Deps = ();
            fn create(args: Arc<AtomicU64>, _: ()) -> Self {
                TrackActor { count: args }
            }
        }

        struct TrackMsg;
        impl Message for TrackMsg {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<TrackMsg> for TrackActor {
            async fn handle(&mut self, _msg: TrackMsg, _ctx: &mut ActorContext) {
                self.count.fetch_add(1, Ordering::SeqCst);
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn_with_options::<TrackActor>(
            "tracker",
            count_clone,
            SpawnOptions {
                interceptors: vec![Box::new(RetryInterceptor)],
                ..Default::default()
            },
        ).await.unwrap();

        actor.tell(TrackMsg).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        assert_eq!(
            handler_count.load(Ordering::SeqCst),
            0,
            "handler should not be called when Retry"
        );
    }

    #[tokio::test]
    async fn test_multiple_interceptors_execute_in_order() {
        let log = Arc::new(Mutex::new(Vec::new()));

        struct OrderedInterceptor {
            id: u32,
            log: Arc<Mutex<Vec<String>>>,
        }

        impl InboundInterceptor for OrderedInterceptor {
            fn name(&self) -> &'static str {
                "ordered"
            }

            fn on_receive(
                &self,
                _ctx: &InboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                self.log
                    .lock()
                    .unwrap()
                    .push(format!("interceptor-{}", self.id));
                Disposition::Continue
            }
        }

        let runtime = TestRuntime::new();
        let counter = runtime.spawn_with_options::<Counter>(
            "counter",
            Counter { count: 0 },
            SpawnOptions {
                interceptors: vec![
                    Box::new(OrderedInterceptor {
                        id: 1,
                        log: log.clone(),
                    }),
                    Box::new(OrderedInterceptor {
                        id: 2,
                        log: log.clone(),
                    }),
                    Box::new(OrderedInterceptor {
                        id: 3,
                        log: log.clone(),
                    }),
                ],
                ..Default::default()
            },
        ).await.unwrap();

        counter.tell(Increment(1)).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        let entries = log.lock().unwrap();
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0], "interceptor-1");
        assert_eq!(entries[1], "interceptor-2");
        assert_eq!(entries[2], "interceptor-3");
    }

    #[tokio::test]
    async fn test_drop_interceptor_short_circuits_chain() {
        let log = Arc::new(Mutex::new(Vec::new()));

        struct LabelInterceptor {
            label: &'static str,
            log: Arc<Mutex<Vec<String>>>,
        }

        impl InboundInterceptor for LabelInterceptor {
            fn name(&self) -> &'static str {
                self.label
            }

            fn on_receive(
                &self,
                _ctx: &InboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                self.log.lock().unwrap().push(self.label.to_string());
                Disposition::Continue
            }
        }

        struct DropAtSecond;

        impl InboundInterceptor for DropAtSecond {
            fn name(&self) -> &'static str {
                "drop-at-second"
            }

            fn on_receive(
                &self,
                _ctx: &InboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                Disposition::Drop
            }
        }

        let runtime = TestRuntime::new();
        let counter = runtime.spawn_with_options::<Counter>(
            "counter",
            Counter { count: 0 },
            SpawnOptions {
                interceptors: vec![
                    Box::new(LabelInterceptor {
                        label: "first",
                        log: log.clone(),
                    }),
                    Box::new(DropAtSecond),
                    Box::new(LabelInterceptor {
                        label: "third",
                        log: log.clone(),
                    }),
                ],
                ..Default::default()
            },
        ).await.unwrap();

        counter.tell(Increment(1)).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        let entries = log.lock().unwrap();
        // Only the first interceptor should have been called (second drops, third skipped)
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0], "first");
    }

    #[tokio::test]
    async fn test_disposition_delay() {
        struct DelayInterceptor;

        impl InboundInterceptor for DelayInterceptor {
            fn name(&self) -> &'static str {
                "delay"
            }

            fn on_receive(
                &self,
                _ctx: &InboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                Disposition::Delay(Duration::from_millis(100))
            }
        }

        let runtime = TestRuntime::new();
        let counter = runtime.spawn_with_options::<Counter>(
            "counter",
            Counter { count: 0 },
            SpawnOptions {
                interceptors: vec![Box::new(DelayInterceptor)],
                ..Default::default()
            },
        ).await.unwrap();

        let start = tokio::time::Instant::now();
        counter.tell(Increment(1)).unwrap();

        // Ask blocks until tell+ask are both processed (sequentially, both delayed)
        let count = counter.ask(GetCount, None).unwrap().await.unwrap();
        let elapsed = start.elapsed();

        assert_eq!(count, 1);
        // Both the tell and the ask were delayed by 100ms each
        assert!(
            elapsed >= Duration::from_millis(180),
            "expected cumulative delay, got {:?}",
            elapsed
        );
    }

    #[tokio::test]
    async fn test_cumulative_delays_from_multiple_interceptors() {
        struct SmallDelay(u64);

        impl InboundInterceptor for SmallDelay {
            fn name(&self) -> &'static str {
                "small-delay"
            }

            fn on_receive(
                &self,
                _ctx: &InboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                Disposition::Delay(Duration::from_millis(self.0))
            }
        }

        let runtime = TestRuntime::new();
        let counter = runtime.spawn_with_options::<Counter>(
            "counter",
            Counter { count: 0 },
            SpawnOptions {
                interceptors: vec![Box::new(SmallDelay(50)), Box::new(SmallDelay(50))],
                ..Default::default()
            },
        ).await.unwrap();

        let start = tokio::time::Instant::now();
        // Use ask to block until message is processed
        let count = counter.ask(GetCount, None).unwrap().await.unwrap();
        let elapsed = start.elapsed();

        assert_eq!(count, 0);
        // 50ms + 50ms = 100ms cumulative delay
        assert!(
            elapsed >= Duration::from_millis(80),
            "expected ~100ms cumulative delay, got {:?}",
            elapsed
        );
    }

    #[tokio::test]
    async fn test_no_interceptors_existing_behavior_unchanged() {
        // Existing spawn() path should work identically
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        counter.tell(Increment(10)).unwrap();
        let count = counter.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(count, 10);
    }

    #[tokio::test]
    async fn test_interceptor_can_inspect_message_type() {
        let log = Arc::new(Mutex::new(Vec::new()));

        struct TypeLogInterceptor {
            log: Arc<Mutex<Vec<String>>>,
        }

        impl InboundInterceptor for TypeLogInterceptor {
            fn name(&self) -> &'static str {
                "type-log"
            }

            fn on_receive(
                &self,
                ctx: &InboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                self.log
                    .lock()
                    .unwrap()
                    .push(format!("{}:{:?}", ctx.message_type, ctx.send_mode));
                Disposition::Continue
            }
        }

        let runtime = TestRuntime::new();
        let counter = runtime.spawn_with_options::<Counter>(
            "counter",
            Counter { count: 0 },
            SpawnOptions {
                interceptors: vec![Box::new(TypeLogInterceptor { log: log.clone() })],
                ..Default::default()
            },
        ).await.unwrap();

        counter.tell(Increment(1)).unwrap();
        let _ = counter.ask(GetCount, None).unwrap().await.unwrap();

        let entries = log.lock().unwrap();
        assert_eq!(entries.len(), 2);
        // First message is Tell, second is Ask
        assert!(entries[0].contains("Tell"), "got: {}", entries[0]);
        assert!(entries[1].contains("Ask"), "got: {}", entries[1]);
    }

    #[tokio::test]
    async fn test_interceptor_can_downcast_message() {
        let captured = Arc::new(Mutex::new(Vec::new()));

        struct DowncastInterceptor {
            captured: Arc<Mutex<Vec<u64>>>,
        }

        impl InboundInterceptor for DowncastInterceptor {
            fn name(&self) -> &'static str {
                "downcast"
            }

            fn on_receive(
                &self,
                _ctx: &InboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                msg: &dyn Any,
            ) -> Disposition {
                if let Some(inc) = msg.downcast_ref::<Increment>() {
                    self.captured.lock().unwrap().push(inc.0);
                }
                Disposition::Continue
            }
        }

        let runtime = TestRuntime::new();
        let counter = runtime.spawn_with_options::<Counter>(
            "counter",
            Counter { count: 0 },
            SpawnOptions {
                interceptors: vec![Box::new(DowncastInterceptor {
                    captured: captured.clone(),
                })],
                ..Default::default()
            },
        ).await.unwrap();

        counter.tell(Increment(42)).unwrap();
        counter.tell(Increment(7)).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        let values = captured.lock().unwrap();
        assert_eq!(*values, vec![42, 7]);
    }

    // -- Outbound interceptor tests ----------------------------------------

    #[tokio::test]
    async fn test_outbound_interceptor_on_send_called() {
        use std::sync::Mutex;

        let log = Arc::new(Mutex::new(Vec::<String>::new()));

        struct OutLog {
            log: Arc<Mutex<Vec<String>>>,
        }

        impl OutboundInterceptor for OutLog {
            fn name(&self) -> &'static str {
                "out-log"
            }

            fn on_send(
                &self,
                ctx: &OutboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                self.log
                    .lock()
                    .unwrap()
                    .push(format!("on_send:{}", ctx.message_type));
                Disposition::Continue
            }
        }

        let mut runtime = TestRuntime::new();
        runtime.add_outbound_interceptor(Box::new(OutLog { log: log.clone() }));
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        counter.tell(Increment(5)).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        let entries = log.lock().unwrap();
        assert!(!entries.is_empty());
        assert!(entries[0].contains("Increment"));
    }

    #[tokio::test]
    async fn test_outbound_reject_ask() {
        struct RejectOut;

        impl OutboundInterceptor for RejectOut {
            fn name(&self) -> &'static str {
                "reject-out"
            }

            fn on_send(
                &self,
                _ctx: &OutboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                Disposition::Reject("outbound blocked".into())
            }
        }

        let mut runtime = TestRuntime::new();
        runtime.add_outbound_interceptor(Box::new(RejectOut));
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 42 }).await.unwrap();

        let result = counter.ask(GetCount, None).unwrap().await;
        match result.unwrap_err() {
            RuntimeError::Rejected {
                interceptor,
                reason,
            } => {
                assert_eq!(interceptor, "reject-out");
                assert_eq!(reason, "outbound blocked");
            }
            other => panic!("expected Rejected, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_outbound_stamps_header() {
        use crate::message::Priority;

        struct StampPriority;

        impl OutboundInterceptor for StampPriority {
            fn name(&self) -> &'static str {
                "stamp"
            }

            fn on_send(
                &self,
                _ctx: &OutboundContext<'_>,
                _rh: &RuntimeHeaders,
                headers: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                headers.insert(Priority::HIGH);
                Disposition::Continue
            }
        }

        let mut runtime = TestRuntime::new();
        runtime.add_outbound_interceptor(Box::new(StampPriority));
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        counter.tell(Increment(1)).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;
        // Header was stamped on outbound side — verified by no panic
    }

    #[tokio::test]
    async fn test_outbound_retry_ask() {
        struct RetryOut;

        impl OutboundInterceptor for RetryOut {
            fn name(&self) -> &'static str {
                "retry-out"
            }

            fn on_send(
                &self,
                _ctx: &OutboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                Disposition::Retry(Duration::from_millis(250))
            }
        }

        let mut runtime = TestRuntime::new();
        runtime.add_outbound_interceptor(Box::new(RetryOut));
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        let result = counter.ask(GetCount, None).unwrap().await;
        match result.unwrap_err() {
            RuntimeError::RetryAfter {
                interceptor,
                retry_after,
            } => {
                assert_eq!(interceptor, "retry-out");
                assert_eq!(retry_after, Duration::from_millis(250));
            }
            other => panic!("expected RetryAfter, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_outbound_drop_tell_silently_drops() {
        struct DropOut;

        impl OutboundInterceptor for DropOut {
            fn name(&self) -> &'static str {
                "drop-out"
            }

            fn on_send(
                &self,
                _ctx: &OutboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                Disposition::Drop
            }
        }

        let mut runtime = TestRuntime::new();
        runtime.add_outbound_interceptor(Box::new(DropOut));
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        // tell should succeed (no error path) but message should not be delivered
        counter.tell(Increment(100)).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Verify actor still has count=0 via ask (without outbound drop)
        // Since the outbound interceptor drops all messages including ask,
        // we just verify tell returned Ok.
    }

    #[tokio::test]
    async fn test_outbound_drop_ask_returns_channel_closed() {
        struct DropOut;

        impl OutboundInterceptor for DropOut {
            fn name(&self) -> &'static str {
                "drop-out"
            }

            fn on_send(
                &self,
                _ctx: &OutboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                Disposition::Drop
            }
        }

        let mut runtime = TestRuntime::new();
        runtime.add_outbound_interceptor(Box::new(DropOut));
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        let result = counter.ask(GetCount, None).unwrap().await;
        // Dropped ask returns a channel-closed error (ActorNotFound)
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_outbound_interceptor_sees_ask_send_mode() {
        use std::sync::Mutex;

        let log = Arc::new(Mutex::new(Vec::<String>::new()));

        struct ModeLog {
            log: Arc<Mutex<Vec<String>>>,
        }

        impl OutboundInterceptor for ModeLog {
            fn name(&self) -> &'static str {
                "mode-log"
            }

            fn on_send(
                &self,
                ctx: &OutboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                self.log
                    .lock()
                    .unwrap()
                    .push(format!("{:?}", ctx.send_mode));
                Disposition::Continue
            }
        }

        let mut runtime = TestRuntime::new();
        runtime.add_outbound_interceptor(Box::new(ModeLog { log: log.clone() }));
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        counter.tell(Increment(1)).unwrap();
        let _ = counter.ask(GetCount, None).unwrap().await;

        let entries = log.lock().unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0], "Tell");
        assert_eq!(entries[1], "Ask");
    }

    // -- Lifecycle & ErrorAction tests -------------------------------------

    #[tokio::test]
    async fn test_stop_triggers_on_stop() {
        let log = Arc::new(Mutex::new(Vec::new()));

        struct StopTracker {
            log: Arc<Mutex<Vec<String>>>,
        }

        #[async_trait]
        impl Actor for StopTracker {
            type Args = Arc<Mutex<Vec<String>>>;
            type Deps = ();
            fn create(args: Arc<Mutex<Vec<String>>>, _: ()) -> Self {
                StopTracker { log: args }
            }
            async fn on_stop(&mut self) {
                self.log.lock().unwrap().push("on_stop".into());
            }
        }

        struct Ping;
        impl Message for Ping {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<Ping> for StopTracker {
            async fn handle(&mut self, _: Ping, _: &mut ActorContext) {}
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<StopTracker>("tracker", log.clone()).await.unwrap();

        actor.tell(Ping).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        actor.stop();
        tokio::time::sleep(Duration::from_millis(50)).await;

        let entries = log.lock().unwrap();
        assert!(entries.contains(&"on_stop".to_string()));
        assert!(!actor.is_alive());
    }

    #[tokio::test]
    async fn test_stop_makes_tell_fail() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        counter.stop();
        tokio::time::sleep(Duration::from_millis(50)).await;

        assert!(!counter.is_alive());
        // Sending to a stopped actor should fail
        let result = counter.tell(Increment(1));
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_on_error_resume_continues() {
        struct ResumeActor {
            count: Arc<AtomicU64>,
        }

        #[async_trait]
        impl Actor for ResumeActor {
            type Args = Arc<AtomicU64>;
            type Deps = ();
            fn create(args: Arc<AtomicU64>, _: ()) -> Self {
                ResumeActor { count: args }
            }
            fn on_error(&mut self, _: &ActorError) -> ErrorAction {
                ErrorAction::Resume
            }
        }

        struct PanicMsg;
        impl Message for PanicMsg {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<PanicMsg> for ResumeActor {
            async fn handle(&mut self, _: PanicMsg, _: &mut ActorContext) {
                panic!("intentional panic");
            }
        }

        struct CountMsg;
        impl Message for CountMsg {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<CountMsg> for ResumeActor {
            async fn handle(&mut self, _: CountMsg, _: &mut ActorContext) {
                self.count.fetch_add(1, Ordering::SeqCst);
            }
        }

        let count = Arc::new(AtomicU64::new(0));
        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<ResumeActor>("resume", count.clone()).await.unwrap();

        actor.tell(PanicMsg).unwrap(); // should panic but resume
        actor.tell(CountMsg).unwrap(); // should still be processed

        tokio::time::sleep(Duration::from_millis(100)).await;
        assert_eq!(
            count.load(Ordering::SeqCst),
            1,
            "actor should resume after panic"
        );
        assert!(actor.is_alive());
    }

    #[tokio::test]
    async fn test_on_error_stop_terminates() {
        struct StopOnError {
            alive_flag: Arc<AtomicBool>,
        }

        #[async_trait]
        impl Actor for StopOnError {
            type Args = Arc<AtomicBool>;
            type Deps = ();
            fn create(args: Arc<AtomicBool>, _: ()) -> Self {
                StopOnError { alive_flag: args }
            }
            fn on_error(&mut self, _: &ActorError) -> ErrorAction {
                ErrorAction::Stop
            }
            async fn on_stop(&mut self) {
                self.alive_flag.store(false, Ordering::SeqCst);
            }
        }

        struct PanicMsg;
        impl Message for PanicMsg {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<PanicMsg> for StopOnError {
            async fn handle(&mut self, _: PanicMsg, _: &mut ActorContext) {
                panic!("intentional");
            }
        }

        let alive = Arc::new(AtomicBool::new(true));
        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<StopOnError>("stopper", alive.clone()).await.unwrap();

        actor.tell(PanicMsg).unwrap();
        tokio::time::sleep(Duration::from_millis(100)).await;

        assert!(
            !alive.load(Ordering::SeqCst),
            "on_stop should have been called"
        );
        assert!(!actor.is_alive());
    }

    #[tokio::test]
    async fn test_on_error_default_is_stop() {
        struct PanicCounter {
            #[allow(dead_code)]
            count: u64,
        }

        impl Actor for PanicCounter {
            type Args = Self;
            type Deps = ();
            fn create(args: Self, _: ()) -> Self {
                args
            }
        }

        struct PanicIncrement;
        impl Message for PanicIncrement {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<PanicIncrement> for PanicCounter {
            async fn handle(&mut self, _: PanicIncrement, _: &mut ActorContext) {
                panic!("boom");
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<PanicCounter>("panic-counter", PanicCounter { count: 0 }).await.unwrap();

        actor.tell(PanicIncrement).unwrap();
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Default on_error is Stop, so actor should be dead
        assert!(!actor.is_alive());
    }

    #[tokio::test]
    async fn test_actor_context_has_send_mode() {
        let mode = Arc::new(Mutex::new(None));

        struct ModeTracker {
            mode: Arc<Mutex<Option<SendMode>>>,
        }

        impl Actor for ModeTracker {
            type Args = Arc<Mutex<Option<SendMode>>>;
            type Deps = ();
            fn create(args: Arc<Mutex<Option<SendMode>>>, _: ()) -> Self {
                ModeTracker { mode: args }
            }
        }

        struct Check;
        impl Message for Check {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<Check> for ModeTracker {
            async fn handle(&mut self, _: Check, ctx: &mut ActorContext) {
                *self.mode.lock().unwrap() = ctx.send_mode;
            }
        }

        let mode_ref = mode.clone();
        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<ModeTracker>("tracker", mode_ref).await.unwrap();

        actor.tell(Check).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        assert_eq!(*mode.lock().unwrap(), Some(SendMode::Tell));
    }

    #[tokio::test]
    async fn test_actor_context_has_ask_send_mode() {
        let mode = Arc::new(Mutex::new(None));

        struct AskModeTracker {
            mode: Arc<Mutex<Option<SendMode>>>,
        }

        impl Actor for AskModeTracker {
            type Args = Arc<Mutex<Option<SendMode>>>;
            type Deps = ();
            fn create(args: Arc<Mutex<Option<SendMode>>>, _: ()) -> Self {
                AskModeTracker { mode: args }
            }
        }

        struct AskCheck;
        impl Message for AskCheck {
            type Reply = u64;
        }

        #[async_trait]
        impl Handler<AskCheck> for AskModeTracker {
            async fn handle(&mut self, _: AskCheck, ctx: &mut ActorContext) -> u64 {
                *self.mode.lock().unwrap() = ctx.send_mode;
                42
            }
        }

        let mode_ref = mode.clone();
        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<AskModeTracker>("tracker", mode_ref).await.unwrap();

        let _ = actor.ask(AskCheck, None).unwrap().await.unwrap();

        assert_eq!(*mode.lock().unwrap(), Some(SendMode::Ask));
    }

    #[tokio::test]
    async fn test_on_error_restart_treated_as_resume() {
        struct RestartActor {
            count: Arc<AtomicU64>,
        }

        #[async_trait]
        impl Actor for RestartActor {
            type Args = Arc<AtomicU64>;
            type Deps = ();
            fn create(args: Arc<AtomicU64>, _: ()) -> Self {
                RestartActor { count: args }
            }
            fn on_error(&mut self, _: &ActorError) -> ErrorAction {
                ErrorAction::Restart
            }
        }

        struct RestartPanicMsg;
        impl Message for RestartPanicMsg {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<RestartPanicMsg> for RestartActor {
            async fn handle(&mut self, _: RestartPanicMsg, _: &mut ActorContext) {
                panic!("intentional panic");
            }
        }

        struct RestartCountMsg;
        impl Message for RestartCountMsg {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<RestartCountMsg> for RestartActor {
            async fn handle(&mut self, _: RestartCountMsg, _: &mut ActorContext) {
                self.count.fetch_add(1, Ordering::SeqCst);
            }
        }

        let count = Arc::new(AtomicU64::new(0));
        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<RestartActor>("restart", count.clone()).await.unwrap();

        actor.tell(RestartPanicMsg).unwrap();
        actor.tell(RestartCountMsg).unwrap();

        tokio::time::sleep(Duration::from_millis(100)).await;
        // Restart is treated as Resume for now
        assert_eq!(
            count.load(Ordering::SeqCst),
            1,
            "actor should continue after restart-as-resume"
        );
        assert!(actor.is_alive());
    }

    // -- Mailbox tests ------------------------------------------------------

    #[tokio::test]
    async fn test_unbounded_mailbox_accepts_many() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        for _ in 0..1000 {
            counter.tell(Increment(1)).unwrap();
        }

        tokio::time::sleep(Duration::from_millis(200)).await;
        let count = counter.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(count, 1000);
    }

    #[tokio::test]
    async fn test_default_spawn_is_unbounded() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        for _ in 0..100 {
            counter.tell(Increment(1)).unwrap();
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
        let count = counter.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(count, 100);
    }

    #[tokio::test]
    async fn test_mailbox_config_in_spawn_options() {
        let opts = SpawnOptions {
            mailbox: MailboxConfig::Bounded {
                capacity: 5,
                overflow: OverflowStrategy::RejectWithError,
            },
            ..Default::default()
        };
        assert_eq!(
            opts.mailbox,
            MailboxConfig::Bounded {
                capacity: 5,
                overflow: OverflowStrategy::RejectWithError,
            }
        );
    }

    // Slow actor used by bounded mailbox tests
    struct SlowActor;
    impl Actor for SlowActor {
        type Args = ();
        type Deps = ();
        fn create(_: (), _: ()) -> Self {
            SlowActor
        }
    }

    struct SlowMsg;
    impl Message for SlowMsg {
        type Reply = ();
    }

    #[async_trait]
    impl Handler<SlowMsg> for SlowActor {
        async fn handle(&mut self, _: SlowMsg, _: &mut ActorContext) {
            tokio::time::sleep(Duration::from_secs(10)).await;
        }
    }

    #[tokio::test]
    async fn test_bounded_reject_when_full() {
        let runtime = TestRuntime::new();
        let actor = runtime.spawn_with_options::<SlowActor>(
            "slow",
            (),
            SpawnOptions {
                mailbox: MailboxConfig::Bounded {
                    capacity: 2,
                    overflow: OverflowStrategy::RejectWithError,
                },
                ..Default::default()
            },
        ).await.unwrap();

        // First message starts processing (blocks in handler)
        actor.tell(SlowMsg).unwrap();
        tokio::time::sleep(Duration::from_millis(10)).await;

        // Fill the bounded channel (capacity=2)
        actor.tell(SlowMsg).unwrap();
        actor.tell(SlowMsg).unwrap();

        // Third should fail — mailbox full
        let result = actor.tell(SlowMsg);
        assert!(result.is_err(), "should reject when mailbox full");
    }

    #[tokio::test]
    async fn test_bounded_drop_newest_when_full() {
        let runtime = TestRuntime::new();
        let actor = runtime.spawn_with_options::<SlowActor>(
            "slow",
            (),
            SpawnOptions {
                mailbox: MailboxConfig::Bounded {
                    capacity: 2,
                    overflow: OverflowStrategy::DropNewest,
                },
                ..Default::default()
            },
        ).await.unwrap();

        actor.tell(SlowMsg).unwrap();
        tokio::time::sleep(Duration::from_millis(10)).await;
        actor.tell(SlowMsg).unwrap();
        actor.tell(SlowMsg).unwrap();

        // Should succeed — silently dropped
        let result = actor.tell(SlowMsg);
        assert!(result.is_ok(), "DropNewest should silently succeed");
    }

    // -- Supervision / DeathWatch tests -------------------------------------

    use crate::supervision::ChildTerminated;

    struct Watcher {
        events: Arc<Mutex<Vec<ChildTerminated>>>,
    }

    impl Actor for Watcher {
        type Args = Arc<Mutex<Vec<ChildTerminated>>>;
        type Deps = ();
        fn create(args: Arc<Mutex<Vec<ChildTerminated>>>, _: ()) -> Self {
            Watcher { events: args }
        }
    }

    #[async_trait]
    impl Handler<ChildTerminated> for Watcher {
        async fn handle(&mut self, msg: ChildTerminated, _ctx: &mut ActorContext) {
            self.events.lock().unwrap().push(msg);
        }
    }

    struct WatcherPing;
    impl Message for WatcherPing {
        type Reply = ();
    }

    #[async_trait]
    impl Handler<WatcherPing> for Watcher {
        async fn handle(&mut self, _: WatcherPing, _: &mut ActorContext) {}
    }

    struct Worker;
    impl Actor for Worker {
        type Args = ();
        type Deps = ();
        fn create(_: (), _: ()) -> Self {
            Worker
        }
    }

    struct WorkerMsg;
    impl Message for WorkerMsg {
        type Reply = ();
    }

    #[async_trait]
    impl Handler<WorkerMsg> for Worker {
        async fn handle(&mut self, _: WorkerMsg, _: &mut ActorContext) {}
    }

    #[tokio::test]
    async fn test_watch_receives_child_terminated() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let runtime = TestRuntime::new();
        let watcher = runtime.spawn::<Watcher>("watcher", events.clone()).await.unwrap();
        let worker = runtime.spawn::<Worker>("worker", ()).await.unwrap();

        let worker_id = worker.id();
        runtime.watch(&watcher, worker_id.clone());

        // Stop the worker
        worker.stop();
        tokio::time::sleep(Duration::from_millis(100)).await;

        let evts = events.lock().unwrap();
        assert_eq!(evts.len(), 1);
        assert_eq!(evts[0].child_id, worker_id);
        assert_eq!(evts[0].child_name, "worker");
        assert!(
            evts[0].reason.is_none(),
            "graceful stop should have no reason"
        );
    }

    #[tokio::test]
    async fn test_unwatch_stops_notifications() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let runtime = TestRuntime::new();
        let watcher = runtime.spawn::<Watcher>("watcher", events.clone()).await.unwrap();
        let worker = runtime.spawn::<Worker>("worker", ()).await.unwrap();

        let worker_id = worker.id();
        let watcher_id = watcher.id();
        runtime.watch(&watcher, worker_id.clone());

        // Unwatch before stopping
        runtime.unwatch(&watcher_id, &worker_id);

        worker.stop();
        tokio::time::sleep(Duration::from_millis(100)).await;

        let evts = events.lock().unwrap();
        assert!(evts.is_empty(), "unwatch should prevent notification");
    }

    #[tokio::test]
    async fn test_watch_panic_includes_reason() {
        struct PanicWorker;
        impl Actor for PanicWorker {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self {
                PanicWorker
            }
        }

        struct PanicMsg;
        impl Message for PanicMsg {
            type Reply = ();
        }

        #[async_trait]
        impl Handler<PanicMsg> for PanicWorker {
            async fn handle(&mut self, _: PanicMsg, _: &mut ActorContext) {
                panic!("boom");
            }
        }

        let events = Arc::new(Mutex::new(Vec::new()));
        let runtime = TestRuntime::new();
        let watcher = runtime.spawn::<Watcher>("watcher", events.clone()).await.unwrap();
        let worker = runtime.spawn::<PanicWorker>("panic-worker", ()).await.unwrap();

        let worker_id = worker.id();
        runtime.watch(&watcher, worker_id.clone());

        // Send a message that causes a panic (default on_error returns Stop)
        worker.tell(PanicMsg).unwrap();
        tokio::time::sleep(Duration::from_millis(100)).await;

        let evts = events.lock().unwrap();
        assert_eq!(evts.len(), 1);
        assert_eq!(evts[0].child_id, worker_id);
        assert_eq!(evts[0].reason, Some("handler panicked".into()));
    }

    #[tokio::test]
    async fn test_watch_multiple_watchers() {
        let events1 = Arc::new(Mutex::new(Vec::new()));
        let events2 = Arc::new(Mutex::new(Vec::new()));
        let runtime = TestRuntime::new();
        let watcher1 = runtime.spawn::<Watcher>("watcher1", events1.clone()).await.unwrap();
        let watcher2 = runtime.spawn::<Watcher>("watcher2", events2.clone()).await.unwrap();
        let worker = runtime.spawn::<Worker>("worker", ()).await.unwrap();

        let worker_id = worker.id();
        runtime.watch(&watcher1, worker_id.clone());
        runtime.watch(&watcher2, worker_id.clone());

        worker.stop();
        tokio::time::sleep(Duration::from_millis(100)).await;

        let evts1 = events1.lock().unwrap();
        let evts2 = events2.lock().unwrap();
        assert_eq!(evts1.len(), 1, "watcher1 should receive notification");
        assert_eq!(evts2.len(), 1, "watcher2 should receive notification");
        assert_eq!(evts1[0].child_id, worker_id);
        assert_eq!(evts2[0].child_id, worker_id);
    }

    // ======================================================================
    // Stream tests
    // ======================================================================

    struct LogServer {
        logs: Vec<String>,
    }

    impl Actor for LogServer {
        type Args = Vec<String>;
        type Deps = ();
        fn create(args: Vec<String>, _: ()) -> Self {
            LogServer { logs: args }
        }
    }

    struct GetLogs;
    impl Message for GetLogs {
        type Reply = String;
    }

    #[async_trait]
    impl ExpandHandler<GetLogs, String> for LogServer {
        async fn handle_expand(
            &mut self,
            _msg: GetLogs,
            sender: StreamSender<String>,
            _ctx: &mut ActorContext,
        ) {
            for log in &self.logs {
                if sender.send(log.clone()).await.is_err() {
                    break;
                }
            }
        }
    }

    #[tokio::test]
    async fn test_stream_returns_items() {
        use tokio_stream::StreamExt;

        let runtime = TestRuntime::new();
        let server = runtime
            .spawn::<LogServer>("logs", vec!["line1".into(), "line2".into(), "line3".into()]).await.unwrap();

        let mut stream = server.expand(GetLogs, 16, None, None).unwrap();
        let mut items = Vec::new();
        while let Some(item) = stream.next().await {
            items.push(item);
        }

        assert_eq!(items, vec!["line1", "line2", "line3"]);
    }

    #[tokio::test]
    async fn test_stream_empty() {
        use tokio_stream::StreamExt;

        let runtime = TestRuntime::new();
        let server = runtime.spawn::<LogServer>("logs", vec![]).await.unwrap();

        let mut stream = server.expand(GetLogs, 16, None, None).unwrap();
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn test_stream_consumer_drops_early() {
        use tokio_stream::StreamExt;

        let logs: Vec<String> = (0..1000).map(|i| format!("line-{}", i)).collect();
        let runtime = TestRuntime::new();
        let server = runtime.spawn::<LogServer>("logs", logs).await.unwrap();

        let mut stream = server.expand(GetLogs, 4, None, None).unwrap();
        let item1 = stream.next().await.unwrap();
        let item2 = stream.next().await.unwrap();
        assert_eq!(item1, "line-0");
        assert_eq!(item2, "line-1");

        // Drop stream — actor's sender.send() should return ConsumerDropped
        drop(stream);
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Actor should still be alive (dropping a stream doesn't kill the actor)
        assert!(server.is_alive());
    }

    #[tokio::test]
    async fn test_stream_items_in_order() {
        struct NumberStream;
        impl Actor for NumberStream {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self {
                NumberStream
            }
        }

        struct GetNumbers {
            count: u64,
        }
        impl Message for GetNumbers {
            type Reply = u64;
        }

        #[async_trait]
        impl ExpandHandler<GetNumbers, u64> for NumberStream {
            async fn handle_expand(
                &mut self,
                msg: GetNumbers,
                sender: StreamSender<u64>,
                _ctx: &mut ActorContext,
            ) {
                for i in 0..msg.count {
                    if sender.send(i).await.is_err() {
                        break;
                    }
                }
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<NumberStream>("numbers", ()).await.unwrap();

        let stream = actor
            .expand(GetNumbers { count: 100 }, 16, None, None)
            .unwrap();
        let items: Vec<u64> = tokio_stream::StreamExt::collect(stream).await;

        assert_eq!(items.len(), 100);
        for (i, val) in items.iter().enumerate() {
            assert_eq!(*val, i as u64);
        }
    }

    #[tokio::test]
    async fn test_stream_backpressure() {
        use tokio_stream::StreamExt;

        struct SlowStream;
        impl Actor for SlowStream {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self {
                SlowStream
            }
        }

        struct GetItems;
        impl Message for GetItems {
            type Reply = u64;
        }

        #[async_trait]
        impl ExpandHandler<GetItems, u64> for SlowStream {
            async fn handle_expand(
                &mut self,
                _: GetItems,
                sender: StreamSender<u64>,
                _ctx: &mut ActorContext,
            ) {
                for i in 0..10 {
                    if sender.send(i).await.is_err() {
                        break;
                    }
                }
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<SlowStream>("slow", ()).await.unwrap();
        let mut stream = actor.expand(GetItems, 1, None, None).unwrap();

        // Read slowly — backpressure should prevent buffer overflow
        let mut items = Vec::new();
        while let Some(item) = stream.next().await {
            items.push(item);
            tokio::time::sleep(Duration::from_millis(10)).await;
        }

        assert_eq!(items.len(), 10);
    }

    // ── Feed (client-streaming) tests ─────────────────────────────────

    #[tokio::test]
    async fn test_feed_sum_integers() {
        struct Summer;
        impl Actor for Summer {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self {
                Summer
            }
        }

        #[async_trait]
        impl ReduceHandler<u64, u64> for Summer {
            async fn handle_reduce(
                &mut self,
                mut receiver: StreamReceiver<u64>,
                _ctx: &mut ActorContext,
            ) -> u64 {
                let mut total = 0u64;
                while let Some(n) = receiver.recv().await {
                    total += n;
                }
                total
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<Summer>("summer", ()).await.unwrap();

        let input = futures::stream::iter(vec![10u64, 20, 30, 40, 50]);
        let reply = actor
            .reduce::<u64, u64>(Box::pin(input), 8, None, None)
            .unwrap()
            .await
            .unwrap();
        assert_eq!(reply, 150);
    }

    #[tokio::test]
    async fn test_feed_empty_stream() {
        struct Summer;
        impl Actor for Summer {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self {
                Summer
            }
        }

        #[async_trait]
        impl ReduceHandler<u64, u64> for Summer {
            async fn handle_reduce(
                &mut self,
                mut receiver: StreamReceiver<u64>,
                _ctx: &mut ActorContext,
            ) -> u64 {
                let mut total = 0u64;
                while let Some(n) = receiver.recv().await {
                    total += n;
                }
                total
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<Summer>("summer", ()).await.unwrap();

        let input = futures::stream::iter(Vec::<u64>::new());
        let reply = actor
            .reduce::<u64, u64>(Box::pin(input), 8, None, None)
            .unwrap()
            .await
            .unwrap();
        assert_eq!(reply, 0);
    }

    #[tokio::test]
    async fn test_feed_100_items_in_order() {
        struct Collector {
            items: Vec<u64>,
        }
        impl Actor for Collector {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self {
                Collector { items: Vec::new() }
            }
        }

        #[async_trait]
        impl ReduceHandler<u64, Vec<u64>> for Collector {
            async fn handle_reduce(
                &mut self,
                mut receiver: StreamReceiver<u64>,
                _ctx: &mut ActorContext,
            ) -> Vec<u64> {
                self.items.clear();
                while let Some(n) = receiver.recv().await {
                    self.items.push(n);
                }
                self.items.clone()
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<Collector>("collector", ()).await.unwrap();

        let values: Vec<u64> = (0..100).collect();
        let input = futures::stream::iter(values.clone());
        let reply = actor
            .reduce::<u64, Vec<u64>>(Box::pin(input), 16, None, None)
            .unwrap()
            .await
            .unwrap();
        assert_eq!(reply, values);
    }

    #[tokio::test]
    async fn test_feed_backpressure_buffer_1() {
        struct SlowConsumer;
        impl Actor for SlowConsumer {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self {
                SlowConsumer
            }
        }

        #[async_trait]
        impl ReduceHandler<u64, u64> for SlowConsumer {
            async fn handle_reduce(
                &mut self,
                mut receiver: StreamReceiver<u64>,
                _ctx: &mut ActorContext,
            ) -> u64 {
                let mut count = 0u64;
                while receiver.recv().await.is_some() {
                    count += 1;
                    tokio::time::sleep(Duration::from_millis(5)).await;
                }
                count
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<SlowConsumer>("slow", ()).await.unwrap();

        let input = futures::stream::iter(0u64..20);
        let reply = actor
            .reduce::<u64, u64>(Box::pin(input), 1, None, None)
            .unwrap()
            .await
            .unwrap();
        assert_eq!(reply, 20);
    }

    // ── Transform (N→M) tests ──────────────────────────────

    #[tokio::test]
    async fn test_transform_doubler() {
        use tokio_stream::StreamExt;

        struct Doubler;
        impl Actor for Doubler {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self { Doubler }
        }

        #[async_trait]
        impl TransformHandler<i32, i32> for Doubler {
            async fn handle_transform(
                &mut self,
                item: i32,
                sender: &StreamSender<i32>,
                _ctx: &mut ActorContext,
            ) {
                let _ = sender.send(item * 2).await;
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<Doubler>("doubler", ()).await.unwrap();

        let input = Box::pin(futures::stream::iter(vec![1, 2, 3, 4, 5]));
        let output: Vec<i32> = actor
            .transform::<i32, i32>(input, 8, None, None)
            .unwrap()
            .collect()
            .await;
        assert_eq!(output, vec![2, 4, 6, 8, 10]);
    }

    #[tokio::test]
    async fn test_transform_splitter() {
        use tokio_stream::StreamExt;

        struct Splitter;
        impl Actor for Splitter {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self { Splitter }
        }

        #[async_trait]
        impl TransformHandler<String, String> for Splitter {
            async fn handle_transform(
                &mut self,
                item: String,
                sender: &StreamSender<String>,
                _ctx: &mut ActorContext,
            ) {
                for word in item.split_whitespace() {
                    if sender.send(word.to_string()).await.is_err() {
                        break;
                    }
                }
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<Splitter>("splitter", ()).await.unwrap();

        let input = Box::pin(futures::stream::iter(vec![
            "hello world".to_string(),
            "foo bar baz".to_string(),
        ]));
        let output: Vec<String> = actor
            .transform::<String, String>(input, 8, None, None)
            .unwrap()
            .collect()
            .await;
        assert_eq!(output, vec!["hello", "world", "foo", "bar", "baz"]);
    }

    #[tokio::test]
    async fn test_transform_filter() {
        use tokio_stream::StreamExt;

        struct EvenFilter;
        impl Actor for EvenFilter {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self { EvenFilter }
        }

        #[async_trait]
        impl TransformHandler<i32, i32> for EvenFilter {
            async fn handle_transform(
                &mut self,
                item: i32,
                sender: &StreamSender<i32>,
                _ctx: &mut ActorContext,
            ) {
                if item % 2 == 0 {
                    let _ = sender.send(item).await;
                }
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<EvenFilter>("filter", ()).await.unwrap();

        let input = Box::pin(futures::stream::iter(1..=10));
        let output: Vec<i32> = actor
            .transform::<i32, i32>(input, 8, None, None)
            .unwrap()
            .collect()
            .await;
        assert_eq!(output, vec![2, 4, 6, 8, 10]);
    }

    #[tokio::test]
    async fn test_transform_empty_input() {
        use tokio_stream::StreamExt;

        struct Doubler;
        impl Actor for Doubler {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self { Doubler }
        }

        #[async_trait]
        impl TransformHandler<i32, i32> for Doubler {
            async fn handle_transform(
                &mut self,
                item: i32,
                sender: &StreamSender<i32>,
                _ctx: &mut ActorContext,
            ) {
                let _ = sender.send(item * 2).await;
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<Doubler>("doubler", ()).await.unwrap();

        let input = Box::pin(futures::stream::iter(Vec::<i32>::new()));
        let output: Vec<i32> = actor
            .transform::<i32, i32>(input, 8, None, None)
            .unwrap()
            .collect()
            .await;
        assert!(output.is_empty());
    }

    #[tokio::test]
    async fn test_transform_on_complete_emits_final() {
        use tokio_stream::StreamExt;

        struct SumAndEmit {
            sum: i32,
        }
        impl Actor for SumAndEmit {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self { SumAndEmit { sum: 0 } }
        }

        #[async_trait]
        impl TransformHandler<i32, i32> for SumAndEmit {
            async fn handle_transform(
                &mut self,
                item: i32,
                _sender: &StreamSender<i32>,
                _ctx: &mut ActorContext,
            ) {
                self.sum += item;
            }

            async fn on_transform_complete(
                &mut self,
                sender: &StreamSender<i32>,
                _ctx: &mut ActorContext,
            ) {
                let _ = sender.send(self.sum).await;
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<SumAndEmit>("sum-emit", ()).await.unwrap();

        let input = Box::pin(futures::stream::iter(vec![10, 20, 30]));
        let output: Vec<i32> = actor
            .transform::<i32, i32>(input, 8, None, None)
            .unwrap()
            .collect()
            .await;
        assert_eq!(output, vec![60]);
    }

    #[tokio::test]
    async fn test_transform_batched_preserves_order() {
        use crate::stream::BatchConfig;
        use tokio_stream::StreamExt;

        struct Doubler;
        impl Actor for Doubler {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self {
                Doubler
            }
        }

        #[async_trait]
        impl TransformHandler<i32, i32> for Doubler {
            async fn handle_transform(
                &mut self,
                item: i32,
                sender: &StreamSender<i32>,
                _ctx: &mut ActorContext,
            ) {
                let _ = sender.send(item * 2).await;
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<Doubler>("doubler-batched", ()).await.unwrap();

        let input = Box::pin(futures::stream::iter(vec![1, 2, 3, 4, 5]));
        let batch_config = BatchConfig::new(2, Duration::from_secs(10));
        let output: Vec<i32> = actor
            .transform::<i32, i32>(input, 8, Some(batch_config), None)
            .unwrap()
            .collect()
            .await;
        assert_eq!(output, vec![2, 4, 6, 8, 10], "batched transform should preserve order");
    }

    // ── Cancellation tests ──────────────────────────────

    #[tokio::test]
    async fn test_cancel_ask_before_handler() {
        let token = CancellationToken::new();
        token.cancel(); // cancel immediately

        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();

        let result = counter.ask(GetCount, Some(token)).unwrap().await;
        // Should be Err(Cancelled) because cancelled before handler ran
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), RuntimeError::Cancelled));
    }

    #[tokio::test]
    async fn test_cancel_after_timeout() {
        use crate::actor::cancel_after;

        struct SlowActor;
        impl Actor for SlowActor {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self {
                SlowActor
            }
        }
        struct SlowMsg;
        impl Message for SlowMsg {
            type Reply = String;
        }
        #[async_trait]
        impl Handler<SlowMsg> for SlowActor {
            async fn handle(&mut self, _: SlowMsg, _ctx: &mut ActorContext) -> String {
                tokio::time::sleep(Duration::from_secs(10)).await;
                "done".into()
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<SlowActor>("slow", ()).await.unwrap();
        let token = cancel_after(Duration::from_millis(50));
        let result = actor.ask(SlowMsg, Some(token)).unwrap().await;
        assert!(result.is_err()); // cancelled during handler execution
    }

    #[tokio::test]
    async fn test_no_cancel_runs_to_completion() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter", Counter { count: 42 }).await.unwrap();
        let result = counter.ask(GetCount, None).unwrap().await;
        assert_eq!(result.unwrap(), 42);
    }

    #[tokio::test]
    async fn test_ctx_cancelled_in_handler() {
        use crate::actor::cancel_after;

        struct CancelAwareActor;
        impl Actor for CancelAwareActor {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self {
                CancelAwareActor
            }
        }
        struct LongTask;
        impl Message for LongTask {
            type Reply = String;
        }
        #[async_trait]
        impl Handler<LongTask> for CancelAwareActor {
            async fn handle(&mut self, _: LongTask, ctx: &mut ActorContext) -> String {
                tokio::select! {
                    _ = tokio::time::sleep(Duration::from_secs(10)) => "completed".into(),
                    _ = ctx.cancelled() => "cancelled".into(),
                }
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<CancelAwareActor>("aware", ()).await.unwrap();
        let token = cancel_after(Duration::from_millis(50));
        let result = actor.ask(LongTask, Some(token)).unwrap().await.unwrap();
        assert_eq!(result, "cancelled");
    }

    #[tokio::test]
    async fn test_cancel_stream() {
        use crate::actor::cancel_after;
        use tokio_stream::StreamExt;

        struct SlowStreamer;
        impl Actor for SlowStreamer {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self {
                SlowStreamer
            }
        }
        struct StreamForever;
        impl Message for StreamForever {
            type Reply = u64;
        }
        #[async_trait]
        impl ExpandHandler<StreamForever, u64> for SlowStreamer {
            async fn handle_expand(
                &mut self,
                _msg: StreamForever,
                sender: StreamSender<u64>,
                _ctx: &mut ActorContext,
            ) {
                let mut i = 0u64;
                loop {
                    tokio::time::sleep(Duration::from_millis(20)).await;
                    if sender.send(i).await.is_err() {
                        break;
                    }
                    i += 1;
                }
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<SlowStreamer>("streamer", ()).await.unwrap();
        let token = cancel_after(Duration::from_millis(100));
        let mut stream = actor.expand(StreamForever, 4, None, Some(token)).unwrap();

        let mut items = Vec::new();
        while let Some(item) = stream.next().await {
            items.push(item);
        }
        // Stream should have ended due to cancellation — got some items but not infinite
        assert!(!items.is_empty());
        assert!(items.len() < 20);
    }

    #[tokio::test]
    async fn test_cancel_feed() {
        use crate::actor::cancel_after;

        struct FeedActor;
        impl Actor for FeedActor {
            type Args = ();
            type Deps = ();
            fn create(_: (), _: ()) -> Self {
                FeedActor
            }
        }
        #[async_trait]
        impl ReduceHandler<u64, Vec<u64>> for FeedActor {
            async fn handle_reduce(
                &mut self,
                mut receiver: StreamReceiver<u64>,
                _ctx: &mut ActorContext,
            ) -> Vec<u64> {
                let mut items = Vec::new();
                while let Some(item) = receiver.recv().await {
                    items.push(item);
                }
                items
            }
        }

        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<FeedActor>("feed-actor", ()).await.unwrap();

        // Create a slow infinite stream
        let input = futures::stream::unfold(0u64, |state| async move {
            tokio::time::sleep(Duration::from_millis(20)).await;
            Some((state, state + 1))
        });

        let token = cancel_after(Duration::from_millis(100));
        let result = actor
            .reduce::<u64, Vec<u64>>(Box::pin(input), 4, None, Some(token))
            .unwrap()
            .await;
        // The operation was cancelled — either we get a partial result or an error
        // When the dispatch loop's select fires cancellation, the handler future is dropped
        // and the caller receives an error (channel closed).
        match result {
            Ok(items) => {
                // If the handler finished before cancellation propagated, we get partial items
                assert!(!items.is_empty());
                assert!(items.len() < 20);
            }
            Err(_) => {
                // Cancellation dropped the handler before it could return
            }
        }
    }

    #[tokio::test]
    async fn test_cancelled_returns_pending_when_no_token() {
        // Verify that ctx.cancelled() never resolves when no token is set
        let ctx = ActorContext {
            actor_id: ActorId {
                node: NodeId("n1".into()),
                local: 1,
            },
            actor_name: "test".into(),
            send_mode: None,
            headers: Headers::new(),
            cancellation_token: None,
        };

        // cancelled() should not resolve — use select to prove it
        tokio::select! {
            _ = ctx.cancelled() => panic!("cancelled() should never resolve without a token"),
            _ = tokio::time::sleep(Duration::from_millis(50)) => {
                // expected: timeout wins because cancelled() returns pending
            }
        }
    }

    // ── Conformance suite ────────────────────────────────
    mod conformance_tests {
        use super::*;
        use crate::test_support::conformance;

        #[tokio::test]
        async fn conformance_tell_and_ask() {
            let runtime = TestRuntime::new();
            conformance::test_tell_and_ask(|name, init| {
                runtime.spawn::<conformance::ConformanceCounter>(name, init)
            })
            .await;
        }

        #[tokio::test]
        async fn conformance_message_ordering() {
            let runtime = TestRuntime::new();
            conformance::test_message_ordering(|name, init| {
                runtime.spawn::<conformance::ConformanceCounter>(name, init)
            })
            .await;
        }

        #[tokio::test]
        async fn conformance_ask_reply() {
            let runtime = TestRuntime::new();
            conformance::test_ask_reply(|name, init| {
                runtime.spawn::<conformance::ConformanceCounter>(name, init)
            })
            .await;
        }

        #[tokio::test]
        async fn conformance_stop() {
            let runtime = TestRuntime::new();
            conformance::test_stop(|name, init| {
                runtime.spawn::<conformance::ConformanceCounter>(name, init)
            })
            .await;
        }

        #[tokio::test]
        async fn conformance_unique_ids() {
            let runtime = TestRuntime::new();
            conformance::test_unique_ids(|name, init| {
                runtime.spawn::<conformance::ConformanceCounter>(name, init)
            })
            .await;
        }

        #[tokio::test]
        async fn conformance_actor_name() {
            let runtime = TestRuntime::new();
            conformance::test_actor_name(|name, init| {
                runtime.spawn::<conformance::ConformanceCounter>(name, init)
            })
            .await;
        }

        #[tokio::test]
        async fn conformance_stream_items() {
            let runtime = TestRuntime::new();
            conformance::test_stream_items(|name, init| {
                runtime.spawn::<conformance::ConformanceStreamer>(name, init)
            })
            .await;
        }

        #[tokio::test]
        async fn conformance_stream_empty() {
            let runtime = TestRuntime::new();
            conformance::test_stream_empty(|name, init| {
                runtime.spawn::<conformance::ConformanceStreamer>(name, init)
            })
            .await;
        }

        #[tokio::test]
        async fn conformance_feed_sum() {
            let runtime = TestRuntime::new();
            conformance::test_feed_sum(|name, init| {
                runtime.spawn::<conformance::ConformanceAggregator>(name, init)
            })
            .await;
        }

        #[tokio::test]
        async fn conformance_lifecycle_ordering() {
            let runtime = TestRuntime::new();
            conformance::test_lifecycle_ordering(|name, init| {
                runtime.spawn::<conformance::ConformanceLifecycle>(name, init)
            })
            .await;
        }

        #[tokio::test]
        async fn conformance_cancel_ask() {
            let runtime = TestRuntime::new();
            conformance::test_cancel_ask(|name, init| {
                runtime.spawn::<conformance::ConformanceCounter>(name, init)
            })
            .await;
        }

        #[tokio::test]
        async fn conformance_on_error_resume() {
            let runtime = TestRuntime::new();
            conformance::test_on_error_resume(|name, init| {
                runtime.spawn::<conformance::ConformanceResumeActor>(name, init)
            })
            .await;
        }

        // ── Conformance transform tests ───────────────────────────────────

        #[tokio::test]
        async fn conformance_transform_doubler() {
            let runtime = TestRuntime::new();
            conformance::test_transform_doubler(|name, init| {
                runtime.spawn::<conformance::ConformanceDoubler>(name, init)
            })
            .await;
        }

        #[tokio::test]
        async fn conformance_transform_empty() {
            let runtime = TestRuntime::new();
            conformance::test_transform_empty(|name, init| {
                runtime.spawn::<conformance::ConformanceDoubler>(name, init)
            })
            .await;
        }

        // ── Batched stream/feed integration tests ─────────────────────────

        #[tokio::test]
        async fn test_expand_batched_returns_items_in_order() {
            use crate::stream::BatchConfig;
            use tokio_stream::StreamExt;

            let runtime = TestRuntime::new();
            let server = runtime.spawn::<LogServer>(
                "logs-batched",
                vec!["a".into(), "b".into(), "c".into(), "d".into(), "e".into()],
            ).await.unwrap();

            let batch_config = BatchConfig::new(2, Duration::from_secs(10));
            let mut stream = server
                .expand(GetLogs, 16, Some(batch_config), None)
                .unwrap();
            let mut items = Vec::new();
            while let Some(item) = stream.next().await {
                items.push(item);
            }

            assert_eq!(items, vec!["a", "b", "c", "d", "e"]);
        }

        #[tokio::test]
        async fn test_reduce_batched_sum() {
            use crate::stream::BatchConfig;

            struct Summer;
            impl Actor for Summer {
                type Args = ();
                type Deps = ();
                fn create(_: (), _: ()) -> Self {
                    Summer
                }
            }

            #[async_trait]
            impl ReduceHandler<u64, u64> for Summer {
                async fn handle_reduce(
                    &mut self,
                    mut receiver: StreamReceiver<u64>,
                    _ctx: &mut ActorContext,
                ) -> u64 {
                    let mut total = 0u64;
                    while let Some(n) = receiver.recv().await {
                        total += n;
                    }
                    total
                }
            }

            let runtime = TestRuntime::new();
            let actor = runtime.spawn::<Summer>("sum-batched", ()).await.unwrap();

            let input = futures::stream::iter(vec![10u64, 20, 30, 40, 50]);
            let batch_config = BatchConfig::new(3, Duration::from_secs(10));
            let total = actor
                .reduce::<u64, u64>(Box::pin(input), 8, Some(batch_config), None)
                .unwrap()
                .await
                .unwrap();

            assert_eq!(total, 150);
        }
    }

    // -- F6: on_reply wiring test -------------------------------------------

    #[tokio::test]
    async fn test_outbound_on_reply_called_for_ask() {
        use std::sync::atomic::AtomicU64;

        struct ReplyObserver {
            call_count: Arc<AtomicU64>,
        }
        impl OutboundInterceptor for ReplyObserver {
            fn name(&self) -> &'static str {
                "reply-observer"
            }
            fn on_reply(
                &self,
                _ctx: &OutboundContext<'_>,
                _rh: &RuntimeHeaders,
                _headers: &Headers,
                outcome: &Outcome<'_>,
            ) {
                if matches!(outcome, Outcome::AskSuccess { .. }) {
                    self.call_count.fetch_add(1, Ordering::SeqCst);
                }
            }
        }

        let call_count = Arc::new(AtomicU64::new(0));
        let mut runtime = TestRuntime::new();
        runtime.add_outbound_interceptor(Box::new(ReplyObserver {
            call_count: call_count.clone(),
        }));

        let actor = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();
        actor.tell(Increment(42)).unwrap();

        let count = actor.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(count, 42);
        // on_reply should have been called exactly once
        tokio::time::sleep(Duration::from_millis(20)).await;
        assert_eq!(call_count.load(Ordering::SeqCst), 1);

        // Second ask
        let count2 = actor.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(count2, 42);
        tokio::time::sleep(Duration::from_millis(20)).await;
        assert_eq!(call_count.load(Ordering::SeqCst), 2);
    }

    // -- Dead letter handler tests ------------------------------------------

    #[tokio::test]
    async fn test_dead_letter_handler_on_stopped_actor_tell() {
        use crate::dead_letter::{CollectingDeadLetterHandler, DeadLetterReason};

        let collector = Arc::new(CollectingDeadLetterHandler::new());
        let mut runtime = TestRuntime::new();
        runtime.set_dead_letter_handler(collector.clone());

        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();
        counter.stop();
        tokio::time::sleep(Duration::from_millis(50)).await;

        let result = counter.tell(Increment(1));
        assert!(result.is_err());

        assert_eq!(collector.count(), 1);
        let events = collector.events();
        assert!(matches!(events[0].reason, DeadLetterReason::ActorStopped));
        assert_eq!(events[0].send_mode, SendMode::Tell);
        assert!(events[0].message_type.contains("Increment"));
    }

    #[tokio::test]
    async fn test_dead_letter_handler_on_stopped_actor_ask() {
        use crate::dead_letter::{CollectingDeadLetterHandler, DeadLetterReason};

        let collector = Arc::new(CollectingDeadLetterHandler::new());
        let mut runtime = TestRuntime::new();
        runtime.set_dead_letter_handler(collector.clone());

        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();
        counter.stop();
        tokio::time::sleep(Duration::from_millis(50)).await;

        let result = counter.ask(GetCount, None);
        assert!(result.is_err());

        assert_eq!(collector.count(), 1);
        let events = collector.events();
        assert!(matches!(events[0].reason, DeadLetterReason::ActorStopped));
        assert_eq!(events[0].send_mode, SendMode::Ask);
        assert!(events[0].message_type.contains("GetCount"));
    }

    #[tokio::test]
    async fn test_dead_letter_handler_on_inbound_interceptor_drop() {
        use crate::dead_letter::{CollectingDeadLetterHandler, DeadLetterReason};

        struct DropAllInterceptor;
        impl InboundInterceptor for DropAllInterceptor {
            fn name(&self) -> &'static str {
                "drop-all"
            }
            fn on_receive(
                &self,
                _ctx: &InboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &mut Headers,
                _msg: &dyn Any,
            ) -> Disposition {
                Disposition::Drop
            }
            fn on_complete(
                &self,
                _ctx: &InboundContext<'_>,
                _rh: &RuntimeHeaders,
                _h: &Headers,
                _outcome: &Outcome<'_>,
            ) {
            }
        }

        let collector = Arc::new(CollectingDeadLetterHandler::new());
        let mut runtime = TestRuntime::new();
        runtime.set_dead_letter_handler(collector.clone());

        let counter = runtime.spawn_with_options::<Counter>(
            "counter",
            Counter { count: 0 },
            SpawnOptions {
                interceptors: vec![Box::new(DropAllInterceptor)],
                ..Default::default()
            },
        ).await.unwrap();

        counter.tell(Increment(1)).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        assert_eq!(collector.count(), 1);
        let events = collector.events();
        match &events[0].reason {
            DeadLetterReason::DroppedByInterceptor { interceptor } => {
                assert_eq!(interceptor, "drop-all");
            }
            other => panic!("expected DroppedByInterceptor, got {:?}", other),
        }
        assert_eq!(events[0].send_mode, SendMode::Tell);
        assert!(events[0].message_type.contains("Increment"));
    }

    #[tokio::test]
    async fn test_dead_letter_collecting_handler_multiple_events() {
        use crate::dead_letter::{CollectingDeadLetterHandler, DeadLetterReason};

        let collector = Arc::new(CollectingDeadLetterHandler::new());
        let mut runtime = TestRuntime::new();
        runtime.set_dead_letter_handler(collector.clone());

        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();
        counter.stop();
        tokio::time::sleep(Duration::from_millis(50)).await;

        let _ = counter.tell(Increment(1));
        let _ = counter.tell(Increment(2));
        let _ = counter.ask(GetCount, None);

        assert_eq!(collector.count(), 3);
        let events = collector.events();
        assert!(events
            .iter()
            .all(|e| matches!(e.reason, DeadLetterReason::ActorStopped)));

        collector.clear();
        assert_eq!(collector.count(), 0);
    }

    // -- Built-in metrics integration tests --------------------------------

    #[cfg(feature = "metrics")]
    #[tokio::test]
    async fn test_metrics_enabled_tracks_messages() {
        let mut runtime = TestRuntime::new();
        runtime.enable_metrics();

        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();
        counter.tell(Increment(1)).unwrap();
        counter.tell(Increment(2)).unwrap();
        let _ = counter.ask(GetCount, None).unwrap().await.unwrap();

        let store = runtime.metrics().unwrap();
        assert_eq!(store.total_messages(), 3);
        assert_eq!(store.total_errors(), 0);
        assert_eq!(store.actor_count(), 1);
    }

    #[cfg(feature = "metrics")]
    #[tokio::test]
    async fn test_metrics_shared_across_actors() {
        let mut runtime = TestRuntime::new();
        runtime.enable_metrics();

        let a = runtime.spawn::<Counter>("a", Counter { count: 0 }).await.unwrap();
        let b = runtime.spawn::<Counter>("b", Counter { count: 0 }).await.unwrap();

        a.tell(Increment(1)).unwrap();
        b.tell(Increment(1)).unwrap();
        b.tell(Increment(2)).unwrap();

        // Wait for messages to be processed
        let _ = a.ask(GetCount, None).unwrap().await.unwrap();
        let _ = b.ask(GetCount, None).unwrap().await.unwrap();

        let store = runtime.metrics().unwrap();
        // 3 tells + 2 asks = 5 total messages, 2 actors
        assert_eq!(store.total_messages(), 5);
        assert_eq!(store.actor_count(), 2);
    }

    #[cfg(feature = "metrics")]
    #[tokio::test]
    async fn test_runtime_metrics_snapshot() {
        let mut runtime = TestRuntime::new();
        runtime.enable_metrics();

        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();
        counter.tell(Increment(1)).unwrap();
        let _ = counter.ask(GetCount, None).unwrap().await.unwrap();

        let snapshot = runtime.metrics().unwrap().runtime_metrics();
        assert_eq!(snapshot.actor_count, 1);
        assert_eq!(snapshot.total_messages, 2);
        assert_eq!(snapshot.total_errors, 0);
        assert!(snapshot.message_rate > 0.0);
        assert_eq!(snapshot.error_rate, 0.0);
        assert_eq!(snapshot.window, std::time::Duration::from_secs(60));
    }

    #[cfg(feature = "metrics")]
    #[tokio::test]
    async fn test_metrics_not_tracked_when_disabled() {
        let runtime = TestRuntime::new();
        assert!(runtime.metrics().is_none());

        let counter = runtime.spawn::<Counter>("counter", Counter { count: 0 }).await.unwrap();
        counter.tell(Increment(1)).unwrap();
        let _ = counter.ask(GetCount, None).unwrap().await.unwrap();

        // No metrics store — nothing to query
        assert!(runtime.metrics().is_none());
    }

    // -- Registry tests -----------------------------------------------------

    #[tokio::test]
    async fn test_registry_auto_register_on_spawn() {
        let runtime = TestRuntime::new();
        let _counter = runtime.spawn::<Counter>("my-counter", Counter { count: 0 }).await.unwrap();

        assert!(runtime.registry().contains("my-counter"));
        let looked_up: Option<TestActorRef<Counter>> = runtime.registry().lookup("my-counter");
        assert!(looked_up.is_some());
    }

    #[tokio::test]
    async fn test_registry_lookup_and_use() {
        let runtime = TestRuntime::new();
        let counter = runtime.spawn::<Counter>("counter-a", Counter { count: 0 }).await.unwrap();
        counter.tell(Increment(10)).unwrap();

        // Look up by name and send a message through the looked-up ref
        let looked_up: TestActorRef<Counter> = runtime.registry().lookup("counter-a").unwrap();
        looked_up.tell(Increment(5)).unwrap();

        let count = looked_up.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(count, 15);
    }

    #[tokio::test]
    async fn test_registry_lookup_wrong_type_returns_none() {
        let runtime = TestRuntime::new();
        let _counter = runtime.spawn::<Counter>("typed-actor", Counter { count: 0 }).await.unwrap();

        // Greeter is a different actor type — lookup should return None
        let wrong: Option<TestActorRef<Greeter>> = runtime.registry().lookup("typed-actor");
        assert!(wrong.is_none());
    }

    #[tokio::test]
    async fn test_registry_lookup_missing_name_returns_none() {
        let runtime = TestRuntime::new();
        let missing: Option<TestActorRef<Counter>> = runtime.registry().lookup("no-such-actor");
        assert!(missing.is_none());
    }

    #[tokio::test]
    async fn test_registry_unregister() {
        let runtime = TestRuntime::new();
        let _counter = runtime.spawn::<Counter>("removable", Counter { count: 0 }).await.unwrap();
        assert!(runtime.registry().contains("removable"));

        assert!(runtime.registry().unregister("removable"));
        assert!(!runtime.registry().contains("removable"));

        let gone: Option<TestActorRef<Counter>> = runtime.registry().lookup("removable");
        assert!(gone.is_none());
    }

    #[tokio::test]
    async fn test_registry_multiple_actors() {
        let runtime = TestRuntime::new();
        let _c1 = runtime.spawn::<Counter>("counter-1", Counter { count: 0 }).await.unwrap();
        let _c2 = runtime.spawn::<Counter>("counter-2", Counter { count: 100 }).await.unwrap();
        let _g = runtime.spawn::<Greeter>("greeter", ()).await.unwrap();

        assert_eq!(runtime.registry().len(), 3);

        let c1: TestActorRef<Counter> = runtime.registry().lookup("counter-1").unwrap();
        c1.tell(Increment(1)).unwrap();
        let v1 = c1.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(v1, 1);

        let c2: TestActorRef<Counter> = runtime.registry().lookup("counter-2").unwrap();
        let v2 = c2.ask(GetCount, None).unwrap().await.unwrap();
        assert_eq!(v2, 100);

        let g: TestActorRef<Greeter> = runtime.registry().lookup("greeter").unwrap();
        let reply = g.ask(Greet("World".into()), None).unwrap().await.unwrap();
        assert_eq!(reply, "Hello, World!");
    }

    // -- JH5: TestRuntime await_stop / await_all / cleanup_finished / active_handle_count --

    #[tokio::test]
    async fn jh5_await_stop_resolves_after_actor_stops() {
        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<Counter>("await-stop-actor", Counter { count: 0 }).await.unwrap();
        let actor_id = actor.id();

        actor.stop();
        let result = runtime.await_stop(&actor_id).await;
        assert!(result.is_ok());
        assert_eq!(runtime.active_handle_count(), 0);
    }

    #[tokio::test]
    async fn jh5_await_stop_unknown_id_returns_ok() {
        let runtime = TestRuntime::new();
        let fake_id = ActorId {
            node: NodeId("fake".into()),
            local: 999,
        };
        let result = runtime.await_stop(&fake_id).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn jh5_await_all_waits_for_all_actors() {
        let runtime = TestRuntime::new();
        let a1 = runtime.spawn::<Counter>("aa1", Counter { count: 0 }).await.unwrap();
        let a2 = runtime.spawn::<Counter>("aa2", Counter { count: 0 }).await.unwrap();
        let a3 = runtime.spawn::<Counter>("aa3", Counter { count: 0 }).await.unwrap();

        assert_eq!(runtime.active_handle_count(), 3);

        a1.stop();
        a2.stop();
        a3.stop();

        let result = runtime.await_all().await;
        assert!(result.is_ok());
        assert_eq!(runtime.active_handle_count(), 0);
    }

    #[tokio::test]
    async fn jh5_cleanup_finished_removes_stopped_actors() {
        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<Counter>("cleanup-test", Counter { count: 0 }).await.unwrap();
        assert_eq!(runtime.active_handle_count(), 1);

        actor.stop();
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        runtime.cleanup_finished();
        assert_eq!(runtime.active_handle_count(), 0);
    }

    #[tokio::test]
    async fn jh5_active_handle_count() {
        let runtime = TestRuntime::new();
        assert_eq!(runtime.active_handle_count(), 0);

        let _a = runtime.spawn::<Counter>("hc1", Counter { count: 0 }).await.unwrap();
        assert_eq!(runtime.active_handle_count(), 1);

        let _b = runtime.spawn::<Counter>("hc2", Counter { count: 0 }).await.unwrap();
        assert_eq!(runtime.active_handle_count(), 2);
    }

    struct PanickingActor;

    #[async_trait]
    impl Actor for PanickingActor {
        type Args = ();
        type Deps = ();
        fn create(_: (), _: ()) -> Self { PanickingActor }

        async fn on_stop(&mut self) {
            panic!("intentional on_stop panic");
        }
    }

    struct Ping;
    impl Message for Ping { type Reply = (); }

    #[async_trait]
    impl Handler<Ping> for PanickingActor {
        async fn handle(&mut self, _msg: Ping, _ctx: &mut ActorContext) {}
    }

    #[tokio::test]
    async fn jh5_panic_propagated_through_await_stop() {
        let runtime = TestRuntime::new();
        let actor = runtime.spawn::<PanickingActor>("panic-actor", ()).await.unwrap();
        let actor_id = actor.id();

        actor.stop();
        let result = runtime.await_stop(&actor_id).await;
        assert!(result.is_err(), "expected error from panicking on_stop");
    }
}