asupersync 0.3.1

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
//! Martingale progress certificates for cancellation drain.
//!
//! # Purpose
//!
//! Provides statistically grounded guarantees that cancellation
//! drain is making progress toward quiescence. Uses supermartingale theory
//! to prove that a cancelling system will terminate within bounded time,
//! with explicit certificates that can be audited.
//!
//! # Mathematical Foundation
//!
//! A **supermartingale** is a stochastic process {Mₜ} where
//! `E[Mₜ₊₁ | Fₜ] ≤ Mₜ`. For cancellation drain, define the progress
//! process:
//!
//! ```text
//! Mₜ = V(Σₜ) + Σᵢ₌₁ᵗ cᵢ
//! ```
//!
//! where `V(Σₜ)` is the Lyapunov potential at step `t` and `cᵢ ≥ 0` is
//! the "progress credit" consumed at step `i`.
//!
//! **Key theorem (Optional Stopping):** If Mₜ is a supermartingale and
//! `V(Σₜ) ≥ 0`, then:
//!
//! ```text
//! E[τ] ≤ V(Σ₀) / min_credit
//! ```
//!
//! where `τ = inf{t : V(Σₜ) = 0}` is the hitting time of quiescence.
//!
//! **Azuma–Hoeffding concentration bound:**
//!
//! ```text
//! P(V(Σₜ) > V(Σ₀) - t·μ + λ) ≤ exp(-2λ² / (t·c²))
//! ```
//!
//! where `μ` is mean progress per step and `c` is the max step size.
//! This gives a **probabilistic certificate**: "with probability ≥ 1-δ,
//! quiescence is reached within T steps."
//!
//! **Ville's maximal inequality** (see also `eprocess.rs`):
//!
//! ```text
//! P(sup_{t≥0} Mₜ ≥ C) ≤ M₀ / C
//! ```
//!
//! # Integration Points
//!
//! - [`LyapunovGovernor`](crate::obligation::lyapunov::LyapunovGovernor) —
//!   provides `V(Σₜ)` potential values via [`PotentialRecord`].
//! - [`EProcess`](crate::lab::oracle::eprocess::EProcess) — sister
//!   martingale monitoring framework for invariant checking.
//! - [`SymbolCancelToken`](super::symbol_cancel::SymbolCancelToken) —
//!   cancellation cascade system whose drain we certificate.
//! - [`Budget`](crate::types::Budget) — poll quota provides a hard
//!   upper bound that serves as an independent safety net.
//!
//! # Usage
//!
//! ```
//! use asupersync::cancel::progress_certificate::{
//!     ProgressCertificate, ProgressConfig, CertificateVerdict,
//! };
//!
//! let config = ProgressConfig::default();
//! let mut cert = ProgressCertificate::new(config);
//!
//! // Feed potential values from successive drain steps.
//! cert.observe(100.0);
//! cert.observe(80.0);
//! cert.observe(55.0);
//! cert.observe(30.0);
//! cert.observe(10.0);
//! cert.observe(0.0);
//!
//! let verdict = cert.verdict();
//! assert!(verdict.converging);
//! assert!(verdict.confidence_bound > 0.95);
//! ```

use std::fmt;

// ============================================================================
// Configuration
// ============================================================================

/// Configuration for progress certificate monitoring.
///
/// Controls the statistical parameters governing stall detection,
/// concentration bounds, and certificate confidence levels.
#[derive(Debug, Clone)]
pub struct ProgressConfig {
    /// Desired confidence level for probabilistic bounds (e.g. 0.95).
    ///
    /// Must be in `(0, 1)`. The Azuma–Hoeffding bound targets
    /// `P(quiescence within T) ≥ confidence`.
    pub confidence: f64,

    /// Upper bound on the absolute potential change in a single step.
    ///
    /// This is the `c` in the Azuma–Hoeffding inequality. Must be
    /// positive and finite. If a step exceeds this bound, the
    /// certificate logs an evidence entry but does not panic.
    pub max_step_bound: f64,

    /// Number of consecutive non-decreasing steps before declaring a stall.
    ///
    /// Stall detection uses a sliding window: if the last
    /// `stall_threshold` steps all have `delta ≥ 0` (potential did not
    /// decrease), the certificate flags a stall. Must be ≥ 1.
    pub stall_threshold: usize,

    /// Minimum number of observations before issuing any verdict.
    ///
    /// Below this count, `verdict()` returns a provisional result with
    /// `converging = false` and no bounds. Must be ≥ 2 (need at least
    /// one delta).
    pub min_observations: usize,

    /// Small epsilon for floating-point comparisons.
    ///
    /// Two potentials are considered "equal" if they differ by less
    /// than this value. Prevents false stall detection from rounding.
    pub epsilon: f64,
}

impl Default for ProgressConfig {
    fn default() -> Self {
        Self {
            confidence: 0.95,
            max_step_bound: 100.0,
            stall_threshold: 10,
            min_observations: 5,
            epsilon: 1e-12,
        }
    }
}

impl ProgressConfig {
    /// Validates the configuration.
    ///
    /// Returns `Err` with a description if any constraint is violated.
    pub fn validate(&self) -> Result<(), String> {
        if !self.confidence.is_finite() || self.confidence <= 0.0 || self.confidence >= 1.0 {
            return Err(format!(
                "confidence must be in (0, 1), got {}",
                self.confidence
            ));
        }
        if !self.max_step_bound.is_finite() || self.max_step_bound <= 0.0 {
            return Err(format!(
                "max_step_bound must be positive and finite, got {}",
                self.max_step_bound
            ));
        }
        if self.stall_threshold == 0 {
            return Err("stall_threshold must be >= 1".to_owned());
        }
        if self.min_observations < 2 {
            return Err(format!(
                "min_observations must be >= 2, got {}",
                self.min_observations
            ));
        }
        if !self.epsilon.is_finite() || self.epsilon < 0.0 {
            return Err(format!(
                "epsilon must be non-negative and finite, got {}",
                self.epsilon
            ));
        }
        Ok(())
    }

    /// Configuration tuned for tight stall detection (aggressive monitoring).
    #[must_use]
    pub fn aggressive() -> Self {
        Self {
            confidence: 0.99,
            max_step_bound: 50.0,
            stall_threshold: 5,
            min_observations: 3,
            epsilon: 1e-12,
        }
    }

    /// Configuration tuned for long-running drains with high variance.
    #[must_use]
    pub fn tolerant() -> Self {
        Self {
            confidence: 0.90,
            max_step_bound: 500.0,
            stall_threshold: 25,
            min_observations: 10,
            epsilon: 1e-10,
        }
    }
}

// ============================================================================
// Observation
// ============================================================================

/// A single observation in the progress process.
///
/// Each observation records the Lyapunov potential at one drain step,
/// together with derived quantities used for martingale analysis.
#[derive(Debug, Clone)]
pub struct ProgressObservation {
    /// Zero-based step index.
    pub step: usize,
    /// Lyapunov potential `V(Σₜ)` at this step.
    pub potential: f64,
    /// Change from previous step: `V(Σₜ) - V(Σₜ₋₁)`.
    ///
    /// Negative means progress (potential decreased). For the first
    /// observation this is `0.0`.
    pub delta: f64,
    /// Progress credit consumed at this step: `max(0, -delta)`.
    ///
    /// This is the `cₜ` term in the supermartingale decomposition.
    pub credit: f64,
}

// ============================================================================
// Evidence
// ============================================================================

/// An auditable evidence entry in a progress certificate.
///
/// Evidence entries form the proof trail that auditors (human or machine)
/// can inspect to verify certificate claims.
#[derive(Debug, Clone)]
pub struct EvidenceEntry {
    /// Step at which this evidence was recorded.
    pub step: usize,
    /// Potential value at this step.
    pub potential: f64,
    /// The Azuma–Hoeffding bound at this step (upper tail probability).
    pub bound: f64,
    /// Human-readable description of the evidence.
    pub description: String,
}

impl fmt::Display for EvidenceEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "step={}: V={:.4}, bound={:.6}{}",
            self.step, self.potential, self.bound, self.description,
        )
    }
}

// ============================================================================
// Drain Phase
// ============================================================================

/// Phase of the cancellation drain process.
///
/// Determined automatically from the credit stream using an exponential
/// moving average to detect transitions between rapid drain and slow
/// convergence tail. This enables phase-adaptive timeout policies:
/// during `RapidDrain` the system can use aggressive timeouts, while
/// `SlowTail` warrants patience and `Stalled` warrants escalation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DrainPhase {
    /// Insufficient observations to classify the phase.
    Warmup,
    /// Rapid initial drain: high credit per step, potential falling fast.
    RapidDrain,
    /// Slow tail convergence: diminishing returns per step.
    SlowTail,
    /// No meaningful progress is being made.
    Stalled,
    /// Potential is at or near zero; drain is complete.
    Quiescent,
}

impl fmt::Display for DrainPhase {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Warmup => f.write_str("warmup"),
            Self::RapidDrain => f.write_str("rapid_drain"),
            Self::SlowTail => f.write_str("slow_tail"),
            Self::Stalled => f.write_str("stalled"),
            Self::Quiescent => f.write_str("quiescent"),
        }
    }
}

// ============================================================================
// Certificate Verdict
// ============================================================================

/// Certificate verdict with probabilistic bounds.
///
/// Summarises the statistical analysis of a progress trace. All fields
/// are derived from the observation history using the mathematical
/// framework described in the module documentation.
#[derive(Debug, Clone)]
pub struct CertificateVerdict {
    /// Whether the process appears to be converging (potential trending
    /// downward with statistical significance).
    pub converging: bool,

    /// Estimated remaining steps to quiescence via the Optional Stopping
    /// Theorem: `V(Σₜ) / mean_credit`. `None` if insufficient data or
    /// zero mean credit.
    pub estimated_remaining_steps: Option<f64>,

    /// Lower bound on P(quiescence within T steps) from the
    /// Azuma–Hoeffding inequality, where T is the estimated remaining
    /// steps. In `[0, 1]`.
    pub confidence_bound: f64,

    /// Whether a stall was detected (last `stall_threshold` steps all
    /// had non-decreasing potential).
    pub stall_detected: bool,

    /// The Azuma–Hoeffding concentration bound at the current step.
    ///
    /// This is `exp(-2λ² / (t·c²))` evaluated at the current
    /// deviation from expected progress.
    pub azuma_bound: f64,

    /// Number of observations processed.
    pub total_steps: usize,

    /// Current potential value.
    pub current_potential: f64,

    /// Initial potential value (at step 0).
    pub initial_potential: f64,

    /// Mean credit (progress) per step.
    pub mean_credit: f64,

    /// Maximum single-step absolute change observed.
    pub max_observed_step: f64,

    /// Freedman's inequality bound (variance-adaptive, strictly dominates
    /// Azuma–Hoeffding when empirical variance is below worst-case).
    ///
    /// ```text
    /// P(Sₜ ≥ λ) ≤ exp(-λ² / (2(Vₜ + bλ/3)))
    /// ```
    ///
    /// where `Vₜ` is the predictable quadratic variation and `b` is the
    /// max step size. Always `≤ azuma_bound`.
    pub freedman_bound: f64,

    /// Current drain phase classification.
    pub drain_phase: DrainPhase,

    /// Empirical variance of per-step deltas (`None` if < 2 observations).
    pub empirical_variance: Option<f64>,

    /// Auditable evidence trail.
    pub evidence: Vec<EvidenceEntry>,
}

impl fmt::Display for CertificateVerdict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Progress Certificate Verdict")?;
        writeln!(f, "============================")?;
        writeln!(f, "Converging:         {}", self.converging)?;
        writeln!(f, "Stall detected:     {}", self.stall_detected)?;
        writeln!(f, "Steps:              {}", self.total_steps)?;
        writeln!(f, "V(Σ₀):              {:.4}", self.initial_potential)?;
        writeln!(f, "V(Σₜ):              {:.4}", self.current_potential)?;
        writeln!(f, "Mean credit/step:   {:.4}", self.mean_credit)?;
        writeln!(f, "Max |Δ|:            {:.4}", self.max_observed_step)?;
        writeln!(f, "Drain phase:        {}", self.drain_phase)?;
        writeln!(f, "Confidence bound:   {:.6}", self.confidence_bound)?;
        writeln!(f, "Azuma bound:        {:.6}", self.azuma_bound)?;
        writeln!(f, "Freedman bound:     {:.6}", self.freedman_bound)?;
        if let Some(var) = self.empirical_variance {
            writeln!(f, "Delta variance:     {var:.6}")?;
        }
        if let Some(est) = self.estimated_remaining_steps {
            writeln!(f, "Est. remaining:     {est:.1} steps")?;
        } else {
            writeln!(f, "Est. remaining:     N/A")?;
        }
        if !self.evidence.is_empty() {
            writeln!(f, "Evidence ({} entries):", self.evidence.len())?;
            for e in &self.evidence {
                writeln!(f, "  {e}")?;
            }
        }
        Ok(())
    }
}

// ============================================================================
// Progress Certificate
// ============================================================================

