asupersync 0.3.4

Spec-first, cancel-correct, capability-secure async runtime for 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
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
//! Symbol broadcast cancellation protocol implementation.
//!
//! Provides [`SymbolCancelToken`] for embedding cancellation in symbol metadata,
//! [`CancelMessage`] for broadcast propagation, [`CancelBroadcaster`] for
//! coordinating cancellation across peers, and [`CleanupCoordinator`] for
//! managing partial symbol set cleanup.

use core::fmt;
use parking_lot::RwLock;
use smallvec::SmallVec;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

use crate::types::symbol::{ObjectId, Symbol};
use crate::types::{Budget, CancelAttributionConfig, CancelKind, CancelReason, Time};
use crate::util::DetRng;

// ============================================================================
// CancelKind wire-format helpers
// ============================================================================

fn cancel_kind_to_u8(kind: CancelKind) -> u8 {
    match kind {
        CancelKind::User => 0,
        CancelKind::Timeout => 1,
        CancelKind::Deadline => 2,
        CancelKind::PollQuota => 3,
        CancelKind::CostBudget => 4,
        CancelKind::FailFast => 5,
        CancelKind::RaceLost => 6,
        CancelKind::ParentCancelled => 7,
        CancelKind::ResourceUnavailable => 8,
        CancelKind::Shutdown => 9,
        CancelKind::LinkedExit => 10,
    }
}

fn cancel_kind_from_u8(b: u8) -> Option<CancelKind> {
    match b {
        0 => Some(CancelKind::User),
        1 => Some(CancelKind::Timeout),
        2 => Some(CancelKind::Deadline),
        3 => Some(CancelKind::PollQuota),
        4 => Some(CancelKind::CostBudget),
        5 => Some(CancelKind::FailFast),
        6 => Some(CancelKind::RaceLost),
        7 => Some(CancelKind::ParentCancelled),
        8 => Some(CancelKind::ResourceUnavailable),
        9 => Some(CancelKind::Shutdown),
        10 => Some(CancelKind::LinkedExit),
        _ => None,
    }
}

// ============================================================================
// Cancel Listener
// ============================================================================

/// Trait for cancellation listeners.
pub trait CancelListener: Send + Sync {
    /// Called when cancellation is requested.
    fn on_cancel(&self, reason: &CancelReason, at: Time);
}

impl<F> CancelListener for F
where
    F: Fn(&CancelReason, Time) + Send + Sync,
{
    fn on_cancel(&self, reason: &CancelReason, at: Time) {
        self(reason, at);
    }
}

// ============================================================================
// SymbolCancelToken
// ============================================================================

/// Internal shared state for a cancellation token.
struct CancelTokenState {
    /// Unique token ID.
    token_id: u64,
    /// The object this token relates to.
    object_id: ObjectId,
    /// Whether cancellation has been requested.
    cancelled: AtomicBool,
    /// When cancellation was requested (nanos since epoch).
    /// `u64::MAX` is the "not yet recorded" sentinel; legitimate timestamps
    /// are clamped to `u64::MAX - 1` at store time so the sentinel cannot
    /// collide with a real cancellation time.
    cancelled_at: AtomicU64,
    /// The cancellation reason (set when cancelled).
    reason: RwLock<Option<CancelReason>>,
    /// Cleanup budget for this cancellation.
    cleanup_budget: Budget,
    /// Child tokens (for hierarchical cancellation).
    children: RwLock<SmallVec<[SymbolCancelToken; 2]>>,
    /// Listeners to notify on cancellation.
    ///
    /// br-asupersync-frm9u9: listeners are retained (not drained) after
    /// the first cancel so a later `cancel()` whose reason strictly
    /// strengthens the stored severity (e.g., Timeout → Shutdown) can
    /// re-fire them with the new reason. The `notified_severity` field
    /// below records the highest severity each listener has already
    /// observed so re-notification is monotone — listeners only see
    /// progressively-stronger reasons, never the same severity twice.
    listeners: RwLock<SmallVec<[ListenerEntry; 2]>>,
    /// br-asupersync-mzamuo — Count of listener `on_cancel` callbacks
    /// (and listener-Drop side effects routed through them) that
    /// panicked and were caught via `catch_unwind`. Surfaced via
    /// [`SymbolCancelToken::listener_panic_count`] so silently-
    /// swallowed listener-reentrancy panics become observable
    /// instead of remaining invisible. Every such panic also emits
    /// a `tracing::warn!` (when the `tracing-integration` feature
    /// is on) carrying the panic message.
    listener_panic_count: AtomicU64,
}

/// One registered cancel listener plus the severity at which it was
/// most recently notified. `0` means the listener has not yet been
/// notified (e.g., registered while `cancelled == false`).
struct ListenerEntry {
    listener: Box<dyn CancelListener>,
    /// Last severity the listener was notified at. Updated under the
    /// `listeners` write lock + `reason` write lock to keep the
    /// "every listener saw at least the current stored reason"
    /// invariant.
    notified_severity: u8,
}

/// A cancellation token that can be embedded in symbol metadata.
///
/// Tokens are lightweight identifiers that reference a shared cancellation
/// state. They can be cloned and distributed across symbol transmissions.
/// When cancelled, all children and listeners are notified.
#[derive(Clone)]
pub struct SymbolCancelToken {
    /// Shared state for this cancellation token.
    state: Arc<CancelTokenState>,
}

impl SymbolCancelToken {
    /// Creates a new cancellation token for an object.
    #[must_use]
    pub fn new(object_id: ObjectId, rng: &mut DetRng) -> Self {
        Self {
            state: Arc::new(CancelTokenState {
                token_id: rng.next_u64(),
                object_id,
                cancelled: AtomicBool::new(false),
                cancelled_at: AtomicU64::new(u64::MAX),
                reason: RwLock::new(None),
                cleanup_budget: Budget::default(),
                children: RwLock::new(SmallVec::new()),
                listeners: RwLock::new(SmallVec::new()),
                listener_panic_count: AtomicU64::new(0),
            }),
        }
    }

    /// Creates a token with a specific cleanup budget.
    #[must_use]
    pub fn with_budget(object_id: ObjectId, budget: Budget, rng: &mut DetRng) -> Self {
        Self {
            state: Arc::new(CancelTokenState {
                token_id: rng.next_u64(),
                object_id,
                cancelled: AtomicBool::new(false),
                cancelled_at: AtomicU64::new(u64::MAX),
                reason: RwLock::new(None),
                cleanup_budget: budget,
                children: RwLock::new(SmallVec::new()),
                listeners: RwLock::new(SmallVec::new()),
                listener_panic_count: AtomicU64::new(0),
            }),
        }
    }

    /// br-asupersync-mzamuo — Number of listener `on_cancel` calls
    /// that panicked and were recovered via `catch_unwind`. A
    /// non-zero value indicates that a listener (or its Drop impl)
    /// raised a panic during cancel notification — most commonly a
    /// listener whose Drop re-entered the originating token's cancel
    /// path. The runtime keeps running because of the `catch_unwind`
    /// guard, but operators can poll this counter to detect the
    /// invariant violation that would otherwise be silenced.
    #[must_use]
    pub fn listener_panic_count(&self) -> u64 {
        self.state.listener_panic_count.load(Ordering::Relaxed)
    }

    fn record_listener_panic(
        state: &CancelTokenState,
        panic_payload: Box<dyn std::any::Any + Send>,
    ) {
        // Always increment the counter first - this is the most critical operation
        // and least likely to panic (atomic operation on existing memory)
        state.listener_panic_count.fetch_add(1, Ordering::Relaxed);

        // Protect tracing operations from double-panic by wrapping in catch_unwind
        #[cfg(feature = "tracing-integration")]
        {
            let _trace_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                let panic_msg = if let Some(s) = panic_payload.downcast_ref::<&str>() {
                    (*s).to_string()
                } else if let Some(s) = panic_payload.downcast_ref::<String>() {
                    s.clone()
                } else {
                    "<non-string panic payload>".to_string()
                };
                tracing::warn!(
                    object_id = ?state.object_id,
                    token_id = state.token_id,
                    panic = %panic_msg,
                    "cancel listener panicked during on_cancel — caught and logged \
                     instead of silently swallowed (br-asupersync-mzamuo)"
                );
            }));
            // If tracing itself panics, silently continue - we've already recorded the count
        }
        #[cfg(not(feature = "tracing-integration"))]
        {
            let _ = panic_payload;
        }
    }

    /// br-asupersync-mzamuo — Invoke a listener's `on_cancel` under
    /// `catch_unwind`. On panic, increment the per-token listener-
    /// panic counter and emit a `tracing::warn!`. Replaces the
    /// previous bare `let _ = catch_unwind(...)` shape that silently
    /// swallowed every panic, masking listener-Drop re-entrancy bugs
    /// (the scenario the bead exists to surface).
    fn notify_listener_with_panic_logging(
        state: &CancelTokenState,
        listener: &dyn CancelListener,
        reason: &CancelReason,
        now: Time,
    ) {
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            listener.on_cancel(reason, now);
        }));
        if let Err(panic_payload) = result {
            Self::record_listener_panic(state, panic_payload);
        }
    }

    /// Late-add listeners are not retained, so this variant also
    /// covers any panic in the listener's `Drop` path by ensuring the
    /// owned box is dropped inside the `catch_unwind` boundary.
    fn notify_owned_listener_with_panic_logging(
        state: &CancelTokenState,
        listener: Box<dyn CancelListener>,
        reason: &CancelReason,
        now: Time,
    ) {
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
            listener.on_cancel(reason, now);
            drop(listener);
        }));
        if let Err(panic_payload) = result {
            Self::record_listener_panic(state, panic_payload);
        }
    }

    fn notify_retained_listeners_until_current(
        state: &CancelTokenState,
        target_reason: &CancelReason,
        target_severity: u8,
        force_target_notification: bool,
    ) {
        let notify_at_nanos = state.cancelled_at.load(Ordering::Acquire);
        let notify_at = if notify_at_nanos == u64::MAX {
            Time::ZERO
        } else {
            Time::from_nanos(notify_at_nanos)
        };
        let mut retained = {
            let mut listeners = state.listeners.write();
            std::mem::take(&mut *listeners)
        };

        for entry in &mut retained {
            if force_target_notification || entry.notified_severity < target_severity {
                Self::notify_listener_with_panic_logging(
                    state,
                    entry.listener.as_ref(),
                    target_reason,
                    notify_at,
                );
                entry.notified_severity = target_severity;
            }
        }

        // br-asupersync-4txkrb: Bound iteration count to prevent livelock
        // if concurrent threads keep strengthening the reason. After MAX_CATCH_UP_ITERATIONS
        // we yield and use snapshot semantics to avoid chasing a moving target.
        const MAX_CATCH_UP_ITERATIONS: u32 = 8;

        for iteration in 0..MAX_CATCH_UP_ITERATIONS {
            let reason_guard = state.reason.write();
            let Some(current_reason) = reason_guard.clone() else {
                let mut listeners = state.listeners.write();
                listeners.extend(retained);
                return;
            };
            let current_severity = current_reason.kind.severity();
            if retained
                .iter()
                .all(|entry| entry.notified_severity >= current_severity)
            {
                let mut listeners = state.listeners.write();
                listeners.extend(retained);
                return;
            }
            drop(reason_guard);

            for entry in &mut retained {
                if entry.notified_severity < current_severity {
                    Self::notify_listener_with_panic_logging(
                        state,
                        entry.listener.as_ref(),
                        &current_reason,
                        notify_at,
                    );
                    entry.notified_severity = current_severity;
                }
            }

            // Yield after each iteration except the last to allow other threads to progress
            if iteration < MAX_CATCH_UP_ITERATIONS - 1 {
                // Use cooperative yielding hint instead of async yield to avoid
                // changing function signature and breaking callers
                std::hint::spin_loop();
            }
        }

        // If we reach here, we've hit the iteration limit. Use snapshot semantics:
        // notify listeners with the final observed severity and return. This prevents
        // livelock while ensuring listeners see a reasonably recent severity level.
        let final_reason = {
            let reason_guard = state.reason.write();
            reason_guard
                .clone()
                .unwrap_or_else(CancelReason::parent_cancelled)
        };
        let final_severity = final_reason.kind.severity();

        for entry in &mut retained {
            if entry.notified_severity < final_severity {
                Self::notify_listener_with_panic_logging(
                    state,
                    entry.listener.as_ref(),
                    &final_reason,
                    notify_at,
                );
                entry.notified_severity = final_severity;
            }
        }

        // Restore retained listeners to the listener slab
        let mut listeners = state.listeners.write();
        listeners.extend(retained);
    }

    /// Returns the token ID.
    #[inline]
    #[must_use]
    pub fn token_id(&self) -> u64 {
        self.state.token_id
    }

    /// Returns the object ID this token relates to.
    #[inline]
    #[must_use]
    pub fn object_id(&self) -> ObjectId {
        self.state.object_id
    }

    /// Returns true if cancellation has been requested.
    #[inline]
    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.state.cancelled.load(Ordering::Acquire)
    }

    /// Returns the cancellation reason, if cancelled.
    #[must_use]
    pub fn reason(&self) -> Option<CancelReason> {
        self.state.reason.read().clone()
    }

    /// Returns when cancellation was requested, if cancelled.
    #[inline]
    #[must_use]
    pub fn cancelled_at(&self) -> Option<Time> {
        let nanos = self.state.cancelled_at.load(Ordering::Acquire);
        if nanos == u64::MAX {
            if self.is_cancelled() {
                // If it's cancelled but nanos is u64::MAX, we caught it in the middle of
                // the cancel() function. Wait for the reason lock to ensure
                // the cancel() function has finished updating cancelled_at.
                let _guard = self.state.reason.read();
                let nanos_sync = self.state.cancelled_at.load(Ordering::Acquire);
                if nanos_sync == u64::MAX {
                    None // Should only happen if parsed from bytes and reason never set
                } else {
                    Some(Time::from_nanos(nanos_sync))
                }
            } else {
                None
            }
        } else {
            Some(Time::from_nanos(nanos))
        }
    }

    /// Returns the cleanup budget.
    #[must_use]
    pub fn cleanup_budget(&self) -> Budget {
        self.state.cleanup_budget
    }

    fn parent_cancelled_with_cause(parent_reason: &CancelReason, at: Time) -> CancelReason {
        CancelReason::parent_cancelled()
            .with_timestamp(at)
            .with_cause_limited(parent_reason.clone(), &CancelAttributionConfig::default())
    }

    fn parent_cascade_reason_at(&self, at: Time) -> CancelReason {
        self.state.reason.read().as_ref().map_or_else(
            || CancelReason::parent_cancelled().with_timestamp(at),
            |reason| Self::parent_cancelled_with_cause(reason, at),
        )
    }

    /// Requests cancellation with the given reason.
    ///
    /// Returns true if this call triggered the cancellation (first caller wins).
    ///
    /// # Listener re-notification on strengthened reason
    /// (br-asupersync-frm9u9)
    ///
    /// Listeners are retained across cancel calls (not drained on the
    /// first call). On the first call, every listener is notified with
    /// the supplied reason. On subsequent calls, the stored reason is
    /// strengthened via `CancelReason::strengthen`; if the strengthen
    /// strictly raised severity, every listener whose most-recently-
    /// notified severity is now below the new severity is re-notified
    /// with the strengthened reason. A listener is therefore guaranteed
    /// to observe at least the strongest cancel kind that ever arrived,
    /// in monotone order — same severity is never delivered twice.
    #[allow(clippy::must_use_candidate)]
    pub fn cancel(&self, reason: &CancelReason, now: Time) -> bool {
        // Hold the reason lock to serialize updates and ensure visibility consistency.
        // This prevents a race where a listener observes cancelled=true but reason=None.
        let mut reason_guard = self.state.reason.write();

        if self
            .state
            .cancelled
            .compare_exchange(false, true, Ordering::Release, Ordering::Acquire)
            .is_ok()
        {
            // We won the race. State is now cancelled.
            // Clamp to u64::MAX - 1 to avoid colliding with the
            // "not yet recorded" sentinel in cancelled_at queries.
            let stored_nanos = now.as_nanos().min(u64::MAX - 1);
            self.state
                .cancelled_at
                .store(stored_nanos, Ordering::Release);
            *reason_guard = Some(reason.clone());

            // Drop the reason lock before notifying to avoid reentrancy
            // deadlocks. Retained listeners are moved out of the listener
            // slab before callbacks run, then reinserted after catching up
            // to any concurrently strengthened reason. This lets a listener
            // re-enter `add_listener`: the late listener self-notifies via
            // the post-cancel path and is not retained.
            drop(reason_guard);

            let new_severity = reason.kind.severity();
            Self::notify_retained_listeners_until_current(&self.state, reason, new_severity, true);

            // Drain children without holding the lock. Safe because
            // `cancelled` is already true (CAS above), so any concurrent
            // `child()` will observe the flag and cancel directly instead
            // of pushing into this vec.
            let children = {
                let mut children = self.state.children.write();
                std::mem::take(&mut *children)
            };
            let parent_reason = self.parent_cascade_reason_at(now);
            for child in children {
                child.cancel(&parent_reason, now);
            }

            true
        } else {
            // Already cancelled. Strengthen the stored reason if the new
            // one is more severe, preserving the monotone-severity
            // invariant required by the cancellation protocol.
            //
            // Since we hold the write lock, and the winner releases the lock
            // only after writing Some(reason), we are guaranteed to see
            // the existing reason here.
            let prior_severity;
            let strengthened_reason;
            if let Some(ref mut stored) = *reason_guard {
                prior_severity = stored.kind.severity();
                stored.strengthen(reason);
                strengthened_reason = stored.clone();
            } else {
                // Unreachable under the new locking protocol; handle
                // safely for the from_bytes-then-cancel edge.
                prior_severity = 0;
                *reason_guard = Some(reason.clone());
                strengthened_reason = reason.clone();
                let stored_nanos = now.as_nanos().min(u64::MAX - 1);
                self.state
                    .cancelled_at
                    .compare_exchange(u64::MAX, stored_nanos, Ordering::Release, Ordering::Relaxed)
                    .ok();
            }
            let new_severity = strengthened_reason.kind.severity();

            drop(reason_guard);

            // br-asupersync-frm9u9: re-notify any listener whose last
            // observed severity is strictly below the new (strengthened)
            // severity. Listeners that already saw an equal-or-stronger
            // reason are skipped to keep delivery monotone and
            // idempotent at each severity level.
            if new_severity > prior_severity {
                Self::notify_retained_listeners_until_current(
                    &self.state,
                    &strengthened_reason,
                    new_severity,
                    false,
                );
            }

            false
        }
    }

    /// Returns the cancellation timestamp to inherit in `child()`
    /// after `cancelled == true` has been observed under the
    /// `children` lock.
    ///
    /// br-asupersync-n1a1br: if a local `cancel()` is in flight, the
    /// flag can become visible before `cancelled_at` is written. In
    /// that window the reason write lock is still held, so `try_read`
    /// fails and we spin until the timestamp is published. For
    /// deserialized remote tokens (`from_bytes`) there is no local
    /// writer and `reason == None`, so the fallback remains
    /// `Time::ZERO`.
    fn cancelled_at_snapshot_for_child(&self) -> Option<Time> {
        if !self.is_cancelled() {
            return None;
        }

        // br-asupersync-wze4x9: Replace infinite spin with bounded retry + yield
        // to prevent livelock under thread contention. The race window should
        // resolve quickly under normal circumstances.
        const MAX_RETRIES: u32 = 1000;
        for _attempt in 0..MAX_RETRIES {
            let nanos = self.state.cancelled_at.load(Ordering::Acquire);
            if nanos != u64::MAX {
                return Some(Time::from_nanos(nanos));
            }

            if let Some(reason_guard) = self.state.reason.try_read() {
                if reason_guard.is_none() {
                    return Some(Time::ZERO);
                }

                let synced = self.state.cancelled_at.load(Ordering::Acquire);
                debug_assert_ne!(
                    synced,
                    u64::MAX,
                    "cancelled_at must be published before reason write lock is released"
                );
                return Some(if synced == u64::MAX {
                    Time::ZERO
                } else {
                    Time::from_nanos(synced)
                });
            }

            // Yield control instead of spinning to prevent livelock
            std::thread::sleep(std::time::Duration::from_nanos(100));
        }

        // If we exceed retry limit, fall back to Time::ZERO (cancelled but unknown timestamp)
        // This should be extremely rare and indicates a pathological contention scenario.
        Some(Time::ZERO)
    }

    /// Creates a child token linked to this one.
    ///
    /// When this token is cancelled, the child is also cancelled.
    #[must_use]
    pub fn child(&self, rng: &mut DetRng) -> Self {
        let child = Self::new(self.state.object_id, rng);

        // Hold the children lock across the cancelled check to avoid a TOCTOU
        // race: cancel() sets the `cancelled` flag (Release) *before* reading
        // children, so if we observe !cancelled (Acquire) under the write lock
        // the subsequent cancel() will see our child when it reads the list.
        //
        // br-asupersync-7yjuw7: Fix race condition where a child could be added
        // after parent cancellation. The original code dropped the children lock
        // and re-acquired it, creating a window where cancellation could complete
        // between the two lock acquisitions. Fixed by holding children lock during
        // the entire cancelled_at check sequence to ensure atomicity.
        let mut children = self.state.children.write();
        if !self.state.cancelled.load(Ordering::Acquire) {
            children.push(child.clone());
            return child;
        }

        // Parent is cancelled. Drop the children lock before waiting for timestamp
        // to avoid blocking other child creation during the timestamp resolution.
        drop(children);

        if let Some(at) = self.cancelled_at_snapshot_for_child() {
            let parent_reason = self.parent_cascade_reason_at(at);
            child.cancel(&parent_reason, at);
        } else {
            // Timestamp not yet available. Re-acquire children lock and check again.
            // This ensures we don't add a child if cancellation completed while
            // we were waiting for the timestamp.
            let mut children = self.state.children.write();
            if !self.state.cancelled.load(Ordering::Acquire) {
                children.push(child.clone());
            } else {
                // Parent became fully cancelled while we waited. Cancel the child.
                drop(children);
                // Wait for timestamp with exponential backoff to avoid busy spinning
                let mut backoff_ms = 1;
                for _ in 0..10 {
                    if let Some(at) = self.cancelled_at_snapshot_for_child() {
                        let parent_reason = self.parent_cascade_reason_at(at);
                        child.cancel(&parent_reason, at);
                        break;
                    }
                    std::thread::sleep(std::time::Duration::from_millis(backoff_ms));
                    backoff_ms = (backoff_ms * 2).min(16);
                }
            }
        }

        child
    }

    /// Adds a listener to be notified on cancellation.
    ///
    /// # Race-free reason snapshot (br-asupersync-2bm1a3)
    ///
    /// Previous behaviour: `add_listener` checked `is_cancelled()`, then
    /// dropped the listeners lock and called `self.reason()` which only
    /// took a *read* lock. Between `cancel()`'s release of the
    /// `cancelled` Release-CAS and its write of the reason under the
    /// `reason.write()` lock, a racing `add_listener` could observe
    /// `cancelled == true` but read `reason() == None`. The fallback
    /// `unwrap_or_else(|| CancelReason::new(CancelKind::User))` then
    /// fabricated a `CancelKind::User @ Time::ZERO` notification — a
    /// silent protocol-misclassification (a cleanup handler that
    /// distinguishes `User` from `Timeout`/`Shutdown` would route the
    /// task down the wrong branch).
    ///
    /// New behaviour: this method takes the `reason.write()` lock
    /// itself, mirroring the discipline `cancel()` uses. Either it
    /// observes `cancelled == false` and pushes the listener (cancel
    /// will pick it up under the same lock), or it observes
    /// `cancelled == true` AND finds the stored reason already
    /// written. If the stored reason is `None` despite `cancelled == true`
    /// (the valid `from_bytes` round-trip shape where `cancel()` was never
    /// called locally), the function falls back to the parent-cancel reason —
    /// never fabricates a `CancelKind::User`.
    pub fn add_listener(&self, listener: impl CancelListener + 'static) {
        // Take the reason lock first (mirrors cancel()'s ordering:
        // reason → listeners → drop reason → take listeners). Holding
        // the reason lock here makes the cancelled-check race-free:
        // cancel() can only flip `cancelled` while holding this same
        // write lock, so we either see (false, _) or (true, Some(_)).
        let reason_guard = self.state.reason.write();
        let mut listeners = self.state.listeners.write();
        if self.state.cancelled.load(Ordering::Acquire) {
            // We're cancelled. The reason MUST be Some at this point
            // because cancel() writes the reason under this same
            // write lock before flipping the cancelled flag (CAS at
            // line ~218 with the reason write held). The from_bytes
            // path is the only way to reach Some(cancelled)+None
            // (parsed-from-wire token never had cancel() called
            // locally); in that case fall back to parent_cancelled
            // — never to the silent CancelKind::User fabrication.
            let reason = reason_guard
                .clone()
                .unwrap_or_else(CancelReason::parent_cancelled);
            let at_nanos = self.state.cancelled_at.load(Ordering::Acquire);
            debug_assert!(
                at_nanos != u64::MAX || reason_guard.is_none(),
                "add_listener must not observe reason=Some(_) with unpublished cancelled_at"
            );
            let at = if at_nanos == u64::MAX {
                Time::ZERO
            } else {
                Time::from_nanos(at_nanos)
            };
            // Drop both locks before invoking the listener so a
            // listener that re-enters the token (e.g., to read
            // reason()) does not deadlock on this thread. The
            // listener fires synchronously on the calling thread
            // here and is NOT retained — re-notification on a later
            // strengthen does not apply to listeners added after
            // cancel completed. This mirrors the pre-fix
            // post-cancel-add semantic; documented in the
            // type-level rustdoc.
            drop(listeners);
            drop(reason_guard);
            // br-asupersync-mzamuo — same panic-logging discipline as
            // the cancel/strengthen paths. The listener is not boxed
            // here so we route through the helper via a transient
            // Box<dyn> indirection; the cost is amortised because
            // this path only runs on add-after-cancel.
            let boxed: Box<dyn CancelListener> = Box::new(listener);
            Self::notify_owned_listener_with_panic_logging(&self.state, boxed, &reason, at);
        } else {
            listeners.push(ListenerEntry {
                listener: Box::new(listener),
                notified_severity: 0,
            });
            drop(listeners);
            drop(reason_guard);
        }
    }

    /// Serializes the token for embedding in symbol metadata.
    ///
    /// Wire format (25 bytes): token_id(8) + object_high(8) + object_low(8) + cancelled(1).
    #[must_use]
    pub fn to_bytes(&self) -> [u8; TOKEN_WIRE_SIZE] {
        let mut buf = [0u8; TOKEN_WIRE_SIZE];

        buf[0..8].copy_from_slice(&self.state.token_id.to_be_bytes());
        buf[8..16].copy_from_slice(&self.state.object_id.high().to_be_bytes());
        buf[16..24].copy_from_slice(&self.state.object_id.low().to_be_bytes());
        buf[24] = u8::from(self.is_cancelled());

        buf
    }

    /// Deserializes a token from bytes.
    ///
    /// Note: This creates a new token state; it does not link to the original.
    #[must_use]
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() < TOKEN_WIRE_SIZE {
            return None;
        }

        let token_id = u64::from_be_bytes(data[0..8].try_into().ok()?);
        let high = u64::from_be_bytes(data[8..16].try_into().ok()?);
        let low = u64::from_be_bytes(data[16..24].try_into().ok()?);
        let cancelled = data[24] != 0;

        Some(Self {
            state: Arc::new(CancelTokenState {
                token_id,
                object_id: ObjectId::new(high, low),
                cancelled: AtomicBool::new(cancelled),
                cancelled_at: AtomicU64::new(u64::MAX),
                reason: RwLock::new(None),
                cleanup_budget: Budget::default(),
                children: RwLock::new(SmallVec::new()),
                listeners: RwLock::new(SmallVec::new()),
                listener_panic_count: AtomicU64::new(0),
            }),
        })
    }

    /// Creates a token for testing.
    ///
    /// br-asupersync-wm9h2a: previously this was an unconditionally
    /// `pub` constructor — gated only by `#[doc(hidden)]`, which
    /// hides the method from rustdoc but does NOT prevent production
    /// callers from invoking it. That left an open capability-
    /// boundary hole: any code in the dependency graph could mint a
    /// `SymbolCancelToken` with arbitrary `(token_id, object_id)`
    /// values, bypass the `CancelBroadcaster::register` /
    /// `prepare_cancel` issuance path, and forge cancels for objects
    /// it never owned. The asupersync 'no ambient authority'
    /// invariant requires every capability-bearing token to flow
    /// through an explicit issuance ceremony.
    ///
    /// br-asupersync-evpqdt — the wm9h2a fix originally gated this
    /// behind `#[cfg(any(test, feature = "test-internals"))]`. That
    /// gate was ILLUSORY in default builds because Cargo.toml has
    /// `default = ["test-internals", "proc-macros"]` — `test-internals`
    /// is enabled by default for any consumer who adds asupersync to
    /// their `Cargo.toml` without `default-features = false`. The
    /// constructor remained freely callable from any external crate,
    /// reopening the exact forgery surface wm9h2a was supposed to
    /// close.
    ///
    /// The current gate is `#[cfg(test)]` only — strict in-crate
    /// test compilation. External crates that need to mint synthetic
    /// `SymbolCancelToken` values for their own tests must go
    /// through the legitimate issuance ceremony
    /// (`CancelBroadcaster::register` / `prepare_cancel`); there is
    /// no longer any cross-crate-reachable forgery path. The only
    /// internal callers are the wm9h2a regression test and the
    /// listener-uniqueness test inside this file.
    #[doc(hidden)]
    #[must_use]
    #[cfg(test)]
    pub fn new_for_test(token_id: u64, object_id: ObjectId) -> Self {
        Self {
            state: Arc::new(CancelTokenState {
                token_id,
                object_id,
                cancelled: AtomicBool::new(false),
                cancelled_at: AtomicU64::new(u64::MAX),
                reason: RwLock::new(None),
                cleanup_budget: Budget::default(),
                children: RwLock::new(SmallVec::new()),
                listeners: RwLock::new(SmallVec::new()),
                listener_panic_count: AtomicU64::new(0),
            }),
        }
    }
}