/// Running progress certificate with statistical guarantees.
///
/// Tracks a sequence of Lyapunov potential values from successive
/// cancellation drain steps and maintains the supermartingale
/// decomposition `Mₜ = V(Σₜ) + Σcᵢ`. At any point, callers can
/// request a [`CertificateVerdict`] with probabilistic bounds on
/// time-to-quiescence and stall detection.
///
/// # Supermartingale Property
///
/// If the scheduler is well-behaved (each step makes expected progress),
/// the compensated process `Mₜ` is a supermartingale. The certificate
/// verifies this empirically and uses concentration inequalities to
/// quantify deviations.
///
/// # Bounded Memory
///
/// Observations are retained for audit. If memory is a concern, use
/// [`compact`](Self::compact) to discard old observations while
/// preserving sufficient statistics.
#[derive(Debug, Clone)]
pub struct ProgressCertificate {
    /// Retained observation history for audit/debug.
    ///
    /// This may be compacted via [`compact`](Self::compact). Aggregate
    /// statistics remain global across the full run.
    observations: Vec<ProgressObservation>,
    /// Configuration.
    config: ProgressConfig,
    /// Total number of observations recorded since last reset.
    ///
    /// This count is independent of retained history and is not affected by
    /// [`compact`](Self::compact).
    total_observations: usize,
    /// Number of observed deltas (always `total_observations - 1` when non-zero).
    total_deltas: usize,
    /// Initial potential `V(Σ₀)` for this certificate run.
    initial_potential: Option<f64>,
    /// Most recent potential value, even if older observations were compacted.
    last_potential: Option<f64>,
    /// Running sum of deltas `ΣΔᵢ` across all observed steps.
    sum_delta: f64,
    /// Running sum of credits: `Σcᵢ`.
    total_credit: f64,
    /// Running sum of squared deltas for variance estimation.
    sum_delta_sq: f64,
    /// Maximum absolute delta observed.
    max_abs_delta: f64,
    /// Number of steps with potential increase (violations of monotone
    /// decrease).
    increase_count: usize,
    /// Length of the current non-decreasing tail (for stall detection).
    stall_run: usize,
    /// Exponential moving average of per-step credit for phase detection.
    ///
    /// Uses smoothing factor `alpha = 2 / (window + 1)` with `window = 8`.
    ema_credit: f64,
}

impl ProgressCertificate {
    /// Creates a new progress certificate with the given configuration.
    ///
    /// # Panics
    ///
    /// Panics if `config` fails validation.
    #[must_use]
    pub fn new(config: ProgressConfig) -> Self {
        assert!(
            config.validate().is_ok(),
            "ProgressConfig validation failed: {}",
            config.validate().expect_err("expected validation to fail")
        );
        Self {
            observations: Vec::new(),
            config,
            total_observations: 0,
            total_deltas: 0,
            initial_potential: None,
            last_potential: None,
            sum_delta: 0.0,
            total_credit: 0.0,
            sum_delta_sq: 0.0,
            max_abs_delta: 0.0,
            increase_count: 0,
            stall_run: 0,
            ema_credit: 0.0,
        }
    }

    /// Creates a new progress certificate with default configuration.
    #[must_use]
    pub fn with_defaults() -> Self {
        Self::new(ProgressConfig::default())
    }

    /// Records a potential observation.
    ///
    /// `potential` must be non-negative (Lyapunov functions are ≥ 0).
    /// If `potential` is negative, it is clamped to zero and an internal
    /// note is recorded.
    pub fn observe(&mut self, potential: f64) {
        let potential = if potential.is_finite() {
            potential.max(0.0)
        } else {
            0.0
        };
        let step = self.total_observations;

        let delta = self.last_potential.map_or(0.0, |prev| potential - prev);

        let credit = (-delta).max(0.0);

        self.total_credit += credit;
        if step > 0 {
            self.total_deltas += 1;
            self.sum_delta += delta;
            self.sum_delta_sq += delta * delta;
        }

        let abs_delta = delta.abs();
        if abs_delta > self.max_abs_delta {
            self.max_abs_delta = abs_delta;
        }

        if step > 0 && delta > self.config.epsilon {
            self.increase_count += 1;
        }

        // Update exponential moving average of credit for phase detection.
        // Alpha = 2 / (8 + 1) ≈ 0.222. The EMA tracks whether the credit
        // rate is accelerating (rapid drain) or decelerating (slow tail).
        if step > 0 {
            if self.total_deltas == 1 {
                self.ema_credit = credit;
            } else {
                const EMA_ALPHA: f64 = 2.0 / 9.0;
                self.ema_credit = EMA_ALPHA.mul_add(credit, (1.0 - EMA_ALPHA) * self.ema_credit);
            }
        }

        // Stall run: count consecutive non-decreasing steps at the tail.
        if step > 0 && delta >= -self.config.epsilon {
            self.stall_run += 1;
        } else {
            self.stall_run = 0;
        }

        self.observations.push(ProgressObservation {
            step,
            potential,
            delta,
            credit,
        });
        if self.initial_potential.is_none() {
            self.initial_potential = Some(potential);
        }
        self.last_potential = Some(potential);
        self.total_observations += 1;
    }

    /// Records a potential value from a [`PotentialRecord`](crate::obligation::lyapunov::PotentialRecord).
    ///
    /// Convenience wrapper that extracts the total potential.
    pub fn observe_potential_record(
        &mut self,
        record: &crate::obligation::lyapunov::PotentialRecord,
    ) {
        self.observe(record.total);
    }

    /// Computes the Azuma–Hoeffding tail bound.
    ///
    /// Given `t` steps with mean progress `mu` per step and max step
    /// size `c`, the probability that the potential exceeds
    /// `V₀ - t·mu + lambda` is bounded by:
    ///
    /// ```text
    /// P(excess ≥ lambda) ≤ exp(-2·lambda² / (t·c²))
    /// ```
    ///
    /// We compute this with `lambda` chosen such that `V₀ - t·mu + lambda = 0`
    /// (the critical threshold for quiescence), giving the probability that
    /// quiescence has NOT been reached by step `t` under the mean-progress
    /// assumption.
    #[must_use]
    fn azuma_hoeffding_bound(&self, t: usize, mean_credit: f64, step_bound: f64) -> f64 {
        if t == 0 || step_bound <= 0.0 {
            return 1.0;
        }

        let initial = self.initial_potential.unwrap_or(0.0);

        // Expected potential at step t: V₀ - t·mu.
        // lambda = residual potential assuming expected progress:
        //   lambda = V₀ - t·mu  (= expected current potential)
        // But we cap lambda at 0 from below — if expected progress
        // already exceeds V₀, the bound is trivially satisfied.
        #[allow(clippy::cast_precision_loss)]
        let t_f = t as f64;
        let expected_remaining = t_f.mul_add(-mean_credit, initial);
        let lambda = (-expected_remaining).max(0.0);

        // Azuma–Hoeffding: P(Sₜ ≥ lambda) ≤ exp(-2·lambda² / (t·c²))
        let exponent = -2.0 * lambda * lambda / (t_f * step_bound * step_bound);

        exponent.exp()
    }

    /// Computes the Ville's maximal inequality bound.
    ///
    /// ```text
    /// P(sup_{s≥0} Mₛ ≥ C) ≤ M₀ / C
    /// ```
    ///
    /// For the progress supermartingale, `M₀ = V(Σ₀)` and `C` is the
    /// threshold. We use `C = V₀ · (1 + margin)` to bound the probability
    /// that the potential ever exceeds its initial value by more than
    /// `margin` fraction.
    #[must_use]
    fn ville_bound(&self, margin: f64) -> f64 {
        let v0 = self.initial_potential.unwrap_or(0.0);
        if v0 <= 0.0 {
            return 0.0;
        }
        let threshold = v0 * (1.0 + margin);
        (v0 / threshold).min(1.0)
    }

    /// Computes Freedman's inequality bound (variance-adaptive).
    ///
    /// Freedman's inequality is a variance-sensitive analogue of
    /// Azuma–Hoeffding that replaces the worst-case `t·c²` term with the
    /// predictable quadratic variation `Vₜ = Σ Var(Xᵢ | Fᵢ₋₁)`:
    ///
    /// ```text
    /// P(Sₜ ≥ λ AND Vₜ ≤ v) ≤ exp(-λ² / (2(v + bλ/3)))
    /// ```
    ///
    /// where `b` is the max step size. This is strictly tighter than
    /// Azuma whenever empirical variance is below `c²`, which is the
    /// common case for well-behaved cancellation drains with occasional
    /// jitter. The improvement can be orders of magnitude.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    fn freedman_bound(&self, t: usize, mean_credit: f64, step_bound: f64) -> f64 {
        if t == 0 || step_bound <= 0.0 {
            return 1.0;
        }

        let initial = self.initial_potential.unwrap_or(0.0);
        let t_f = t as f64;
        let expected_remaining = t_f.mul_add(-mean_credit, initial);
        let lambda = (-expected_remaining).max(0.0);

        // Use empirical variance if available, else fall back to worst-case
        // (which makes Freedman equivalent to Azuma).
        let variance = self.delta_variance().unwrap_or(step_bound * step_bound);
        let predictable_variation = t_f * variance;

        let denom = 2.0 * step_bound.mul_add(lambda / 3.0, predictable_variation);

        if !denom.is_finite() || denom <= 0.0 {
            return 1.0;
        }

        (-lambda * lambda / denom).exp()
    }

    /// Returns the current drain phase.
    ///
    /// Phase classification uses the exponential moving average of credit
    /// compared to the overall mean credit rate:
    ///
    /// - **Quiescent**: potential ≈ 0 (drain complete)
    /// - **Stalled**: stall run ≥ threshold (no progress)
    /// - **RapidDrain**: EMA credit ≥ 50% of mean credit
    /// - **SlowTail**: EMA credit < 50% of mean credit
    /// - **Warmup**: insufficient data
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn drain_phase(&self) -> DrainPhase {
        if self.total_observations < self.config.min_observations {
            return DrainPhase::Warmup;
        }
        let current = self.last_potential.unwrap_or(0.0);
        if current <= self.config.epsilon {
            return DrainPhase::Quiescent;
        }
        if self.stall_run >= self.config.stall_threshold {
            return DrainPhase::Stalled;
        }
        let mean_credit = if self.total_deltas > 0 {
            self.total_credit / self.total_deltas as f64
        } else {
            return DrainPhase::Warmup;
        };
        if mean_credit <= self.config.epsilon {
            return DrainPhase::Stalled;
        }
        if self.ema_credit >= 0.5 * mean_credit {
            DrainPhase::RapidDrain
        } else {
            DrainPhase::SlowTail
        }
    }

    /// Produces a certificate verdict from the current observation history.
    ///
    /// This is the main query interface. The verdict includes:
    /// - Convergence status (statistical trend analysis)
    /// - Estimated remaining steps (Optional Stopping Theorem)
    /// - Confidence bound (Azuma–Hoeffding)
    /// - Stall detection (sliding window)
    /// - Full evidence trail
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn verdict(&self) -> CertificateVerdict {
        const MAX_CONVERGENCE_VIOLATION_RATE: f64 = 0.25;
        let n = self.total_observations;

        // --- Insufficient data: provisional verdict ---
        if n < self.config.min_observations {
            return CertificateVerdict {
                converging: false,
                estimated_remaining_steps: None,
                confidence_bound: 0.0,
                stall_detected: false,
                azuma_bound: 1.0,
                total_steps: n,
                current_potential: self.last_potential.unwrap_or(0.0),
                initial_potential: self.initial_potential.unwrap_or(0.0),
                mean_credit: 0.0,
                max_observed_step: self.max_abs_delta,
                freedman_bound: 1.0,
                drain_phase: DrainPhase::Warmup,
                empirical_variance: None,
                evidence: Vec::new(),
            };
        }

        let v_initial = self.initial_potential.unwrap_or(0.0);
        let v_current = self.last_potential.unwrap_or(0.0);
        let steps_with_deltas = self.total_deltas;
        let mean_credit = if steps_with_deltas > 0 {
            self.total_credit / steps_with_deltas as f64
        } else {
            0.0
        };

        let effective_step_bound = if self.max_abs_delta > self.config.max_step_bound {
            self.max_abs_delta
        } else {
            self.config.max_step_bound
        };
        let azuma =
            self.azuma_hoeffding_bound(steps_with_deltas, mean_credit, effective_step_bound);
        let freedman = self.freedman_bound(steps_with_deltas, mean_credit, effective_step_bound);

        let estimated_remaining =
            (mean_credit > self.config.epsilon).then(|| v_current / mean_credit);

        // Use Freedman (tighter) for confidence bound when available.
        let confidence_bound = estimated_remaining.map_or(0.0, |t_rem| {
            if v_current <= self.config.epsilon {
                return 1.0;
            }
            // Safety factor of 2 for variance.
            #[allow(clippy::cast_sign_loss)]
            let extra = (2.0 * t_rem).ceil().max(0.0) as usize;
            let total_t = steps_with_deltas.saturating_add(extra);
            let tail = self.freedman_bound(total_t, mean_credit, effective_step_bound);
            (1.0 - tail).clamp(0.0, 1.0)
        });

        let stall_detected = self.stall_run >= self.config.stall_threshold;

        // Convergence gate combines concentration and empirical trend, while
        // rejecting strongly oscillatory traces. Uses Freedman (variance-
        // adaptive) instead of raw Azuma for strictly tighter decisions.
        let violation_rate = if steps_with_deltas > 0 {
            self.increase_count as f64 / steps_with_deltas as f64
        } else {
            0.0
        };
        let reduction_ratio = if v_initial > self.config.epsilon {
            ((v_initial - v_current) / v_initial).clamp(0.0, 1.0)
        } else {
            1.0
        };
        let strong_concentration = freedman < (1.0 - self.config.confidence);
        let strong_empirical_reduction = reduction_ratio >= self.config.confidence;
        let converging = mean_credit > self.config.epsilon
            && !stall_detected
            && violation_rate <= MAX_CONVERGENCE_VIOLATION_RATE
            && (strong_concentration || strong_empirical_reduction);

        let evidence = self.build_evidence(
            n,
            v_initial,
            v_current,
            steps_with_deltas,
            mean_credit,
            azuma,
            freedman,
            stall_detected,
            effective_step_bound,
        );

        CertificateVerdict {
            converging,
            estimated_remaining_steps: estimated_remaining,
            confidence_bound,
            stall_detected,
            azuma_bound: azuma,
            total_steps: n,
            current_potential: v_current,
            initial_potential: v_initial,
            mean_credit,
            max_observed_step: self.max_abs_delta,
            freedman_bound: freedman,
            drain_phase: self.drain_phase(),
            empirical_variance: self.delta_variance(),
            evidence,
        }
    }

    /// Builds the auditable evidence trail for a verdict.
    #[allow(clippy::too_many_arguments, clippy::cast_precision_loss)]
    fn build_evidence(
        &self,
        n: usize,
        v_initial: f64,
        v_current: f64,
        steps_with_deltas: usize,
        mean_credit: f64,
        azuma: f64,
        freedman: f64,
        stall_detected: bool,
        _effective_step_bound: f64,
    ) -> Vec<EvidenceEntry> {
        let mut evidence = Vec::new();
        let last_step = n - 1;

        // Step bound exceeded.
        if self.max_abs_delta > self.config.max_step_bound {
            let max_obs = self.max_abs_delta;
            let configured = self.config.max_step_bound;
            // `bound` is contractually a probability in [0, 1]. Using the
            // observed step magnitude here would violate that invariant,
            // so we emit the current Azuma probability bound instead and
            // surface the step-size information in the description.
            evidence.push(EvidenceEntry {
                step: last_step,
                potential: v_current,
                bound: azuma,
                description: format!(
                    "max observed step {max_obs:.4} exceeds configured bound \
                     {configured:.4}; using observed max for Azuma bound",
                ),
            });
        }

        // Quiescence achieved.
        if v_current <= self.config.epsilon {
            evidence.push(EvidenceEntry {
                step: last_step,
                potential: v_current,
                bound: 0.0,
                description: "quiescence reached (V ≈ 0)".to_owned(),
            });
        }

        // Stall evidence.
        if stall_detected {
            let run = self.stall_run;
            let threshold = self.config.stall_threshold;
            // `bound` must remain a valid probability; surface the run
            // length through the description instead.
            evidence.push(EvidenceEntry {
                step: last_step,
                potential: v_current,
                bound: azuma.min(1.0).max(0.0),
                description: format!(
                    "stall: {run} consecutive non-decreasing steps (threshold: {threshold})",
                ),
            });
        }

        // Monotonicity violations.
        if self.increase_count > 0 {
            let violation_rate = self.increase_count as f64 / steps_with_deltas as f64;
            let count = self.increase_count;
            evidence.push(EvidenceEntry {
                step: last_step,
                potential: v_current,
                bound: violation_rate,
                description: format!(
                    "{count} monotonicity violations out of {steps_with_deltas} steps \
                     (rate: {violation_rate:.4})",
                ),
            });
        }

        // Ville's bound on worst-case exceedance.
        let ville = self.ville_bound(0.5);
        if ville > 0.01 {
            evidence.push(EvidenceEntry {
                step: last_step,
                potential: v_current,
                bound: ville,
                description: format!(
                    "Ville bound: P(potential ever exceeds 1.5\u{00b7}V\u{2080}) \u{2264} {ville:.4}",
                ),
            });
        }

        // Progress summary with both bounds.
        let total_progress = v_initial - v_current;
        evidence.push(EvidenceEntry {
            step: last_step,
            potential: v_current,
            bound: azuma,
            description: format!(
                "total progress {total_progress:.4} over {steps_with_deltas} steps, \
                 mean credit {mean_credit:.4}/step, Azuma tail P \u{2264} {azuma:.6}",
            ),
        });

        // Freedman bound (variance-adaptive, dominates Azuma).
        if (freedman - azuma).abs() > 1e-12 {
            let improvement = if azuma > 1e-15 {
                (1.0 - freedman / azuma) * 100.0
            } else {
                0.0
            };
            evidence.push(EvidenceEntry {
                step: last_step,
                potential: v_current,
                bound: freedman,
                description: format!(
                    "Freedman bound P \u{2264} {freedman:.6} \
                     ({improvement:.1}% tighter than Azuma)",
                ),
            });
        }

        evidence
    }

    /// Returns the number of retained observations.
    #[must_use]
    pub fn len(&self) -> usize {
        self.observations.len()
    }

    /// Returns whether no observations have been recorded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.observations.is_empty()
    }

    /// Returns retained observation history (possibly compacted).
    #[must_use]
    pub fn observations(&self) -> &[ProgressObservation] {
        &self.observations
    }

    /// Returns the total number of observations recorded since last reset.
    ///
    /// Unlike [`len`](Self::len), this count is not reduced by
    /// [`compact`](Self::compact).
    #[must_use]
    pub fn total_observations(&self) -> usize {
        self.total_observations
    }

    /// Returns the configuration.
    #[must_use]
    pub fn config(&self) -> &ProgressConfig {
        &self.config
    }

    /// Returns the current supermartingale value `Mₜ = V(Σₜ) + Σcᵢ`.
    #[must_use]
    pub fn martingale_value(&self) -> f64 {
        let v = self.last_potential.unwrap_or(0.0);
        v + self.total_credit
    }

    /// Returns the total accumulated credit.
    #[must_use]
    pub fn total_credit(&self) -> f64 {
        self.total_credit
    }

    /// Returns the number of monotonicity violations observed.
    #[must_use]
    pub fn increase_count(&self) -> usize {
        self.increase_count
    }

    /// Discards observations older than `keep_last`, preserving
    /// sufficient statistics (totals, max, counts).
    ///
    /// This does NOT alter the statistical summaries — verdicts
    /// computed after compaction use the same totals as before.
    /// Only the per-step audit trail is truncated.
    pub fn compact(&mut self, keep_last: usize) {
        if self.observations.len() <= keep_last {
            return;
        }
        let drain_count = self.observations.len() - keep_last;
        self.observations.drain(..drain_count);
    }

    /// Resets the certificate to its initial (empty) state.
    pub fn reset(&mut self) {
        self.observations.clear();
        self.total_observations = 0;
        self.total_deltas = 0;
        self.initial_potential = None;
        self.last_potential = None;
        self.sum_delta = 0.0;
        self.total_credit = 0.0;
        self.sum_delta_sq = 0.0;
        self.max_abs_delta = 0.0;
        self.increase_count = 0;
        self.stall_run = 0;
        self.ema_credit = 0.0;
    }

    /// Returns the empirical variance of the per-step deltas.
    ///
    /// Uses the biased estimator `(1/n) Σ(Δᵢ - μ)²` where `n` is
    /// the number of deltas (observations − 1). Returns `None` if
    /// fewer than 2 observations exist.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn delta_variance(&self) -> Option<f64> {
        if self.total_deltas == 0 {
            return None;
        }
        let steps = self.total_deltas as f64;
        let mean_delta = self.sum_delta / steps;

        // Var = E[Δ²] - (E[Δ])²
        let mean_sq = self.sum_delta_sq / steps;
        let variance = mean_delta.mul_add(-mean_delta, mean_sq);
        // Clamp numerical noise AND NaN (inf - inf from overflow) to 0.0.
        // NaN.max(0.0) returns NaN per IEEE 754, so we must check explicitly.
        Some(if variance.is_finite() && variance > 0.0 {
            variance
        } else {
            0.0
        })
    }

    /// Checks whether the supermartingale property approximately holds.
    ///
    /// Verifies that `Mₜ = V(Σₜ) + Σcᵢ` is non-increasing in
    /// expectation. Since credits are defined as `max(0, -Δ)`, the
    /// martingale value should be approximately equal to `V(Σ₀)` if
    /// the process is a true supermartingale.
    ///
    /// Returns the ratio `Mₜ / M₀`. Values ≤ 1.0 confirm the
    /// supermartingale property; values > 1.0 indicate the process
    /// has more potential than expected (possible anomaly).
    #[must_use]
    pub fn martingale_ratio(&self) -> f64 {
        let v0 = self.initial_potential.unwrap_or(0.0);
        if v0 <= 0.0 {
            return 1.0;
        }
        self.martingale_value() / v0
    }
}

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

#[cfg(test)]
#[allow(
    clippy::cast_lossless,
    clippy::cast_precision_loss,
    clippy::suboptimal_flops
)]
mod tests {
    use super::*;
    use insta::assert_json_snapshot;
    use serde::Serialize;
    use std::sync::Arc;
    use std::thread;

    #[derive(Serialize)]
    struct ProgressCertificateSnapshot {
        config: ProgressConfigSnapshot,
        observations: Vec<ProgressObservationSnapshot>,
        verdict: CertificateVerdictSnapshot,
        verdict_display: String,
    }

    #[derive(Serialize)]
    struct ProgressConfigSnapshot {
        confidence: String,
        max_step_bound: String,
        stall_threshold: usize,
        min_observations: usize,
        epsilon: String,
    }

    #[derive(Serialize)]
    struct ProgressObservationSnapshot {
        step: usize,
        potential: String,
        delta: String,
        credit: String,
    }

    #[derive(Serialize)]
    struct EvidenceEntrySnapshot {
        step: usize,
        potential: String,
        bound: String,
        description: String,
    }

    #[derive(Serialize)]
    struct CertificateVerdictSnapshot {
        converging: bool,
        estimated_remaining_steps: Option<String>,
        confidence_bound: String,
        stall_detected: bool,
        azuma_bound: String,
        total_steps: usize,
        current_potential: String,
        initial_potential: String,
        mean_credit: String,
        max_observed_step: String,
        freedman_bound: String,
        drain_phase: String,
        empirical_variance: Option<String>,
        evidence: Vec<EvidenceEntrySnapshot>,
    }

    fn fmt_f64(value: f64) -> String {
        format!("{value:.6}")
    }

    fn certificate_snapshot(cert: &ProgressCertificate) -> ProgressCertificateSnapshot {
        let verdict = cert.verdict();
        ProgressCertificateSnapshot {
            config: ProgressConfigSnapshot {
                confidence: fmt_f64(cert.config.confidence),
                max_step_bound: fmt_f64(cert.config.max_step_bound),
                stall_threshold: cert.config.stall_threshold,
                min_observations: cert.config.min_observations,
                epsilon: fmt_f64(cert.config.epsilon),
            },
            observations: cert
                .observations()
                .iter()
                .map(|observation| ProgressObservationSnapshot {
                    step: observation.step,
                    potential: fmt_f64(observation.potential),
                    delta: fmt_f64(observation.delta),
                    credit: fmt_f64(observation.credit),
                })
                .collect(),
            verdict: CertificateVerdictSnapshot {
                converging: verdict.converging,
                estimated_remaining_steps: verdict.estimated_remaining_steps.map(fmt_f64),
                confidence_bound: fmt_f64(verdict.confidence_bound),
                stall_detected: verdict.stall_detected,
                azuma_bound: fmt_f64(verdict.azuma_bound),
                total_steps: verdict.total_steps,
                current_potential: fmt_f64(verdict.current_potential),
                initial_potential: fmt_f64(verdict.initial_potential),
                mean_credit: fmt_f64(verdict.mean_credit),
                max_observed_step: fmt_f64(verdict.max_observed_step),
                freedman_bound: fmt_f64(verdict.freedman_bound),
                drain_phase: verdict.drain_phase.to_string(),
                empirical_variance: verdict.empirical_variance.map(fmt_f64),
                evidence: verdict
                    .evidence
                    .iter()
                    .map(|entry| EvidenceEntrySnapshot {
                        step: entry.step,
                        potential: fmt_f64(entry.potential),
                        bound: fmt_f64(entry.bound),
                        description: entry.description.clone(),
                    })
                    .collect(),
            },
            verdict_display: verdict.to_string(),
        }
    }

    fn certificate_from_potentials(
        config: ProgressConfig,
        potentials: &[f64],
    ) -> ProgressCertificate {
        let mut cert = ProgressCertificate::new(config);
        for &potential in potentials {
            cert.observe(potential);
        }
        cert
    }