impl fmt::Debug for SymbolCancelToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SymbolCancelToken")
            .field("token_id", &format!("{:016x}", self.state.token_id))
            .field("object_id", &self.state.object_id)
            .field("cancelled", &self.is_cancelled())
            .finish()
    }
}

/// Token wire format size: token_id(8) + high(8) + low(8) + cancelled(1) = 25.
const TOKEN_WIRE_SIZE: usize = 25;

// ============================================================================
// CancelMessage
// ============================================================================

/// A cancellation message that can be broadcast to peers.
///
/// Messages include a hop counter to prevent infinite propagation and a
/// sequence number for deduplication.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CancelMessage {
    /// The token ID being cancelled.
    token_id: u64,
    /// The object ID being cancelled.
    object_id: ObjectId,
    /// The cancellation kind.
    kind: CancelKind,
    /// When the cancellation was initiated.
    initiated_at: Time,
    /// Sequence number for deduplication.
    sequence: u64,
    /// Hop count (for limiting propagation).
    hops: u8,
    /// Maximum hops allowed.
    max_hops: u8,
}

/// Message wire format size: token_id(8) + high(8) + low(8) + kind(1) +
/// initiated_at(8) + sequence(8) + hops(1) + max_hops(1) = 43.
const MESSAGE_WIRE_SIZE: usize = 43;

impl CancelMessage {
    /// Creates a new cancellation message.
    #[must_use]
    pub fn new(
        token_id: u64,
        object_id: ObjectId,
        kind: CancelKind,
        initiated_at: Time,
        sequence: u64,
    ) -> Self {
        Self {
            token_id,
            object_id,
            kind,
            initiated_at,
            sequence,
            hops: 0,
            max_hops: 10,
        }
    }

    /// Returns the token ID.
    #[inline]
    #[must_use]
    pub const fn token_id(&self) -> u64 {
        self.token_id
    }

    /// Returns the object ID.
    #[inline]
    #[must_use]
    pub const fn object_id(&self) -> ObjectId {
        self.object_id
    }

    /// Returns the cancellation kind.
    #[inline]
    #[must_use]
    pub const fn kind(&self) -> CancelKind {
        self.kind
    }

    /// Returns when the cancellation was initiated.
    #[inline]
    #[must_use]
    pub const fn initiated_at(&self) -> Time {
        self.initiated_at
    }

    /// Returns the sequence number.
    #[inline]
    #[must_use]
    pub const fn sequence(&self) -> u64 {
        self.sequence
    }

    /// Returns the current hop count.
    #[inline]
    #[must_use]
    pub const fn hops(&self) -> u8 {
        self.hops
    }

    /// Returns true if the message can be forwarded (not at max hops).
    #[inline]
    #[must_use]
    pub const fn can_forward(&self) -> bool {
        self.hops < self.max_hops
    }

    /// Creates a forwarded copy with incremented hop count.
    #[must_use]
    pub fn forwarded(&self) -> Option<Self> {
        if !self.can_forward() {
            return None;
        }

        Some(Self {
            hops: self.hops + 1,
            ..self.clone()
        })
    }

    /// Sets the maximum hops.
    #[inline]
    #[must_use]
    pub const fn with_max_hops(mut self, max: u8) -> Self {
        self.max_hops = max;
        self
    }

    /// Serializes to bytes.
    #[must_use]
    pub fn to_bytes(&self) -> [u8; MESSAGE_WIRE_SIZE] {
        let mut buf = [0u8; MESSAGE_WIRE_SIZE];

        buf[0..8].copy_from_slice(&self.token_id.to_be_bytes());
        buf[8..16].copy_from_slice(&self.object_id.high().to_be_bytes());
        buf[16..24].copy_from_slice(&self.object_id.low().to_be_bytes());
        buf[24] = cancel_kind_to_u8(self.kind);
        buf[25..33].copy_from_slice(&self.initiated_at.as_nanos().to_be_bytes());
        buf[33..41].copy_from_slice(&self.sequence.to_be_bytes());
        buf[41] = self.hops;
        buf[42] = self.max_hops;

        buf
    }

    /// Deserializes from bytes.
    #[must_use]
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() < MESSAGE_WIRE_SIZE {
            return None;
        }

        let token_id = u64::from_be_bytes(data[0..8].try_into().ok()?);
        let high = u64::from_be_bytes(data[8..16].try_into().ok()?);
        let low = u64::from_be_bytes(data[16..24].try_into().ok()?);
        let kind = cancel_kind_from_u8(data[24])?;
        let initiated_at = Time::from_nanos(u64::from_be_bytes(data[25..33].try_into().ok()?));
        let sequence = u64::from_be_bytes(data[33..41].try_into().ok()?);
        let hops = data[41];
        let max_hops = data[42];

        Some(Self {
            token_id,
            object_id: ObjectId::new(high, low),
            kind,
            initiated_at,
            sequence,
            hops,
            max_hops,
        })
    }
}

// ============================================================================
// PeerId
// ============================================================================

/// Peer identifier.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PeerId(String);

impl PeerId {
    /// Creates a new peer ID.
    #[inline]
    #[must_use]
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// Returns the ID as a string slice.
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

// ============================================================================
// CancelSink trait
// ============================================================================

/// Trait for sending cancellation messages to peers.
pub trait CancelSink: Send + Sync {
    /// Sends a cancellation message to a specific peer.
    fn send_to(
        &self,
        peer: &PeerId,
        msg: &CancelMessage,
    ) -> impl std::future::Future<Output = crate::error::Result<()>> + Send;

    /// Broadcasts a cancellation message to all peers.
    fn broadcast(
        &self,
        msg: &CancelMessage,
    ) -> impl std::future::Future<Output = crate::error::Result<usize>> + Send;
}

// ============================================================================
// CancelBroadcastMetrics
// ============================================================================

/// Metrics for cancellation broadcast.
#[derive(Clone, Debug, Default)]
pub struct CancelBroadcastMetrics {
    /// Cancellations initiated locally.
    pub initiated: u64,
    /// Cancellations received from peers.
    pub received: u64,
    /// Cancellations forwarded to peers.
    pub forwarded: u64,
    /// Duplicate cancellations ignored.
    pub duplicates: u64,
    /// Cancellations that reached max hops.
    pub max_hops_reached: u64,
    /// Failed broadcast messages pending retry.
    /// br-asupersync-dm6ci4: Track count of messages queued for retry
    /// after failed broadcast attempts.
    pub pending_retries: u64,
}

// ============================================================================
// CancelBroadcaster
// ============================================================================

/// Coordinates cancellation broadcast across peers.
///
/// The broadcaster tracks active cancellation tokens, deduplicates messages,
/// and forwards cancellations within hop limits. Sync methods
/// ([`prepare_cancel`][Self::prepare_cancel], [`receive_message`][Self::receive_message])
/// handle the core logic; async methods ([`cancel`][Self::cancel],
/// [`handle_message`][Self::handle_message]) add network dispatch.
pub struct CancelBroadcaster<S: CancelSink> {
    /// Known peers.
    peers: RwLock<SmallVec<[PeerId; 4]>>,
    /// Active cancellation tokens by object ID.
    active_tokens: RwLock<HashMap<ObjectId, SymbolCancelToken>>,
    /// Seen message sequences for deduplication (with insertion order).
    seen_sequences: RwLock<SeenSequences>,
    /// Maximum seen sequences to retain.
    max_seen: usize,
    /// Broadcast sink for sending messages.
    sink: S,
    /// Local sequence counter.
    next_sequence: AtomicU64,
    /// Failed broadcast messages pending retry.
    /// br-asupersync-dm6ci4: Preserve failed forward broadcasts for retry
    /// instead of dropping them on broadcast errors. The retry queue maintains
    /// failed messages in order for deterministic re-attempt behavior.
    pending_retries: RwLock<VecDeque<CancelMessage>>,
    /// Ensures only one retry pass drains the retry queue at a time.
    /// Concurrent retry callers otherwise can split the queue and violate
    /// the FIFO "stop on first failure" contract documented below.
    retry_in_progress: AtomicBool,
    /// br-asupersync-ml5ba5 — Per-broadcaster random tag mixed into
    /// the synthetic token_id `prepare_cancel` mints when no local
    /// `SymbolCancelToken` exists for an object. Without this,
    /// every broadcaster computed the same synthetic
    /// `object_id.high ^ object_id.low`, which (1) collided across
    /// senders that both cancelled the same object without holding a
    /// local token, causing the receiver's `(object_id, token_id,
    /// sequence)` dedup set to incorrectly suppress the second
    /// sender's cancel when sequence numbers happened to overlap
    /// (each broadcaster's `next_sequence` starts from 0); and
    /// (2) was publicly derivable from the on-the-wire ObjectId, so
    /// an attacker could mint cancels with the predictable token_id
    /// and arbitrary sequence numbers to flush the dedup set or
    /// pre-poison it. Sender_tag is OS-random per-broadcaster, so
    /// two different broadcasters produce distinct synthetic
    /// token_ids for the same ObjectId — preserving the
    /// single-sender contract (same broadcaster + same object →
    /// same synthetic, since `sender_tag` is stable for the
    /// broadcaster's lifetime) while defeating cross-sender
    /// collision.
    sender_tag: u64,
    /// Atomic metrics counters.
    initiated: AtomicU64,
    received: AtomicU64,
    forwarded: AtomicU64,
    duplicates: AtomicU64,
    max_hops_reached: AtomicU64,
}

/// Deterministic dedup tracking with bounded memory.
type SeenKey = (ObjectId, u64, u64);

#[derive(Debug, Default)]
struct SeenSequences {
    set: HashSet<SeenKey>,
    order: VecDeque<SeenKey>,
}

impl SeenSequences {
    fn insert(&mut self, key: SeenKey) -> bool {
        if self.set.insert(key) {
            self.order.push_back(key);
            true
        } else {
            false
        }
    }

    fn remove_oldest(&mut self) -> Option<SeenKey> {
        let oldest = self.order.pop_front()?;
        self.set.remove(&oldest);
        Some(oldest)
    }
}

impl<S: CancelSink> CancelBroadcaster<S> {
    /// Creates a new broadcaster with the given sink.
    pub fn new(sink: S) -> Self {
        // br-asupersync-ml5ba5 — Mint a per-broadcaster random
        // sender_tag from the OS entropy source. The tag is stable
        // for the broadcaster's lifetime and is mixed into synthetic
        // token_ids when no local token exists for an object.
        let mut tag_buf = [0u8; 8];
        getrandom::fill(&mut tag_buf).expect("OS entropy source unavailable");
        let sender_tag = u64::from_ne_bytes(tag_buf);
        Self {
            peers: RwLock::new(SmallVec::new()),
            active_tokens: RwLock::new(HashMap::new()),
            seen_sequences: RwLock::new(SeenSequences::default()),
            max_seen: 10_000,
            sink,
            next_sequence: AtomicU64::new(0),
            sender_tag,
            pending_retries: RwLock::new(VecDeque::new()),
            retry_in_progress: AtomicBool::new(false),
            initiated: AtomicU64::new(0),
            received: AtomicU64::new(0),
            forwarded: AtomicU64::new(0),
            duplicates: AtomicU64::new(0),
            max_hops_reached: AtomicU64::new(0),
        }
    }

    /// Registers a peer.
    pub fn add_peer(&self, peer: PeerId) {
        let mut peers = self.peers.write();
        if !peers.contains(&peer) {
            peers.push(peer);
        }
    }

    /// Removes a peer.
    pub fn remove_peer(&self, peer: &PeerId) {
        self.peers.write().retain(|p| p != peer);
    }

    /// Registers a cancellation token for an object.
    pub fn register_token(&self, token: SymbolCancelToken) {
        self.active_tokens.write().insert(token.object_id(), token);
    }

    /// Unregisters a token.
    pub fn unregister_token(&self, object_id: &ObjectId) {
        self.active_tokens.write().remove(object_id);
    }

    /// Cancels a local token and creates a broadcast message.
    ///
    /// This is the synchronous core of [`cancel`][Self::cancel]. It cancels the
    /// local token, creates a dedup-tracked message, and returns it for dispatch.
    pub fn prepare_cancel(
        &self,
        object_id: ObjectId,
        reason: &CancelReason,
        now: Time,
    ) -> CancelMessage {
        // Extract token and ID without holding the lock during cancel.
        // br-asupersync-ml5ba5 — synthetic fallback now mixes
        // self.sender_tag so two broadcasters cancelling the same
        // ObjectId without a local token produce distinct token_ids,
        // defeating the cross-sender dedup collision and the
        // publicly-derivable token_id attack.
        let (token, token_id) = {
            let tokens = self.active_tokens.read();
            tokens.get(&object_id).map_or_else(
                || (None, self.sender_tag ^ object_id.high() ^ object_id.low()),
                |token| (Some(token.clone()), token.token_id()),
            )
        };

        if let Some(token) = token {
            token.cancel(reason, now);
        }

        let sequence = self.next_sequence.fetch_add(1, Ordering::Relaxed);
        let msg = CancelMessage::new(token_id, object_id, reason.kind(), now, sequence);

        self.mark_seen(object_id, msg.token_id(), sequence);
        self.initiated.fetch_add(1, Ordering::Relaxed);

        msg
    }

    /// Handles a received cancellation message synchronously.
    ///
    /// Returns the forwarded message if the message should be relayed, or `None`
    /// if the message was a duplicate or reached max hops. This is the
    /// synchronous core of [`handle_message`][Self::handle_message].
    pub fn receive_message(
        &self,
        msg: &CancelMessage,
        _received_at: Time,
    ) -> Option<CancelMessage> {
        // Check for duplicate
        if self.is_seen(msg.object_id(), msg.token_id(), msg.sequence()) {
            self.duplicates.fetch_add(1, Ordering::Relaxed);
            return None;
        }

        self.mark_seen(msg.object_id(), msg.token_id(), msg.sequence());
        self.received.fetch_add(1, Ordering::Relaxed);

        // Cancel local token if present
        let token = self.active_tokens.read().get(&msg.object_id()).cloned(); // ubs:ignore - internal cancellation token, not a secret
        if let Some(token) = token {
            let reason = CancelReason::new(msg.kind()).with_timestamp(msg.initiated_at());
            // br-asupersync-zmeazg: a forwarded cancel must preserve the origin
            // timestamp carried on the wire. Using the local receipt time here
            // skews cancelled_at/listener observations on every downstream peer.
            token.cancel(&reason, msg.initiated_at());
        }

        // Forward if allowed
        msg.forwarded().map_or_else(
            || {
                self.max_hops_reached.fetch_add(1, Ordering::Relaxed);
                None
            },
            |forwarded| {
                self.forwarded.fetch_add(1, Ordering::Relaxed);
                Some(forwarded)
            },
        )
    }

    /// Initiates cancellation and broadcasts to peers.
    pub async fn cancel(
        &self,
        object_id: ObjectId,
        reason: &CancelReason,
        now: Time,
    ) -> crate::error::Result<usize> {
        let msg = self.prepare_cancel(object_id, reason, now);
        match self.sink.broadcast(&msg).await {
            Ok(count) => Ok(count),
            Err(err) => {
                // br-asupersync-dm6ci4: On broadcast failure, preserve the message
                // for retry instead of dropping it. This ensures failed forward
                // broadcasts can be re-attempted later via retry_failed_broadcasts().
                self.pending_retries.write().push_back(msg);
                Err(err)
            }
        }
    }

    /// Handles a received cancellation message and forwards if appropriate.
    pub async fn handle_message(&self, msg: CancelMessage, now: Time) -> crate::error::Result<()> {
        if let Some(forwarded) = self.receive_message(&msg, now) {
            match self.sink.broadcast(&forwarded).await {
                Ok(_) => Ok(()),
                Err(err) => {
                    // br-asupersync-dm6ci4: On forward broadcast failure, preserve
                    // the forwarded message for retry instead of dropping it.
                    self.pending_retries.write().push_back(forwarded);
                    Err(err)
                }
            }
        } else {
            Ok(())
        }
    }

    /// Retries failed broadcast messages.
    ///
    /// br-asupersync-dm6ci4: Re-attempts broadcasting of messages that previously
    /// failed due to network or sink errors. Messages are retried in FIFO order
    /// to preserve temporal causality. Successfully broadcast messages are removed
    /// from the retry queue; failed messages remain queued for subsequent retries.
    /// Only one retry pass may run at a time; concurrent callers return without
    /// consuming queue state so they cannot reorder pending messages.
    ///
    /// Returns the number of messages successfully retried and any error from the
    /// last failed retry attempt.
    pub async fn retry_failed_broadcasts(&self) -> (usize, Option<crate::error::Error>) {
        struct RetryGuard<'a>(&'a AtomicBool);

        impl Drop for RetryGuard<'_> {
            fn drop(&mut self) {
                self.0.store(false, Ordering::Release);
            }
        }

        if self
            .retry_in_progress
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return (0, None);
        }
        let _retry_guard = RetryGuard(&self.retry_in_progress);

        let mut retried_count = 0;
        let mut last_error = None;

        // Process retry queue until empty or we hit a failure
        loop {
            let (msg, original_queue_len) = {
                let mut retries = self.pending_retries.write();
                let msg = retries.pop_front();
                let queue_len = retries.len();
                (msg, queue_len)
            };

            let Some(msg) = msg else {
                break; // No more messages to retry
            };

            match self.sink.broadcast(&msg).await {
                Ok(_) => {
                    retried_count += 1;
                    // Successfully retried, continue with next message
                }
                Err(err) => {
                    // Failed again, put message back preserving FIFO order.
                    // Insert at the position it would have been if we hadn't removed it,
                    // accounting for any messages added during the async broadcast.
                    {
                        let mut retries = self.pending_retries.write();
                        let current_len = retries.len();
                        if current_len > original_queue_len {
                            // New messages were added during broadcast, insert after original messages
                            // but before the newly added ones to preserve temporal ordering
                            retries.insert(original_queue_len, msg);
                        } else {
                            // No new messages added, safe to put back at front
                            retries.push_front(msg);
                        }
                    }
                    last_error = Some(err);
                    break; // Stop retrying on first failure to preserve order
                }
            }
        }

        (retried_count, last_error)
    }

    /// Returns a snapshot of current metrics.
    #[must_use]
    pub fn metrics(&self) -> CancelBroadcastMetrics {
        CancelBroadcastMetrics {
            initiated: self.initiated.load(Ordering::Relaxed),
            received: self.received.load(Ordering::Relaxed),
            forwarded: self.forwarded.load(Ordering::Relaxed),
            duplicates: self.duplicates.load(Ordering::Relaxed),
            max_hops_reached: self.max_hops_reached.load(Ordering::Relaxed),
            pending_retries: self.pending_retries.read().len() as u64,
        }
    }

    fn is_seen(&self, object_id: ObjectId, token_id: u64, sequence: u64) -> bool {
        self.seen_sequences
            .read()
            .set
            .contains(&(object_id, token_id, sequence))
    }

    fn mark_seen(&self, object_id: ObjectId, token_id: u64, sequence: u64) {
        let mut seen = self.seen_sequences.write();
        if seen.set.contains(&(object_id, token_id, sequence)) {
            return;
        }

        // br-asupersync-as12cf — evict BEFORE insert, not after.
        // The previous shape (insert -> evict-while-over-cap) left
        // the set holding `max_seen + 1` entries during the brief
        // window between the insert and the eviction loop. Although
        // the write lock prevents any other thread from observing
        // the over-allocated state, the bounded-memory contract is
        // a documentation invariant that future maintainers (and
        // peak-memory accounting tools) read literally. Evicting
        // first keeps `seen.set.len()` strictly within `max_seen`
        // at every observable point in time.
        while seen.set.len() >= self.max_seen {
            if seen.remove_oldest().is_none() {
                break;
            }
        }

        seen.insert((object_id, token_id, sequence));
    }
}

// ============================================================================
// Cleanup types
// ============================================================================

/// Trait for cleanup handlers.
pub trait CleanupHandler: Send + Sync {
    /// Called to clean up symbols for a cancelled object.
    ///
    /// Returns the number of symbols cleaned up.
    ///
    /// Return `Err(...)` if the batch could not be completed. The coordinator
    /// preserves the pending set for a later retry on the error path.
    #[allow(clippy::result_large_err)]
    fn cleanup(&self, object_id: ObjectId, symbols: Vec<Symbol>) -> crate::error::Result<usize>;

    /// Returns the name of this handler (for logging).
    fn name(&self) -> &'static str;
}

/// A set of symbols pending cleanup.
#[derive(Clone)]
struct PendingSymbolSet {
    /// Accumulated symbols.
    symbols: Vec<Symbol>,
    /// Total bytes.
    total_bytes: usize,
    /// When the set was created.
    _created_at: Time,
}

/// Result of a cleanup operation.
#[derive(Clone, Debug)]
pub struct CleanupResult {
    /// The object ID.
    pub object_id: ObjectId,
    /// Number of symbols cleaned up.
    pub symbols_cleaned: usize,
    /// Bytes freed.
    pub bytes_freed: usize,
    /// Whether cleanup completed within budget.
    pub within_budget: bool,
    /// Whether cleanup fully completed and no retry state was retained.
    pub completed: bool,
    /// Handlers that ran.
    pub handlers_run: Vec<String>,
    /// Errors returned by cleanup handlers.
    pub handler_errors: Vec<String>,
}

/// Statistics about pending cleanups.
#[derive(Clone, Debug, Default)]
pub struct CleanupStats {
    /// Number of objects with pending symbols.
    pub pending_objects: usize,
    /// Total pending symbols.
    pub pending_symbols: usize,
    /// Total pending bytes.
    pub pending_bytes: usize,
}

struct ActiveCleanupGuard<'a> {
    object_id: ObjectId,
    active: &'a RwLock<HashSet<ObjectId>>,
}

impl Drop for ActiveCleanupGuard<'_> {
    fn drop(&mut self) {
        self.active.write().remove(&self.object_id);
    }
}

/// Coordinates cleanup of partial symbol sets.
pub struct CleanupCoordinator {
    /// Pending symbol sets by object ID.
    pending: RwLock<HashMap<ObjectId, PendingSymbolSet>>,
    /// Cleanup handlers by object ID.
    handlers: RwLock<HashMap<ObjectId, Box<dyn CleanupHandler>>>,
    /// Completed object IDs that no longer accept pending symbols.
    completed: RwLock<HashSet<ObjectId>>,
    /// Symbols buffered during cleanup attempts (to prevent drops during retry).
    cleanup_buffer: RwLock<HashMap<ObjectId, Vec<Symbol>>>,
    /// Object IDs currently executing a cleanup attempt.
    cleanup_active: RwLock<HashSet<ObjectId>>,
    /// Default cleanup budget.
    default_budget: Budget,
}

impl CleanupCoordinator {
    /// Creates a new cleanup coordinator.
    #[must_use]
    pub fn new() -> Self {
        Self {
            pending: RwLock::new(HashMap::new()),
            handlers: RwLock::new(HashMap::new()),
            completed: RwLock::new(HashSet::new()),
            cleanup_buffer: RwLock::new(HashMap::new()),
            cleanup_active: RwLock::new(HashSet::new()),
            default_budget: Budget::new().with_poll_quota(1000),
        }
    }

    /// Sets the default cleanup budget.
    #[must_use]
    pub fn with_default_budget(mut self, budget: Budget) -> Self {
        self.default_budget = budget;
        self
    }

    /// Registers symbols as pending for an object.
    #[allow(clippy::significant_drop_tightening)]
    pub fn register_pending(&self, object_id: ObjectId, symbol: Symbol, now: Time) {
        let mut pending = self.pending.write();
        // Check completion while holding the pending map lock so retry-state
        // restoration can reopen an object without a lost-symbol race.
        if self.completed.read().contains(&object_id) {
            return;
        }

        // Check if object is in cleanup buffer (mid-retry); if so, buffer the symbol
        // rather than dropping it, so it can be replayed when retry completes.
        let mut cleanup_buffer = self.cleanup_buffer.write();
        if cleanup_buffer.contains_key(&object_id) {
            cleanup_buffer.entry(object_id).or_default().push(symbol);
            return;
        }
        drop(cleanup_buffer); // Release buffer lock before modifying pending

        let set = pending
            .entry(object_id)
            .or_insert_with(|| PendingSymbolSet {
                symbols: Vec::new(),
                total_bytes: 0,
                _created_at: now,
            });

        set.total_bytes = set.total_bytes.saturating_add(symbol.len());
        set.symbols.push(symbol);
    }

    #[allow(clippy::significant_drop_tightening)]
    fn restore_retry_state(
        &self,
        object_id: ObjectId,
        handler: Box<dyn CleanupHandler>,
        mut pending_set: PendingSymbolSet,
    ) {
        // Take the handler table before the retry-state locks. Keeping this
        // acquisition out of the pending/completed critical path avoids a
        // future handlers->pending caller turning this path into an AB-BA cycle.
        let mut handlers = self.handlers.write();

        // Keep `pending` held while draining the cleanup buffer and clearing
        // `completed` so reopening retry state is atomic with respect to
        // register_pending() and cannot drop symbols in the reopen window.
        let mut pending = self.pending.write();
        let mut completed = self.completed.write();

        // If clear_pending was called concurrently during a cleanup attempt,
        // the object has been successfully decoded. We must not restore the
        // retry state (which would un-complete the object and cause memory leaks).
        if completed.contains(&object_id) {
            // Also clean up any trailing buffered symbols that arrived late
            self.cleanup_buffer.write().remove(&object_id);
            return;
        }

        handlers.insert(object_id, handler);

        let mut cleanup_buffer = self.cleanup_buffer.write();
        if let Some(buffered_symbols) = cleanup_buffer.remove(&object_id) {
            for symbol in buffered_symbols {
                pending_set.total_bytes = pending_set.total_bytes.saturating_add(symbol.len());
                pending_set.symbols.push(symbol);
            }
        }
        pending.insert(object_id, pending_set);
        completed.remove(&object_id);
    }

    #[allow(clippy::significant_drop_tightening)]
    fn restore_pending_only_state(&self, object_id: ObjectId, mut pending_set: PendingSymbolSet) {
        let mut pending = self.pending.write();
        let mut completed = self.completed.write();

        if completed.contains(&object_id) {
            self.cleanup_buffer.write().remove(&object_id);
            return;
        }

        let mut cleanup_buffer = self.cleanup_buffer.write();
        if let Some(buffered_symbols) = cleanup_buffer.remove(&object_id) {
            for symbol in buffered_symbols {
                pending_set.total_bytes = pending_set.total_bytes.saturating_add(symbol.len());
                pending_set.symbols.push(symbol);
            }
        }
        pending.insert(object_id, pending_set);
        completed.remove(&object_id);
    }

    /// Registers a cleanup handler for an object.
    pub fn register_handler(&self, object_id: ObjectId, handler: impl CleanupHandler + 'static) {
        self.handlers.write().insert(object_id, Box::new(handler));
    }

    #[inline]
    fn empty_pending_set() -> PendingSymbolSet {
        PendingSymbolSet {
            symbols: Vec::new(),
            total_bytes: 0,
            _created_at: Time::ZERO,
        }
    }

    /// Clears pending symbols for an object (e.g., after successful decode).
    pub fn clear_pending(&self, object_id: &ObjectId) -> Option<usize> {
        // A successfully decoded object no longer needs its cleanup handler;
        // retaining it would leak per-object handler state indefinitely.
        self.handlers.write().remove(object_id);
        let mut pending = self.pending.write();
        self.completed.write().insert(*object_id);
        pending.remove(object_id).map(|set| set.symbols.len())
    }

    /// Triggers cleanup for a cancelled object.
    pub fn cleanup(&self, object_id: ObjectId, budget: Option<Budget>) -> CleanupResult {
        let budget = budget.unwrap_or(self.default_budget);
        let mut result = CleanupResult {
            object_id,
            symbols_cleaned: 0,
            bytes_freed: 0,
            within_budget: true,
            completed: true,
            handlers_run: Vec::new(),
            handler_errors: Vec::new(),
        };

        let _active_guard = {
            let mut active = self.cleanup_active.write();
            if !active.insert(object_id) {
                result.completed = false;
                result.handler_errors.push(format!(
                    "cleanup already in progress for object {object_id:?}; \
                     rejecting reentrant cleanup attempt (br-asupersync-a19xwn)"
                ));
                return result;
            }
            ActiveCleanupGuard {
                object_id,
                active: &self.cleanup_active,
            }
        };

        // Create the cleanup buffer entry before extracting pending symbols so
        // register_pending() callers racing with cleanup() are captured in the
        // buffer rather than silently repopulating `pending` behind this pass.
        self.cleanup_buffer.write().entry(object_id).or_default();

        // Atomically extract the handler and pending symbols. Don't mark as
        // completed until handler succeeds.
        let handler = { self.handlers.write().remove(&object_id) };
        let pending_set = { self.pending.write().remove(&object_id) };
        let had_handler = handler.is_some();

        if let Some(set) = pending_set {
            let symbol_count = set.symbols.len();
            let total_bytes = set.total_bytes;

            // Run registered handler.
            if let Some(handler) = handler {
                if budget.poll_quota == 0 {
                    // No budget to even attempt the handler; keep the pending state
                    // and handler for an explicit retry.
                    self.restore_retry_state(object_id, handler, set);
                    result.within_budget = false;
                    result.completed = false;
                } else {
                    let handler_name = handler.name().to_string();
                    let retry_set = set.clone();

                    result.handlers_run.push(handler_name.clone());
                    match handler.cleanup(object_id, set.symbols) {
                        Ok(_) => {
                            // Handler succeeded - mark as completed and clean up buffer
                            self.completed.write().insert(object_id);
                            self.cleanup_buffer.write().remove(&object_id);
                            result.symbols_cleaned = symbol_count;
                            result.bytes_freed = total_bytes;
                        }
                        Err(err) => {
                            // The cleanup attempt failed; retain the pending set and
                            // handler so the caller can retry deterministically.
                            // The cleanup buffer is preserved by restore_retry_state.
                            self.restore_retry_state(object_id, handler, retry_set);
                            result.completed = false;
                            result.handler_errors.push(format!("{handler_name}: {err}"));
                        }
                    }
                }
            } else {
                // br-asupersync-batcyw: pending symbols exist but no
                // CleanupHandler is registered for this object_id.
                // Previous behaviour set symbols_cleaned = N and
                // bytes_freed = total — silently REPORTING the
                // symbols as cleaned even though no handler ever
                // ran. This is the observable shape callers used to
                // distinguish "release was acked by the application"
                // from "release dropped on the floor", and the bug
                // collapsed the two into the same "success" record.
                //
                // New behaviour: leave symbols_cleaned and
                // bytes_freed at zero, mark the result as not
                // completed, push a typed error into handler_errors
                // identifying the missing-handler condition, and
                // restore the pending set so a later
                // register_handler + retry can drive cleanup to
                // completion. The completed-set entry inserted at
                // line 1015 above is rolled back here too — a
                // missing-handler outcome is NOT a completion.
                result.completed = false;
                result.handler_errors.push(format!(
                    "no cleanup handler registered for object {object_id:?}; \
                     {symbol_count} symbol(s) / {total_bytes} byte(s) deferred \
                     (br-asupersync-batcyw)"
                ));

                // Merge any buffered symbols back into the pending set
                let mut cleanup_buffer = self.cleanup_buffer.write();
                let mut restored_set = set;
                if let Some(buffered_symbols) = cleanup_buffer.remove(&object_id) {
                    for symbol in buffered_symbols {
                        restored_set.total_bytes =
                            restored_set.total_bytes.saturating_add(symbol.len());
                        restored_set.symbols.push(symbol);
                    }
                }
                drop(cleanup_buffer);

                // Restore pending; don't mark completed (no handler to retry with).
                self.pending.write().insert(object_id, restored_set);
            }
        } else {
            // No pending symbols, but check cleanup buffer for symbols that arrived
            // during a previous cleanup attempt
            let buffered_symbol_count = self
                .cleanup_buffer
                .read()
                .get(&object_id)
                .map_or(0, Vec::len);
            if buffered_symbol_count > 0 {
                let new_set = Self::empty_pending_set();
                if let Some(handler) = handler {
                    self.restore_retry_state(object_id, handler, new_set);
                } else {
                    self.restore_pending_only_state(object_id, new_set);
                }
                result.completed = false; // Can't complete without symbols to clean
            } else {
                self.cleanup_buffer.write().remove(&object_id);
            }
            if result.completed && had_handler {
                // A registered handler with no pending or buffered symbols still
                // represents a fully completed cleanup lifecycle. Record that
                // completion so late register_pending() calls cannot silently
                // reopen the object after its handler has been dropped.
                self.completed.write().insert(object_id);
            }
        }

        if result.completed {
            // Reentrant or concurrent register_handler() calls during cleanup
            // must not leak stale per-object handlers after the object has
            // reached a completed terminal state.
            self.handlers.write().remove(&object_id);
        }

        result
    }