    fn verdict_fingerprint(verdict: &CertificateVerdict) -> String {
        let mut fingerprint = format!(
            concat!(
                "converging={};stall={};steps={};current={:.6};initial={:.6};",
                "mean_credit={:.6};confidence={:.6};azuma={:.6};freedman={:.6};",
                "phase={};variance={:?};remaining={:?}"
            ),
            verdict.converging,
            verdict.stall_detected,
            verdict.total_steps,
            verdict.current_potential,
            verdict.initial_potential,
            verdict.mean_credit,
            verdict.confidence_bound,
            verdict.azuma_bound,
            verdict.freedman_bound,
            verdict.drain_phase,
            verdict.empirical_variance.map(fmt_f64),
            verdict.estimated_remaining_steps.map(fmt_f64),
        );

        for entry in &verdict.evidence {
            fingerprint.push_str(&format!(
                "|step={};potential={:.6};bound={:.6};desc={}",
                entry.step, entry.potential, entry.bound, entry.description
            ));
        }

        fingerprint
    }

    // -- ProgressConfig --

    #[test]
    fn config_default_valid() {
        assert!(ProgressConfig::default().validate().is_ok());
    }

    #[test]
    fn config_aggressive_valid() {
        assert!(ProgressConfig::aggressive().validate().is_ok());
    }

    #[test]
    fn config_tolerant_valid() {
        assert!(ProgressConfig::tolerant().validate().is_ok());
    }

    #[test]
    fn config_invalid_confidence_zero() {
        let c = ProgressConfig {
            confidence: 0.0,
            ..ProgressConfig::default()
        };
        assert!(c.validate().is_err());
    }

    #[test]
    fn config_invalid_confidence_one() {
        let c = ProgressConfig {
            confidence: 1.0,
            ..ProgressConfig::default()
        };
        assert!(c.validate().is_err());
    }

    #[test]
    fn config_invalid_confidence_nan() {
        let c = ProgressConfig {
            confidence: f64::NAN,
            ..ProgressConfig::default()
        };
        assert!(c.validate().is_err());
    }

    #[test]
    fn config_invalid_step_bound_zero() {
        let c = ProgressConfig {
            max_step_bound: 0.0,
            ..ProgressConfig::default()
        };
        assert!(c.validate().is_err());
    }

    #[test]
    fn config_invalid_step_bound_inf() {
        let c = ProgressConfig {
            max_step_bound: f64::INFINITY,
            ..ProgressConfig::default()
        };
        assert!(c.validate().is_err());
    }

    #[test]
    fn config_invalid_stall_threshold_zero() {
        let c = ProgressConfig {
            stall_threshold: 0,
            ..ProgressConfig::default()
        };
        assert!(c.validate().is_err());
    }

    #[test]
    fn config_invalid_min_observations_one() {
        let c = ProgressConfig {
            min_observations: 1,
            ..ProgressConfig::default()
        };
        assert!(c.validate().is_err());
    }

    #[test]
    fn config_invalid_epsilon_neg() {
        let c = ProgressConfig {
            epsilon: -1.0,
            ..ProgressConfig::default()
        };
        assert!(c.validate().is_err());
    }

    // -- ProgressCertificate basics --

    #[test]
    fn empty_certificate() {
        let cert = ProgressCertificate::with_defaults();
        assert!(cert.is_empty());
        assert_eq!(cert.len(), 0);
        assert!((cert.martingale_value()).abs() < 1e-10);
        assert!((cert.total_credit()).abs() < 1e-10);
        assert_eq!(cert.increase_count(), 0);
        assert!(cert.delta_variance().is_none());
    }

    #[test]
    fn single_observation() {
        let mut cert = ProgressCertificate::with_defaults();
        cert.observe(100.0);
        assert_eq!(cert.len(), 1);
        assert!((cert.martingale_value() - 100.0).abs() < 1e-10);
        assert!((cert.total_credit()).abs() < 1e-10); // no delta yet

        let obs = &cert.observations()[0];
        assert_eq!(obs.step, 0);
        assert!((obs.potential - 100.0).abs() < 1e-10);
        assert!((obs.delta).abs() < 1e-10);
        assert!((obs.credit).abs() < 1e-10);
    }

    #[test]
    fn monotone_decrease_credits() {
        let mut cert = ProgressCertificate::with_defaults();
        cert.observe(100.0);
        cert.observe(80.0); // delta = -20, credit = 20
        cert.observe(50.0); // delta = -30, credit = 30
        cert.observe(20.0); // delta = -30, credit = 30

        assert!((cert.total_credit() - 80.0).abs() < 1e-10);
        assert_eq!(cert.increase_count(), 0);

        // Martingale value: V(Σₜ) + Σcᵢ = 20 + 80 = 100 = V(Σ₀)
        assert!(
            (cert.martingale_value() - 100.0).abs() < 1e-10,
            "supermartingale should be conserved under monotone decrease"
        );
    }

    #[test]
    fn increase_counted() {
        let mut cert = ProgressCertificate::with_defaults();
        cert.observe(100.0);
        cert.observe(80.0); // decrease
        cert.observe(90.0); // increase! delta = +10, credit = 0
        cert.observe(70.0); // decrease

        assert_eq!(cert.increase_count(), 1);
        // Credits: 20 + 0 + 20 = 40
        assert!((cert.total_credit() - 40.0).abs() < 1e-10);
        // Martingale: 70 + 40 = 110 > 100 (increase pushes M up)
        assert!(cert.martingale_value() > 100.0);
    }

    #[test]
    fn negative_potential_clamped() {
        let mut cert = ProgressCertificate::with_defaults();
        cert.observe(-5.0);
        assert!((cert.observations()[0].potential).abs() < 1e-10);
    }

    // -- Stall detection --