    /// Returns statistics about pending cleanups.
    #[must_use]
    pub fn stats(&self) -> CleanupStats {
        let pending = self.pending.read();

        let mut total_symbols = 0;
        let mut total_bytes = 0;

        for set in pending.values() {
            total_symbols += set.symbols.len();
            total_bytes += set.total_bytes;
        }

        CleanupStats {
            pending_objects: pending.len(),
            pending_symbols: total_symbols,
            pending_bytes: total_bytes,
        }
    }
}

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

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;
    use crate::conformance::{ConformanceTarget, LabRuntimeTarget, TestConfig};
    use crate::runtime::yield_now;
    use crate::test_utils::init_test_logging;
    use crate::types::symbol::{ObjectId, Symbol};
    use serde_json::Value;
    use std::sync::Mutex as StdMutex;
    use std::sync::atomic::AtomicUsize;

    struct CountingCleanupHandler;
    impl CleanupHandler for CountingCleanupHandler {
        fn cleanup(
            &self,
            _object_id: ObjectId,
            symbols: Vec<Symbol>,
        ) -> crate::error::Result<usize> {
            Ok(symbols.len())
        }

        fn name(&self) -> &'static str {
            "counting"
        }
    }

    struct NullSink;

    impl CancelSink for NullSink {
        fn send_to(
            &self,
            _peer: &PeerId,
            _msg: &CancelMessage,
        ) -> impl std::future::Future<Output = crate::error::Result<()>> + Send {
            std::future::ready(Ok(()))
        }

        fn broadcast(
            &self,
            _msg: &CancelMessage,
        ) -> impl std::future::Future<Output = crate::error::Result<usize>> + Send {
            std::future::ready(Ok(0))
        }
    }

    struct RecordingSink {
        label: &'static str,
        checkpoints: Arc<StdMutex<Vec<Value>>>,
        messages: Arc<StdMutex<Vec<CancelMessage>>>,
    }

    #[derive(Debug, PartialEq, Eq)]
    struct TokenSnapshot {
        token_id: u64,
        cancelled: bool,
        reason_kind: Option<CancelKind>,
        cancelled_at_nanos: Option<u64>,
        queued_children: usize,
        queued_listeners: usize,
    }

    fn snapshot_token(token: &SymbolCancelToken) -> TokenSnapshot {
        TokenSnapshot {
            token_id: token.token_id(),
            cancelled: token.is_cancelled(),
            reason_kind: token.reason().map(|reason| reason.kind),
            cancelled_at_nanos: token.cancelled_at().map(Time::as_nanos),
            queued_children: token.state.children.read().len(),
            queued_listeners: token.state.listeners.read().len(),
        }
    }

    fn attach_order_listener(token: &SymbolCancelToken, order: &Arc<StdMutex<Vec<u64>>>) {
        let token_id = token.token_id();
        let order = Arc::clone(order);
        token.add_listener(move |_: &CancelReason, _: Time| {
            order.lock().unwrap().push(token_id); // ubs:ignore - test helper
        });
    }

    fn attach_named_order_listener(
        token: &SymbolCancelToken,
        label: &'static str,
        order: &Arc<StdMutex<Vec<&'static str>>>,
    ) {
        let order = Arc::clone(order);
        token.add_listener(move |_: &CancelReason, _: Time| {
            order.lock().unwrap().push(label);
        });
    }

    #[derive(Debug, PartialEq, Eq)]
    struct ReasonSnapshot {
        cancelled: bool,
        kind: Option<CancelKind>,
        cancelled_at_nanos: Option<u64>,
        cause_chain: Vec<CancelKind>,
    }

    fn snapshot_reason(token: &SymbolCancelToken) -> ReasonSnapshot {
        let reason = token.reason();
        let cause_chain = reason
            .as_ref()
            .map(|reason| reason.chain().map(|reason| reason.kind).collect())
            .unwrap_or_default();
        ReasonSnapshot {
            cancelled: token.is_cancelled(),
            kind: reason.as_ref().map(|reason| reason.kind),
            cancelled_at_nanos: token.cancelled_at().map(Time::as_nanos),
            cause_chain,
        }
    }

    fn reason_chain_kinds(token: &SymbolCancelToken) -> Vec<CancelKind> {
        token
            .reason()
            .map(|reason| reason.chain().map(|reason| reason.kind).collect())
            .unwrap_or_default()
    }

    fn observable_token_state_json(token: &SymbolCancelToken) -> Value {
        serde_json::json!({
            "cancelled": token.is_cancelled(),
            "cancelled_at_nanos": token.cancelled_at().map(Time::as_nanos),
            "queued_children": token.state.children.read().len(),
            "queued_listeners": token.state.listeners.read().len(),
            "reason_kind": token.reason().map(|reason| format!("{:?}", reason.kind)),
        })
    }

    #[derive(Debug, PartialEq, Eq)]
    struct DescendantInvariantScenario {
        creation_order: Vec<&'static str>,
        observed_order: Vec<&'static str>,
        left_before_parent: ReasonSnapshot,
        left_after_parent: ReasonSnapshot,
        right_child_after_parent: ReasonSnapshot,
        right_leaf_after_parent: ReasonSnapshot,
    }

    fn run_descendant_invariant_scenario(
        swap_creation_order: bool,
        drop_right_child_handle: bool,
    ) -> DescendantInvariantScenario {
        let mut rng = DetRng::new(0xCACE_1001);
        let parent = SymbolCancelToken::new(ObjectId::new_for_test(77), &mut rng);
        let order = Arc::new(StdMutex::new(Vec::<&'static str>::new()));
        let creation_order = if swap_creation_order {
            vec!["right", "left"]
        } else {
            vec!["left", "right"]
        };

        let mut left_child: Option<SymbolCancelToken> = None;
        let mut left_leaf: Option<SymbolCancelToken> = None;
        let mut right_child: Option<SymbolCancelToken> = None;
        let mut right_leaf: Option<SymbolCancelToken> = None;

        for label in &creation_order {
            let child = parent.child(&mut rng);
            attach_named_order_listener(&child, label, &order);
            let leaf = child.child(&mut rng);
            match *label {
                "left" => {
                    left_child = Some(child);
                    left_leaf = Some(leaf);
                }
                "right" => {
                    right_child = Some(child);
                    right_leaf = Some(leaf);
                }
                _ => unreachable!("unexpected branch label"),
            }
        }

        let left_leaf = left_leaf.expect("left leaf should be created");
        let right_leaf_observer = right_leaf.expect("right leaf should be created");
        let right_child_observer = right_child
            .as_ref()
            .expect("right child should be created")
            .clone();

        let descendant_reason = CancelReason::shutdown()
            .with_cause(CancelReason::timeout().with_cause(CancelReason::user("left-root-cause")));
        let descendant_at = Time::from_millis(15);
        assert!(left_leaf.cancel(&descendant_reason, descendant_at));
        let left_before_parent = snapshot_reason(&left_leaf);

        if drop_right_child_handle {
            drop(right_child.take());
        }
        drop(left_child);

        assert!(parent.cancel(&CancelReason::user("parent-cascade"), Time::from_millis(30)));

        DescendantInvariantScenario {
            creation_order,
            observed_order: order.lock().unwrap().clone(),
            left_before_parent,
            left_after_parent: snapshot_reason(&left_leaf),
            right_child_after_parent: snapshot_reason(&right_child_observer),
            right_leaf_after_parent: snapshot_reason(&right_leaf_observer),
        }
    }

    impl CancelSink for RecordingSink {
        fn send_to(
            &self,
            _peer: &PeerId,
            _msg: &CancelMessage,
        ) -> impl std::future::Future<Output = crate::error::Result<()>> + Send {
            std::future::ready(Ok(()))
        }

        fn broadcast(
            &self,
            msg: &CancelMessage,
        ) -> impl std::future::Future<Output = crate::error::Result<usize>> + Send {
            let label = self.label;
            let checkpoints = Arc::clone(&self.checkpoints);
            let messages = Arc::clone(&self.messages);
            let message = msg.clone();

            async move {
                let event = serde_json::json!({
                    "phase": format!("{label}_broadcast"),
                    "kind": format!("{:?}", message.kind()),
                    "sequence": message.sequence(),
                    "hops": message.hops(),
                });
                tracing::info!(event = %event, "symbol_cancel_lab_checkpoint");
                {
                    checkpoints.lock().unwrap().push(event);
                    messages.lock().unwrap().push(message); // ubs:ignore - test helper
                } // Drop mutex guards before yield
                yield_now().await;
                Ok(1)
            }
        }
    }

    #[test]
    fn test_token_creation() {
        let mut rng = DetRng::new(42);
        let obj = ObjectId::new_for_test(1);
        let cancel_handle = SymbolCancelToken::new(obj, &mut rng);

        assert_eq!(cancel_handle.object_id(), obj);
        assert!(!cancel_handle.is_cancelled());
        assert!(cancel_handle.reason().is_none());
        assert!(cancel_handle.cancelled_at().is_none());
    }

    // br-asupersync-wm9h2a: SymbolCancelToken::new_for_test is now
    // gated behind `#[cfg(any(test, feature = "test-internals"))]`.
    // Inside this `#[cfg(test)]` module the gate's positive arm is
    // active, so the constructor is reachable and we can pin its
    // forgery-shape behaviour:
    //   1. The constructor accepts arbitrary token_id / object_id
    //      values without going through the broadcaster issuance
    //      ceremony — exactly what makes it a forgery primitive
    //      and exactly why production must NOT have access.
    //   2. The constructor mints distinct Arc<CancelTokenState>
    //      instances for every call, so two synthesized tokens with
    //      the same (token_id, object_id) are NOT aliased — proving
    //      the constructor is not a deduplicating issuer that
    //      could coincidentally mimic a real broadcaster lookup.
    //
    // The negative arm of the gate (production builds compile-failing
    // on any reference to new_for_test) cannot be tested from inside
    // a `#[cfg(test)]` block by definition — by the time the test
    // compiles, the gate's positive arm is on. The compile-fail
    // contract is documented above the constructor and is enforced
    // by the cfg attribute itself.
    #[test]
    fn test_new_for_test_is_a_forgery_primitive_and_must_be_gated_wm9h2a() {
        let object_id = ObjectId::new_for_test(0xdead_beef);
        let forged_a = SymbolCancelToken::new_for_test(0x1111_2222_3333_4444, object_id);
        let forged_b = SymbolCancelToken::new_for_test(0x1111_2222_3333_4444, object_id);

        // Property (1): forged tokens carry exactly the values the
        // caller supplied, with no broadcaster involvement.
        assert_eq!(forged_a.object_id(), object_id);
        assert_eq!(forged_b.object_id(), object_id);

        // Property (2): two forgeries with identical (token_id,
        // object_id) inputs are still distinct Arc instances — they
        // share neither cancellation state nor listener slabs. A
        // production caller that obtained both could cancel one
        // without affecting the other, which is the textbook shape
        // of a capability-boundary breach.
        forged_a.cancel(&CancelReason::user("forgery-A"), Time::from_millis(1));
        assert!(forged_a.is_cancelled());
        assert!(
            !forged_b.is_cancelled(),
            "two new_for_test tokens with the same id must not share state — \
             this confirms the constructor is a forgery primitive that MUST \
             stay gated behind test or test-internals"
        );
    }

    #[test]
    fn test_token_cancel_once() {
        let mut rng = DetRng::new(42);
        let cancel_handle = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);

        let now = Time::from_millis(100);
        let reason = CancelReason::user("test");

        // First cancel succeeds
        assert!(cancel_handle.cancel(&reason, now));
        assert!(cancel_handle.is_cancelled());
        assert_eq!(cancel_handle.reason().unwrap().kind, CancelKind::User);
        assert_eq!(cancel_handle.cancelled_at(), Some(now));

        // Second cancel returns false (not first caller) but strengthens
        assert!(!cancel_handle.cancel(&CancelReason::timeout(), Time::from_millis(200)));

        // Reason strengthened to Timeout (more severe than User)
        assert_eq!(cancel_handle.reason().unwrap().kind, CancelKind::Timeout);
    }

    #[test]
    fn test_token_cancel_clamps_time_max_away_from_sentinel() {
        let mut rng = DetRng::new(42);
        let cancel_handle = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);

        assert!(cancel_handle.cancel(&CancelReason::timeout(), Time::MAX));
        assert!(cancel_handle.is_cancelled());
        assert_eq!(cancel_handle.reason().unwrap().kind, CancelKind::Timeout);
        assert_eq!(
            cancel_handle.cancelled_at(),
            Some(Time::from_nanos(u64::MAX - 1))
        );
    }

    #[test]
    fn test_token_reason_propagates() {
        let mut rng = DetRng::new(42);
        let cancel_handle = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);

        let reason = CancelReason::timeout().with_message("timed out");
        cancel_handle.cancel(&reason, Time::from_millis(500));

        let stored = cancel_handle.reason().unwrap();
        assert_eq!(stored.kind, CancelKind::Timeout);
        assert_eq!(stored.message, Some("timed out".to_string()));
    }

    #[test]
    fn test_token_child_inherits_cancellation() {
        let mut rng = DetRng::new(42);
        let parent = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);
        let child = parent.child(&mut rng);

        assert!(!child.is_cancelled());

        // Cancel parent
        parent.cancel(&CancelReason::user("test"), Time::from_millis(100));

        // Child should be cancelled too
        assert!(child.is_cancelled());
        assert_eq!(child.reason().unwrap().kind, CancelKind::ParentCancelled);
        assert_eq!(
            reason_chain_kinds(&child),
            vec![CancelKind::ParentCancelled, CancelKind::User],
            "child cancellation should carry the root parent reason as a cause"
        );
    }

    #[test]
    fn test_token_listener_notified() {
        use std::sync::atomic::{AtomicBool, Ordering};

        let mut rng = DetRng::new(42);
        let cancel_handle = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);

        let notified = Arc::new(AtomicBool::new(false));
        let notified_clone = notified.clone();

        cancel_handle.add_listener(move |_reason: &CancelReason, _at: Time| {
            notified_clone.store(true, Ordering::SeqCst);
        });

        assert!(!notified.load(Ordering::SeqCst));

        cancel_handle.cancel(&CancelReason::user("test"), Time::from_millis(100));

        assert!(notified.load(Ordering::SeqCst));
    }

    #[test]
    fn metamorphic_descendant_cancellation_observable_under_reorder_and_drop() {
        let baseline = run_descendant_invariant_scenario(false, false);
        let swapped = run_descendant_invariant_scenario(true, false);
        let dropped = run_descendant_invariant_scenario(false, true);

        for scenario in [&baseline, &swapped, &dropped] {
            assert_eq!(
                scenario.observed_order, scenario.creation_order,
                "sibling cancellation listener order should follow child registration order"
            );
            assert_eq!(
                scenario.left_before_parent, scenario.left_after_parent,
                "a self-cancelled descendant must remain observable with the same cause chain after parent cancellation"
            );
            assert_eq!(
                scenario.right_child_after_parent.kind,
                Some(CancelKind::ParentCancelled),
                "uncancelled sibling should be cancelled by the parent cascade"
            );
            assert_eq!(
                scenario.right_leaf_after_parent.kind,
                Some(CancelKind::ParentCancelled),
                "grandchild under the uncancelled sibling should inherit parent cancellation"
            );
            assert_eq!(
                scenario.right_child_after_parent.cause_chain,
                vec![CancelKind::ParentCancelled, CancelKind::User],
                "sibling child should retain the parent cancellation as its cause"
            );
            assert_eq!(
                scenario.right_leaf_after_parent.cause_chain,
                vec![
                    CancelKind::ParentCancelled,
                    CancelKind::ParentCancelled,
                    CancelKind::User,
                ],
                "dropped-handle descendant should preserve the full parent-cancelled cause chain"
            );
        }

        assert_eq!(
            baseline.left_after_parent.kind,
            Some(CancelKind::Shutdown),
            "the stronger descendant cancellation should not be weakened by a later parent cascade"
        );
        assert_eq!(
            baseline.left_after_parent.cause_chain,
            vec![CancelKind::Shutdown, CancelKind::Timeout, CancelKind::User],
            "descendant cause chain should remain intact"
        );
        assert_eq!(
            baseline.left_after_parent, swapped.left_after_parent,
            "sibling creation order should not change descendant observability"
        );
        assert_eq!(
            baseline.left_after_parent, dropped.left_after_parent,
            "dropping a sibling handle must not corrupt an already-cancelled descendant"
        );
        assert_eq!(
            baseline.right_child_after_parent, swapped.right_child_after_parent,
            "sibling reordering should not change cascade outcome"
        );
        assert_eq!(
            baseline.right_child_after_parent, dropped.right_child_after_parent,
            "dropping the sibling handle must preserve child cancellation outcome"
        );
        assert_eq!(
            baseline.right_leaf_after_parent, swapped.right_leaf_after_parent,
            "sibling reordering should not change leaf cascade outcome"
        );
        assert_eq!(
            baseline.right_leaf_after_parent, dropped.right_leaf_after_parent,
            "dropping the sibling handle must preserve descendant cascade outcome"
        );
    }

    #[test]
    fn test_token_serialization() {
        let mut rng = DetRng::new(42);
        let obj = ObjectId::new(0x1234_5678_9abc_def0, 0xfedc_ba98_7654_3210);
        let cancel_handle = SymbolCancelToken::new(obj, &mut rng);

        let bytes = cancel_handle.to_bytes();
        assert_eq!(bytes.len(), TOKEN_WIRE_SIZE);

        let parsed = SymbolCancelToken::from_bytes(&bytes).unwrap();
        assert_eq!(parsed.token_id(), cancel_handle.token_id());
        assert_eq!(parsed.object_id(), cancel_handle.object_id());
        assert!(!parsed.is_cancelled());
    }

    #[test]
    fn test_token_cancel_sets_reason_when_already_cancelled() {
        let mut rng = DetRng::new(42);
        let cancel_handle = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);
        cancel_handle.cancel(&CancelReason::user("initial"), Time::from_millis(100));

        let parsed = SymbolCancelToken::from_bytes(&cancel_handle.to_bytes()).unwrap();
        assert!(parsed.is_cancelled());
        assert!(parsed.reason().is_none());

        let reason = CancelReason::timeout();
        assert!(!parsed.cancel(&reason, Time::from_millis(200)));
        assert_eq!(parsed.reason().unwrap().kind, CancelKind::Timeout);
    }

    #[test]
    fn test_cancel_token_transition_serialization_golden() {
        let mut rng = DetRng::new(0x1337_beef_cafe_dead);

        // Test different token states for golden snapshot stability
        let scenarios = vec![
            ("fresh_token", {
                let obj = ObjectId::new(0x1111_2222_3333_4444, 0x5555_6666_7777_8888);
                SymbolCancelToken::new(obj, &mut rng)
            }),
            ("cancelled_token", {
                let obj = ObjectId::new(0xaaaa_bbbb_cccc_dddd, 0xeeee_ffff_0000_1111);
                let token = SymbolCancelToken::new(obj, &mut rng);
                token.cancel(
                    &CancelReason::timeout(),
                    crate::types::Time::from_millis(1000),
                );
                token
            }),
            ("test_token_minimal", {
                SymbolCancelToken::new_for_test(0x1234_5678_9abc_def0, ObjectId::new(0x0, 0x1))
            }),
            ("test_token_max_values", {
                let token = SymbolCancelToken::new_for_test(
                    0xffff_ffff_ffff_ffff,
                    ObjectId::new(0xdead_beef_cafe_babe, 0x1337_1337_1337_1337),
                );
                token.cancel(
                    &CancelReason::user("test"),
                    crate::types::Time::from_millis(9999),
                );
                token
            }),
        ];

        // Capture wire format serialization as stable golden artifacts
        for (name, token) in scenarios {
            let bytes = token.to_bytes();

            // Create deterministic hex representation for golden comparison
            let hex_output = format!(
                "Token: {}\n\
                Token ID: 0x{:016x}\n\
                Object ID: 0x{:016x}:0x{:016x}\n\
                Cancelled: {}\n\
                Wire bytes: [{}]\n\
                Hex: {}",
                name,
                token.token_id(),
                token.object_id().high(),
                token.object_id().low(),
                token.is_cancelled(),
                bytes
                    .iter()
                    .map(|b| format!("{:02x}", b))
                    .collect::<Vec<_>>()
                    .join(", "),
                bytes
                    .iter()
                    .map(|b| format!("{:02x}", b))
                    .collect::<String>()
            );

            let expected = match name {
                "fresh_token" => concat!(
                    "Token: fresh_token\n",
                    "Token ID: 0xc35d712d21a92850\n",
                    "Object ID: 0x1111222233334444:0x5555666677778888\n",
                    "Cancelled: false\n",
                    "Wire bytes: [c3, 5d, 71, 2d, 21, a9, 28, 50, 11, 11, 22, 22, 33, 33, 44, 44, 55, 55, 66, 66, 77, 77, 88, 88, 00]\n",
                    "Hex: c35d712d21a928501111222233334444555566667777888800"
                ),
                "cancelled_token" => concat!(
                    "Token: cancelled_token\n",
                    "Token ID: 0x24c64de6e8aa6e00\n",
                    "Object ID: 0xaaaabbbbccccdddd:0xeeeeffff00001111\n",
                    "Cancelled: true\n",
                    "Wire bytes: [24, c6, 4d, e6, e8, aa, 6e, 00, aa, aa, bb, bb, cc, cc, dd, dd, ee, ee, ff, ff, 00, 00, 11, 11, 01]\n",
                    "Hex: 24c64de6e8aa6e00aaaabbbbccccddddeeeeffff0000111101"
                ),
                "test_token_minimal" => concat!(
                    "Token: test_token_minimal\n",
                    "Token ID: 0x123456789abcdef0\n",
                    "Object ID: 0x0000000000000000:0x0000000000000001\n",
                    "Cancelled: false\n",
                    "Wire bytes: [12, 34, 56, 78, 9a, bc, de, f0, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 01, 00]\n",
                    "Hex: 123456789abcdef00000000000000000000000000000000100"
                ),
                "test_token_max_values" => concat!(
                    "Token: test_token_max_values\n",
                    "Token ID: 0xffffffffffffffff\n",
                    "Object ID: 0xdeadbeefcafebabe:0x1337133713371337\n",
                    "Cancelled: true\n",
                    "Wire bytes: [ff, ff, ff, ff, ff, ff, ff, ff, de, ad, be, ef, ca, fe, ba, be, 13, 37, 13, 37, 13, 37, 13, 37, 01]\n",
                    "Hex: ffffffffffffffffdeadbeefcafebabe133713371337133701"
                ),
                _ => unreachable!("unknown cancel token serialization scenario: {name}"),
            };

            assert_eq!(hex_output, expected);
        }
    }

    #[test]
    fn cancel_token_phase_transition_trace_canonical() {
        let mut rng = DetRng::new(0x53A9_0001_0002_0003);
        let parent = SymbolCancelToken::new(
            ObjectId::new(0x1111_2222_3333_4444, 0x5555_6666_7777_8888),
            &mut rng,
        );
        let preexisting_child = parent.child(&mut rng);
        let listener_events = Arc::new(StdMutex::new(Vec::<Value>::new()));
        let listener_events_for_callback = Arc::clone(&listener_events);
        parent.add_listener(move |reason: &CancelReason, at: Time| {
            listener_events_for_callback
                .lock()
                .unwrap()
                .push(serde_json::json!({
                    "at_nanos": at.as_nanos(),
                    "kind": format!("{:?}", reason.kind),
                }));
        });

        let fresh_parent = observable_token_state_json(&parent);
        let fresh_preexisting_child = observable_token_state_json(&preexisting_child);

        let first_cancel_at = Time::from_nanos(991);
        assert!(
            parent.cancel(&CancelReason::user("phase-zero"), first_cancel_at),
            "first cancel should transition the token"
        );

        let after_first_cancel_events = listener_events.lock().unwrap().clone();
        let after_first_cancel_parent = observable_token_state_json(&parent);
        let after_first_cancel_preexisting_child = observable_token_state_json(&preexisting_child);

        let late_child = parent.child(&mut rng);
        let after_late_child_parent = observable_token_state_json(&parent);
        let after_late_child_late_child = observable_token_state_json(&late_child);

        let strengthened_returned_first_caller =
            parent.cancel(&CancelReason::shutdown(), Time::from_nanos(4096));

        let after_strengthen_events = listener_events.lock().unwrap().clone();
        let after_strengthen_parent = observable_token_state_json(&parent);
        let after_strengthen_preexisting_child = observable_token_state_json(&preexisting_child);
        let after_strengthen_late_child = observable_token_state_json(&late_child);

        let trace = serde_json::json!({
            "fresh": {
                "parent": fresh_parent,
                "preexisting_child": fresh_preexisting_child,
            },
            "after_first_cancel": {
                "listener_events": after_first_cancel_events,
                "parent": after_first_cancel_parent,
                "preexisting_child": after_first_cancel_preexisting_child,
            },
            "after_late_child": {
                "late_child": after_late_child_late_child,
                "parent": after_late_child_parent,
            },
            "after_strengthen": {
                "late_child": after_strengthen_late_child,
                "listener_events": after_strengthen_events,
                "parent": after_strengthen_parent,
                "preexisting_child": after_strengthen_preexisting_child,
                "strengthened_returned_first_caller": strengthened_returned_first_caller,
            },
        });

        insta::assert_json_snapshot!("cancel_token_phase_transition_trace_canonical", trace);
    }

    /// br-asupersync-64ijds — Conformance: a panic inside a registered
    /// `CancelListener::on_cancel` MUST NOT propagate to the caller of
    /// `SymbolCancelToken::cancel`. The implementation wraps each
    /// listener invocation in `std::panic::catch_unwind` (3 sites:
    /// the cancel hot path, the strengthen-and-renotify path, and the
    /// late-add notification path) — this test pins that contract so
    /// a future refactor can't accidentally remove the catch_unwind
    /// and propagate a malicious-listener panic up to the caller, who
    /// would then have its own protocol state corrupted by an
    /// unwinding stack.
    #[test]
    fn listener_panic_does_not_propagate_to_cancel_caller() {
        struct PanickingListener;
        impl CancelListener for PanickingListener {
            fn on_cancel(&self, _reason: &CancelReason, _at: Time) {
                panic!("br-asupersync-64ijds: listener intentionally panics");
            }
        }

        struct CountingListener {
            calls: Arc<std::sync::atomic::AtomicU64>,
        }
        impl CancelListener for CountingListener {
            fn on_cancel(&self, _reason: &CancelReason, _at: Time) {
                self.calls
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            }
        }

        let mut rng = DetRng::new(64);
        let token = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);

        // Attach panicking listener FIRST, then counting listener
        // SECOND. If catch_unwind ever regressed, the panicking
        // listener would short-circuit notification of subsequent
        // listeners — testing this proves the isolation extends past
        // the panic and reaches the next listener in the slot list.
        token.add_listener(PanickingListener);
        let calls = Arc::new(std::sync::atomic::AtomicU64::new(0));
        token.add_listener(CountingListener {
            calls: Arc::clone(&calls),
        });

        // Path 1: initial cancel. The panicking listener fires first;
        // catch_unwind absorbs the panic; the counting listener still
        // fires; cancel() returns true to the caller without unwinding.
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            token.cancel(&CancelReason::user("initial"), Time::from_millis(100))
        }));
        assert!(
            result.is_ok(),
            "br-asupersync-64ijds: cancel must not propagate listener panic"
        );
        assert_eq!(result.unwrap(), true, "first cancel should return true");
        assert_eq!(
            calls.load(std::sync::atomic::Ordering::Relaxed),
            1,
            "br-asupersync-64ijds: counting listener must fire even when prior listener panicked"
        );
        assert!(token.is_cancelled());

        // Path 2: strengthen-and-renotify. A higher-severity reason
        // hits the renotification path which has its own catch_unwind;
        // verify the same isolation invariant.
        let result2 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            token.cancel(&CancelReason::timeout(), Time::from_millis(200))
        }));
        assert!(
            result2.is_ok(),
            "br-asupersync-64ijds: renotification must not propagate listener panic"
        );
        // Both listeners fire on renotify; counting listener should
        // see at least one more call.
        assert!(
            calls.load(std::sync::atomic::Ordering::Relaxed) >= 2,
            "counting listener must fire on renotification"
        );

        // Path 3: late-attach replay. Adding a listener AFTER the
        // token is already cancelled triggers the catch_unwind'd
        // late-add notification path. A panicking listener attached
        // post-cancel must not propagate either.
        let result3 = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            token.add_listener(PanickingListener);
        }));
        assert!(
            result3.is_ok(),
            "br-asupersync-64ijds: late-add must not propagate listener panic"
        );
    }

    #[test]
    fn test_deserialized_cancelled_token_notifies_listener() {
        use std::sync::{
            Mutex,
            atomic::{AtomicBool, Ordering},
        };

        let mut rng = DetRng::new(42);
        let cancel_handle = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);
        cancel_handle.cancel(&CancelReason::user("initial"), Time::from_millis(100));

        let parsed = SymbolCancelToken::from_bytes(&cancel_handle.to_bytes()).unwrap();
        assert!(parsed.is_cancelled());

        let notified = Arc::new(AtomicBool::new(false));
        let notified_clone = Arc::clone(&notified);
        let seen_at = Arc::new(Mutex::new(None::<Time>));
        let seen_at_clone = Arc::clone(&seen_at);
        parsed.add_listener(move |_reason: &CancelReason, at: Time| {
            notified_clone.store(true, Ordering::SeqCst);
            *seen_at_clone.lock().unwrap() = Some(at);
        });

        assert!(notified.load(Ordering::SeqCst));
        assert_eq!(
            *seen_at.lock().unwrap(),
            Some(Time::ZERO),
            "deserialized cancelled tokens must replay with Time::ZERO instead of deadlocking"
        );
    }

    #[test]
    fn test_message_serialization() {
        let msg = CancelMessage::new(
            0x1234_5678_9abc_def0,
            ObjectId::new_for_test(42),
            CancelKind::Timeout,
            Time::from_millis(1000),
            999,
        )
        .with_max_hops(5);

        let bytes = msg.to_bytes();
        assert_eq!(bytes.len(), MESSAGE_WIRE_SIZE);

        let parsed = CancelMessage::from_bytes(&bytes).unwrap();
        assert_eq!(parsed.token_id(), msg.token_id());
        assert_eq!(parsed.object_id(), msg.object_id());
        assert_eq!(parsed.kind(), msg.kind());
        assert_eq!(parsed.initiated_at(), msg.initiated_at());
        assert_eq!(parsed.sequence(), msg.sequence());
    }

    #[test]
    fn test_message_hop_limit() {
        let msg = CancelMessage::new(
            1,
            ObjectId::new_for_test(1),
            CancelKind::User,
            Time::from_millis(100),
            0,
        )
        .with_max_hops(3);

        assert!(msg.can_forward());
        assert_eq!(msg.hops(), 0);

        let msg1 = msg.forwarded().unwrap();
        assert_eq!(msg1.hops(), 1);

        let msg2 = msg1.forwarded().unwrap();
        assert_eq!(msg2.hops(), 2);

        let msg3 = msg2.forwarded().unwrap();
        assert_eq!(msg3.hops(), 3);

        // At max hops, can't forward
        assert!(msg3.forwarded().is_none());
        assert!(!msg3.can_forward());
    }

    #[test]
    fn test_broadcaster_deduplication() {
        let broadcaster = CancelBroadcaster::new(NullSink);
        let msg = CancelMessage::new(
            1,
            ObjectId::new_for_test(1),
            CancelKind::User,
            Time::from_millis(100),
            0,
        );
        let now = Time::from_millis(100);

        // First receive should process
        let _ = broadcaster.receive_message(&msg, now);

        // Second receive should be duplicate
        let result = broadcaster.receive_message(&msg, now);
        assert!(result.is_none());

        let metrics = broadcaster.metrics();
        assert_eq!(metrics.received, 1);
        assert_eq!(metrics.duplicates, 1);
    }

    #[test]
    fn test_prepare_cancel_uses_token_id() {
        let mut rng = DetRng::new(7);
        let object_id = ObjectId::new_for_test(42);
        let cancel_handle = SymbolCancelToken::new(object_id, &mut rng);
        let token_id = cancel_handle.token_id();

        let broadcaster = CancelBroadcaster::new(NullSink);
        broadcaster.register_token(cancel_handle);

        let msg = broadcaster.prepare_cancel(
            object_id,
            &CancelReason::user("cancel"),
            Time::from_millis(10),
        );
        assert_eq!(msg.token_id(), token_id);
    }

    /// br-asupersync-ml5ba5 — Two distinct broadcasters cancelling
    /// the same ObjectId without holding a local token must produce
    /// distinct synthetic token_ids. The previous fallback
    /// `object_id.high() ^ object_id.low()` collapsed both to the
    /// same value, so a receiver dedup keyed on `(object_id,
    /// token_id, sequence)` could incorrectly suppress the second
    /// broadcaster's cancel when both sender's `next_sequence`
    /// happened to overlap (each starts from 0). The fix mixes a
    /// per-broadcaster random `sender_tag`.
    #[test]
    fn cross_sender_synthetic_token_id_does_not_collide() {
        let object_id = ObjectId::new_for_test(0xCAFE);
        let reason = CancelReason::user("cross-sender test");

        // Two broadcasters, no local tokens registered.
        let bcast_a = CancelBroadcaster::new(NullSink);
        let bcast_b = CancelBroadcaster::new(NullSink);

        let msg_a = bcast_a.prepare_cancel(object_id, &reason, Time::from_millis(10));
        let msg_b = bcast_b.prepare_cancel(object_id, &reason, Time::from_millis(20));

        // The synthetic token_ids differ across senders. (Tiny chance
        // — 2^-64 — of a random sender_tag collision; cosmically
        // unlikely.)
        assert_ne!(
            msg_a.token_id(),
            msg_b.token_id(),
            "br-asupersync-ml5ba5: two broadcasters must produce distinct synthetic token_ids"
        );

        // Receiver dedup contract: a fresh broadcaster receiving both
        // messages must NOT classify the second as a duplicate of
        // the first. Since the seen-key is (object_id, token_id,
        // sequence) and the token_ids differ, both messages survive
        // dedup independently.
        let receiver = CancelBroadcaster::new(NullSink);
        let f_a = receiver.receive_message(&msg_a, Time::from_millis(30));
        let f_b = receiver.receive_message(&msg_b, Time::from_millis(40));
        assert!(f_a.is_some(), "first cancel must forward");
        assert!(
            f_b.is_some(),
            "br-asupersync-ml5ba5: second sender's cancel must NOT be suppressed as duplicate"
        );
    }

    /// br-asupersync-ml5ba5 — Same-broadcaster path: two
    /// `prepare_cancel` calls on the same broadcaster + same
    /// ObjectId without a local token MUST mint the same synthetic
    /// token_id (the dedup contract that lets the receiver see them
    /// as the same logical cancel). `sender_tag` is stable per
    /// broadcaster, so this holds.
    #[test]
    fn same_sender_synthetic_token_id_is_stable() {
        let object_id = ObjectId::new_for_test(0xBEEF);
        let reason = CancelReason::user("stable");

        let bcast = CancelBroadcaster::new(NullSink);
        let msg1 = bcast.prepare_cancel(object_id, &reason, Time::from_millis(10));
        let msg2 = bcast.prepare_cancel(object_id, &reason, Time::from_millis(20));

        assert_eq!(
            msg1.token_id(),
            msg2.token_id(),
            "br-asupersync-ml5ba5: same broadcaster must produce stable synthetic token_id"
        );
    }

    #[test]
    fn test_broadcaster_forwards_message() {
        let broadcaster = CancelBroadcaster::new(NullSink);
        let msg = CancelMessage::new(
            1,
            ObjectId::new_for_test(1),
            CancelKind::User,
            Time::from_millis(100),
            0,
        );

        let forwarded = broadcaster.receive_message(&msg, Time::from_millis(100));
        assert!(forwarded.is_some());
        assert_eq!(forwarded.unwrap().hops(), 1);

        let metrics = broadcaster.metrics();
        assert_eq!(metrics.received, 1);
        assert_eq!(metrics.forwarded, 1);
    }

    #[test]
    fn receive_message_preserves_origin_initiated_at_for_local_tokens() {
        let mut rng = DetRng::new(88);
        let object_id = ObjectId::new_for_test(88);
        let token = SymbolCancelToken::new(object_id, &mut rng);
        let child = token.child(&mut rng);
        let seen_at = Arc::new(StdMutex::new(None::<Time>));
        let seen_at_clone = Arc::clone(&seen_at);
        token.add_listener(move |_reason: &CancelReason, at: Time| {
            *seen_at_clone.lock().unwrap() = Some(at);
        });

        let broadcaster = CancelBroadcaster::new(NullSink);
        broadcaster.register_token(token.clone());

        let initiated_at = Time::from_millis(125);
        let received_at = Time::from_millis(500);
        let msg = CancelMessage::new(
            token.token_id(),
            object_id,
            CancelKind::Shutdown,
            initiated_at,
            0,
        );

        let forwarded = broadcaster.receive_message(&msg, received_at);
        assert!(forwarded.is_some(), "fresh cancel should still forward");
        assert_eq!(
            token.cancelled_at(),
            Some(initiated_at),
            "br-asupersync-zmeazg: remote cancel must preserve origin initiated_at"
        );
        assert_eq!(
            child.cancelled_at(),
            Some(initiated_at),
            "child cascade should inherit the same origin initiated_at"
        );
        assert_eq!(
            *seen_at.lock().unwrap(),
            Some(initiated_at),
            "listener callbacks must observe the origin initiated_at, not local receipt time"
        );
    }

    #[test]
    fn cancel_broadcast_drains_remote_children_under_lab_runtime() {
        init_test_logging();
        crate::test_phase!("cancel_broadcast_drains_remote_children_under_lab_runtime");

        let config = TestConfig::new()
            .with_seed(0xCAA0_CE11)
            .with_tracing(true)
            .with_max_steps(20_000);
        let mut runtime = LabRuntimeTarget::create_runtime(config);
        let checkpoints = Arc::new(StdMutex::new(Vec::<Value>::new()));
        let local_messages = Arc::new(StdMutex::new(Vec::<CancelMessage>::new()));
        let remote_messages = Arc::new(StdMutex::new(Vec::<CancelMessage>::new()));

        let (
            local_cancelled,
            remote_cancelled,
            remote_child_cancelled,
            late_child_cancelled,
            remote_reason,
            remote_metrics,
            checkpoints,
        ) = LabRuntimeTarget::block_on(&mut runtime, async move {
            let cx = crate::cx::Cx::current().expect("lab runtime should install a current Cx");
            let local_spawn_cx = cx.clone();
            let remote_spawn_cx = cx.clone();
            let object_id = ObjectId::new_for_test(44);

            let local_sink = RecordingSink {
                label: "local",
                checkpoints: Arc::clone(&checkpoints),
                messages: Arc::clone(&local_messages),
            };
            let remote_sink = RecordingSink {
                label: "remote",
                checkpoints: Arc::clone(&checkpoints),
                messages: Arc::clone(&remote_messages),
            };

            let local_broadcaster = Arc::new(CancelBroadcaster::new(local_sink));
            let remote_broadcaster = Arc::new(CancelBroadcaster::new(remote_sink));

            let mut local_rng = DetRng::new(101);
            let local_token = SymbolCancelToken::new(object_id, &mut local_rng);
            local_broadcaster.register_token(local_token.clone());

            let mut remote_rng = DetRng::new(202);
            let remote_token = SymbolCancelToken::new(object_id, &mut remote_rng);
            let remote_child = remote_token.child(&mut remote_rng);
            let late_child = Arc::new(StdMutex::new(None::<SymbolCancelToken>));
            let late_child_listener = Arc::clone(&late_child);
            let listener_checkpoints = Arc::clone(&checkpoints);
            let remote_token_for_listener = remote_token.clone();
            remote_token.add_listener(move |reason: &CancelReason, at: Time| {
                let listener_event = serde_json::json!({
                    "phase": "remote_listener_invoked",
                    "kind": format!("{:?}", reason.kind),
                    "at_millis": at.as_millis(),
                });
                tracing::info!(event = %listener_event, "symbol_cancel_lab_checkpoint");
                listener_checkpoints.lock().unwrap().push(listener_event);

                let mut child_rng = DetRng::new(303);
                let child = remote_token_for_listener.child(&mut child_rng);
                *late_child_listener.lock().unwrap() = Some(child);
            });
            remote_broadcaster.register_token(remote_token.clone());

            let local_task = LabRuntimeTarget::spawn(&local_spawn_cx, Budget::INFINITE, {
                let local_broadcaster = Arc::clone(&local_broadcaster);
                let local_token = local_token.clone();
                let checkpoints = Arc::clone(&checkpoints);
                async move {
                    let request = serde_json::json!({
                        "phase": "local_cancel_requested",
                        "object_high": object_id.high(),
                    });
                    tracing::info!(event = %request, "symbol_cancel_lab_checkpoint");
                    checkpoints.lock().unwrap().push(request);

                    let sent = local_broadcaster
                        .cancel(object_id, &CancelReason::shutdown(), Time::from_millis(100))
                        .await
                        .expect("local cancel should broadcast successfully");

                    let completed = serde_json::json!({
                        "phase": "local_cancel_completed",
                        "sent": sent,
                    });
                    tracing::info!(event = %completed, "symbol_cancel_lab_checkpoint");
                    checkpoints.lock().unwrap().push(completed);
                    local_token.is_cancelled()
                }
            });

            let local_outcome = local_task.await;
            crate::assert_with_log!(
                matches!(local_outcome, crate::types::Outcome::Ok(true)),
                "local cancel task completes successfully",
                true,
                matches!(local_outcome, crate::types::Outcome::Ok(true))
            );
            let crate::types::Outcome::Ok(local_cancelled) = local_outcome else {
                panic!("local cancel task should finish successfully");
            };

            let forwarded = local_messages
                .lock()
                .unwrap()
                .first()
                .cloned()
                .expect("local cancel should emit a broadcast message");

            let remote_task = LabRuntimeTarget::spawn(&remote_spawn_cx, Budget::INFINITE, {
                let remote_broadcaster = Arc::clone(&remote_broadcaster);
                let remote_token = remote_token.clone();
                let remote_child = remote_child.clone();
                let late_child = Arc::clone(&late_child);
                let checkpoints = Arc::clone(&checkpoints);
                async move {
                    let received = serde_json::json!({
                        "phase": "remote_handle_started",
                        "sequence": forwarded.sequence(),
                    });
                    tracing::info!(event = %received, "symbol_cancel_lab_checkpoint");
                    checkpoints.lock().unwrap().push(received);

                    remote_broadcaster
                        .handle_message(forwarded, Time::from_millis(125))
                        .await
                        .expect("remote handle_message should succeed");

                    let completed = serde_json::json!({
                        "phase": "remote_handle_completed",
                        "forwarded_count": remote_broadcaster.metrics().forwarded,
                    });
                    tracing::info!(event = %completed, "symbol_cancel_lab_checkpoint");
                    checkpoints.lock().unwrap().push(completed);

                    (
                        remote_token.is_cancelled(),
                        remote_child.is_cancelled(),
                        late_child
                            .lock()
                            .unwrap()
                            .clone()
                            .expect("late child should be created by remote listener")
                            .is_cancelled(),
                        remote_token
                            .reason()
                            .expect("remote token should have a reason")
                            .kind,
                        remote_broadcaster.metrics(),
                    )
                }
            });

            let remote_outcome = remote_task.await;
            crate::assert_with_log!(
                matches!(remote_outcome, crate::types::Outcome::Ok(_)),
                "remote handle task completes successfully",
                true,
                matches!(remote_outcome, crate::types::Outcome::Ok(_))
            );
            let crate::types::Outcome::Ok((
                remote_cancelled,
                remote_child_cancelled,
                late_child_cancelled,
                remote_reason,
                remote_metrics,
            )) = remote_outcome
            else {
                panic!("remote handle task should finish successfully");
            };

            assert_eq!(
                remote_token.state.children.read().len(),
                0,
                "remote cancellation should drain queued children before returning"
            );
            assert_eq!(
                remote_token.state.listeners.read().len(),
                1,
                "remote cancellation should retain only the original listener before returning"
            );

            (
                local_cancelled,
                remote_cancelled,
                remote_child_cancelled,
                late_child_cancelled,
                remote_reason,
                remote_metrics,
                checkpoints.lock().unwrap().clone(),
            )
        });

        assert!(
            local_cancelled,
            "local token should be cancelled by broadcaster.cancel"
        );
        assert!(
            remote_cancelled,
            "remote token should be cancelled by forwarded message"
        );
        assert!(
            remote_child_cancelled,
            "remote pre-existing child should be drained during cancellation"
        );
        assert!(
            late_child_cancelled,
            "listener-spawned child should be cancelled before handle_message returns"
        );
        assert_eq!(remote_reason, CancelKind::Shutdown);
        assert_eq!(remote_metrics.received, 1);
        assert_eq!(remote_metrics.forwarded, 1);
        assert!(
            checkpoints
                .iter()
                .any(|event| event["phase"] == "local_broadcast"),
            "local broadcast checkpoint should be recorded"
        );
        assert!(
            checkpoints
                .iter()
                .any(|event| event["phase"] == "remote_listener_invoked"),
            "remote listener checkpoint should be recorded"
        );
        assert!(
            checkpoints
                .iter()
                .any(|event| event["phase"] == "remote_handle_completed"),
            "remote completion checkpoint should be recorded"
        );

        let violations = runtime.oracles.check_all(runtime.now());
        assert!(
            violations.is_empty(),
            "symbol cancel lab-runtime test should leave runtime invariants clean: {violations:?}"
        );
    }

    #[test]
    fn test_broadcaster_seen_eviction_is_fifo() {
        let mut broadcaster = CancelBroadcaster::new(NullSink);
        broadcaster.max_seen = 3;
        let object_id = ObjectId::new_for_test(1);

        // Insert 4 distinct sequences; oldest should be evicted.
        for seq in 0..4 {
            broadcaster.mark_seen(object_id, 1, seq);
        }

        let (len, has_10, has_11, front) = {
            let seen = broadcaster.seen_sequences.read();
            let len = seen.set.len();
            let has_10 = seen.set.contains(&(object_id, 1, 0));
            let has_11 = seen.set.contains(&(object_id, 1, 1));
            let front = seen.order.front().copied();
            drop(seen);
            (len, has_10, has_11, front)
        };
        assert_eq!(len, 3);
        assert!(!has_10);
        assert!(has_11);
        assert_eq!(front, Some((object_id, 1, 1)));
    }

    #[test]
    fn test_cleanup_pending_symbols() {
        let coordinator = CleanupCoordinator::new();
        let object_id = ObjectId::new_for_test(1);
        let now = Time::from_millis(100);

        coordinator.register_handler(object_id, CountingCleanupHandler);

        // Register some symbols
        for i in 0..5 {
            let symbol = Symbol::new_for_test(1, 0, i, &[1, 2, 3, 4]);
            coordinator.register_pending(object_id, symbol, now);
        }

        let stats = coordinator.stats();
        assert_eq!(stats.pending_objects, 1);
        assert_eq!(stats.pending_symbols, 5);
        assert_eq!(stats.pending_bytes, 20); // 5 * 4 bytes

        // Cleanup
        let result = coordinator.cleanup(object_id, None);
        assert_eq!(result.symbols_cleaned, 5);
        assert_eq!(result.bytes_freed, 20);
        assert!(result.within_budget);

        // Stats should be zero
        let stats = coordinator.stats();
        assert_eq!(stats.pending_objects, 0);
    }

    #[test]
    fn test_cleanup_within_budget() {
        let coordinator = CleanupCoordinator::new();
        let object_id = ObjectId::new_for_test(1);
        let now = Time::from_millis(100);

        let symbol = Symbol::new_for_test(1, 0, 0, &[1, 2, 3, 4]);
        coordinator.register_pending(object_id, symbol, now);

        // Generous budget
        let budget = Budget::new().with_poll_quota(1000);
        let result = coordinator.cleanup(object_id, Some(budget));
        assert!(result.within_budget);
    }

    #[test]
    fn test_cleanup_handler_called() {
        use std::sync::atomic::{AtomicBool, Ordering};

        struct TestHandler {
            called: Arc<AtomicBool>,
        }

        impl CleanupHandler for TestHandler {
            fn cleanup(
                &self,
                _object_id: ObjectId,
                _symbols: Vec<Symbol>,
            ) -> crate::error::Result<usize> {
                self.called.store(true, Ordering::SeqCst);
                Ok(0)
            }

            fn name(&self) -> &'static str {
                "test"
            }
        }

        let coordinator = CleanupCoordinator::new();
        let object_id = ObjectId::new_for_test(1);
        let now = Time::from_millis(100);

        let called = Arc::new(AtomicBool::new(false));
        coordinator.register_handler(
            object_id,
            TestHandler {
                called: called.clone(),
            },
        );

        let symbol = Symbol::new_for_test(1, 0, 0, &[1, 2]);
        coordinator.register_pending(object_id, symbol, now);

        let result = coordinator.cleanup(object_id, None);
        assert!(called.load(Ordering::SeqCst));
        assert_eq!(result.handlers_run, vec!["test"]);
        assert!(result.completed);
        assert!(result.handler_errors.is_empty());
    }

    #[test]
    fn test_cleanup_with_handler_and_no_symbols_marks_completed() {
        let coordinator = CleanupCoordinator::new();
        let object_id = ObjectId::new_for_test(10);

        coordinator.register_handler(object_id, CountingCleanupHandler);

        let result = coordinator.cleanup(object_id, None);
        assert!(result.completed, "empty cleanup should complete");
        assert!(
            coordinator.completed.read().contains(&object_id),
            "successful empty cleanup must mark object completed"
        );
        assert_eq!(
            coordinator
                .handlers
                .read()
                .get(&object_id)
                .map(|handler| handler.name()),
            None,
            "cleanup should drop the registered handler"
        );

        coordinator.register_pending(
            object_id,
            Symbol::new_for_test(10, 0, 0, &[1, 2, 3]),
            Time::from_millis(101),
        );

        let stats = coordinator.stats();
        assert_eq!(
            stats.pending_objects, 0,
            "late pending symbols must be rejected after completed empty cleanup"
        );
        assert_eq!(stats.pending_symbols, 0);
    }

    #[test]
    fn test_clear_pending_drops_registered_handler() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct DropCountingHandler {
            drops: Arc<AtomicUsize>,
        }

        impl Drop for DropCountingHandler {
            fn drop(&mut self) {
                self.drops.fetch_add(1, Ordering::SeqCst);
            }
        }

        impl CleanupHandler for DropCountingHandler {
            fn cleanup(
                &self,
                _object_id: ObjectId,
                _symbols: Vec<Symbol>,
            ) -> crate::error::Result<usize> {
                Ok(0)
            }

            fn name(&self) -> &'static str {
                "drop-counting"
            }
        }

        let coordinator = CleanupCoordinator::new();
        let object_id = ObjectId::new_for_test(6);
        let now = Time::from_millis(100);
        let drops = Arc::new(AtomicUsize::new(0));

        coordinator.register_handler(
            object_id,
            DropCountingHandler {
                drops: Arc::clone(&drops),
            },
        );
        coordinator.register_pending(object_id, Symbol::new_for_test(6, 0, 0, &[1, 2, 3]), now);

        assert_eq!(coordinator.handlers.read().len(), 1);
        assert_eq!(coordinator.clear_pending(&object_id), Some(1));
        assert_eq!(coordinator.handlers.read().len(), 0);
        assert_eq!(drops.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_cleanup_handler_error_preserves_retry_state() {
        struct FailingHandler;

        impl CleanupHandler for FailingHandler {
            fn cleanup(
                &self,
                _object_id: ObjectId,
                _symbols: Vec<Symbol>,
            ) -> crate::error::Result<usize> {
                Err(crate::error::Error::new(crate::error::ErrorKind::Internal)
                    .with_message("cleanup failed"))
            }

            fn name(&self) -> &'static str {
                "failing"
            }
        }

        let coordinator = CleanupCoordinator::new();
        let object_id = ObjectId::new_for_test(7);
        let now = Time::from_millis(100);

        coordinator.register_handler(object_id, FailingHandler);
        coordinator.register_pending(object_id, Symbol::new_for_test(7, 0, 0, &[1, 2, 3]), now);

        let result = coordinator.cleanup(object_id, None);
        assert!(
            !result.completed,
            "failed handler must not report completion"
        );
        assert_eq!(
            result.symbols_cleaned, 0,
            "failed cleanup must not report cleaned symbols"
        );
        assert_eq!(
            result.bytes_freed, 0,
            "failed cleanup must not report freed bytes"
        );
        assert_eq!(result.handlers_run, vec!["failing"]);
        assert_eq!(result.handler_errors.len(), 1);
        assert!(
            result.handler_errors[0].contains("cleanup failed"),
            "{}",
            result.handler_errors[0]
        );

        let stats = coordinator.stats();
        assert_eq!(
            stats.pending_objects, 1,
            "failed cleanup must remain retryable"
        );
        assert_eq!(stats.pending_symbols, 1);
        assert_eq!(stats.pending_bytes, 3);
    }

    #[test]
    fn restore_retry_state_acquires_handler_table_before_pending_state() {
        use std::sync::Barrier;
        use std::time::{Duration, Instant};

        let coordinator = Arc::new(CleanupCoordinator::new());
        let object_id = ObjectId::new_for_test(70);
        let pending_set = PendingSymbolSet {
            symbols: vec![Symbol::new_for_test(70, 0, 0, &[1, 2, 3])],
            total_bytes: 3,
            _created_at: Time::from_millis(100),
        };
        let pending_guard = coordinator.pending.write();
        let started = Arc::new(Barrier::new(2));
        let restore_started = Arc::clone(&started);
        let restore_coordinator = Arc::clone(&coordinator);

        let handle = std::thread::spawn(move || {
            restore_started.wait();
            restore_coordinator.restore_retry_state(
                object_id,
                Box::new(CountingCleanupHandler),
                pending_set,
            );
        });

        started.wait();
        let mut saw_handler_table_locked = false;
        let deadline = Instant::now() + Duration::from_secs(1);
        while Instant::now() < deadline {
            if coordinator.handlers.try_write().is_none() {
                saw_handler_table_locked = true;
                break;
            }
            std::thread::yield_now();
        }

        drop(pending_guard);
        handle
            .join()
            .expect("retry-state restoration thread should finish");

        assert!(
            saw_handler_table_locked,
            "restore_retry_state must acquire handlers before waiting for pending; \
             otherwise a handlers->pending caller can form an AB-BA lock cycle"
        );
        assert!(
            coordinator.handlers.read().contains_key(&object_id),
            "retry restoration should preserve the cleanup handler"
        );
        assert_eq!(
            coordinator.stats().pending_symbols,
            1,
            "retry restoration should preserve pending symbols"
        );
    }

    #[test]
    fn test_cleanup_handler_error_reopens_object_for_new_pending_symbols() {
        struct FailingHandler;

        impl CleanupHandler for FailingHandler {
            fn cleanup(
                &self,
                _object_id: ObjectId,
                _symbols: Vec<Symbol>,
            ) -> crate::error::Result<usize> {
                Err(crate::error::Error::new(crate::error::ErrorKind::Internal)
                    .with_message("cleanup failed"))
            }

            fn name(&self) -> &'static str {
                "failing"
            }
        }

        let coordinator = CleanupCoordinator::new();
        let object_id = ObjectId::new_for_test(8);
        let now = Time::from_millis(100);

        coordinator.register_handler(object_id, FailingHandler);
        coordinator.register_pending(object_id, Symbol::new_for_test(8, 0, 0, &[1, 2, 3]), now);

        let result = coordinator.cleanup(object_id, None);
        assert!(
            !result.completed,
            "failed cleanup must leave object retryable"
        );

        coordinator.register_pending(
            object_id,
            Symbol::new_for_test(8, 0, 1, &[4, 5]),
            Time::from_millis(101),
        );

        let stats = coordinator.stats();
        assert_eq!(
            stats.pending_symbols, 2,
            "retryable cleanup must continue accepting pending symbols"
        );
        assert_eq!(stats.pending_bytes, 5);
    }

    #[test]
    fn test_cleanup_budget_exhaustion_reopens_object_for_new_pending_symbols() {
        struct RecordingHandler;

        impl CleanupHandler for RecordingHandler {
            fn cleanup(
                &self,
                _object_id: ObjectId,
                _symbols: Vec<Symbol>,
            ) -> crate::error::Result<usize> {
                Ok(1)
            }

            fn name(&self) -> &'static str {
                "recording"
            }
        }

        let coordinator = CleanupCoordinator::new();
        let object_id = ObjectId::new_for_test(9);
        let now = Time::from_millis(100);

        coordinator.register_handler(object_id, RecordingHandler);
        coordinator.register_pending(object_id, Symbol::new_for_test(9, 0, 0, &[1]), now);

        let budget = Budget::new().with_poll_quota(0);
        let result = coordinator.cleanup(object_id, Some(budget));
        assert!(
            !result.completed,
            "budget-exhausted cleanup must leave object retryable"
        );
        assert!(
            !result.within_budget,
            "zero-poll budget should report budget exhaustion"
        );

        coordinator.register_pending(
            object_id,
            Symbol::new_for_test(9, 0, 1, &[2, 3]),
            Time::from_millis(101),
        );

        let stats = coordinator.stats();
        assert_eq!(
            stats.pending_symbols, 2,
            "budget-exhausted cleanup must continue accepting pending symbols"
        );
        assert_eq!(stats.pending_bytes, 3);
    }

    #[test]
    fn test_cleanup_handler_invoked_without_holding_handler_lock() {
        use std::sync::atomic::{AtomicBool, Ordering};

        struct LockCheckHandler {
            coordinator: Arc<CleanupCoordinator>,
            write_lock_available: Arc<AtomicBool>,
        }

        impl CleanupHandler for LockCheckHandler {
            fn cleanup(
                &self,
                _object_id: ObjectId,
                _symbols: Vec<Symbol>,
            ) -> crate::error::Result<usize> {
                let can_acquire_write = self.coordinator.handlers.try_write().is_some();
                self.write_lock_available
                    .store(can_acquire_write, Ordering::SeqCst);
                Ok(0)
            }

            fn name(&self) -> &'static str {
                "lock-check"
            }
        }

        let coordinator = Arc::new(CleanupCoordinator::new());
        let object_id = ObjectId::new_for_test(99);
        let now = Time::from_millis(100);
        let write_lock_available = Arc::new(AtomicBool::new(false));

        coordinator.register_handler(
            object_id,
            LockCheckHandler {
                coordinator: Arc::clone(&coordinator),
                write_lock_available: Arc::clone(&write_lock_available),
            },
        );

        coordinator.register_pending(object_id, Symbol::new_for_test(99, 0, 0, &[1]), now);
        let _ = coordinator.cleanup(object_id, None);

        assert!(
            write_lock_available.load(Ordering::SeqCst),
            "cleanup handler callback should execute without handlers lock held"
        );
    }

    #[test]
    fn test_cleanup_stats_accurate() {
        let coordinator = CleanupCoordinator::new();
        let now = Time::from_millis(100);

        // Empty stats
        let stats = coordinator.stats();
        assert_eq!(stats.pending_objects, 0);
        assert_eq!(stats.pending_symbols, 0);
        assert_eq!(stats.pending_bytes, 0);

        // Add symbols for two objects
        let obj1 = ObjectId::new_for_test(1);
        let obj2 = ObjectId::new_for_test(2);

        coordinator.register_pending(obj1, Symbol::new_for_test(1, 0, 0, &[1, 2, 3]), now);
        coordinator.register_pending(obj1, Symbol::new_for_test(1, 0, 1, &[4, 5, 6]), now);
        coordinator.register_pending(obj2, Symbol::new_for_test(2, 0, 0, &[7, 8]), now);

        let stats = coordinator.stats();
        assert_eq!(stats.pending_objects, 2);
        assert_eq!(stats.pending_symbols, 3);
        assert_eq!(stats.pending_bytes, 8); // 3 + 3 + 2

        // Clear one object
        coordinator.clear_pending(&obj1);

        let stats = coordinator.stats();
        assert_eq!(stats.pending_objects, 1);
        assert_eq!(stats.pending_symbols, 1);
        assert_eq!(stats.pending_bytes, 2);
    }

    // ---- Cancel propagation: grandchild inherits cancellation -----------

    #[test]
    fn test_grandchild_inherits_cancellation() {
        let mut rng = DetRng::new(42);
        let grandparent = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);
        let parent = grandparent.child(&mut rng);
        let child = parent.child(&mut rng);

        assert!(!child.is_cancelled());

        // Cancel grandparent — should propagate to grandchild.
        grandparent.cancel(&CancelReason::user("cascade"), Time::from_millis(100));

        assert!(parent.is_cancelled());
        assert!(child.is_cancelled());
        assert_eq!(child.reason().unwrap().kind, CancelKind::ParentCancelled);
        assert_eq!(
            reason_chain_kinds(&child),
            vec![
                CancelKind::ParentCancelled,
                CancelKind::ParentCancelled,
                CancelKind::User,
            ],
            "grandchild cancellation should validate the full parent chain"
        );
    }

    #[test]
    fn test_cancel_drains_children_and_late_child_is_not_queued() {
        let mut rng = DetRng::new(7);
        let parent = SymbolCancelToken::new(ObjectId::new_for_test(5), &mut rng);
        let child_a = parent.child(&mut rng);
        let child_b = parent.child(&mut rng);

        assert_eq!(
            parent.state.children.read().len(),
            2,
            "precondition: both children should be queued under parent"
        );

        let now = Time::from_millis(100);
        assert!(
            parent.cancel(&CancelReason::user("drain"), now),
            "first caller should trigger cancellation"
        );
        assert!(child_a.is_cancelled(), "queued child A must be cancelled");
        assert!(child_b.is_cancelled(), "queued child B must be cancelled");
        assert_eq!(
            parent.state.children.read().len(),
            0,
            "children vector must be drained after parent cancel"
        );

        let late_child = parent.child(&mut rng);
        assert!(
            late_child.is_cancelled(),
            "late child should be cancelled immediately when parent already cancelled"
        );
        assert_eq!(
            parent.state.children.read().len(),
            0,
            "late child should not be retained in parent children vector"
        );
    }

    #[test]
    fn test_listener_spawned_child_is_drained_inline() {
        let mut rng = DetRng::new(91);
        let parent = SymbolCancelToken::new(ObjectId::new_for_test(6), &mut rng);
        let observed_child = Arc::new(std::sync::Mutex::new(None::<SymbolCancelToken>));
        let observed_child_clone = Arc::clone(&observed_child);
        let parent_for_listener = parent.clone();

        parent.add_listener(move |_: &CancelReason, _: Time| {
            let mut child_rng = DetRng::new(92);
            let child = parent_for_listener.child(&mut child_rng);
            *observed_child_clone.lock().unwrap() = Some(child);
        });

        let now = Time::from_millis(150);
        assert!(
            parent.cancel(&CancelReason::user("listener-child"), now),
            "first caller should trigger cancellation"
        );

        let late_child = observed_child
            .lock()
            .unwrap()
            .clone()
            .expect("listener should create a child during cancellation");
        assert!(
            late_child.is_cancelled(),
            "child created during listener callback must be cancelled before cancel() returns"
        );
        assert_eq!(
            late_child.reason().unwrap().kind,
            CancelKind::ParentCancelled,
            "late child should inherit parent-cancelled semantics"
        );
        assert_eq!(
            reason_chain_kinds(&late_child),
            vec![CancelKind::ParentCancelled, CancelKind::User],
            "late child created inside listener should retain the parent reason as a cause"
        );
        assert_eq!(
            late_child.cancelled_at(),
            Some(now),
            "late child should observe the parent cancellation timestamp"
        );
        assert_eq!(
            parent.state.children.read().len(),
            0,
            "listener-spawned child must not be retained after drain completes"
        );
    }

    #[test]
    fn test_listener_registered_during_cancel_not_requeued() {
        let mut rng = DetRng::new(93);
        let token = SymbolCancelToken::new(ObjectId::new_for_test(7), &mut rng);
        let notification_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let seen_kind = Arc::new(std::sync::Mutex::new(None::<CancelKind>));
        let seen_time = Arc::new(std::sync::Mutex::new(None::<Time>));

        let token_for_listener = token.clone();
        let notification_count_clone = Arc::clone(&notification_count);
        let seen_kind_clone = Arc::clone(&seen_kind);
        let seen_time_clone = Arc::clone(&seen_time);
        token.add_listener(move |_: &CancelReason, _: Time| {
            token_for_listener.add_listener({
                let notification_count_clone = Arc::clone(&notification_count_clone);
                let seen_kind_clone = Arc::clone(&seen_kind_clone);
                let seen_time_clone = Arc::clone(&seen_time_clone);
                move |reason: &CancelReason, at: Time| {
                    notification_count_clone.fetch_add(1, Ordering::SeqCst);
                    *seen_kind_clone.lock().unwrap() = Some(reason.kind);
                    *seen_time_clone.lock().unwrap() = Some(at);
                }
            });
        });

        let now = Time::from_millis(175);
        assert!(
            token.cancel(&CancelReason::timeout(), now),
            "first caller should trigger listener drain"
        );
        assert_eq!(
            notification_count.load(Ordering::SeqCst),
            1,
            "listener registered during cancellation should be invoked inline exactly once"
        );
        assert_eq!(
            *seen_kind.lock().unwrap(),
            Some(CancelKind::Timeout),
            "late listener should observe the current cancellation kind"
        );
        assert_eq!(
            *seen_time.lock().unwrap(),
            Some(now),
            "late listener should observe the current cancellation timestamp"
        );
        assert_eq!(
            token.state.listeners.read().len(),
            1,
            "the original retained listener remains, but the late listener must not be queued"
        );

        token.cancel(&CancelReason::shutdown(), Time::from_millis(200));
        assert_eq!(
            notification_count.load(Ordering::SeqCst),
            2,
            "the retained original listener should run again on strengthen and self-notify one late listener"
        );
        assert_eq!(
            *seen_kind.lock().unwrap(),
            Some(CancelKind::Shutdown),
            "late listener should observe the strengthened cancellation kind"
        );
        assert_eq!(
            *seen_time.lock().unwrap(),
            Some(now),
            "late listener should observe the canonical first-cancel timestamp after strengthen"
        );
        assert_eq!(
            token.state.listeners.read().len(),
            1,
            "strengthened cancellations retain only the original listener"
        );
    }

    #[test]
    fn test_listener_registered_during_cancel_can_spawn_child_without_leak() {
        let mut rng = DetRng::new(94);
        let token = SymbolCancelToken::new(ObjectId::new_for_test(8), &mut rng);
        let spawned_child = Arc::new(std::sync::Mutex::new(None::<SymbolCancelToken>));
        let spawned_child_clone = Arc::clone(&spawned_child);
        let child_notification_count = Arc::new(AtomicUsize::new(0));
        let child_notification_count_clone = Arc::clone(&child_notification_count);
        let token_for_listener = token.clone();

        token.add_listener(move |_: &CancelReason, _: Time| {
            token_for_listener.add_listener({
                let spawned_child_clone = Arc::clone(&spawned_child_clone);
                let child_notification_count_clone = Arc::clone(&child_notification_count_clone);
                let token_for_listener = token_for_listener.clone();
                move |reason: &CancelReason, at: Time| {
                    child_notification_count_clone.fetch_add(1, Ordering::SeqCst);
                    let mut child_rng = DetRng::new(95);
                    let child = token_for_listener.child(&mut child_rng);
                    assert!(
                        child.is_cancelled(),
                        "child created from a late listener must be cancelled inline"
                    );
                    assert_eq!(
                        child.reason().unwrap().kind,
                        CancelKind::ParentCancelled,
                        "late child should inherit parent-cancelled semantics"
                    );
                    assert_eq!(
                        child.cancelled_at(),
                        Some(at),
                        "late child should observe the current cancellation timestamp"
                    );
                    assert_eq!(
                        reason.kind,
                        CancelKind::Shutdown,
                        "late listener should observe the active cancellation reason"
                    );
                    *spawned_child_clone.lock().unwrap() = Some(child);
                }
            });
        });

        let now = Time::from_millis(250);
        assert!(
            token.cancel(&CancelReason::shutdown(), now),
            "first caller should trigger cancellation"
        );

        let child = spawned_child
            .lock()
            .unwrap()
            .clone()
            .expect("late listener should have spawned a child");
        assert_eq!(
            child_notification_count.load(Ordering::SeqCst),
            1,
            "late listener should run exactly once during drain"
        );
        assert!(child.is_cancelled(), "spawned child must remain cancelled");
        assert_eq!(
            child.cancelled_at(),
            Some(now),
            "spawned child should be cancelled before cancel() returns"
        );
        assert_eq!(
            token.state.listeners.read().len(),
            1,
            "drain must retain only the original listener, not the late listener"
        );
        assert_eq!(
            token.state.children.read().len(),
            0,
            "drain must leave no late children queued"
        );
    }

    // ---- Cancel propagation: child cancel does not affect parent --------

    #[test]
    fn test_child_cancel_does_not_propagate_upward() {
        let mut rng = DetRng::new(42);
        let parent = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);
        let child = parent.child(&mut rng);

        // Cancel the child directly.
        child.cancel(&CancelReason::user("child only"), Time::from_millis(100));

        assert!(child.is_cancelled());
        assert!(!parent.is_cancelled());
    }

    // ---- Cancel severity ordering: stronger reason wins -----------------

    #[test]
    fn test_cancel_strengthens_reason() {
        let mut rng = DetRng::new(42);
        let cancel_handle = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);

        // First cancel with User reason.
        let first = cancel_handle.cancel(&CancelReason::user("first"), Time::from_millis(100));
        assert!(first);

        // Second cancel with Shutdown reason — should strengthen.
        let second = cancel_handle.cancel(
            &CancelReason::new(CancelKind::Shutdown),
            Time::from_millis(200),
        );
        assert!(!second); // not the first caller

        // Reason strengthened to Shutdown (more severe).
        assert_eq!(cancel_handle.reason().unwrap().kind, CancelKind::Shutdown);
        // Timestamp unchanged (first cancel time preserved).
        assert_eq!(cancel_handle.cancelled_at(), Some(Time::from_millis(100)));
    }

    #[test]
    fn test_cancel_does_not_weaken_reason() {
        let mut rng = DetRng::new(42);
        let cancel_handle = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);

        // First cancel with Shutdown reason.
        let first = cancel_handle.cancel(
            &CancelReason::new(CancelKind::Shutdown),
            Time::from_millis(100),
        );
        assert!(first);

        // Second cancel with weaker User reason — should not weaken.
        let second = cancel_handle.cancel(&CancelReason::user("gentle"), Time::from_millis(200));
        assert!(!second);

        // Reason stays at Shutdown.
        assert_eq!(cancel_handle.reason().unwrap().kind, CancelKind::Shutdown);
    }

    // ---- Multiple listeners notified on cancel --------------------------

    #[test]
    fn test_multiple_listeners_all_notified() {
        use std::sync::atomic::{AtomicU32, Ordering};

        let mut rng = DetRng::new(42);
        let cancel_handle = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);

        let count = Arc::new(AtomicU32::new(0));

        for _ in 0..3 {
            let c = count.clone();
            cancel_handle.add_listener(move |_: &CancelReason, _: Time| {
                c.fetch_add(1, Ordering::SeqCst);
            });
        }

        cancel_handle.cancel(&CancelReason::timeout(), Time::from_millis(100));

        assert_eq!(count.load(Ordering::SeqCst), 3);
    }

    // ---- Cleanup coordinator: multiple objects cleaned independently -----

    #[test]
    fn test_cleanup_multiple_objects_independent() {
        let coordinator = CleanupCoordinator::new();
        let now = Time::from_millis(100);
        let obj1 = ObjectId::new_for_test(1);
        let obj2 = ObjectId::new_for_test(2);

        coordinator.register_handler(obj1, CountingCleanupHandler);

        // Register symbols for two separate objects.
        for i in 0..3 {
            coordinator.register_pending(obj1, Symbol::new_for_test(1, 0, i, &[1, 2]), now);
        }
        for i in 0..2 {
            coordinator.register_pending(obj2, Symbol::new_for_test(2, 0, i, &[3, 4, 5]), now);
        }

        let stats = coordinator.stats();
        assert_eq!(stats.pending_objects, 2);
        assert_eq!(stats.pending_symbols, 5);

        // Cleanup only obj1.
        let result = coordinator.cleanup(obj1, None);
        assert_eq!(result.symbols_cleaned, 3);
        assert_eq!(result.bytes_freed, 6); // 3 * 2

        // obj2 still has its symbols.
        let stats = coordinator.stats();
        assert_eq!(stats.pending_objects, 1);
        assert_eq!(stats.pending_symbols, 2);
        assert_eq!(stats.pending_bytes, 6); // 2 * 3
    }

    // ---- Token serialization roundtrip preserves all fields -------------

    #[test]
    fn test_token_serialization_roundtrip_deterministic() {
        let mut rng = DetRng::new(99);
        let obj = ObjectId::new(0xdead_beef_cafe_babe, 0x1234_5678_9abc_def0);
        let cancel_handle = SymbolCancelToken::new(obj, &mut rng);

        // Serialize and deserialize twice — should produce identical results.
        let bytes1 = cancel_handle.to_bytes();
        let parsed1 = SymbolCancelToken::from_bytes(&bytes1).unwrap();
        let bytes2 = parsed1.to_bytes();

        assert_eq!(bytes1, bytes2, "serialization must be deterministic");
        assert_eq!(parsed1.token_id(), cancel_handle.token_id());
        assert_eq!(parsed1.object_id(), cancel_handle.object_id());
    }

    // ---- Message forwarding exhaustion ----------------------------------

    #[test]
    fn test_message_forwarding_exhausts_at_zero_hops() {
        let msg = CancelMessage::new(
            1,
            ObjectId::new_for_test(1),
            CancelKind::User,
            Time::from_millis(100),
            0,
        )
        .with_max_hops(0);

        // Cannot forward when max_hops is 0.
        assert!(!msg.can_forward());
        assert!(msg.forwarded().is_none());
    }

    // ---- Broadcaster: separate token IDs not conflated ------------------

    #[test]
    fn test_broadcaster_separate_tokens_independent() {
        let broadcaster = CancelBroadcaster::new(NullSink);

        let msg1 = CancelMessage::new(
            1,
            ObjectId::new_for_test(1),
            CancelKind::User,
            Time::from_millis(100),
            0,
        );
        let msg2 = CancelMessage::new(
            2,
            ObjectId::new_for_test(2),
            CancelKind::Timeout,
            Time::from_millis(200),
            0,
        );

        let now = Time::from_millis(100);
        let r1 = broadcaster.receive_message(&msg1, now);
        let r2 = broadcaster.receive_message(&msg2, now);

        // Both should be processed (different token IDs).
        assert!(r1.is_some());
        assert!(r2.is_some());

        let metrics = broadcaster.metrics();
        assert_eq!(metrics.received, 2);
        assert_eq!(metrics.duplicates, 0);
    }

    // =========================================================================
    // Metamorphic Testing: Cascade Invariants (META-CANCEL)
    // =========================================================================

    /// META-CANCEL-001: Transitive Cascade Property
    /// If A→B→C (chain), then cancel(A) = {A,B,C} all cancelled
    /// Metamorphic relation: cancel_depth(chain, root) = all_descendants_cancelled(root)
    #[test]
    fn meta_transitive_cascade_property() {
        let mut rng = DetRng::new(12345);
        let root = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng);
        let level1 = root.child(&mut rng);
        let level2 = level1.child(&mut rng);
        let level3 = level2.child(&mut rng);

        // Create reference chain for comparison
        let mut rng2 = DetRng::new(12345); // Same seed = same behavior
        let ref_root = SymbolCancelToken::new(ObjectId::new_for_test(1), &mut rng2);
        let ref_level1 = ref_root.child(&mut rng2);
        let ref_level2 = ref_level1.child(&mut rng2);
        let ref_level3 = ref_level2.child(&mut rng2);

        let now = Time::from_millis(500);

        // Metamorphic relation: cancelling at any depth should produce same cascade pattern
        root.cancel(&CancelReason::user("cascade_test"), now);
        ref_root.cancel(&CancelReason::user("cascade_test"), now);

        // All descendants should be cancelled in both chains
        assert_eq!(root.is_cancelled(), ref_root.is_cancelled());
        assert_eq!(level1.is_cancelled(), ref_level1.is_cancelled());
        assert_eq!(level2.is_cancelled(), ref_level2.is_cancelled());
        assert_eq!(level3.is_cancelled(), ref_level3.is_cancelled());

        // All should have ParentCancelled except root
        assert_eq!(root.reason().unwrap().kind, CancelKind::User);
        assert_eq!(level1.reason().unwrap().kind, CancelKind::ParentCancelled);
        assert_eq!(level2.reason().unwrap().kind, CancelKind::ParentCancelled);
        assert_eq!(level3.reason().unwrap().kind, CancelKind::ParentCancelled);
        assert_eq!(
            reason_chain_kinds(&level3),
            vec![
                CancelKind::ParentCancelled,
                CancelKind::ParentCancelled,
                CancelKind::ParentCancelled,
                CancelKind::User,
            ],
            "deep descendant should retain every parent-cancelled hop plus the root cause"
        );
    }

    /// META-CANCEL-002: Order Independence Property
    /// Children added in different orders should be cancelled identically
    /// Metamorphic relation: cancel(permute(children)) = same_cancelled_set
    #[test]
    fn meta_order_independence_cascade() {
        // Setup 1: Add children in order A, B, C
        let mut rng1 = DetRng::new(67890);
        let parent1 = SymbolCancelToken::new(ObjectId::new_for_test(10), &mut rng1);
        let child1a = parent1.child(&mut rng1);
        let child1b = parent1.child(&mut rng1);
        let child1c = parent1.child(&mut rng1);

        // Setup 2: Add children in order C, A, B (permuted)
        let mut rng2 = DetRng::new(67890); // Same initial seed
        let _parent2 = SymbolCancelToken::new(ObjectId::new_for_test(10), &mut rng2);
        // Skip ahead to same RNG state as after child1c creation
        let _ = rng2.next_u64(); // child1a token_id
        let _ = rng2.next_u64(); // child1b token_id
        let _ = rng2.next_u64(); // child1c token_id

        // Reset and create in different order
        let mut rng2 = DetRng::new(67890);
        let parent2 = SymbolCancelToken::new(ObjectId::new_for_test(10), &mut rng2);
        // Create children in permuted order but with same logical identity
        let child2a = parent2.child(&mut rng2);
        let child2c = parent2.child(&mut rng2);
        let child2b = parent2.child(&mut rng2);

        let now = Time::from_millis(1000);

        // Cancel both parents
        parent1.cancel(&CancelReason::timeout(), now);
        parent2.cancel(&CancelReason::timeout(), now);

        // Metamorphic relation: cancellation results should be identical regardless of creation order
        assert_eq!(parent1.is_cancelled(), parent2.is_cancelled());
        assert_eq!(child1a.is_cancelled(), child2a.is_cancelled());
        assert_eq!(child1b.is_cancelled(), child2b.is_cancelled());
        assert_eq!(child1c.is_cancelled(), child2c.is_cancelled());

        // All children should have same reason kind
        assert_eq!(
            child1a.reason().unwrap().kind,
            child2a.reason().unwrap().kind
        );
        assert_eq!(
            child1b.reason().unwrap().kind,
            child2b.reason().unwrap().kind
        );
        assert_eq!(
            child1c.reason().unwrap().kind,
            child2c.reason().unwrap().kind
        );
    }

    /// META-CANCEL-003: Reason Monotonicity Property
    /// Multiple cancellations should only strengthen, never weaken reason severity
    /// Metamorphic relation: strength(apply_sequence(reasons)) = max(strength(reasons))
    #[test]
    fn meta_reason_monotonicity_cascade() {
        let mut rng = DetRng::new(11111);
        let token = SymbolCancelToken::new(ObjectId::new_for_test(20), &mut rng);

        // Create sequence of reasons with different severities
        let weak_reasons = vec![CancelReason::user("weak1"), CancelReason::user("weak2")];
        let strong_reasons = vec![
            CancelReason::timeout(),
            CancelReason::new(CancelKind::Shutdown),
        ];

        let now = Time::from_millis(2000);

        // Apply weak reasons first
        for reason in &weak_reasons {
            token.cancel(reason, now);
        }
        let after_weak = token.reason().unwrap().kind;

        // Apply strong reasons
        for reason in &strong_reasons {
            token.cancel(reason, now);
        }
        let after_strong = token.reason().unwrap().kind;

        // Metamorphic relation: final reason should be strongest applied
        assert_eq!(after_strong, CancelKind::Shutdown); // Strongest
        // Monotonicity: strength never decreases
        assert!(matches!(
            (after_weak, after_strong),
            (
                CancelKind::User | CancelKind::Timeout | CancelKind::Shutdown,
                CancelKind::Shutdown
            )
        ));
    }

    /// META-CANCEL-003B: Idempotent Repeat-Cancel Property
    /// Re-applying the same cancellation should not change the observable state.
    /// Metamorphic relation: cancel_once(tree) = cancel_n_times(tree, same_reason)
    #[test]
    fn meta_repeat_cancel_matches_single_cancel_observable_state() {
        let mut once_rng = DetRng::new(16_777_216);
        let once_root = SymbolCancelToken::new(ObjectId::new_for_test(21), &mut once_rng);
        let once_child_a = once_root.child(&mut once_rng);
        let once_child_b = once_root.child(&mut once_rng);
        let once_grandchild = once_child_a.child(&mut once_rng);

        let once_order = Arc::new(StdMutex::new(Vec::new()));
        for token in [&once_root, &once_child_a, &once_child_b, &once_grandchild] {
            attach_order_listener(token, &once_order);
        }

        let mut repeated_rng = DetRng::new(16_777_216);
        let repeated_root = SymbolCancelToken::new(ObjectId::new_for_test(21), &mut repeated_rng);
        let repeated_child_a = repeated_root.child(&mut repeated_rng);
        let repeated_child_b = repeated_root.child(&mut repeated_rng);
        let repeated_grandchild = repeated_child_a.child(&mut repeated_rng);

        let repeated_order = Arc::new(StdMutex::new(Vec::new()));
        for token in [
            &repeated_root,
            &repeated_child_a,
            &repeated_child_b,
            &repeated_grandchild,
        ] {
            attach_order_listener(token, &repeated_order);
        }

        let reason = CancelReason::timeout();
        let now = Time::from_millis(2_500);

        assert!(
            once_root.cancel(&reason, now),
            "first cancellation should win for single-cancel fixture"
        );
        assert!(
            repeated_root.cancel(&reason, now),
            "first cancellation should win for repeated-cancel fixture"
        );
        for _ in 0..3 {
            assert!(
                !repeated_root.cancel(&reason, now),
                "subsequent identical cancellations must be idempotent"
            );
        }

        assert_eq!(snapshot_token(&once_root), snapshot_token(&repeated_root));
        assert_eq!(
            snapshot_token(&once_child_a),
            snapshot_token(&repeated_child_a)
        );
        assert_eq!(
            snapshot_token(&once_child_b),
            snapshot_token(&repeated_child_b)
        );
        assert_eq!(
            snapshot_token(&once_grandchild),
            snapshot_token(&repeated_grandchild)
        );
        assert_eq!(
            *once_order.lock().unwrap(),
            *repeated_order.lock().unwrap(),
            "identical repeated cancellations must not perturb drain order"
        );
    }

    /// META-CANCEL-004: Upward Isolation Property
    /// Child cancellation should never affect parent or siblings
    /// Metamorphic relation: cancel(child) ∩ affect(parent ∪ siblings) = ∅
    #[test]
    fn meta_upward_isolation_property() {
        let mut rng = DetRng::new(22222);
        let parent = SymbolCancelToken::new(ObjectId::new_for_test(30), &mut rng);
        let child_a = parent.child(&mut rng);
        let child_b = parent.child(&mut rng);
        let child_c = parent.child(&mut rng);

        // Take snapshots before child cancellation
        let parent_before = parent.is_cancelled();
        let sibling_b_before = child_b.is_cancelled();
        let sibling_c_before = child_c.is_cancelled();

        // Cancel only child_a
        child_a.cancel(&CancelReason::user("isolated"), Time::from_millis(3000));

        // Metamorphic relation: isolation should preserve parent and siblings
        assert_eq!(parent.is_cancelled(), parent_before);
        assert_eq!(child_b.is_cancelled(), sibling_b_before);
        assert_eq!(child_c.is_cancelled(), sibling_c_before);

        // Only the cancelled child should be affected
        assert!(child_a.is_cancelled());
        assert!(!parent.is_cancelled());
        assert!(!child_b.is_cancelled());
        assert!(!child_c.is_cancelled());
    }

    /// META-CANCEL-004B: Sibling Subtree Isolation Property
    /// Cancelling one subtree parent should affect only that subtree.
    /// Metamorphic relation: cancel(parent_a) ∩ affect(subtree_b) = ∅
    #[test]
    fn meta_sibling_subtrees_are_isolated_from_local_parent_cancel() {
        let mut rng = DetRng::new(22_223);
        let root = SymbolCancelToken::new(ObjectId::new_for_test(31), &mut rng);
        let branch_a = root.child(&mut rng);
        let branch_b = root.child(&mut rng);
        let leaf_a = branch_a.child(&mut rng);
        let leaf_b = branch_b.child(&mut rng);

        let now = Time::from_millis(3_100);
        branch_a.cancel(&CancelReason::user("branch_a_only"), now);

        assert!(
            branch_a.is_cancelled(),
            "the locally cancelled subtree root must be cancelled"
        );
        assert!(
            leaf_a.is_cancelled(),
            "descendants of the locally cancelled subtree must cascade"
        );
        assert!(
            !root.is_cancelled(),
            "local subtree cancellation must not bubble up to the shared root"
        );
        assert!(
            !branch_b.is_cancelled(),
            "sibling subtree root must remain untouched"
        );
        assert!(
            !leaf_b.is_cancelled(),
            "sibling subtree descendants must remain untouched"
        );
        assert_eq!(branch_a.reason().unwrap().kind, CancelKind::User);
        assert_eq!(leaf_a.reason().unwrap().kind, CancelKind::ParentCancelled);
        assert!(branch_b.reason().is_none());
        assert!(leaf_b.reason().is_none());
    }

    /// META-CANCEL-005: Listener Multiplicativity Property
    /// Retained listeners are notified once per strictly stronger cancellation severity.
    /// Metamorphic relation: notifications_received = listeners_count × severity_levels_seen
    #[test]
    fn meta_listener_multiplicativity() {
        use std::sync::atomic::{AtomicU32, Ordering};

        let mut rng = DetRng::new(33333);
        let token = SymbolCancelToken::new(ObjectId::new_for_test(40), &mut rng);

        let notification_count = Arc::new(AtomicU32::new(0));
        let listener_count = 5u32;

        // Add N listeners
        for _ in 0..listener_count {
            let count_clone = notification_count.clone();
            token.add_listener(move |_: &CancelReason, _: Time| {
                count_clone.fetch_add(1, Ordering::SeqCst);
            });
        }

        // Cancel once
        token.cancel(&CancelReason::timeout(), Time::from_millis(4000));

        // Metamorphic relation: exactly N notifications for 1 cancellation
        assert_eq!(notification_count.load(Ordering::SeqCst), listener_count);

        // A stronger cancellation re-notifies retained listeners once.
        let before_second = notification_count.load(Ordering::SeqCst);
        token.cancel(
            &CancelReason::new(CancelKind::Shutdown),
            Time::from_millis(5000),
        );
        let after_second = notification_count.load(Ordering::SeqCst);

        assert_eq!(before_second, listener_count);
        assert_eq!(after_second, listener_count * 2);

        // Same-severity repeats must remain idempotent.
        token.cancel(
            &CancelReason::new(CancelKind::Shutdown),
            Time::from_millis(6000),
        );
        assert_eq!(notification_count.load(Ordering::SeqCst), after_second);
    }

    /// META-CANCEL-006: Broadcast Deduplication Property
    /// Identical messages should be deduplicated regardless of processing order
    /// Metamorphic relation: process(permute(duplicates)) = process_once(unique)
    #[test]
    fn meta_broadcast_deduplication_invariant() {
        let broadcaster = CancelBroadcaster::new(NullSink);

        let msg = CancelMessage::new(
            12345,
            ObjectId::new_for_test(50),
            CancelKind::Timeout,
            Time::from_millis(6000),
            777,
        );

        let now = Time::from_millis(6000);

        // Process same message multiple times in different patterns
        let results: Vec<_> = (0..5)
            .map(|_| broadcaster.receive_message(&msg, now))
            .collect();

        // Metamorphic relation: only first should succeed, rest should be None (duplicate)
        assert!(results[0].is_some(), "first message should be processed");
        assert!(
            results[1..].iter().all(|r| r.is_none()),
            "subsequent messages should be duplicates"
        );

        let metrics = broadcaster.metrics();
        assert_eq!(
            metrics.received, 1,
            "only one message should be counted as received"
        );
        assert_eq!(metrics.duplicates, 4, "four duplicates should be detected");
    }

    /// META-CANCEL-007: Cascade Depth Invariance Property
    /// Cancellation effects should be invariant to tree structure depth
    /// Metamorphic relation: cancel(flatten(tree)) = cancel(nested(tree))
    #[test]
    fn meta_cascade_depth_invariance() {
        let mut rng = DetRng::new(44444);

        // Flat structure: root with 3 direct children
        let flat_root = SymbolCancelToken::new(ObjectId::new_for_test(60), &mut rng);
        let flat_children: Vec<_> = (0..3).map(|_| flat_root.child(&mut rng)).collect();

        // Nested structure: root → child1 → child2 → child3 (3 levels deep)
        let mut rng2 = DetRng::new(44444); // Same seed for comparison
        let nested_root = SymbolCancelToken::new(ObjectId::new_for_test(60), &mut rng2);
        let nested_l1 = nested_root.child(&mut rng2);
        let nested_l2 = nested_l1.child(&mut rng2);
        let nested_l3 = nested_l2.child(&mut rng2);

        let now = Time::from_millis(7000);

        // Cancel both structures
        flat_root.cancel(&CancelReason::new(CancelKind::Deadline), now);
        nested_root.cancel(&CancelReason::new(CancelKind::Deadline), now);

        // Metamorphic relation: all descendants cancelled regardless of structure
        assert!(flat_root.is_cancelled());
        assert!(nested_root.is_cancelled());

        // All children/descendants should be cancelled
        assert!(flat_children.iter().all(|child| child.is_cancelled()));
        assert!(nested_l1.is_cancelled());
        assert!(nested_l2.is_cancelled());
        assert!(nested_l3.is_cancelled());

        // All derived cancellations should have ParentCancelled reason
        assert!(
            flat_children
                .iter()
                .all(|child| child.reason().unwrap().kind == CancelKind::ParentCancelled)
        );
        assert_eq!(
            nested_l1.reason().unwrap().kind,
            CancelKind::ParentCancelled
        );
        assert_eq!(
            nested_l2.reason().unwrap().kind,
            CancelKind::ParentCancelled
        );
        assert_eq!(
            nested_l3.reason().unwrap().kind,
            CancelKind::ParentCancelled
        );
    }

    /// META-CANCEL-007B: Seeded Drain Determinism Property
    /// Equivalent seeded setups must drain listeners in the same order.
    /// Metamorphic relation: drain_order(seed, setup_a) = drain_order(seed, setup_b)
    #[test]
    fn meta_seeded_cascade_order_is_deterministic() {
        let mut rng_a = DetRng::new(44_445);
        let root_a = SymbolCancelToken::new(ObjectId::new_for_test(61), &mut rng_a);
        let left_a = root_a.child(&mut rng_a);
        let right_a = root_a.child(&mut rng_a);
        let left_leaf_a = left_a.child(&mut rng_a);
        let right_leaf_a = right_a.child(&mut rng_a);

        let mut rng_b = DetRng::new(44_445);
        let root_b = SymbolCancelToken::new(ObjectId::new_for_test(61), &mut rng_b);
        let left_b = root_b.child(&mut rng_b);
        let right_b = root_b.child(&mut rng_b);
        let left_leaf_b = left_b.child(&mut rng_b);
        let right_leaf_b = right_b.child(&mut rng_b);

        let order_a = Arc::new(StdMutex::new(Vec::new()));
        for token in [&root_a, &left_a, &right_a, &left_leaf_a, &right_leaf_a] {
            attach_order_listener(token, &order_a);
        }

        let order_b = Arc::new(StdMutex::new(Vec::new()));
        for token in [&root_b, &left_b, &right_b, &left_leaf_b, &right_leaf_b] {
            attach_order_listener(token, &order_b);
        }

        let now = Time::from_millis(7_100);
        let reason = CancelReason::new(CancelKind::Deadline);
        root_a.cancel(&reason, now);
        root_b.cancel(&reason, now);

        let order_a = order_a.lock().unwrap().clone();
        let order_b = order_b.lock().unwrap().clone();

        assert_eq!(
            order_a, order_b,
            "identical seeded cancellation trees must drain in the same observable order"
        );
        assert_eq!(
            order_a,
            vec![
                root_a.token_id(),
                left_a.token_id(),
                left_leaf_a.token_id(),
                right_a.token_id(),
                right_leaf_a.token_id(),
            ],
            "seeded drain order should follow deterministic parent-before-child traversal"
        );
    }

    /// META-CANCEL-008: Cleanup Coordinator Independence Property
    /// Object cleanup should be independent across different objects
    /// Metamorphic relation: cleanup(O1 ∪ O2) = cleanup(O1) + cleanup(O2)
    #[test]
    fn meta_cleanup_independence_property() {
        let coordinator = CleanupCoordinator::new();
        let now = Time::from_millis(8000);

        let obj1 = ObjectId::new_for_test(70);
        let obj2 = ObjectId::new_for_test(71);

        coordinator.register_handler(obj1, CountingCleanupHandler);

        // Register symbols for both objects
        for i in 0..3 {
            coordinator.register_pending(obj1, Symbol::new_for_test(70, 0, i, &[1, 2]), now);
        }
        for i in 0..2 {
            coordinator.register_pending(obj2, Symbol::new_for_test(71, 0, i, &[3, 4, 5]), now);
        }

        // Create separate coordinators for independent cleanup comparison
        let coord1 = CleanupCoordinator::new();
        let coord2 = CleanupCoordinator::new();
        coord1.register_handler(obj1, CountingCleanupHandler);

        // Register same symbols in separate coordinators
        for i in 0..3 {
            coord1.register_pending(obj1, Symbol::new_for_test(70, 0, i, &[1, 2]), now);
        }
        for i in 0..2 {
            coord2.register_pending(obj2, Symbol::new_for_test(71, 0, i, &[3, 4, 5]), now);
        }

        // Cleanup obj1 in both scenarios
        let combined_result1 = coordinator.cleanup(obj1, None);
        let independent_result1 = coord1.cleanup(obj1, None);

        // Metamorphic relation: obj1 cleanup should be identical regardless of obj2 presence
        assert_eq!(
            combined_result1.symbols_cleaned,
            independent_result1.symbols_cleaned
        );
        assert_eq!(
            combined_result1.bytes_freed,
            independent_result1.bytes_freed
        );
        assert_eq!(combined_result1.completed, independent_result1.completed);

        // obj2 should be unaffected in combined coordinator
        let stats_after = coordinator.stats();
        assert_eq!(stats_after.pending_objects, 1); // only obj2 remains
        assert_eq!(stats_after.pending_symbols, 2); // obj2 symbols still there
    }

    // =========================================================================
    // Wave 58 – pure data-type trait coverage
    // =========================================================================

    #[test]
    fn cancel_broadcast_metrics_debug_clone_default() {
        let m = CancelBroadcastMetrics::default();
        let dbg = format!("{m:?}");
        assert!(dbg.contains("CancelBroadcastMetrics"), "{dbg}");
        let cloned = m;
        assert_eq!(cloned.initiated, 0);
    }

    #[test]
    fn cleanup_stats_debug_clone_default() {
        let s = CleanupStats::default();
        let dbg = format!("{s:?}");
        assert!(dbg.contains("CleanupStats"), "{dbg}");
        let cloned = s;
        assert_eq!(cloned.pending_objects, 0);
    }

    #[test]
    fn cleanup_result_debug_clone() {
        let r = CleanupResult {
            object_id: ObjectId::new_for_test(1),
            symbols_cleaned: 5,
            bytes_freed: 1024,
            within_budget: true,
            completed: true,
            handlers_run: vec!["h1".to_string()],
            handler_errors: Vec::new(),
        };
        let dbg = format!("{r:?}");
        assert!(dbg.contains("CleanupResult"), "{dbg}");
        let cloned = r;
        assert_eq!(cloned.symbols_cleaned, 5);
        assert!(cloned.completed);
    }

    // --- br-asupersync-frm9u9: re-notify on strengthened reason ----

    #[test]
    fn cancel_strengthen_re_notifies_listeners_with_stronger_reason() {
        // br-asupersync-frm9u9: a listener registered before any
        // cancel must observe BOTH the initial weaker reason AND a
        // subsequent strengthened reason. Equal-severity cancels do
        // not re-fire (idempotence at each level). The observed
        // sequence must be monotone-non-decreasing in severity.
        use std::sync::Arc;
        use std::sync::Mutex as StdMutex;
        let mut rng = DetRng::new(0x_face_d00d);
        let token = SymbolCancelToken::new(ObjectId::new_for_test(7), &mut rng);
        let observed: Arc<StdMutex<Vec<(crate::types::CancelKind, Time)>>> =
            Arc::new(StdMutex::new(Vec::new()));
        {
            let observed = Arc::clone(&observed);
            token.add_listener(move |reason: &CancelReason, at: Time| {
                observed.lock().unwrap().push((reason.kind, at));
            });
        }

        // Initial cancel: lower severity (User).
        let weak = CancelReason::new(crate::types::CancelKind::User);
        token.cancel(&weak, Time::from_nanos(100));
        // Same severity again — must NOT re-notify.
        token.cancel(&weak, Time::from_nanos(150));
        // Stronger cancel (Shutdown is the strongest fixed kind in
        // the lattice) — MUST re-notify.
        let strong = CancelReason::new(crate::types::CancelKind::Shutdown);
        token.cancel(&strong, Time::from_nanos(200));

        let log = observed.lock().unwrap().clone();
        assert!(
            log.len() >= 2,
            "listener must observe both the initial cancel and the strengthen, got {log:?}"
        );
        assert_eq!(
            log.first().map(|(kind, _)| *kind),
            Some(crate::types::CancelKind::User),
            "first notification must carry the initial weak reason, got {log:?}"
        );
        assert!(
            log.iter()
                .any(|(kind, at)| *kind == crate::types::CancelKind::Shutdown
                    && *at == Time::from_nanos(100)),
            "listener must be re-notified with the strengthened reason, got {log:?}"
        );
        // No duplicate same-severity notifications.
        let user_count = log
            .iter()
            .filter(|(kind, _)| *kind == crate::types::CancelKind::User)
            .count();
        assert_eq!(
            user_count, 1,
            "same-severity cancel must not re-fire listeners, got {log:?}"
        );
        assert!(
            log.iter().all(|(_, at)| *at == Time::from_nanos(100)),
            "all retained-listener notifications must use the canonical first-cancel timestamp, got {log:?}"
        );
    }

    // --- br-asupersync-2bm1a3: add_listener race fix ---------------

    #[test]
    fn add_listener_post_cancel_uses_real_reason_not_fabricated_user() {
        // br-asupersync-2bm1a3: a listener registered AFTER a cancel
        // already fired must observe the actual stored reason, not a
        // fabricated `CancelKind::User @ Time::ZERO` from the
        // pre-fix race window. This test exercises the
        // happens-before-cancel-completed branch directly: the
        // listener is added strictly after `cancel()` returns, so
        // the reason is fully written; the new locking discipline
        // returns the real reason (Timeout) instead of the
        // fabricated User.
        use std::sync::Arc;
        use std::sync::Mutex as StdMutex;
        let mut rng = DetRng::new(0x_dead_beef);
        let token = SymbolCancelToken::new(ObjectId::new_for_test(11), &mut rng);
        let timeout = CancelReason::new(crate::types::CancelKind::Timeout);
        token.cancel(&timeout, Time::from_nanos(42));

        let observed: Arc<StdMutex<Vec<(crate::types::CancelKind, u64)>>> =
            Arc::new(StdMutex::new(Vec::new()));
        {
            let observed = Arc::clone(&observed);
            token.add_listener(move |reason: &CancelReason, at: Time| {
                observed.lock().unwrap().push((reason.kind, at.as_nanos()));
            });
        }

        let log = observed.lock().unwrap().clone();
        assert_eq!(
            log.len(),
            1,
            "post-cancel add_listener must fire exactly once, got {log:?}"
        );
        let (kind, at_nanos) = log[0];
        assert_eq!(
            kind,
            crate::types::CancelKind::Timeout,
            "listener must observe the real reason (Timeout), \
             not the fabricated CancelKind::User"
        );
        assert_eq!(
            at_nanos, 42,
            "listener must observe the real cancelled_at time, not Time::ZERO"
        );
    }

    // --- br-asupersync-batcyw: missing-handler is not "cleaned" ----

    #[test]
    fn cleanup_with_pending_but_no_handler_surfaces_typed_error() {
        // br-asupersync-batcyw: a CleanupCoordinator that holds a
        // pending symbol set but no registered handler must NOT
        // report the symbols as cleaned. The previous behaviour
        // silently set symbols_cleaned = N, hiding application-side
        // handler-registration bugs that drop release receipts.
        // The fix: leave counters at zero, mark completed=false,
        // push a typed error into handler_errors, and restore the
        // pending set so a later register_handler + retry succeeds.
        let coord = CleanupCoordinator::new();
        let object_id = ObjectId::new_for_test(99);
        let now = Time::from_nanos(0);

        // Register three pending symbols WITHOUT registering any
        // CleanupHandler — the exact pre-condition for the bug.
        coord.register_pending(
            object_id,
            Symbol::new_for_test(99, 0, 0, &[1, 2, 3, 4]),
            now,
        );
        coord.register_pending(
            object_id,
            Symbol::new_for_test(99, 0, 1, &[5, 6, 7, 8]),
            now,
        );
        coord.register_pending(
            object_id,
            Symbol::new_for_test(99, 0, 2, &[9, 10, 11, 12]),
            now,
        );

        let result = coord.cleanup(object_id, None);

        // Symbols-without-handler must NOT be reported as cleaned.
        assert_eq!(
            result.symbols_cleaned, 0,
            "no-handler outcome must not claim symbols cleaned, got {result:?}"
        );
        assert_eq!(
            result.bytes_freed, 0,
            "no-handler outcome must not claim bytes freed, got {result:?}"
        );
        assert!(
            !result.completed,
            "no-handler outcome must mark completed=false, got {result:?}"
        );
        assert!(
            result
                .handler_errors
                .iter()
                .any(|e| e.contains("no cleanup handler")),
            "missing-handler condition must surface as a typed error, got {:?}",
            result.handler_errors
        );

        // Pending set was restored so a retry can succeed.
        let stats = coord.stats();
        assert_eq!(
            stats.pending_objects, 1,
            "pending set must be restored for retry, got {stats:?}"
        );
        assert!(
            !coord.completed.read().contains(&object_id),
            "object_id must NOT be in completed set after no-handler outcome"
        );
    }

    /// br-asupersync-mzamuo — A panicking listener must (a) NOT
    /// crash the cancel path, (b) increment the per-token panic
    /// counter so the silent-swallow becomes observable.
    #[test]
    fn cancel_listener_panic_logged_via_counter() {
        struct PanickingListener;
        impl CancelListener for PanickingListener {
            fn on_cancel(&self, _reason: &CancelReason, _at: Time) {
                panic!("simulated listener panic (mzamuo)");
            }
        }

        let mut rng = DetRng::new(0xc0ffee);
        let token = SymbolCancelToken::new(ObjectId::new(1, 1), &mut rng);
        token.add_listener(PanickingListener);

        // First cancel fires the listener → panic → caught + counted.
        let reason = CancelReason::new(CancelKind::User);
        token.cancel(&reason, Time::from_nanos(100));
        assert!(
            token.listener_panic_count() >= 1,
            "expected listener_panic_count >= 1, got {}",
            token.listener_panic_count()
        );

        // Strengthen path: re-fires the listener for severity uplift.
        let stronger = CancelReason::new(CancelKind::Shutdown);
        token.cancel(&stronger, Time::from_nanos(200));
        assert!(
            token.listener_panic_count() >= 2,
            "strengthen path must also count panics, got {}",
            token.listener_panic_count()
        );
    }

    #[test]
    fn late_add_listener_drop_panic_logged_via_counter() {
        struct DropPanickingListener;
        impl CancelListener for DropPanickingListener {
            fn on_cancel(&self, _reason: &CancelReason, _at: Time) {}
        }
        impl Drop for DropPanickingListener {
            fn drop(&mut self) {
                panic!("simulated late-add drop panic (mzamuo)"); // ubs:ignore - test helper
            }
        }

        let mut rng = DetRng::new(0xd00d);
        let token = SymbolCancelToken::new(ObjectId::new(4, 4), &mut rng);
        token.cancel(&CancelReason::new(CancelKind::User), Time::from_nanos(1));

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            token.add_listener(DropPanickingListener);
        }));
        assert!(
            result.is_ok(),
            "late-add path must not propagate listener drop panic"
        );
        assert_eq!(token.listener_panic_count(), 1);
    }

    /// br-asupersync-as12cf — `mark_seen` must NEVER let
    /// `seen_sequences.set.len()` exceed `max_seen` even
    /// transiently. The harness mirrors the production fix
    /// (evict-before-insert) so the invariant can be exercised
    /// without standing up the full coordinator.
    #[test]
    fn mark_seen_never_exceeds_max_seen_transiently() {
        let mut rng = DetRng::new(0xbeef);
        let token = SymbolCancelToken::new(ObjectId::new(7, 7), &mut rng);
        let coord = CancelMarkSeenHarness {
            seen_sequences: parking_lot::RwLock::new(SeenSequences::default()),
            max_seen: 5,
        };
        for i in 0..15u64 {
            coord.mark_seen(token.object_id(), token.token_id(), i);
            let len = coord.seen_sequences.read().set.len();
            assert!(
                len <= coord.max_seen,
                "seen.set.len()={len} exceeded max_seen={} after insert {i}",
                coord.max_seen
            );
        }
    }

    struct CancelMarkSeenHarness {
        seen_sequences: parking_lot::RwLock<SeenSequences>,
        max_seen: usize,
    }

    impl CancelMarkSeenHarness {
        fn mark_seen(&self, object_id: ObjectId, token_id: u64, sequence: u64) {
            let mut seen = self.seen_sequences.write();
            if seen.set.contains(&(object_id, token_id, sequence)) {
                return;
            }
            while seen.set.len() >= self.max_seen {
                if seen.remove_oldest().is_none() {
                    break;
                }
            }
            seen.insert((object_id, token_id, sequence));
        }
    }

    /// br-asupersync-n1a1br — child() must observe a consistent
    /// (is_cancelled, cancelled_at) pair. After the parent is
    /// cancelled, every child created via `child()` must inherit
    /// the parent's cancelled_at value as it was at the moment of
    /// the cancel decision — not a later strengthened value.
    #[test]
    fn child_inherits_parent_cancelled_at_atomically() {
        let mut rng = DetRng::new(0x1234);
        let parent = SymbolCancelToken::new(ObjectId::new(2, 2), &mut rng);
        let cancel_time = Time::from_nanos(500);
        let reason = CancelReason::new(CancelKind::User);
        parent.cancel(&reason, cancel_time);

        // Now create a child after the parent is already cancelled.
        let child = parent.child(&mut rng);
        assert!(child.is_cancelled());
        assert_eq!(
            child.cancelled_at().map(Time::as_nanos),
            Some(cancel_time.as_nanos()),
            "child must inherit the cancelled_at the parent had \
             at the moment of the is_cancelled check (snapshot under lock)"
        );
    }

    /// br-asupersync-n1a1br — if `cancelled` becomes visible before
    /// `cancelled_at` is published, `child()` must wait out that
    /// local-cancel window rather than fabricating `Time::ZERO`.
    #[test]
    fn child_waits_for_inflight_cancelled_at_publication() {
        use std::sync::{
            Arc,
            atomic::{AtomicBool, Ordering},
        };

        let mut rng = DetRng::new(0x5678);
        let parent = SymbolCancelToken::new(ObjectId::new(3, 3), &mut rng);
        let cancel_time = Time::from_nanos(777);
        let started = Arc::new(AtomicBool::new(false));

        let mut reason_guard = parent.state.reason.write();
        *reason_guard = Some(CancelReason::new(CancelKind::User));
        parent.state.cancelled.store(true, Ordering::Release);
        parent.state.cancelled_at.store(u64::MAX, Ordering::Release);

        let parent_for_child = parent.clone();
        let started_for_child = started.clone();
        let join = std::thread::spawn(move || {
            started_for_child.store(true, Ordering::Release);
            let mut child_rng = DetRng::new(0x9abc);
            let child = parent_for_child.child(&mut child_rng);
            child.cancelled_at().map(Time::as_nanos)
        });

        // br-asupersync-wze4x9: Replace infinite spin with bounded retry to prevent test hangs
        const MAX_WAIT_RETRIES: u32 = 10000;
        for _attempt in 0..MAX_WAIT_RETRIES {
            if started.load(Ordering::Acquire) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_nanos(100));
        }
        assert!(
            started.load(Ordering::Acquire),
            "Test thread failed to start within timeout"
        );

        parent
            .state
            .cancelled_at
            .store(cancel_time.as_nanos(), Ordering::Release);
        drop(reason_guard);

        let child_cancelled_at = join.join().expect("child thread must complete");
        assert_eq!(child_cancelled_at, Some(cancel_time.as_nanos()));
    }

    /// br-asupersync-53nvge — a late `child()` call may need to wait for
    /// `cancelled_at` publication, but that wait must not monopolize the
    /// `children` lock. Other threads still need that lock for drain/metrics
    /// work in the same handoff window.
    #[test]
    fn child_wait_for_cancelled_at_does_not_hold_children_lock() {
        use std::sync::{
            Arc,
            atomic::{AtomicBool, Ordering},
        };

        let mut rng = DetRng::new(0x53A9_0001);
        let parent = SymbolCancelToken::new(ObjectId::new(4, 4), &mut rng);
        let started = Arc::new(AtomicBool::new(false));

        let mut reason_guard = parent.state.reason.write();
        *reason_guard = Some(CancelReason::new(CancelKind::User));
        parent.state.cancelled.store(true, Ordering::Release);
        parent.state.cancelled_at.store(u64::MAX, Ordering::Release);

        let parent_for_child = parent.clone();
        let started_for_child = Arc::clone(&started);
        let join = std::thread::spawn(move || {
            started_for_child.store(true, Ordering::Release);
            let mut child_rng = DetRng::new(0x53A9_0002);
            let child = parent_for_child.child(&mut child_rng);
            child.cancelled_at().map(Time::as_nanos)
        });

        const MAX_WAIT_RETRIES: u32 = 10_000;
        for _attempt in 0..MAX_WAIT_RETRIES {
            if started.load(Ordering::Acquire) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_nanos(100));
        }
        assert!(
            started.load(Ordering::Acquire),
            "child thread failed to start within timeout"
        );

        std::thread::sleep(std::time::Duration::from_millis(1));
        assert!(
            parent.state.children.try_write().is_some(),
            "late child creation must not hold children.write() while waiting for cancelled_at"
        );

        let cancel_time = Time::from_nanos(991);
        parent
            .state
            .cancelled_at
            .store(cancel_time.as_nanos(), Ordering::Release);
        drop(reason_guard);

        let child_cancelled_at = join.join().expect("child thread must complete");
        assert_eq!(child_cancelled_at, Some(cancel_time.as_nanos()));
    }

    /// Regression test for asupersync-4txkrb: notify_retained_listeners_until_current()
    /// infinite loop livelock bug. Tests that bounded iteration prevents CPU burnout
    /// when concurrent threads keep strengthening cancel reasons.
    #[test]
    fn notify_listeners_bounded_iteration_prevents_livelock() {
        use std::sync::{
            Arc,
            atomic::{AtomicBool, AtomicU32, Ordering},
        };
        use std::thread;
        use std::time::{Duration, Instant};

        let mut rng = DetRng::new(0x4321);
        let token = SymbolCancelToken::new(ObjectId::new(42, 0), &mut rng);

        // Add several listeners that track notification count
        let notification_count = Arc::new(AtomicU32::new(0));
        for _i in 0..5 {
            let count = Arc::clone(&notification_count);
            token.add_listener(move |_reason: &CancelReason, _time: Time| {
                count.fetch_add(1, Ordering::Relaxed);
                // Simulate listener work to make race condition more likely
                std::hint::spin_loop();
            });
        }

        // Initial cancel with low severity
        let initial_time = Time::from_nanos(1000);
        token.cancel(&CancelReason::new(CancelKind::Timeout), initial_time);

        // Track if the notification process completes in reasonable time
        let completed = Arc::new(AtomicBool::new(false));
        let completed_for_thread = Arc::clone(&completed);

        // Spawn thread that continuously strengthens the reason to trigger
        // the race condition that would cause infinite loop
        let token_for_strengthener = token.clone();
        let strengthener_thread = thread::spawn(move || {
            for severity in [
                CancelKind::Deadline,
                CancelKind::Shutdown,
                CancelKind::FailFast,
            ]
            .iter()
            {
                thread::sleep(Duration::from_millis(1));
                token_for_strengthener.cancel(&CancelReason::new(*severity), initial_time);
            }
        });

        // Main test: trigger listener notification which could previously livelock
        let start = Instant::now();
        let token_for_notify = token.clone();
        let notification_thread = thread::spawn(move || {
            // This call would previously infinite loop if reasons keep strengthening
            // Now it should complete in bounded time due to iteration limit
            token_for_notify.cancel(&CancelReason::new(CancelKind::User), initial_time);
            completed_for_thread.store(true, Ordering::Release);
        });

        // Wait for threads to complete or timeout
        strengthener_thread
            .join()
            .expect("strengthener thread should complete");
        notification_thread
            .join()
            .expect("notification thread should complete");

        let elapsed = start.elapsed();

        // Verify the fix: operation should complete quickly (under 100ms)
        // and not hang indefinitely as it would with the original infinite loop
        assert!(
            elapsed < Duration::from_millis(100),
            "Notification should complete quickly, took {:?}",
            elapsed
        );

        assert!(
            completed.load(Ordering::Acquire),
            "Notification process should have completed"
        );

        // Verify listeners were actually notified (at least once)
        let final_count = notification_count.load(Ordering::Relaxed);
        assert!(
            final_count > 0,
            "Listeners should have been notified, count: {}",
            final_count
        );
    }

    #[test]
    fn cancelled_at_snapshot_for_child_livelock_regression() {
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::{Arc, Barrier};
        use std::thread;
        use std::time::{Duration, Instant};

        // br-asupersync-wze4x9: Regression test for infinite spin loop livelock
        // in cancelled_at_snapshot_for_child() when the cancelled flag is visible
        // before the timestamp is written.

        let mut rng = DetRng::new(0x1234_5678);
        let object_id = ObjectId::new_for_test(0x1234_5678);
        let token = SymbolCancelToken::new(object_id, &mut rng);

        // Create a barrier to synchronize the race condition setup
        let barrier = Arc::new(Barrier::new(2));
        let cancel_started = Arc::new(AtomicBool::new(false));
        let child_created = Arc::new(AtomicBool::new(false));

        let token_for_cancel = token.clone();
        let barrier_for_cancel = Arc::clone(&barrier);
        let cancel_started_for_cancel = Arc::clone(&cancel_started);

        // Thread 1: Start cancel process but hold the write lock longer to create race
        let cancel_thread = thread::spawn(move || {
            barrier_for_cancel.wait(); // Sync with child thread

            // Acquire the reason write lock and set cancelled flag
            let reason = CancelReason::user("livelock test");
            let mut reason_guard = token_for_cancel.state.reason.write();

            // Signal that cancel has started (flag will be visible)
            token_for_cancel
                .state
                .cancelled
                .store(true, Ordering::Release);
            cancel_started_for_cancel.store(true, Ordering::Release);

            // Hold the lock for a bit to ensure race condition
            thread::sleep(Duration::from_millis(10));

            // Set the timestamp (this will unblock the child creation)
            token_for_cancel.state.cancelled_at.store(
                crate::types::Time::from_millis(12345).as_nanos(),
                Ordering::Release,
            );

            // Complete the same reason publication cancel() performs
            // before releasing the write lock so the final token state
            // is reachable in production.
            *reason_guard = Some(reason);

            // Lock will be dropped here, completing the cancel
        });

        let token_for_child = token.clone();
        let barrier_for_child = Arc::clone(&barrier);
        let cancel_started_for_child = Arc::clone(&cancel_started);
        let child_created_for_child = Arc::clone(&child_created);

        // Thread 2: Try to create child during the race window
        let child_thread = thread::spawn(move || {
            barrier_for_child.wait(); // Sync with cancel thread

            // Wait for cancel to start but timestamp not yet set
            while !cancel_started_for_child.load(Ordering::Acquire) {
                thread::sleep(Duration::from_nanos(100));
            }

            // This would previously cause infinite livelock in cancelled_at_snapshot_for_child
            let start = Instant::now();
            let mut child_rng = DetRng::new(0x8765_4321);
            let child = token_for_child.child(&mut child_rng);
            let elapsed = start.elapsed();

            // With the fix, this should complete in bounded time
            assert!(
                elapsed < Duration::from_millis(500),
                "Child creation should not livelock, took {:?}",
                elapsed
            );

            child_created_for_child.store(true, Ordering::Release);
            child
        });

        // Wait for both threads with timeout
        let start = Instant::now();
        cancel_thread.join().expect("Cancel thread should complete");
        let child = child_thread.join().expect("Child thread should complete");
        let total_elapsed = start.elapsed();

        // Verify the test completed quickly (no livelock)
        assert!(
            total_elapsed < Duration::from_secs(1),
            "Test should complete quickly, took {:?}",
            total_elapsed
        );

        // Verify both operations completed successfully
        assert!(
            cancel_started.load(Ordering::Acquire),
            "Cancel should have started"
        );
        assert!(
            child_created.load(Ordering::Acquire),
            "Child should have been created without livelock"
        );

        // Verify final state is consistent
        assert!(token.is_cancelled(), "Token should be cancelled");
        assert!(
            token.cancelled_at().is_some(),
            "Cancelled timestamp should be available"
        );
        assert_eq!(
            token.reason(),
            Some(CancelReason::user("livelock test")),
            "manual race setup must still publish a real final cancel reason"
        );
        assert_eq!(
            child.cancelled_at(),
            Some(crate::types::Time::from_millis(12345)),
            "child created during in-flight cancel must inherit the canonical parent timestamp"
        );
    }

    // --- br-asupersync-9a0x8n: CleanupCoordinator symbol drop fix ---

    #[test]
    fn cleanup_coordinator_buffers_symbols_during_retry() {
        // br-asupersync-9a0x8n: symbols arriving during cleanup retry
        // attempts should be buffered and replayed when retry state
        // is restored, not dropped.

        use std::sync::Arc;
        use std::sync::Mutex;

        let coordinator = CleanupCoordinator::new();
        let object_id = ObjectId::new_for_test(42);
        let now = Time::from_nanos(1000);

        // Register initial symbols
        coordinator.register_pending(object_id, Symbol::new_for_test(42, 0, 0, b"initial1"), now);
        coordinator.register_pending(object_id, Symbol::new_for_test(42, 0, 1, b"initial2"), now);

        // Create a failing handler
        #[derive(Debug)]
        struct FailingHandler {
            attempts: Arc<Mutex<u32>>,
        }

        impl CleanupHandler for FailingHandler {
            fn name(&self) -> &'static str {
                "failing_test_handler"
            }

            fn cleanup(
                &self,
                _object_id: ObjectId,
                symbols: Vec<Symbol>,
            ) -> crate::error::Result<usize> {
                let mut attempts = self.attempts.lock().unwrap();
                *attempts += 1;

                if *attempts == 1 {
                    // First attempt fails, triggering retry logic
                    Err(
                        crate::error::Error::new(crate::error::ErrorKind::ConnectionLost)
                            .with_message("simulated failure"),
                    )
                } else {
                    // Second attempt succeeds
                    assert_eq!(symbols.len(), 4, "Should have initial + buffered symbols");
                    let data: Vec<&[u8]> = symbols.iter().map(Symbol::data).collect();
                    // Should contain initial symbols plus symbols added during first cleanup
                    assert!(data.iter().any(|payload| *payload == b"initial1"));
                    assert!(data.iter().any(|payload| *payload == b"initial2"));
                    assert!(data.iter().any(|payload| *payload == b"during_cleanup1"));
                    assert!(data.iter().any(|payload| *payload == b"during_cleanup2"));
                    Ok(4) // Return count of cleaned symbols
                }
            }
        }

        let attempts = Arc::new(Mutex::new(0u32));
        let handler = FailingHandler {
            attempts: Arc::clone(&attempts),
        };
        coordinator.register_handler(object_id, handler);

        // Start first cleanup (will fail)
        let result1 = coordinator.cleanup(object_id, None);
        assert!(
            !result1.completed,
            "First cleanup should fail and not complete"
        );
        assert!(
            !result1.handler_errors.is_empty(),
            "Should have handler error"
        );

        // Add symbols during retry state (these used to be dropped)
        coordinator.register_pending(
            object_id,
            Symbol::new_for_test(42, 0, 2, b"during_cleanup1"),
            now,
        );
        coordinator.register_pending(
            object_id,
            Symbol::new_for_test(42, 0, 3, b"during_cleanup2"),
            now,
        );

        // Verify symbols are in cleanup buffer, not dropped
        let stats = coordinator.stats();
        assert_eq!(
            stats.pending_objects, 1,
            "Should have pending object after failure"
        );

        // Retry cleanup (will succeed and include buffered symbols)
        let result2 = coordinator.cleanup(object_id, None);
        assert!(result2.completed, "Second cleanup should succeed");
        assert!(
            result2.handler_errors.is_empty(),
            "Should have no handler errors"
        );
        assert_eq!(
            result2.symbols_cleaned, 4,
            "Should clean initial + buffered symbols"
        );

        // Verify no pending symbols remain
        let final_stats = coordinator.stats();
        assert_eq!(
            final_stats.pending_objects, 0,
            "Should have no pending objects"
        );
        assert_eq!(
            final_stats.pending_symbols, 0,
            "Should have no pending symbols"
        );

        // Verify handler was called twice (fail, then success)
        assert_eq!(
            *attempts.lock().unwrap(),
            2,
            "Handler should be called twice"
        );
    }

    #[test]
    fn cleanup_coordinator_no_symbols_lost_during_concurrent_registration() {
        // Regression test for the specific race: symbols registered
        // during the window between cleanup start and retry restoration
        // should not be lost.

        let coordinator = CleanupCoordinator::new();
        let object_id = ObjectId::new_for_test(99);
        let now = Time::from_nanos(2000);

        // Register initial symbol
        coordinator.register_pending(object_id, Symbol::new_for_test(99, 0, 0, b"original"), now);

        // Create handler that always fails (forces retry)
        #[derive(Debug)]
        struct AlwaysFailHandler;

        impl CleanupHandler for AlwaysFailHandler {
            fn name(&self) -> &'static str {
                "always_fail"
            }
            fn cleanup(&self, _: ObjectId, _: Vec<Symbol>) -> crate::error::Result<usize> {
                Err(crate::error::Error::new(crate::error::ErrorKind::Internal)
                    .with_message("always fails"))
            }
        }

        coordinator.register_handler(object_id, AlwaysFailHandler);

        // Start cleanup (will fail and create cleanup buffer)
        let result = coordinator.cleanup(object_id, None);
        assert!(!result.completed);

        // Register more symbols during retry state
        coordinator.register_pending(
            object_id,
            Symbol::new_for_test(99, 0, 1, b"during_retry1"),
            now,
        );
        coordinator.register_pending(
            object_id,
            Symbol::new_for_test(99, 0, 2, b"during_retry2"),
            now,
        );

        // Verify all symbols are preserved (not dropped)
        let stats = coordinator.stats();
        assert_eq!(stats.pending_objects, 1);
        // Original symbol + two added during retry should all be preserved
        assert!(
            stats.pending_symbols >= 3,
            "All symbols should be preserved, got {}",
            stats.pending_symbols
        );

        // Additional symbols after restoration should also work
        coordinator.register_pending(
            object_id,
            Symbol::new_for_test(99, 0, 3, b"after_retry"),
            now,
        );

        let final_stats = coordinator.stats();
        assert!(
            final_stats.pending_symbols >= 4,
            "All symbols including post-retry should be preserved"
        );
    }

    #[test]
    fn cleanup_reentrant_attempt_is_rejected_without_stealing_retry_state() {
        use std::sync::{Arc, Mutex};

        struct ReentrantHandler {
            coordinator: Arc<CleanupCoordinator>,
            nested_result: Arc<Mutex<Option<CleanupResult>>>,
        }

        impl CleanupHandler for ReentrantHandler {
            fn name(&self) -> &'static str {
                "reentrant"
            }

            fn cleanup(
                &self,
                object_id: ObjectId,
                _symbols: Vec<Symbol>,
            ) -> crate::error::Result<usize> {
                self.coordinator.register_pending(
                    object_id,
                    Symbol::new_for_test(123, 0, 1, b"late-symbol"),
                    Time::from_millis(101),
                );
                let nested = self.coordinator.cleanup(object_id, None);
                *self.nested_result.lock().unwrap() = Some(nested);
                Ok(1)
            }
        }

        let coordinator = Arc::new(CleanupCoordinator::new());
        let nested_result = Arc::new(Mutex::new(None));
        let object_id = ObjectId::new_for_test(123);

        coordinator.register_pending(
            object_id,
            Symbol::new_for_test(123, 0, 0, b"initial"),
            Time::from_millis(100),
        );
        coordinator.register_handler(
            object_id,
            ReentrantHandler {
                coordinator: Arc::clone(&coordinator),
                nested_result: Arc::clone(&nested_result),
            },
        );

        let outer = coordinator.cleanup(object_id, None);
        assert!(outer.completed, "outer cleanup should still complete");

        let nested = nested_result
            .lock()
            .unwrap()
            .clone()
            .expect("nested cleanup result should be recorded");
        assert!(
            !nested.completed,
            "reentrant cleanup attempt must fail closed"
        );
        assert_eq!(nested.symbols_cleaned, 0);
        assert_eq!(nested.bytes_freed, 0);
        assert!(
            nested
                .handler_errors
                .iter()
                .any(|err| err.contains("cleanup already in progress")),
            "expected reentrant cleanup error, got {:?}",
            nested.handler_errors
        );

        let stats = coordinator.stats();
        assert_eq!(stats.pending_objects, 0);
        assert_eq!(stats.pending_symbols, 0);
        assert_eq!(stats.pending_bytes, 0);
        assert!(coordinator.completed.read().contains(&object_id));
    }

    #[test]
    fn cleanup_completed_path_scrubs_reentrant_handler_re_registration() {
        use std::sync::Arc;

        struct ReRegisteringHandler {
            coordinator: Arc<CleanupCoordinator>,
        }

        impl CleanupHandler for ReRegisteringHandler {
            fn name(&self) -> &'static str {
                "re-registering"
            }

            fn cleanup(
                &self,
                object_id: ObjectId,
                _symbols: Vec<Symbol>,
            ) -> crate::error::Result<usize> {
                self.coordinator
                    .register_handler(object_id, CountingCleanupHandler);
                Ok(1)
            }
        }

        let coordinator = Arc::new(CleanupCoordinator::new());
        let object_id = ObjectId::new_for_test(1234);

        coordinator.register_pending(
            object_id,
            Symbol::new_for_test(1234, 0, 0, b"initial"),
            Time::from_millis(200),
        );
        coordinator.register_handler(
            object_id,
            ReRegisteringHandler {
                coordinator: Arc::clone(&coordinator),
            },
        );

        let result = coordinator.cleanup(object_id, None);
        assert!(result.completed, "cleanup should still complete");
        assert_eq!(result.symbols_cleaned, 1);
        assert_eq!(result.bytes_freed, b"initial".len());
        assert!(
            !coordinator.handlers.read().contains_key(&object_id),
            "completed cleanup must scrub handlers re-registered during the callback"
        );
        assert!(coordinator.completed.read().contains(&object_id));
    }

    #[test]
    fn cleanup_buffered_only_reopen_restores_handler_for_retry() {
        let coordinator = CleanupCoordinator::new();
        let object_id = ObjectId::new_for_test(124);

        coordinator.register_handler(object_id, CountingCleanupHandler);
        coordinator.cleanup_buffer.write().insert(
            object_id,
            vec![Symbol::new_for_test(124, 0, 0, b"buffered-only")],
        );

        let first = coordinator.cleanup(object_id, None);
        assert!(
            !first.completed,
            "buffered symbols arriving during an otherwise empty cleanup must reopen retry state"
        );
        assert!(
            coordinator.handlers.read().contains_key(&object_id),
            "buffered-only reopen must restore the per-object handler"
        );

        let stats = coordinator.stats();
        assert_eq!(stats.pending_objects, 1);
        assert_eq!(stats.pending_symbols, 1);
        assert_eq!(stats.pending_bytes, b"buffered-only".len());

        let second = coordinator.cleanup(object_id, None);
        assert!(
            second.completed,
            "restored handler should allow retry to finish"
        );
        assert_eq!(second.symbols_cleaned, 1);
        assert_eq!(second.bytes_freed, b"buffered-only".len());
    }

    /// Basic integration test for br-asupersync-dm6ci4: CancelBroadcaster retry mechanism.
    ///
    /// Verifies that the pending_retries field is properly tracked in metrics.
    /// More complex retry scenarios are tested via integration tests.
    #[test]
    fn cancel_broadcaster_tracks_pending_retries_in_metrics() {
        // Test sink is only needed to satisfy the broadcaster type parameter.
        #[derive(Debug)]
        struct TestSink;

        impl CancelSink for TestSink {
            fn send_to(
                &self,
                _peer: &PeerId,
                _msg: &CancelMessage,
            ) -> impl std::future::Future<Output = crate::error::Result<()>> + Send {
                std::future::ready(Ok(()))
            }

            fn broadcast(
                &self,
                _msg: &CancelMessage,
            ) -> impl std::future::Future<Output = crate::error::Result<usize>> + Send {
                std::future::ready(Ok(1))
            }
        }

        let broadcaster = CancelBroadcaster::new(TestSink);
        let object_id = ObjectId::new_for_test(123);

        // Initially no pending retries
        let initial_metrics = broadcaster.metrics();
        assert_eq!(
            initial_metrics.pending_retries, 0,
            "Should start with no pending retries"
        );

        // Manually add a message to retry queue (simulating failed broadcast)
        let test_message =
            CancelMessage::new(42, object_id, CancelKind::User, Time::from_nanos(1000), 1);
        broadcaster.pending_retries.write().push_back(test_message);

        // Metrics should reflect the pending retry
        let metrics_with_pending = broadcaster.metrics();
        assert_eq!(
            metrics_with_pending.pending_retries, 1,
            "Should show 1 pending retry"
        );

        // Clear the retry queue
        broadcaster.pending_retries.write().clear();

        // Metrics should show no pending retries again
        let final_metrics = broadcaster.metrics();
        assert_eq!(
            final_metrics.pending_retries, 0,
            "Should show no pending retries after clear"
        );
    }

    #[test]
    fn cancel_broadcaster_serializes_concurrent_retry_passes() {
        use std::sync::Condvar;
        use std::sync::mpsc;
        use std::time::Duration;

        #[derive(Debug)]
        struct BlockingFirstRetrySink {
            broadcast_calls: Arc<AtomicUsize>,
            first_call_entered: std::sync::Mutex<Option<mpsc::Sender<()>>>,
            release_gate: Arc<(std::sync::Mutex<bool>, Condvar)>,
        }

        impl CancelSink for BlockingFirstRetrySink {
            fn send_to(
                &self,
                _peer: &PeerId,
                _msg: &CancelMessage,
            ) -> impl std::future::Future<Output = crate::error::Result<()>> + Send {
                std::future::ready(Ok(()))
            }

            fn broadcast(
                &self,
                _msg: &CancelMessage,
            ) -> impl std::future::Future<Output = crate::error::Result<usize>> + Send {
                let call_index = self.broadcast_calls.fetch_add(1, Ordering::SeqCst);
                let entered = if call_index == 0 {
                    self.first_call_entered.lock().unwrap().take()
                } else {
                    None
                };
                let release_gate = Arc::clone(&self.release_gate);

                async move {
                    if let Some(entered) = entered {
                        entered.send(()).expect("first retry should signal entry");
                        let (released_lock, released_cv) = &*release_gate;
                        let mut released = released_lock.lock().unwrap();
                        while !*released {
                            released = released_cv.wait(released).unwrap();
                        }
                    }

                    Ok(1)
                }
            }
        }

        let (entered_tx, entered_rx) = mpsc::channel();
        let release_gate = Arc::new((std::sync::Mutex::new(false), Condvar::new()));
        let broadcast_calls = Arc::new(AtomicUsize::new(0));
        let sink = BlockingFirstRetrySink {
            broadcast_calls: Arc::clone(&broadcast_calls),
            first_call_entered: std::sync::Mutex::new(Some(entered_tx)),
            release_gate: Arc::clone(&release_gate),
        };
        let broadcaster = Arc::new(CancelBroadcaster::new(sink));
        let object_id = ObjectId::new_for_test(321);
        broadcaster
            .pending_retries
            .write()
            .push_back(CancelMessage::new(
                1,
                object_id,
                CancelKind::User,
                Time::from_nanos(10),
                0,
            ));
        broadcaster
            .pending_retries
            .write()
            .push_back(CancelMessage::new(
                1,
                object_id,
                CancelKind::User,
                Time::from_nanos(20),
                1,
            ));

        let retry_owner = Arc::clone(&broadcaster);
        let retry_handle = std::thread::spawn(move || {
            futures_lite::future::block_on(retry_owner.retry_failed_broadcasts())
        });

        entered_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("primary retry loop should enter first broadcast");

        let concurrent_result =
            futures_lite::future::block_on(broadcaster.retry_failed_broadcasts());
        assert_eq!(
            concurrent_result.0, 0,
            "concurrent retry callers must not steal later messages from the FIFO queue"
        );
        assert!(
            concurrent_result.1.is_none(),
            "concurrent retry callers must return without surfacing an error: {:?}",
            concurrent_result.1
        );
        assert_eq!(
            broadcaster.pending_retries.read().len(),
            1,
            "the second message should remain queued for the active retry loop"
        );

        let (released_lock, released_cv) = &*release_gate;
        *released_lock.lock().unwrap() = true;
        released_cv.notify_all();

        let owner_result = retry_handle.join().expect("retry thread should join");
        assert_eq!(
            owner_result.0, 2,
            "the owning retry pass should drain both queued messages in order"
        );
        assert!(
            owner_result.1.is_none(),
            "the owning retry pass should complete without surfacing an error: {:?}",
            owner_result.1
        );
        assert_eq!(
            broadcaster.pending_retries.read().len(),
            0,
            "all retry messages should be drained after the owner completes"
        );
        assert_eq!(
            broadcast_calls.load(Ordering::SeqCst),
            2,
            "only the owning retry pass should broadcast the queued messages"
        );
    }
}

#[cfg(test)]
#[path = "symbol_cancel_metamorphic.rs"]
mod symbol_cancel_metamorphic;