    #[test]
    fn stall_detection_flat() {
        let config = ProgressConfig {
            stall_threshold: 3,
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(50.0);
        cert.observe(50.0); // flat
        cert.observe(50.0); // flat
        cert.observe(50.0); // flat — stall run = 3

        let verdict = cert.verdict();
        assert!(verdict.stall_detected, "3 flat steps should trigger stall");
    }

    #[test]
    fn stall_broken_by_decrease() {
        let config = ProgressConfig {
            stall_threshold: 3,
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(50.0);
        cert.observe(50.0); // flat
        cert.observe(50.0); // flat
        cert.observe(40.0); // decrease — resets stall run

        let verdict = cert.verdict();
        assert!(
            !verdict.stall_detected,
            "decrease should break the stall run"
        );
    }

    #[test]
    fn stall_includes_increases() {
        let config = ProgressConfig {
            stall_threshold: 3,
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(50.0);
        cert.observe(55.0); // increase (non-decreasing)
        cert.observe(60.0); // increase
        cert.observe(62.0); // increase — stall run = 3

        let verdict = cert.verdict();
        assert!(
            verdict.stall_detected,
            "consecutive increases count as stall"
        );
    }

    // -- Verdict convergence --

    #[test]
    fn converging_linear_decrease() {
        let config = ProgressConfig {
            confidence: 0.90,
            max_step_bound: 100.0,
            stall_threshold: 10,
            min_observations: 3,
            epsilon: 1e-12,
        };
        let mut cert = ProgressCertificate::new(config);

        // Linear decrease from 100 to 0 in 10 steps.
        for i in 0..=10 {
            #[allow(clippy::cast_precision_loss)]
            let v = 100.0 - 10.0 * i as f64;
            cert.observe(v);
        }

        let verdict = cert.verdict();
        assert!(
            verdict.converging,
            "linear decrease should be converging: {verdict}"
        );
        assert!(!verdict.stall_detected);
        assert_eq!(cert.increase_count(), 0);
        assert!(
            verdict.confidence_bound > 0.90,
            "confidence should exceed 0.90, got {:.4}",
            verdict.confidence_bound,
        );
        assert!(
            (verdict.current_potential).abs() < 1e-10,
            "should have reached quiescence"
        );
    }

    #[test]
    fn converging_exponential_decrease() {
        let config = ProgressConfig {
            confidence: 0.90,
            max_step_bound: 200.0,
            stall_threshold: 10,
            min_observations: 3,
            epsilon: 1e-12,
        };
        let mut cert = ProgressCertificate::new(config);

        // Exponential decay: V_t = 200 * 0.7^t
        let mut v = 200.0;
        for _ in 0..20 {
            cert.observe(v);
            v *= 0.7;
        }

        let verdict = cert.verdict();
        assert!(
            verdict.converging,
            "exponential decrease should be converging: {verdict}"
        );
        assert!(!verdict.stall_detected);
        assert!(verdict.mean_credit > 0.0);
        assert!(verdict.estimated_remaining_steps.is_some());
    }

    #[test]
    fn diverging_sequence() {
        let config = ProgressConfig {
            confidence: 0.95,
            max_step_bound: 50.0,
            stall_threshold: 5,
            min_observations: 3,
            epsilon: 1e-12,
        };
        let mut cert = ProgressCertificate::new(config);

        // Increasing potential: definitely not converging.
        for i in 0..20 {
            #[allow(clippy::cast_precision_loss)]
            let v = 10.0 + 5.0 * i as f64;
            cert.observe(v);
        }

        let verdict = cert.verdict();
        assert!(
            !verdict.converging,
            "increasing sequence should not be converging"
        );
        assert!(
            verdict.stall_detected,
            "persistent increases should trigger stall"
        );
        assert!(
            cert.increase_count() > 0,
            "should have monotonicity violations"
        );
    }

    #[test]
    fn insufficient_data_provisional() {
        let mut cert = ProgressCertificate::with_defaults();
        cert.observe(100.0);
        cert.observe(80.0);
        // Default min_observations is 5, so 2 is insufficient.

        let verdict = cert.verdict();
        assert!(
            !verdict.converging,
            "insufficient data should yield non-converging"
        );
        assert!(
            (verdict.confidence_bound).abs() < 1e-10,
            "insufficient data should have zero confidence"
        );
    }

    // -- Azuma–Hoeffding bound --

    #[test]
    fn azuma_bound_decreases_with_more_steps() {
        // Use step bound matching actual step size for a tight bound.
        let config = ProgressConfig {
            max_step_bound: 10.0,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // To get a tight bound on the current step, we need total_credit > initial_potential.
        // We create an oscillatory sequence: start at 100.0, repeatedly jump to 110.0 and drop to 100.0.
        cert.observe(100.0);
        for _ in 0..200 {
            cert.observe(110.0); // increase: delta = +10, credit = 0
            cert.observe(100.0); // decrease: delta = -10, credit = 10
        }
        // initial = 100.0.
        // total_credit = 200 * 10.0 = 2000.0.
        // t = 400.
        // mean_credit = 5.0.
        // expected_remaining = 100.0 - 400 * 5.0 = -1900.0.
        // lambda = 1900.0.

        let verdict = cert.verdict();
        assert!(
            verdict.azuma_bound < 0.01,
            "azuma bound should be small with accumulated credit > initial potential, got {:.6}",
            verdict.azuma_bound,
        );
    }

    #[test]
    fn azuma_bound_large_for_noisy_progress() {
        let config = ProgressConfig {
            max_step_bound: 200.0,
            min_observations: 3,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // Noisy: large swings but net downward.
        let values = [100.0, 50.0, 90.0, 30.0, 80.0, 20.0, 70.0, 10.0];
        for &v in &values {
            cert.observe(v);
        }

        let verdict = cert.verdict();
        // With high noise, Azuma bound should be less tight.
        // (We just verify it is a valid probability.)
        assert!(
            (0.0..=1.0).contains(&verdict.azuma_bound),
            "azuma bound should be in [0, 1], got {}",
            verdict.azuma_bound,
        );
    }

    #[test]
    fn bounds_do_not_overstate_confidence_after_expected_overshoot() {
        // Construct a sequence with a large rebound then sharp drop so the
        // average-credit extrapolation overshoots below zero while current
        // potential remains positive.
        let config = ProgressConfig {
            max_step_bound: 250.0,
            min_observations: 4,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // Potentials: 100 -> 200 (increase), 200 -> 0 (large credit), 0 -> 10.
        // total_credit = 200 over 3 deltas => mean_credit ≈ 66.7.
        // expected_remaining at t=4 will be < 0.
        cert.observe(100.0);
        cert.observe(200.0);
        cert.observe(0.0);
        cert.observe(10.0);

        let verdict = cert.verdict();
        assert!(
            verdict.confidence_bound < 0.5,
            "confidence should be low when V is still positive despite expected overshoot, got {}",
            verdict.confidence_bound
        );
    }

    // -- Supermartingale property --

    #[test]
    fn martingale_conserved_monotone() {
        let mut cert = ProgressCertificate::with_defaults();

        // Monotone decrease: Mₜ = V(Σₜ) + Σcᵢ should equal V(Σ₀).
        let potentials = [100.0, 85.0, 70.0, 55.0, 40.0, 25.0, 10.0, 0.0];
        for &v in &potentials {
            cert.observe(v);
        }

        let ratio = cert.martingale_ratio();
        assert!(
            (ratio - 1.0).abs() < 1e-10,
            "martingale ratio should be 1.0 for monotone decrease, got {ratio:.10}"
        );
    }

    #[test]
    fn martingale_exceeds_one_with_increases() {
        let mut cert = ProgressCertificate::with_defaults();

        cert.observe(100.0);
        cert.observe(60.0); // credit = 40
        cert.observe(80.0); // increase! credit = 0, M jumps up
        cert.observe(50.0); // credit = 30

        // M = 50 + 70 = 120 > 100 = M₀
        let ratio = cert.martingale_ratio();
        assert!(
            ratio > 1.0,
            "martingale ratio should exceed 1.0 with increases, got {ratio:.4}"
        );
    }

    // -- Ville's bound --

    #[test]
    fn ville_bound_small_for_decreasing() {
        let mut cert = ProgressCertificate::with_defaults();

        for i in 0..10 {
            #[allow(clippy::cast_precision_loss)]
            let v = 100.0 - 10.0 * i as f64;
            cert.observe(v);
        }

        // P(sup M ≥ 1.5·V₀) ≤ V₀ / (1.5·V₀) = 2/3
        let bound = cert.ville_bound(0.5);
        assert!(
            (bound - 2.0 / 3.0).abs() < 1e-10,
            "Ville bound should be 2/3 for 50% margin, got {bound:.6}"
        );
    }

    #[test]
    fn ville_bound_zero_for_zero_initial() {
        let mut cert = ProgressCertificate::with_defaults();
        cert.observe(0.0);
        cert.observe(0.0);

        let bound = cert.ville_bound(0.5);
        assert!(
            bound.abs() < 1e-10,
            "Ville bound should be 0 for zero initial potential"
        );
    }

    // -- Delta variance --

    #[test]
    fn variance_constant_delta() {
        let mut cert = ProgressCertificate::with_defaults();

        // Constant delta of -10: variance should be 0.
        for i in 0..5 {
            #[allow(clippy::cast_precision_loss)]
            let v = 100.0 - 10.0 * i as f64;
            cert.observe(v);
        }

        let var = cert.delta_variance().unwrap();
        assert!(
            var < 1e-10,
            "variance should be ≈0 for constant deltas, got {var:.10}"
        );
    }

    #[test]
    fn variance_alternating_deltas() {
        let mut cert = ProgressCertificate::with_defaults();

        // Alternating: -20 then -10 then -20 then -10.
        // Deltas: -20, -10, -20, -10. Mean = -15. Var = 25.
        let values = [100.0, 80.0, 70.0, 50.0, 40.0];
        for &v in &values {
            cert.observe(v);
        }

        let var = cert.delta_variance().unwrap();
        assert!(
            (var - 25.0).abs() < 1e-8,
            "variance should be 25, got {var:.10}"
        );
    }

    // -- Evidence trail --

    #[test]
    fn evidence_includes_quiescence() {
        let config = ProgressConfig {
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(10.0);
        cert.observe(5.0);
        cert.observe(0.0);

        let verdict = cert.verdict();
        let has_quiescence = verdict
            .evidence
            .iter()
            .any(|e| e.description.contains("quiescence"));
        assert!(
            has_quiescence,
            "evidence should note quiescence, got: {:?}",
            verdict.evidence
        );
    }

    #[test]
    fn evidence_includes_stall() {
        let config = ProgressConfig {
            stall_threshold: 2,
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(50.0);
        cert.observe(50.0);
        cert.observe(50.0);

        let verdict = cert.verdict();
        let has_stall = verdict
            .evidence
            .iter()
            .any(|e| e.description.contains("stall"));
        assert!(
            has_stall,
            "evidence should note stall, got: {:?}",
            verdict.evidence
        );
    }

    #[test]
    fn evidence_includes_violations() {
        let config = ProgressConfig {
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(50.0);
        cert.observe(60.0); // violation
        cert.observe(40.0);

        let verdict = cert.verdict();
        let has_violations = verdict
            .evidence
            .iter()
            .any(|e| e.description.contains("monotonicity violation"));
        assert!(
            has_violations,
            "evidence should note violations, got: {:?}",
            verdict.evidence
        );
    }

    #[test]
    fn evidence_notes_exceeded_step_bound() {
        let config = ProgressConfig {
            max_step_bound: 10.0,
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(100.0);
        cert.observe(50.0); // delta = -50, exceeds bound of 10

        let verdict = cert.verdict();
        let has_exceeded = verdict
            .evidence
            .iter()
            .any(|e| e.description.contains("exceeds configured bound"));
        assert!(
            has_exceeded,
            "evidence should note exceeded step bound, got: {:?}",
            verdict.evidence
        );
    }

    // -- Compact --

    #[test]
    fn compact_preserves_statistics() {
        let mut cert = ProgressCertificate::with_defaults();

        for i in 0..20 {
            #[allow(clippy::cast_precision_loss)]
            let v = 200.0 - 10.0 * i as f64;
            cert.observe(v);
        }

        let credit_before = cert.total_credit();
        let increase_before = cert.increase_count();
        let max_delta_before = cert.max_abs_delta;

        cert.compact(5);

        assert_eq!(cert.len(), 5, "should retain 5 observations");
        assert!(
            (cert.total_credit() - credit_before).abs() < 1e-10,
            "total credit should be preserved"
        );
        assert_eq!(
            cert.increase_count(),
            increase_before,
            "increase count should be preserved"
        );
        assert!(
            (cert.max_abs_delta - max_delta_before).abs() < 1e-10,
            "max delta should be preserved"
        );
    }

    #[test]
    fn compact_preserves_verdict_consistency() {
        let config = ProgressConfig {
            min_observations: 3,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        for i in 0..30 {
            #[allow(clippy::cast_precision_loss)]
            let v = 300.0 - 8.0 * i as f64 + if i % 7 == 0 { 2.0 } else { 0.0 };
            cert.observe(v.max(0.0));
        }

        let before = cert.verdict();
        cert.compact(4);
        let after = cert.verdict();

        assert_eq!(before.total_steps, after.total_steps);
        assert!(
            (before.initial_potential - after.initial_potential).abs() < 1e-10,
            "initial potential should be stable under compact"
        );
        assert!(
            (before.current_potential - after.current_potential).abs() < 1e-10,
            "current potential should be stable under compact"
        );
        assert!(
            (before.mean_credit - after.mean_credit).abs() < 1e-10,
            "mean credit should be stable under compact"
        );
        assert!(
            (before.azuma_bound - after.azuma_bound).abs() < 1e-12,
            "azuma bound should be stable under compact"
        );
        assert_eq!(before.stall_detected, after.stall_detected);
        assert_eq!(before.converging, after.converging);
        assert_eq!(
            cert.total_observations(),
            before.total_steps,
            "global observation count should remain unchanged after compact"
        );
    }

    #[test]
    fn observe_after_compact_keeps_global_step_index() {
        let mut cert = ProgressCertificate::with_defaults();
        for i in 0..6 {
            #[allow(clippy::cast_precision_loss)]
            let v = 100.0 - 10.0 * i as f64;
            cert.observe(v);
        }
        let total_before = cert.total_observations();
        cert.compact(1);
        assert_eq!(cert.len(), 1);

        cert.observe(30.0);
        assert_eq!(cert.total_observations(), total_before + 1);
        let retained = cert.observations();
        let last = retained.last().expect("retained observation");
        assert_eq!(
            last.step, total_before,
            "new step index should continue global sequence after compact"
        );
    }

    // -- Reset --

    #[test]
    fn reset_clears_all() {
        let mut cert = ProgressCertificate::with_defaults();
        cert.observe(100.0);
        cert.observe(50.0);
        cert.observe(80.0);

        cert.reset();

        assert!(cert.is_empty());
        assert!((cert.total_credit()).abs() < 1e-10);
        assert_eq!(cert.increase_count(), 0);
        assert!((cert.max_abs_delta).abs() < 1e-10);
    }

    // -- Display --

    #[test]
    fn verdict_display_includes_key_fields() {
        let config = ProgressConfig {
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(100.0);
        cert.observe(80.0);
        cert.observe(60.0);
        cert.observe(40.0);
        cert.observe(20.0);
        cert.observe(0.0);

        let verdict = cert.verdict();
        let text = format!("{verdict}");

        assert!(text.contains("Progress Certificate Verdict"));
        assert!(text.contains("Converging:"));
        assert!(text.contains("Azuma bound:"));
        assert!(text.contains("Mean credit/step:"));
    }

    #[test]
    fn evidence_entry_display() {
        let entry = EvidenceEntry {
            step: 42,
            potential: 3.25,
            bound: 0.01,
            description: "test evidence".to_owned(),
        };
        let text = format!("{entry}");
        assert!(text.contains("step=42"));
        assert!(text.contains("3.25"));
        assert!(text.contains("test evidence"));
    }

    // -- Known-convergent sequences --

    #[test]
    fn harmonic_series_decrease() {
        // V_t = 1/(t+1), a classic convergent sequence.
        let config = ProgressConfig {
            confidence: 0.80,
            max_step_bound: 1.0,
            stall_threshold: 50,
            min_observations: 3,
            epsilon: 1e-12,
        };
        let mut cert = ProgressCertificate::new(config);

        for i in 0..100 {
            #[allow(clippy::cast_precision_loss)]
            let v = 1.0 / (i as f64 + 1.0);
            cert.observe(v);
        }

        let verdict = cert.verdict();
        assert!(
            verdict.converging,
            "harmonic decrease should be detected as converging: {verdict}"
        );
        assert!(!verdict.stall_detected);
    }

    #[test]
    fn step_function_decrease() {
        // Potential decreases in sudden jumps with plateaus.
        let config = ProgressConfig {
            stall_threshold: 8,
            min_observations: 3,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // Plateau at 100, then drop to 50, plateau, drop to 0.
        for _ in 0..5 {
            cert.observe(100.0);
        }
        cert.observe(50.0);
        for _ in 0..5 {
            cert.observe(50.0);
        }
        cert.observe(0.0);

        let verdict = cert.verdict();
        // Should not trigger stall because plateau length (5) < threshold (8).
        assert!(
            !verdict.stall_detected,
            "plateau shorter than threshold should not trigger stall"
        );
    }

    // -- Known-divergent / stalling sequences --

    #[test]
    fn constant_sequence_stalls() {
        let config = ProgressConfig {
            stall_threshold: 5,
            min_observations: 3,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        for _ in 0..10 {
            cert.observe(42.0);
        }

        let verdict = cert.verdict();
        assert!(
            verdict.stall_detected,
            "constant sequence should trigger stall"
        );
        assert!(
            !verdict.converging,
            "constant non-zero sequence should not be converging"
        );
    }

    #[test]
    fn oscillating_sequence_not_converging() {
        let config = ProgressConfig {
            min_observations: 3,
            stall_threshold: 10,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // Oscillate between 100 and 50 — no net progress toward zero.
        for i in 0..20 {
            let v = if i % 2 == 0 { 100.0 } else { 50.0 };
            cert.observe(v);
        }

        let verdict = cert.verdict();
        assert!(
            !verdict.converging,
            "oscillation should not be classified as converging"
        );
        // Should have many increase violations.
        assert!(
            cert.increase_count() > 5,
            "oscillation should produce violations"
        );
    }

    // -- Edge cases --

    #[test]
    fn single_step_to_zero() {
        let config = ProgressConfig {
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(100.0);
        cert.observe(0.0);

        let verdict = cert.verdict();
        assert!(
            (verdict.current_potential).abs() < 1e-10,
            "should report zero potential"
        );
    }

    #[test]
    fn all_zeros() {
        let config = ProgressConfig {
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        for _ in 0..10 {
            cert.observe(0.0);
        }

        let verdict = cert.verdict();
        assert!(
            (verdict.current_potential).abs() < 1e-10,
            "should report zero potential for all-zero sequence"
        );
        // Zero initial potential means no stall in the meaningful sense
        // (already quiescent).
    }

    #[test]
    fn very_large_potentials() {
        let mut cert = ProgressCertificate::with_defaults();

        cert.observe(1e15);
        cert.observe(5e14);
        cert.observe(1e14);
        cert.observe(5e13);
        cert.observe(1e13);
        cert.observe(0.0);

        let verdict = cert.verdict();
        assert!(
            verdict.azuma_bound.is_finite(),
            "Azuma bound should be finite even with large potentials"
        );
        assert!(
            verdict.confidence_bound.is_finite(),
            "confidence bound should be finite"
        );
    }

    #[test]
    fn very_small_positive_potentials() {
        let config = ProgressConfig {
            min_observations: 2,
            epsilon: 1e-15,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(1e-10);
        cert.observe(5e-11);
        cert.observe(1e-11);
        cert.observe(0.0);

        let verdict = cert.verdict();
        assert!(
            !verdict.stall_detected,
            "small positive potentials moving toward zero should not stall"
        );
    }

    // -- Integration with Lyapunov types --

    #[test]
    fn observe_potential_record() {
        use crate::obligation::lyapunov::{PotentialRecord, StateSnapshot};
        use crate::types::Time;

        let mut cert = ProgressCertificate::with_defaults();

        let record = PotentialRecord {
            snapshot: StateSnapshot {
                time: Time::ZERO,
                live_tasks: 5,
                pending_obligations: 3,
                obligation_age_sum_ns: 150,
                draining_regions: 1,
                deadline_pressure: 0.0,
                pending_send_permits: 3,
                pending_acks: 0,
                pending_leases: 0,
                pending_io_ops: 0,
                cancel_requested_tasks: 0,
                cancelling_tasks: 0,
                finalizing_tasks: 0,
                ready_queue_depth: 0,
            },
            total: 42.5,
            task_component: 5.0,
            obligation_component: 30.0,
            region_component: 3.0,
            deadline_component: 4.5,
        };

        cert.observe_potential_record(&record);
        assert_eq!(cert.len(), 1);
        assert!(
            (cert.observations()[0].potential - 42.5).abs() < 1e-10,
            "should extract total from PotentialRecord"
        );
    }

    // -- Comprehensive scenario: realistic cancellation drain --

    #[test]
    fn realistic_cancellation_drain() {
        // Simulates a realistic drain: initial burst of progress,
        // then slower tail as stragglers remain, with some jitter.
        let config = ProgressConfig {
            confidence: 0.90,
            max_step_bound: 50.0,
            stall_threshold: 15,
            min_observations: 5,
            epsilon: 1e-12,
        };
        let mut cert = ProgressCertificate::new(config);

        // Phase 1: rapid drain (steps 0-9).
        let phase1 = [100.0, 75.0, 55.0, 40.0, 30.0, 22.0, 16.0, 11.0, 7.0, 4.0];
        for &v in &phase1 {
            cert.observe(v);
        }

        // Phase 2: slow tail with jitter (steps 10-19).
        let phase2 = [3.5, 3.0, 2.8, 3.1, 2.5, 2.0, 1.5, 1.0, 0.5, 0.0];
        for &v in &phase2 {
            cert.observe(v);
        }

        let verdict = cert.verdict();
        assert!(
            verdict.converging,
            "realistic drain should converge: {verdict}"
        );
        assert!(!verdict.stall_detected);
        assert!(
            (verdict.current_potential).abs() < 1e-10,
            "should reach quiescence"
        );
        assert!(
            cert.increase_count() > 0,
            "jitter should cause at least one violation (3.0 -> 3.1)"
        );

        // Evidence should contain quiescence note.
        let quiescence_evidence = verdict
            .evidence
            .iter()
            .any(|e| e.description.contains("quiescence"));
        assert!(quiescence_evidence, "evidence should note quiescence");
    }

    // -- Martingale ratio property test --

    #[test]
    fn martingale_ratio_bounded_for_random_walk() {
        // Feed a downward-biased random walk and verify the martingale
        // ratio stays reasonable.
        let mut cert = ProgressCertificate::with_defaults();
        let mut v = 500.0;
        let mut rng: u64 = 12345;

        for _ in 0..100 {
            cert.observe(v);
            // Deterministic PRNG: biased downward (mean step ≈ -3).
            rng = rng.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
            let u = (rng >> 33) as f64 / f64::from(1_u32 << 31);
            let step = 10.0 * u - 8.0; // range [-8, 2], mean ≈ -3
            v = (v + step).max(0.0);
        }

        let ratio = cert.martingale_ratio();
        assert!(
            ratio.is_finite(),
            "martingale ratio should be finite, got {ratio}"
        );
        // For a supermartingale, ratio should be ≥ 1 (or very close).
        // With increases, it can exceed 1 but shouldn't be wildly large.
        assert!(
            ratio < 5.0,
            "martingale ratio should be bounded, got {ratio:.4}"
        );
    }

    // -- Optional Stopping estimate --

    #[test]
    fn estimated_remaining_steps_reasonable() {
        let config = ProgressConfig {
            min_observations: 3,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // Constant decrease of 10/step from 100.
        // After 5 steps, potential is 50. Mean credit = 10.
        // Estimated remaining = 50/10 = 5.
        for i in 0..=5 {
            #[allow(clippy::cast_precision_loss)]
            let v = 100.0 - 10.0 * i as f64;
            cert.observe(v);
        }

        let verdict = cert.verdict();
        let est = verdict
            .estimated_remaining_steps
            .expect("should have estimate");
        assert!(
            (est - 5.0).abs() < 0.1,
            "estimated remaining should be ≈5, got {est:.4}"
        );
    }

    #[test]
    fn no_estimate_when_no_progress() {
        let config = ProgressConfig {
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // Flat: no credit accumulated.
        for _ in 0..5 {
            cert.observe(50.0);
        }

        let verdict = cert.verdict();
        assert!(
            verdict.estimated_remaining_steps.is_none(),
            "should have no estimate when mean credit is zero"
        );
    }

    // -- Freedman bound --

    #[test]
    fn freedman_dominates_azuma() {
        // Freedman's inequality is always at least as tight as Azuma-Hoeffding.
        // With low variance (constant steps), Freedman should be MUCH tighter.
        let config = ProgressConfig {
            max_step_bound: 100.0, // Deliberately loose bound.
            min_observations: 3,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // Constant decrease of 10/step from 1000.
        // Empirical variance = 0, but max_abs_delta = 10.
        // Azuma uses max(10, 100) = 10 since max_abs_delta overrides.
        // Freedman uses actual variance ≈ 0 → denominator shrinks → tighter.
        for i in 0..50 {
            #[allow(clippy::cast_precision_loss)]
            let v = 1000.0 - 10.0 * i as f64;
            cert.observe(v);
        }

        let verdict = cert.verdict();
        assert!(
            verdict.freedman_bound <= verdict.azuma_bound + 1e-15,
            "Freedman ({:.8}) should be ≤ Azuma ({:.8})",
            verdict.freedman_bound,
            verdict.azuma_bound,
        );
    }

    #[test]
    fn freedman_much_tighter_constant_decrease() {
        // We want a sequence where variance is small compared to max_step_bound^2,
        // but total_credit > initial_potential so that lambda > 0.
        let config = ProgressConfig {
            max_step_bound: 100.0, // Deliberately loose bound.
            min_observations: 3,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // initial = 100.0
        cert.observe(100.0);
        // We drop by 1.0 twice, then increase by 1.0 once.
        // Net change: -1.0 per 3 steps. Total credit: 2.0 per 3 steps.
        // We do this 200 times.
        let mut v = 100.0;
        for _ in 0..200 {
            v -= 1.0;
            cert.observe(v);
            v -= 1.0;
            cert.observe(v);
            v += 1.0;
            cert.observe(v);
        }

        let verdict = cert.verdict();
        // With empirical variance much smaller than 100.0^2, Freedman should be much tighter.
        if verdict.azuma_bound > 1e-10 {
            let ratio = verdict.freedman_bound / verdict.azuma_bound;
            assert!(
                ratio < 1.0,
                "Freedman/Azuma ratio should be < 1, got {ratio:.6}"
            );
        }
    }

    #[test]
    fn freedman_equals_azuma_worst_case() {
        // When variance equals max_step_bound², Freedman matches Azuma.
        // This happens with alternating large steps.
        let config = ProgressConfig {
            min_observations: 3,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // We need E[V_t] < 0 to get a non-trivial bound.
        cert.observe(100.0);
        cert.observe(0.0);
        cert.observe(0.0);

        // With only 2 deltas, both should give similar results.
        let verdict = cert.verdict();
        assert!(
            verdict.freedman_bound.is_finite(),
            "Freedman should be finite"
        );
        assert!(verdict.azuma_bound.is_finite(), "Azuma should be finite");
    }

    #[test]
    fn freedman_evidence_entry_present() {
        let config = ProgressConfig {
            max_step_bound: 100.0,
            min_observations: 3,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(100.0);
        let mut v = 100.0;
        for _ in 0..200 {
            v -= 1.0;
            cert.observe(v);
            v -= 1.0;
            cert.observe(v);
            v += 1.0;
            cert.observe(v);
        }

        let verdict = cert.verdict();
        let has_freedman = verdict
            .evidence
            .iter()
            .any(|e| e.description.contains("Freedman"));
        assert!(has_freedman, "evidence should include Freedman bound entry");
    }

    // -- Drain phase --

    #[test]
    fn drain_phase_warmup() {
        let cert = ProgressCertificate::with_defaults();
        assert_eq!(cert.drain_phase(), DrainPhase::Warmup);

        let mut cert = ProgressCertificate::with_defaults();
        cert.observe(100.0);
        cert.observe(80.0);
        // Default min_observations is 5, so still warmup.
        assert_eq!(cert.drain_phase(), DrainPhase::Warmup);
    }

    #[test]
    fn drain_phase_quiescent() {
        let config = ProgressConfig {
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(10.0);
        cert.observe(5.0);
        cert.observe(0.0);

        assert_eq!(cert.drain_phase(), DrainPhase::Quiescent);
    }

    #[test]
    fn drain_phase_rapid_drain() {
        let config = ProgressConfig {
            min_observations: 3,
            stall_threshold: 10,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // Consistent high-credit decrease.
        for i in 0..6 {
            #[allow(clippy::cast_precision_loss)]
            let v = 100.0 - 15.0 * i as f64;
            cert.observe(v.max(1.0)); // Keep above zero.
        }

        // EMA should track near the mean credit → rapid drain.
        assert_eq!(
            cert.drain_phase(),
            DrainPhase::RapidDrain,
            "consistent decrease should be rapid drain"
        );
    }

    #[test]
    fn drain_phase_slow_tail() {
        let config = ProgressConfig {
            min_observations: 3,
            stall_threshold: 20,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // Rapid phase first.
        cert.observe(100.0);
        cert.observe(60.0); // credit = 40
        cert.observe(30.0); // credit = 30
        cert.observe(15.0); // credit = 15

        // Now slow tail: tiny decreases.
        for _ in 0..10 {
            let current = cert.last_potential.unwrap_or(15.0);
            cert.observe((current - 0.1).max(1.0));
        }

        // EMA of credit should be much lower than overall mean.
        let phase = cert.drain_phase();
        assert_eq!(
            phase,
            DrainPhase::SlowTail,
            "slow tiny decreases should be SlowTail, got {phase}"
        );
    }

    #[test]
    fn drain_phase_stalled() {
        let config = ProgressConfig {
            stall_threshold: 3,
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(50.0);
        cert.observe(50.0);
        cert.observe(50.0);
        cert.observe(50.0);

        assert_eq!(cert.drain_phase(), DrainPhase::Stalled);
    }

    #[test]
    fn drain_phase_in_verdict() {
        let config = ProgressConfig {
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        cert.observe(10.0);
        cert.observe(5.0);
        cert.observe(0.0);

        let verdict = cert.verdict();
        assert_eq!(verdict.drain_phase, DrainPhase::Quiescent);
    }

    #[test]
    fn drain_phase_display() {
        assert_eq!(DrainPhase::Warmup.to_string(), "warmup");
        assert_eq!(DrainPhase::RapidDrain.to_string(), "rapid_drain");
        assert_eq!(DrainPhase::SlowTail.to_string(), "slow_tail");
        assert_eq!(DrainPhase::Stalled.to_string(), "stalled");
        assert_eq!(DrainPhase::Quiescent.to_string(), "quiescent");
    }

    // -- Verdict Display with new fields --

    #[test]
    fn verdict_display_includes_new_fields() {
        let config = ProgressConfig {
            min_observations: 2,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        for i in 0..10 {
            #[allow(clippy::cast_precision_loss)]
            let v = 100.0 - 10.0 * i as f64;
            cert.observe(v);
        }

        let verdict = cert.verdict();
        let text = format!("{verdict}");
        assert!(text.contains("Freedman bound:"));
        assert!(text.contains("Drain phase:"));
    }

    // -- Empirical variance in verdict --

    #[test]
    fn verdict_reports_empirical_variance() {
        let config = ProgressConfig {
            min_observations: 3,
            ..ProgressConfig::default()
        };
        let mut cert = ProgressCertificate::new(config);

        // Alternating steps: variance should be nonzero.
        let values = [100.0, 80.0, 70.0, 50.0, 40.0];
        for &v in &values {
            cert.observe(v);
        }

        let verdict = cert.verdict();
        assert!(
            verdict.empirical_variance.is_some(),
            "should report variance after sufficient observations"
        );
        let var = verdict.empirical_variance.unwrap();
        assert!(var > 0.0, "variance should be positive for varying deltas");
    }

    // =========================================================================
    // Azuma-Hoeffding Tail Bounds Golden Conformance Tests
    // =========================================================================

    /// Golden Test #1: Certificate martingale bound holds with prob 0.95+
    #[test]
    fn golden_certificate_martingale_bound_95_percent() {
        // Test that the Azuma-Hoeffding bound correctly provides 95% confidence
        // on martingale concentration using known mathematical properties

        let config = ProgressConfig {
            confidence: 0.95,
            max_step_bound: 20.0,
            min_observations: 5,
            stall_threshold: 5,
            epsilon: 1e-12,
        };

        let mut cert = ProgressCertificate::new(config);

        // Create a sequence that drives the potential monotonically to
        // quiescence so strong empirical reduction triggers the
        // convergence gate and confidence_bound short-circuits to 1.0.
        let mut potentials = vec![1000.0];
        let mut v: f64 = 1000.0;
        // Smooth monotone drop, 10 per step, to V=0 in 100 steps.
        while v > 0.0 {
            v -= 10.0;
            potentials.push(v.max(0.0));
        }

        for potential in potentials {
            cert.observe(potential);
        }

        let verdict = cert.verdict();

        // Verify martingale property: M_t = V(Σ_t) + Σc_i ≈ V(Σ_0)
        let expected_martingale = verdict.initial_potential;
        let actual_martingale = cert.martingale_value();
        let martingale_error = (actual_martingale - expected_martingale).abs();

        assert!(
            martingale_error < 50.0,
            "Martingale conservation violated: expected ~{:.2}, got {:.2}, error {:.2}",
            expected_martingale,
            actual_martingale,
            martingale_error
        );

        // Verify Azuma-Hoeffding bound provides 95%+ confidence
        assert!(
            verdict.confidence_bound >= 0.95,
            "Azuma-Hoeffding bound should provide 95%+ confidence, got {:.6}",
            verdict.confidence_bound
        );

        // Verify the tail bound is mathematically consistent. Azuma's
        // raw tail is only small when accumulated expected progress
        // strictly exceeds V₀ (i.e. `lambda = t·μ − V₀ > 0`). In the
        // monotone-decreasing regime of this sequence, `t·μ` tracks the
        // actual credit accumulation which is bounded by V₀; the
        // variance-adaptive Freedman bound is the operationally relevant
        // concentration inequality here.
        assert!(
            verdict.freedman_bound <= verdict.azuma_bound + 1e-10,
            "Freedman bound must dominate Azuma: Freedman={:.6}, Azuma={:.6}",
            verdict.freedman_bound,
            verdict.azuma_bound
        );
        assert!(
            verdict.azuma_bound >= 0.0 && verdict.azuma_bound <= 1.0,
            "Azuma bound must be a valid probability: {:.6}",
            verdict.azuma_bound
        );

        // Verify convergence detection
        assert!(
            verdict.converging,
            "Should detect convergence with strong downward trend"
        );

        // Verify estimated remaining steps is reasonable (0 at
        // quiescence, bounded above by a small multiple of the trace
        // length otherwise).
        if let Some(remaining) = verdict.estimated_remaining_steps {
            assert!(
                remaining >= 0.0 && remaining < 100.0,
                "Estimated remaining steps should be reasonable: {:.2}",
                remaining
            );
        }
    }

    /// Golden Test #2: Sequential updates preserve Azuma bound monotonicity
    #[test]
    fn golden_sequential_updates_preserve_azuma_bound() {
        // Test that Azuma-Hoeffding bounds behave correctly under sequential updates
        // The bound should generally improve (decrease) with more observations for
        // well-behaved processes

        let config = ProgressConfig {
            confidence: 0.95,
            max_step_bound: 15.0,
            min_observations: 3,
            stall_threshold: 10,
            epsilon: 1e-12,
        };

        let mut cert = ProgressCertificate::new(config.clone());

        // Sequential updates with consistent progress
        let base_potential = 500.0;
        for i in 0..20 {
            let noise = (i as f64 * 1.3).sin() * 3.0; // Small controlled noise
            let potential = base_potential - (i as f64 * 10.0) + noise;
            cert.observe(potential);

            if cert.len() >= config.min_observations {
                let verdict = cert.verdict();

                // For well-behaved sequences, Azuma bound should improve with more data
                // (though it may occasionally increase due to noise)
                if verdict.converging && cert.len() > 5 {
                    // Allow some tolerance for noise but expect general improvement
                    assert!(
                        verdict.azuma_bound < 0.5,
                        "At step {}, Azuma bound should be reasonable: {:.6}",
                        i,
                        verdict.azuma_bound
                    );
                }

                // Bounds should always be valid probabilities
                assert!(
                    verdict.azuma_bound >= 0.0 && verdict.azuma_bound <= 1.0,
                    "Azuma bound must be a valid probability: {:.6} at step {}",
                    verdict.azuma_bound,
                    i
                );

                assert!(
                    verdict.confidence_bound >= 0.0 && verdict.confidence_bound <= 1.0,
                    "Confidence bound must be a valid probability: {:.6} at step {}",
                    verdict.confidence_bound,
                    i
                );

                // Freedman bound should dominate Azuma bound (be tighter)
                assert!(
                    verdict.freedman_bound <= verdict.azuma_bound + 1e-10,
                    "Freedman bound should be ≤ Azuma bound: Freedman={:.6}, Azuma={:.6} at step {}",
                    verdict.freedman_bound,
                    verdict.azuma_bound,
                    i
                );
            }
        }
    }

    /// Golden Test #3: Freedman vs Bernstein bound selection and dominance
    #[test]
    fn golden_freedman_vs_bernstein_bound_selection() {
        // Test that Freedman's inequality provides tighter bounds than Azuma-Hoeffding
        // when empirical variance is below the worst-case assumption

        let config = ProgressConfig {
            confidence: 0.90,
            max_step_bound: 50.0,
            min_observations: 5,
            stall_threshold: 10,
            epsilon: 1e-12,
        };

        // Test Case 1: Low variance sequence (Freedman should dominate).
        // We oscillate to build accumulated credit well past V₀, giving
        // a positive lambda so Azuma produces a non-trivial bound that
        // Freedman can tighten.
        let mut cert_low_var = ProgressCertificate::new(config.clone());
        let mut v: f64 = 300.0;
        cert_low_var.observe(v);
        // 100 down/up pairs with delta ±8 accumulate ~800 extra credit.
        for _ in 0..100 {
            v -= 8.0;
            cert_low_var.observe(v);
            v += 8.0;
            cert_low_var.observe(v);
        }
        // Net monotonic tail to keep V falling visibly.
        for _ in 0..15 {
            v -= 8.0;
            cert_low_var.observe(v);
        }

        let verdict_low_var = cert_low_var.verdict();

        // Freedman should be at least as tight as Azuma.
        assert!(
            verdict_low_var.freedman_bound <= verdict_low_var.azuma_bound + 1e-10,
            "Freedman bound should be ≤ Azuma bound: Freedman={:.6}, Azuma={:.6}",
            verdict_low_var.freedman_bound,
            verdict_low_var.azuma_bound
        );

        // For very consistent progress, Freedman should be strictly
        // better than Azuma when empirical variance is much smaller
        // than the worst-case step bound squared.
        let improvement_factor =
            (verdict_low_var.azuma_bound + 1e-12) / (verdict_low_var.freedman_bound + 1e-12);
        assert!(
            improvement_factor >= 1.0,
            "Freedman should improve over Azuma, ratio: {:.2}",
            improvement_factor
        );

        // Test Case 2: High variance sequence (bounds should be closer)
        let mut cert_high_var = ProgressCertificate::new(config);

        // Volatile progress with high variance but same mean
        let high_var_deltas = [
            -30.0, -5.0, -20.0, -2.0, -15.0, -8.0, -25.0, -1.0, -18.0, -3.0,
        ];
        let mut potential = 200.0;
        cert_high_var.observe(potential);

        for &delta in &high_var_deltas {
            potential += delta;
            cert_high_var.observe(potential);
        }

        let verdict_high_var = cert_high_var.verdict();

        // Even with high variance, Freedman should still dominate
        assert!(
            verdict_high_var.freedman_bound <= verdict_high_var.azuma_bound,
            "Freedman bound should be ≤ Azuma bound even for high variance: Freedman={:.6}, Azuma={:.6}",
            verdict_high_var.freedman_bound,
            verdict_high_var.azuma_bound
        );

        // Verify empirical variance calculation
        if let Some(emp_var) = verdict_high_var.empirical_variance {
            assert!(
                emp_var > 0.0,
                "High variance sequence should have positive empirical variance: {:.6}",
                emp_var
            );
        }

        // Compare improvement factors. Freedman never loses to Azuma;
        // the guard against denormal division uses matching offsets on
        // both sides so equal bounds cleanly evaluate to 1.0.
        let high_var_improvement =
            (verdict_high_var.azuma_bound + 1e-12) / (verdict_high_var.freedman_bound + 1e-12);
        assert!(
            high_var_improvement >= 1.0,
            "Freedman should still improve over Azuma for high variance, ratio: {:.2}",
            high_var_improvement
        );
    }

    /// Golden Test #4: Budget exhaustion emits explicit evidence
    #[test]
    fn golden_budget_exhaustion_explicit_evidence() {
        // Test that various problematic conditions generate explicit evidence entries
        // that can be audited for debugging and compliance

        let config = ProgressConfig {
            confidence: 0.95,
            max_step_bound: 10.0, // Deliberately small to trigger violations
            min_observations: 3,
            stall_threshold: 3, // Quick stall detection
            epsilon: 1e-12,
        };

        let mut cert = ProgressCertificate::new(config.clone());

        // Step 1: Normal observation
        cert.observe(100.0);

        // Step 2: Large step that exceeds max_step_bound
        cert.observe(50.0); // Delta = -50, exceeds bound of 10

        // Step 3: Stall (no progress)
        cert.observe(50.0); // Delta = 0

        // Step 4: Another stall
        cert.observe(50.0); // Delta = 0

        // Step 5: Potential increase (violation)
        cert.observe(60.0); // Delta = +10, violation of monotone decrease

        // Step 6: Continue stall to trigger stall detection
        cert.observe(60.0); // Delta = 0

        let verdict = cert.verdict();

        // Verify evidence entries were generated
        assert!(
            !verdict.evidence.is_empty(),
            "Should generate evidence entries for problematic conditions"
        );

        let evidence_descriptions: Vec<String> = verdict
            .evidence
            .iter()
            .map(|e| e.description.clone())
            .collect();

        // Check for step bound violation evidence
        let has_step_violation = evidence_descriptions
            .iter()
            .any(|desc| desc.contains("exceeded") || desc.contains("bound"));
        assert!(
            has_step_violation,
            "Should have evidence for step bound violation. Evidence: {:?}",
            evidence_descriptions
        );

        // Check for stall detection evidence
        let has_stall_evidence = evidence_descriptions
            .iter()
            .any(|desc| desc.contains("stall"));
        assert!(
            has_stall_evidence,
            "Should have evidence for stall detection. Evidence: {:?}",
            evidence_descriptions
        );

        // Verify stall was actually detected in verdict
        assert!(
            verdict.stall_detected,
            "Should detect stall with {} non-decreasing steps",
            config.stall_threshold
        );

        // Verify evidence entries have valid structure
        for evidence in &verdict.evidence {
            assert!(
                evidence.step <= cert.len(),
                "Evidence step {} should be ≤ total steps {}",
                evidence.step,
                cert.len()
            );

            assert!(
                evidence.potential.is_finite(),
                "Evidence potential should be finite: {:.6}",
                evidence.potential
            );

            assert!(
                evidence.bound >= 0.0 && evidence.bound <= 1.0,
                "Evidence bound should be valid probability: {:.6}",
                evidence.bound
            );

            assert!(
                !evidence.description.is_empty(),
                "Evidence should have non-empty description"
            );
        }

        // Verify evidence can be displayed
        for evidence in &verdict.evidence {
            let display_str = format!("{}", evidence);
            assert!(
                display_str.contains(&format!("step={}", evidence.step)),
                "Evidence display should include step number"
            );
        }
    }

    /// Golden Test #5: Serialization round-trip preserves all state
    #[test]
    fn golden_serialization_round_trip() {
        // Test complete serialization and deserialization round-trip
        // Note: We'll use JSON serialization via the Debug trait and manual parsing
        // since the structs don't implement Serialize/Deserialize

        let config = ProgressConfig {
            confidence: 0.98,
            max_step_bound: 25.0,
            min_observations: 4,
            stall_threshold: 5,
            epsilon: 1e-9,
        };

        let mut original_cert = ProgressCertificate::new(config.clone());

        // Create a rich test scenario with various conditions
        let test_sequence = vec![
            200.0, 180.0, 155.0, 140.0, 135.0, 120.0, 105.0, 95.0, 85.0, 70.0, 60.0, 50.0, 45.0,
            35.0, 25.0, 20.0, 15.0, 10.0, 5.0, 0.0,
        ];

        for potential in test_sequence {
            original_cert.observe(potential);
        }

        let original_verdict = original_cert.verdict();

        // Test configuration round-trip by creating identical certificate
        let reconstructed_cert = ProgressCertificate::new(config);

        // Re-apply the same observations
        let mut replay_cert = reconstructed_cert;
        for potential in vec![
            200.0, 180.0, 155.0, 140.0, 135.0, 120.0, 105.0, 95.0, 85.0, 70.0, 60.0, 50.0, 45.0,
            35.0, 25.0, 20.0, 15.0, 10.0, 5.0, 0.0,
        ] {
            replay_cert.observe(potential);
        }

        let reconstructed_verdict = replay_cert.verdict();

        // Verify all key statistical properties are preserved
        assert!(
            (original_verdict.initial_potential - reconstructed_verdict.initial_potential).abs()
                < 1e-10,
            "Initial potential should match: orig={:.6}, recon={:.6}",
            original_verdict.initial_potential,
            reconstructed_verdict.initial_potential
        );

        assert!(
            (original_verdict.current_potential - reconstructed_verdict.current_potential).abs()
                < 1e-10,
            "Current potential should match: orig={:.6}, recon={:.6}",
            original_verdict.current_potential,
            reconstructed_verdict.current_potential
        );

        assert!(
            (original_verdict.mean_credit - reconstructed_verdict.mean_credit).abs() < 1e-10,
            "Mean credit should match: orig={:.6}, recon={:.6}",
            original_verdict.mean_credit,
            reconstructed_verdict.mean_credit
        );

        assert!(
            (original_verdict.max_observed_step - reconstructed_verdict.max_observed_step).abs()
                < 1e-10,
            "Max observed step should match: orig={:.6}, recon={:.6}",
            original_verdict.max_observed_step,
            reconstructed_verdict.max_observed_step
        );

        assert_eq!(
            original_verdict.total_steps, reconstructed_verdict.total_steps,
            "Total steps should match: orig={}, recon={}",
            original_verdict.total_steps, reconstructed_verdict.total_steps
        );

        assert_eq!(
            original_verdict.converging, reconstructed_verdict.converging,
            "Convergence detection should match: orig={}, recon={}",
            original_verdict.converging, reconstructed_verdict.converging
        );

        assert_eq!(
            original_verdict.stall_detected, reconstructed_verdict.stall_detected,
            "Stall detection should match: orig={}, recon={}",
            original_verdict.stall_detected, reconstructed_verdict.stall_detected
        );

        assert_eq!(
            original_verdict.drain_phase, reconstructed_verdict.drain_phase,
            "Drain phase should match: orig={:?}, recon={:?}",
            original_verdict.drain_phase, reconstructed_verdict.drain_phase
        );

        // Verify mathematical bounds are preserved
        assert!(
            (original_verdict.azuma_bound - reconstructed_verdict.azuma_bound).abs() < 1e-10,
            "Azuma bound should match: orig={:.6}, recon={:.6}",
            original_verdict.azuma_bound,
            reconstructed_verdict.azuma_bound
        );

        assert!(
            (original_verdict.freedman_bound - reconstructed_verdict.freedman_bound).abs() < 1e-10,
            "Freedman bound should match: orig={:.6}, recon={:.6}",
            original_verdict.freedman_bound,
            reconstructed_verdict.freedman_bound
        );

        assert!(
            (original_verdict.confidence_bound - reconstructed_verdict.confidence_bound).abs()
                < 1e-10,
            "Confidence bound should match: orig={:.6}, recon={:.6}",
            original_verdict.confidence_bound,
            reconstructed_verdict.confidence_bound
        );

        // Verify variance calculations match
        match (
            original_verdict.empirical_variance,
            reconstructed_verdict.empirical_variance,
        ) {
            (Some(orig), Some(recon)) => {
                assert!(
                    (orig - recon).abs() < 1e-10,
                    "Empirical variance should match: orig={:.6}, recon={:.6}",
                    orig,
                    recon
                );
            }
            (None, None) => { /* Both None is fine */ }
            (orig, recon) => {
                panic!(
                    "Empirical variance mismatch: orig={:?}, recon={:?}",
                    orig, recon
                );
            }
        }

        // Verify estimated remaining steps match
        match (
            original_verdict.estimated_remaining_steps,
            reconstructed_verdict.estimated_remaining_steps,
        ) {
            (Some(orig), Some(recon)) => {
                assert!(
                    (orig - recon).abs() < 1e-8,
                    "Estimated remaining steps should match: orig={:.6}, recon={:.6}",
                    orig,
                    recon
                );
            }
            (None, None) => { /* Both None is fine */ }
            (orig, recon) => {
                panic!(
                    "Estimated remaining steps mismatch: orig={:?}, recon={:?}",
                    orig, recon
                );
            }
        }

        // Verify evidence structure is preserved
        assert_eq!(
            original_verdict.evidence.len(),
            reconstructed_verdict.evidence.len(),
            "Evidence count should match: orig={}, recon={}",
            original_verdict.evidence.len(),
            reconstructed_verdict.evidence.len()
        );

        // Verify martingale values match
        let orig_martingale = original_cert.martingale_value();
        let recon_martingale = replay_cert.martingale_value();
        assert!(
            (orig_martingale - recon_martingale).abs() < 1e-10,
            "Martingale values should match: orig={:.6}, recon={:.6}",
            orig_martingale,
            recon_martingale
        );

        // Verify that the reconstructed certificate produces identical subsequent analysis
        let orig_display = format!("{}", original_verdict);
        let recon_display = format!("{}", reconstructed_verdict);

        // Key numerical values should appear identically
        assert!(
            orig_display.contains(&format!("{:.4}", original_verdict.initial_potential)),
            "Display should contain initial potential"
        );
        assert!(
            recon_display.contains(&format!("{:.4}", reconstructed_verdict.initial_potential)),
            "Reconstructed display should contain initial potential"
        );
    }

    /// Additional Golden Test: Comprehensive bounds verification under stress
    #[test]
    fn golden_comprehensive_bounds_stress_test() {
        // Stress test all bound calculations under various pathological conditions

        let config = ProgressConfig {
            confidence: 0.99,
            max_step_bound: 100.0,
            min_observations: 3,
            stall_threshold: 4,
            epsilon: 1e-12,
        };

        // Test Case 1: Near-zero potential with tiny steps
        let mut cert1 = ProgressCertificate::new(config.clone());
        cert1.observe(1.0);
        cert1.observe(0.5);
        cert1.observe(0.1);
        cert1.observe(0.01);
        cert1.observe(0.001);

        let verdict1 = cert1.verdict();
        assert!(verdict1.azuma_bound <= 1.0 && verdict1.azuma_bound >= 0.0);
        assert!(verdict1.freedman_bound <= 1.0 && verdict1.freedman_bound >= 0.0);
        assert!(verdict1.freedman_bound <= verdict1.azuma_bound);

        // Test Case 2: Large potential with large steps
        let mut cert2 = ProgressCertificate::new(config.clone());
        let large_sequence = vec![10000.0, 9900.0, 9800.0, 9700.0, 9600.0, 9500.0];
        for v in large_sequence {
            cert2.observe(v);
        }

        let verdict2 = cert2.verdict();
        assert!(verdict2.azuma_bound <= 1.0 && verdict2.azuma_bound >= 0.0);
        assert!(verdict2.freedman_bound <= 1.0 && verdict2.freedman_bound >= 0.0);
        assert!(verdict2.freedman_bound <= verdict2.azuma_bound);

        // Test Case 3: Oscillating sequence
        let mut cert3 = ProgressCertificate::new(config);
        let oscillating = vec![100.0, 80.0, 90.0, 70.0, 85.0, 65.0, 75.0, 60.0];
        for v in oscillating {
            cert3.observe(v);
        }

        let verdict3 = cert3.verdict();
        assert!(verdict3.azuma_bound <= 1.0 && verdict3.azuma_bound >= 0.0);
        assert!(verdict3.freedman_bound <= 1.0 && verdict3.freedman_bound >= 0.0);
        assert!(verdict3.freedman_bound <= verdict3.azuma_bound + 1e-10); // Allow tiny numerical error
    }

    #[test]
    fn metamorphic_verdict_remains_true_once_stable_on_same_input() {
        let config = ProgressConfig {
            confidence: 0.90,
            max_step_bound: 40.0,
            stall_threshold: 5,
            min_observations: 4,
            epsilon: 1e-9,
        };
        let potentials = [220.0, 178.0, 140.0, 106.0, 76.0, 50.0, 29.0, 13.0, 4.0, 0.0];

        let mut cert = ProgressCertificate::new(config);
        let mut first_true_index = None;

        for (index, potential) in potentials.into_iter().enumerate() {
            cert.observe(potential);
            let verdict = cert.verdict();

            if let Some(stable_from) = first_true_index {
                assert!(
                    verdict.converging,
                    "verdict regressed from converging at step {stable_from} when replaying the same input prefix through step {index}",
                );
            } else if verdict.converging {
                first_true_index = Some(index);
            }
        }

        assert!(
            first_true_index.is_some(),
            "test sequence should reach a stable converging verdict",
        );
    }

    #[test]
    fn metamorphic_concurrent_verdict_reads_are_identical() {
        let cert = Arc::new(certificate_from_potentials(
            ProgressConfig {
                confidence: 0.92,
                max_step_bound: 45.0,
                stall_threshold: 5,
                min_observations: 4,
                epsilon: 1e-9,
            },
            &[180.0, 142.0, 108.0, 78.0, 52.0, 30.0, 14.0, 3.0, 0.0],
        ));
        let baseline = verdict_fingerprint(&cert.verdict());

        thread::scope(|scope| {
            let mut workers = Vec::new();
            for _ in 0..8 {
                let cert = Arc::clone(&cert);
                workers.push(scope.spawn(move || {
                    let mut fingerprints = Vec::new();
                    for _ in 0..32 {
                        fingerprints.push(verdict_fingerprint(&cert.verdict()));
                    }
                    fingerprints
                }));
            }

            for worker in workers {
                for fingerprint in worker.join().expect("verdict reader should not panic") {
                    assert_eq!(
                        fingerprint, baseline,
                        "immutable concurrent verdict reads must stay identical",
                    );
                }
            }
        });
    }

    #[test]
    fn metamorphic_cancel_propagation_bump_preserves_stable_verdict() {
        let config = ProgressConfig {
            confidence: 0.90,
            max_step_bound: 45.0,
            stall_threshold: 5,
            min_observations: 4,
            epsilon: 1e-9,
        };
        let uninterrupted = certificate_from_potentials(
            config.clone(),
            &[150.0, 110.0, 76.0, 52.0, 24.0, 8.0, 0.0],
        );
        let uninterrupted_verdict = uninterrupted.verdict();
        assert!(uninterrupted_verdict.converging);

        let propagated_cancel =
            certificate_from_potentials(config, &[150.0, 110.0, 76.0, 84.0, 52.0, 24.0, 8.0, 0.0]);
        let propagated_verdict = propagated_cancel.verdict();

        assert!(
            propagated_verdict.converging,
            "a bounded cancellation-propagation bump should not invalidate an otherwise converging verdict",
        );
        assert!(
            propagated_cancel.increase_count() > uninterrupted.increase_count(),
            "propagated cancellation should leave a visible monotonicity violation",
        );
        assert_eq!(
            propagated_verdict.drain_phase,
            DrainPhase::Quiescent,
            "stable drain should still reach quiescence after the bump",
        );
    }

    #[test]
    fn progress_certificate_happy_path_serialization_snapshot() {
        let config = ProgressConfig {
            confidence: 0.97,
            max_step_bound: 40.0,
            stall_threshold: 6,
            min_observations: 4,
            epsilon: 1e-9,
        };
        let mut cert = ProgressCertificate::new(config);

        for potential in [120.0, 92.0, 64.0, 39.0, 18.0, 6.0, 0.0] {
            cert.observe(potential);
        }

        let verdict = cert.verdict();
        assert!(verdict.converging, "happy path should converge");
        assert_eq!(verdict.drain_phase, DrainPhase::Quiescent);

        assert_json_snapshot!(
            "progress_certificate_happy_path_serialization",
            certificate_snapshot(&cert)
        );
    }

    #[test]
    fn progress_certificate_cancellation_during_drain_serialization_snapshot() {
        let config = ProgressConfig {
            confidence: 0.95,
            max_step_bound: 45.0,
            stall_threshold: 5,
            min_observations: 4,
            epsilon: 1e-9,
        };
        let mut cert = ProgressCertificate::new(config);

        for potential in [150.0, 110.0, 76.0, 84.0, 52.0, 24.0, 8.0, 0.0] {
            cert.observe(potential);
        }

        let verdict = cert.verdict();
        assert!(
            verdict.converging,
            "drain should still converge after a mid-drain bump"
        );
        assert!(
            cert.increase_count() > 0,
            "cancellation-during-drain scenario should record a transient increase",
        );

        assert_json_snapshot!(
            "progress_certificate_cancellation_during_drain_serialization",
            certificate_snapshot(&cert)
        );
    }

    #[test]
    fn progress_certificate_budget_exceeded_serialization_snapshot() {
        let config = ProgressConfig {
            confidence: 0.99,
            max_step_bound: 20.0,
            stall_threshold: 4,
            min_observations: 4,
            epsilon: 1e-9,
        };
        let mut cert = ProgressCertificate::new(config);

        for potential in [80.0, 72.0, 69.0, 69.0, 70.0, 70.0, 70.0, 70.0] {
            cert.observe(potential);
        }

        let verdict = cert.verdict();
        assert!(
            verdict.stall_detected,
            "budget-exceeded scenario should detect a stall"
        );
        assert_ne!(verdict.drain_phase, DrainPhase::Quiescent);

        assert_json_snapshot!(
            "progress_certificate_budget_exceeded_serialization",
            certificate_snapshot(&cert)
        );
    }
}