asupersync 0.3.0

Spec-first, cancel-correct, capability-secure async runtime for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
//! RaptorQ inactivation decoder with deterministic pivoting.
//!
//! Implements a two-phase decoding strategy:
//! 1. **Peeling**: Iteratively solve degree-1 equations (belief propagation)
//! 2. **Inactivation**: Mark stubborn symbols as inactive, defer to Gaussian elimination
//!
//! # Determinism
//!
//! All operations are deterministic:
//! - Pivot selection uses stable lexicographic ordering
//! - Tie-breaking rules are explicit (lowest column index wins)
//! - Same received symbols in same order produce identical decode results

use crate::raptorq::gf256::{Gf256, gf256_addmul_slice};
use crate::raptorq::proof::{
    DecodeConfig, DecodeProof, EliminationTrace, FailureReason, InactivationStrategy, PeelingTrace,
    ReceivedSummary,
};
use crate::raptorq::systematic::{ConstraintMatrix, SystematicParams};
use crate::raptorq::{decision_contract, decision_contract::GovernanceSnapshot};
use crate::types::ObjectId;

use std::collections::{BTreeSet, VecDeque};
use std::hash::{Hash, Hasher};
use std::sync::Arc;

// ============================================================================
// Decoder types
// ============================================================================

/// A received symbol (source or repair) with its equation.
#[derive(Debug, Clone)]
pub struct ReceivedSymbol {
    /// Encoding Symbol Index (ESI).
    pub esi: u32,
    /// Whether this is a source symbol (ESI < K).
    pub is_source: bool,
    /// Column indices that this symbol depends on (intermediate symbol indices).
    /// For source symbols, this is just `[esi]`. For repair, computed from LT encoding.
    pub columns: Vec<usize>,
    /// GF(256) coefficients for each column (same length as `columns`).
    /// For XOR-based LT, all coefficients are 1.
    pub coefficients: Vec<Gf256>,
    /// The symbol data.
    pub data: Vec<u8>,
}

/// Reason for decode failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DecodeError {
    /// Not enough symbols received to solve the system.
    InsufficientSymbols {
        /// Number of symbols received.
        received: usize,
        /// Minimum caller-supplied equations required before decoding can proceed.
        required: usize,
    },
    /// Matrix became singular during Gaussian elimination.
    SingularMatrix {
        /// Deterministic witness row for elimination failure.
        ///
        /// This may be either:
        /// - the original unsolved column id where no pivot was found, or
        /// - an equation row index that reduced to `0 = b` (inconsistent system).
        row: usize,
    },
    /// Symbol size mismatch.
    SymbolSizeMismatch {
        /// Expected size.
        expected: usize,
        /// Actual size found.
        actual: usize,
    },
    /// Received symbol has mismatched equation vectors.
    SymbolEquationArityMismatch {
        /// ESI of the malformed symbol.
        esi: u32,
        /// Number of column indices provided.
        columns: usize,
        /// Number of coefficients provided.
        coefficients: usize,
    },
    /// Received symbol references a column outside the decode domain [0, L).
    ColumnIndexOutOfRange {
        /// ESI of the malformed symbol.
        esi: u32,
        /// Offending column index.
        column: usize,
        /// Exclusive upper bound for valid columns.
        max_valid: usize,
    },
    /// A source symbol used an ESI outside the systematic source domain [0, K).
    SourceEsiOutOfRange {
        /// ESI of the malformed source symbol.
        esi: u32,
        /// Exclusive upper bound for valid source ESIs.
        max_valid: usize,
    },
    /// A source symbol did not use the required identity equation `C[esi] = data`.
    InvalidSourceSymbolEquation {
        /// ESI of the malformed source symbol.
        esi: u32,
        /// Required intermediate column for that source symbol.
        expected_column: usize,
    },
    /// Internal corruption guard: reconstructed output does not satisfy an
    /// input equation and is therefore unsafe to return as success.
    CorruptDecodedOutput {
        /// ESI of the mismatched equation row.
        esi: u32,
        /// First byte index where mismatch was detected.
        byte_index: usize,
        /// Reconstructed byte from decoded intermediate symbols.
        expected: u8,
        /// Received RHS byte from the input symbol.
        actual: u8,
    },
}

/// Decode failure classification used to separate retryable failures from
/// malformed/corruption failures at the API boundary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecodeFailureClass {
    /// Retry may succeed with additional symbols/redundancy.
    Recoverable,
    /// Input is malformed or decode invariants were violated.
    Unrecoverable,
}

impl DecodeError {
    /// Classify this decode failure as recoverable or unrecoverable.
    #[must_use]
    #[inline]
    pub const fn failure_class(&self) -> DecodeFailureClass {
        match self {
            Self::InsufficientSymbols { .. } | Self::SingularMatrix { .. } => {
                DecodeFailureClass::Recoverable
            }
            Self::SymbolSizeMismatch { .. }
            | Self::SymbolEquationArityMismatch { .. }
            | Self::ColumnIndexOutOfRange { .. }
            | Self::SourceEsiOutOfRange { .. }
            | Self::InvalidSourceSymbolEquation { .. }
            | Self::CorruptDecodedOutput { .. } => DecodeFailureClass::Unrecoverable,
        }
    }

    /// True when this failure can be retried by supplying additional symbols.
    #[must_use]
    #[inline]
    pub const fn is_recoverable(&self) -> bool {
        matches!(self.failure_class(), DecodeFailureClass::Recoverable)
    }

    /// True when this failure indicates malformed input or corruption.
    #[must_use]
    #[inline]
    pub const fn is_unrecoverable(&self) -> bool {
        matches!(self.failure_class(), DecodeFailureClass::Unrecoverable)
    }
}

/// Decode statistics for observability.
#[derive(Debug, Clone, Default)]
pub struct DecodeStats {
    /// Symbols solved via peeling (degree-1 propagation).
    pub peeled: usize,
    /// Symbols marked as inactive.
    pub inactivated: usize,
    /// Gaussian elimination row operations performed.
    pub gauss_ops: usize,
    /// Total pivot selections made.
    pub pivots_selected: usize,
    /// True when the decoder entered hard-regime inactivation mode.
    ///
    /// Hard regime is a deterministic fallback for dense/near-square decode
    /// systems where naive pivoting is more likely to encounter fragile paths.
    pub hard_regime_activated: bool,
    /// Number of pivots selected by the hard-regime Markowitz-style strategy.
    pub markowitz_pivots: usize,
    /// Number of times baseline elimination deterministically retried in hard regime.
    pub hard_regime_fallbacks: usize,
    /// Hard-regime branch selected for dense elimination.
    pub hard_regime_branch: Option<&'static str>,
    /// Deterministic reason an accelerated hard-regime branch fell back to conservative mode.
    pub hard_regime_conservative_fallback_reason: Option<&'static str>,
    /// Number of equation indices pushed into the deterministic peel queue.
    pub peel_queue_pushes: usize,
    /// Number of equation indices popped from the deterministic peel queue.
    pub peel_queue_pops: usize,
    /// Maximum queue depth observed during peeling.
    pub peel_frontier_peak: usize,
    /// Number of rows in the extracted dense core presented to elimination.
    pub dense_core_rows: usize,
    /// Number of columns in the extracted dense core presented to elimination.
    pub dense_core_cols: usize,
    /// Number of zero-information rows dropped while extracting the dense core.
    pub dense_core_dropped_rows: usize,
    /// Deterministic reason we fell back from peeling into dense elimination.
    pub peeling_fallback_reason: Option<&'static str>,
    /// Runtime policy mode selected for dense elimination planning.
    pub policy_mode: Option<&'static str>,
    /// Deterministic reason string for the runtime policy decision.
    pub policy_reason: Option<&'static str>,
    /// Replay pointer for policy-decision forensics.
    pub policy_replay_ref: Option<&'static str>,
    /// Concrete G7 governance output for this decoder policy decision.
    pub governance: Option<decision_contract::GovernanceTelemetry>,
    /// Policy feature: matrix density in permille.
    pub policy_density_permille: usize,
    /// Policy feature: estimated rank deficit pressure in permille.
    pub policy_rank_deficit_permille: usize,
    /// Policy feature: inactivation pressure in permille.
    pub policy_inactivation_pressure_permille: usize,
    /// Policy feature: row/column overhead ratio in permille.
    pub policy_overhead_ratio_permille: usize,
    /// True if policy feature extraction exhausted its strict budget.
    pub policy_budget_exhausted: bool,
    /// Expected-loss term for conservative baseline mode.
    pub policy_baseline_loss: u32,
    /// Expected-loss term for high-support mode.
    pub policy_high_support_loss: u32,
    /// Expected-loss term for block-schur mode.
    pub policy_block_schur_loss: u32,
    /// Number of dense-factor cache hits during this decode.
    pub factor_cache_hits: usize,
    /// Number of dense-factor cache misses during this decode.
    pub factor_cache_misses: usize,
    /// Number of dense-factor cache insertions during this decode.
    pub factor_cache_inserts: usize,
    /// Number of dense-factor cache evictions during this decode.
    pub factor_cache_evictions: usize,
    /// Number of fingerprint collisions observed while probing cache keys.
    pub factor_cache_lookup_collisions: usize,
    /// Last dense-factor cache key fingerprint consulted by the decoder.
    pub factor_cache_last_key: Option<u64>,
    /// Deterministic reason for the most recent dense-factor cache decision.
    pub factor_cache_last_reason: Option<&'static str>,
    /// Whether the most recent cache probe was eligible for artifact reuse.
    pub factor_cache_last_reuse_eligible: Option<bool>,
    /// Number of entries resident in the dense-factor cache after the last operation.
    pub factor_cache_entries: usize,
    /// Bounded capacity used by the dense-factor cache policy.
    pub factor_cache_capacity: usize,
    /// True when the wavefront decode pipeline was used.
    pub wavefront_active: bool,
    /// Number of bounded assembly+peel batches processed by the wavefront pipeline.
    pub wavefront_batches: usize,
    /// Number of symbols peeled during assembly batches (overlap region).
    pub wavefront_overlap_peeled: usize,
    /// Wavefront batch size used for assembly+peel fusion.
    pub wavefront_batch_size: usize,
}

/// Result of successful decoding.
#[derive(Debug)]
pub struct DecodeResult {
    /// Recovered intermediate symbols (L symbols).
    pub intermediate: Vec<Vec<u8>>,
    /// Recovered source symbols (first K of intermediate).
    pub source: Vec<Vec<u8>>,
    /// Decode statistics.
    pub stats: DecodeStats,
}

/// Result of decoding with proof artifact.
#[derive(Debug)]
pub struct DecodeResultWithProof {
    /// The decode result (success case).
    pub result: DecodeResult,
    /// Proof artifact explaining the decode process.
    pub proof: DecodeProof,
}

// ============================================================================
// Decoder state
// ============================================================================

/// Internal decoder state during the decode process.
struct DecoderState {
    /// Encoding parameters.
    params: SystematicParams,
    /// Received equations (row-major, each row is an equation).
    equations: Vec<Equation>,
    /// Right-hand side data for each equation.
    rhs: Vec<Vec<u8>>,
    /// Solved intermediate symbols (None if not yet solved).
    solved: Vec<Option<Vec<u8>>>,
    /// Set of active (unsolved, not inactivated) columns.
    active_cols: BTreeSet<usize>,
    /// Set of inactivated columns (will be solved via Gaussian elimination).
    inactive_cols: BTreeSet<usize>,
    /// Statistics.
    stats: DecodeStats,
}

const DENSE_FACTOR_CACHE_CAPACITY: usize = 16;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DenseFactorCacheResult {
    Hit,
    MissInserted,
    MissEvicted,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum DenseFactorCacheLookup {
    Hit(Arc<DenseFactorArtifact>),
    MissNoEntry,
    MissFingerprintCollision,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct DenseFactorArtifact {
    dense_cols: Vec<usize>,
    col_to_dense: DenseColIndexMap,
}

impl DenseFactorArtifact {
    fn new(dense_cols: Vec<usize>) -> Self {
        let col_to_dense = build_dense_col_index_map(&dense_cols);
        Self {
            dense_cols,
            col_to_dense,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum DenseColIndexMap {
    Direct(Vec<usize>),
    SortedPairs(Vec<(usize, usize)>),
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct DenseFactorSignature {
    fingerprint: u64,
    unsolved: Vec<usize>,
    row_offsets: Vec<usize>,
    row_terms_flat: Vec<(usize, u8)>,
}

impl DenseFactorSignature {
    fn from_equations(equations: &[Equation], dense_rows: &[usize], unsolved: &[usize]) -> Self {
        let mut row_offsets = Vec::with_capacity(dense_rows.len());
        // Upper bound avoids growth reallocations in bursty decode signatures.
        let row_terms_capacity = dense_rows
            .iter()
            .map(|&eq_idx| equations[eq_idx].terms.len())
            .sum();
        let mut row_terms_flat = Vec::with_capacity(row_terms_capacity);
        for &eq_idx in dense_rows {
            let mut unsolved_cursor = 0usize;
            for &(col, coef) in &equations[eq_idx].terms {
                if coef.is_zero() {
                    continue;
                }
                while unsolved_cursor < unsolved.len() && unsolved[unsolved_cursor] < col {
                    unsolved_cursor += 1;
                }
                if unsolved_cursor >= unsolved.len() {
                    break;
                }
                if unsolved[unsolved_cursor] == col {
                    row_terms_flat.push((col, coef.raw()));
                }
            }
            row_offsets.push(row_terms_flat.len());
        }

        let mut hasher = crate::util::DetHasher::default();
        unsolved.hash(&mut hasher);
        row_offsets.hash(&mut hasher);
        row_terms_flat.hash(&mut hasher);
        let fingerprint = hasher.finish();

        Self {
            fingerprint,
            unsolved: unsolved.to_vec(),
            row_offsets,
            row_terms_flat,
        }
    }
}

#[derive(Debug, Clone)]
struct DenseFactorCacheEntry {
    signature: DenseFactorSignature,
    artifact: Arc<DenseFactorArtifact>,
}

#[derive(Debug, Default)]
struct DenseFactorCache {
    entries: VecDeque<DenseFactorCacheEntry>,
}

impl DenseFactorCache {
    fn lookup(&self, signature: &DenseFactorSignature) -> DenseFactorCacheLookup {
        let mut saw_fingerprint_collision = false;
        for entry in &self.entries {
            if entry.signature.fingerprint != signature.fingerprint {
                continue;
            }
            if entry.signature == *signature {
                return DenseFactorCacheLookup::Hit(entry.artifact.clone());
            }
            saw_fingerprint_collision = true;
        }

        if saw_fingerprint_collision {
            DenseFactorCacheLookup::MissFingerprintCollision
        } else {
            DenseFactorCacheLookup::MissNoEntry
        }
    }

    fn insert(
        &mut self,
        signature: DenseFactorSignature,
        artifact: Arc<DenseFactorArtifact>,
    ) -> DenseFactorCacheResult {
        if let Some(existing) = self
            .entries
            .iter_mut()
            .find(|entry| entry.signature == signature)
        {
            existing.artifact = artifact;
            return DenseFactorCacheResult::MissInserted;
        }

        let result = if self.entries.len() >= DENSE_FACTOR_CACHE_CAPACITY {
            let _ = self.entries.pop_front();
            DenseFactorCacheResult::MissEvicted
        } else {
            DenseFactorCacheResult::MissInserted
        };
        self.entries.push_back(DenseFactorCacheEntry {
            signature,
            artifact,
        });
        result
    }

    #[inline]
    fn len(&self) -> usize {
        self.entries.len()
    }
}

/// A sparse equation over GF(256).
#[derive(Debug, Clone)]
struct Equation {
    /// (column_index, coefficient) pairs, sorted by column index.
    terms: Vec<(usize, Gf256)>,
    /// Whether this equation has been used (solved or eliminated).
    used: bool,
}

impl Equation {
    fn new(columns: Vec<usize>, coefficients: Vec<Gf256>) -> Self {
        let mut terms: Vec<_> = columns.into_iter().zip(coefficients).collect();
        // Sort by column index for deterministic ordering
        terms.sort_by_key(|(col, _)| *col);
        // Merge duplicates (XOR coefficients)
        let mut merged = Vec::with_capacity(terms.len());
        for (col, coef) in terms {
            if let Some((last_col, last_coef)) = merged.last_mut() {
                if *last_col == col {
                    *last_coef += coef;
                    continue;
                }
            }
            merged.push((col, coef));
        }
        // Remove zero coefficients
        merged.retain(|(_, coef)| !coef.is_zero());
        Self {
            terms: merged,
            used: false,
        }
    }

    /// Returns the degree (number of nonzero terms).
    #[inline]
    fn degree(&self) -> usize {
        self.terms.len()
    }

    /// Returns the coefficient for the given column, or zero.
    #[inline]
    fn coef(&self, col: usize) -> Gf256 {
        self.terms
            .binary_search_by_key(&col, |(c, _)| *c)
            .map_or(Gf256::ZERO, |idx| self.terms[idx].1)
    }
}

#[inline]
fn original_col_for_dense(unsolved: &[usize], dense_col: usize) -> usize {
    unsolved.get(dense_col).copied().unwrap_or(dense_col)
}

#[inline]
fn singular_matrix_error(unsolved: &[usize], dense_col: usize) -> DecodeError {
    DecodeError::SingularMatrix {
        row: original_col_for_dense(unsolved, dense_col),
    }
}

#[inline]
fn inconsistent_matrix_error(unused_eqs: &[usize], dense_row: usize) -> DecodeError {
    DecodeError::SingularMatrix {
        row: unused_eqs.get(dense_row).copied().unwrap_or(dense_row),
    }
}

fn first_inconsistent_dense_row(
    a: &[Gf256],
    n_rows: usize,
    n_cols: usize,
    b: &[Vec<u8>],
) -> Option<usize> {
    (0..n_rows).find(|&row| {
        let row_off = row * n_cols;
        a[row_off..row_off + n_cols]
            .iter()
            .all(|coef| coef.is_zero())
            && b[row].iter().any(|&byte| byte != 0)
    })
}

#[inline]
fn active_degree_one_col(state: &DecoderState, eq: &Equation) -> Option<usize> {
    if eq.used || eq.degree() != 1 {
        return None;
    }
    let col = eq.terms[0].0;
    if state.active_cols.contains(&col) && state.solved[col].is_none() {
        Some(col)
    } else {
        None
    }
}

fn build_dense_core_rows(
    state: &DecoderState,
    unused_eqs: &[usize],
    unsolved: &[usize],
) -> Result<(Vec<usize>, usize), DecodeError> {
    let mut unsolved_mask = vec![false; state.params.l];
    for &col in unsolved {
        unsolved_mask[col] = true;
    }

    let mut dense_rows = Vec::with_capacity(unused_eqs.len());
    let mut dropped_zero_rows = 0usize;

    for &eq_idx in unused_eqs {
        let has_unsolved_term = state.equations[eq_idx]
            .terms
            .iter()
            .any(|(col, coef)| unsolved_mask[*col] && !coef.is_zero());
        if has_unsolved_term {
            dense_rows.push(eq_idx);
            continue;
        }

        if state.rhs[eq_idx].iter().any(|&byte| byte != 0) {
            return Err(DecodeError::SingularMatrix { row: eq_idx });
        }
        dropped_zero_rows += 1;
    }

    Ok((dense_rows, dropped_zero_rows))
}

fn validate_dense_core_rhs_widths(
    state: &DecoderState,
    dense_rows: &[usize],
    symbol_size: usize,
) -> Result<(), DecodeError> {
    for &eq_idx in dense_rows {
        let actual = state.rhs[eq_idx].len();
        if actual != symbol_size {
            return Err(DecodeError::SymbolSizeMismatch {
                expected: symbol_size,
                actual,
            });
        }
    }
    Ok(())
}

const DENSE_COL_ABSENT: usize = usize::MAX;
const DENSE_COL_DIRECT_MAP_RANGE_RATIO: usize = 8;

#[inline]
fn build_dense_col_index_map(unsolved: &[usize]) -> DenseColIndexMap {
    let Some(max_col) = unsolved.iter().copied().max() else {
        return DenseColIndexMap::Direct(Vec::new());
    };

    let direct_map_max_col = unsolved
        .len()
        .saturating_mul(DENSE_COL_DIRECT_MAP_RANGE_RATIO);
    if max_col <= direct_map_max_col {
        let mut col_to_dense = vec![DENSE_COL_ABSENT; max_col.saturating_add(1)];
        for (dense_col, &col) in unsolved.iter().enumerate() {
            col_to_dense[col] = dense_col;
        }
        DenseColIndexMap::Direct(col_to_dense)
    } else {
        let mut pairs: Vec<(usize, usize)> = unsolved
            .iter()
            .copied()
            .enumerate()
            .map(|(dense_col, col)| (col, dense_col))
            .collect();
        pairs.sort_by_key(|(col, _)| *col);
        DenseColIndexMap::SortedPairs(pairs)
    }
}

#[inline]
fn dense_col_index_from_direct(map: &[usize], col: usize) -> Option<usize> {
    let dense_col = *map.get(col)?;
    if dense_col == DENSE_COL_ABSENT {
        return None;
    }
    Some(dense_col)
}

#[inline]
fn dense_col_index_from_sorted_pairs(pairs: &[(usize, usize)], col: usize) -> Option<usize> {
    let idx = pairs
        .binary_search_by_key(&col, |(candidate_col, _)| *candidate_col)
        .ok()?;
    Some(pairs[idx].1)
}

#[inline]
fn dense_col_index(col_to_dense: &DenseColIndexMap, col: usize) -> Option<usize> {
    match col_to_dense {
        DenseColIndexMap::Direct(map) => dense_col_index_from_direct(map, col),
        DenseColIndexMap::SortedPairs(pairs) => dense_col_index_from_sorted_pairs(pairs, col),
    }
}

fn sparse_first_dense_columns(
    equations: &[Equation],
    dense_rows: &[usize],
    unsolved: &[usize],
) -> Vec<usize> {
    if unsolved.len() < 2 {
        return unsolved.to_vec();
    }

    let mut support = vec![0usize; unsolved.len()];

    // Hot-path optimization: runtime unsolved columns are deterministically
    // sorted; use a two-pointer scan to avoid allocating an index map.
    if unsolved.windows(2).all(|w| w[0] <= w[1]) {
        for &eq_idx in dense_rows {
            let mut unsolved_cursor = 0usize;
            for &(col, coef) in &equations[eq_idx].terms {
                if coef.is_zero() {
                    continue;
                }
                while unsolved_cursor < unsolved.len() && unsolved[unsolved_cursor] < col {
                    unsolved_cursor += 1;
                }
                if unsolved_cursor >= unsolved.len() {
                    break;
                }
                if unsolved[unsolved_cursor] == col {
                    support[unsolved_cursor] += 1;
                }
            }
        }
    } else {
        // Compatibility fallback for non-canonical caller input.
        let col_to_dense = build_dense_col_index_map(unsolved);
        for &eq_idx in dense_rows {
            for &(col, coef) in &equations[eq_idx].terms {
                if coef.is_zero() {
                    continue;
                }
                if let Some(dense_col) = dense_col_index(&col_to_dense, col) {
                    support[dense_col] += 1;
                }
            }
        }
    }

    let mut ordered: Vec<(usize, usize)> = unsolved
        .iter()
        .copied()
        .enumerate()
        .map(|(dense_col, col)| (col, support[dense_col]))
        .collect();

    // Sparse-first ordering shrinks expected fill-in while remaining deterministic.
    ordered.sort_by(|(col_a, support_a), (col_b, support_b)| {
        support_a.cmp(support_b).then_with(|| col_a.cmp(col_b))
    });
    ordered.into_iter().map(|(col, _)| col).collect()
}

fn failure_reason_with_trace(err: &DecodeError, elimination: &EliminationTrace) -> FailureReason {
    match err {
        DecodeError::SingularMatrix { row } => FailureReason::SingularMatrix {
            row: *row,
            attempted_cols: elimination.pivot_events.iter().map(|ev| ev.col).collect(),
        },
        _ => FailureReason::from(err),
    }
}

const HARD_REGIME_MIN_COLS: usize = 8;
const HARD_REGIME_DENSITY_PERCENT: usize = 35;
const HARD_REGIME_NEAR_SQUARE_EXTRA_ROWS: usize = 2;
const BLOCK_SCHUR_MIN_COLS: usize = 12;
const BLOCK_SCHUR_MIN_DENSITY_PERCENT: usize = 45;
const BLOCK_SCHUR_TRAILING_COLS: usize = 4;
const HYBRID_SPARSE_COST_NUMERATOR: usize = 3;
const HYBRID_SPARSE_COST_DENOMINATOR: usize = 5;
const SMALL_ROW_DENSE_FASTPATH_COLS: usize = 4;
const POLICY_FEATURE_BUDGET_CELLS: usize = 4096;
const POLICY_REPLAY_REF: &str = "replay:rq-track-f-runtime-policy-v1";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DecoderPolicyFeatures {
    density_permille: usize,
    rank_deficit_permille: usize,
    inactivation_pressure_permille: usize,
    overhead_ratio_permille: usize,
    budget_exhausted: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DecoderPolicyMode {
    ConservativeBaseline,
    HighSupportFirst,
    BlockSchurLowRank,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DecoderPolicyDecision {
    mode: DecoderPolicyMode,
    features: DecoderPolicyFeatures,
    baseline_loss: u32,
    high_support_loss: u32,
    block_schur_loss: u32,
    reason: &'static str,
    governance: Option<decision_contract::GovernanceTelemetry>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HardRegimePlan {
    Markowitz,
    BlockSchurLowRank { split_col: usize },
}

impl HardRegimePlan {
    const fn label(self) -> &'static str {
        match self {
            Self::Markowitz => "markowitz",
            Self::BlockSchurLowRank { .. } => "block_schur_low_rank",
        }
    }

    const fn strategy(self) -> InactivationStrategy {
        match self {
            Self::Markowitz => InactivationStrategy::HighSupportFirst,
            Self::BlockSchurLowRank { .. } => InactivationStrategy::BlockSchurLowRank,
        }
    }
}

fn matrix_nonzero_count(a: &[Gf256]) -> usize {
    a.iter().filter(|coef| !coef.is_zero()).count()
}

fn clamp_usize_to_u32(value: usize) -> u32 {
    u32::try_from(value).unwrap_or(u32::MAX)
}

fn compute_decoder_policy_features(
    n_rows: usize,
    n_cols: usize,
    dense_nonzeros: usize,
    unsupported_cols: usize,
    inactivation_pressure_permille: usize,
) -> DecoderPolicyFeatures {
    if n_rows == 0 || n_cols == 0 {
        return DecoderPolicyFeatures {
            density_permille: 0,
            rank_deficit_permille: 0,
            inactivation_pressure_permille,
            overhead_ratio_permille: 0,
            budget_exhausted: false,
        };
    }

    let total_cells = n_rows.saturating_mul(n_cols);
    let density_permille = dense_nonzeros.saturating_mul(1000) / total_cells.max(1);
    let rank_deficit_permille = unsupported_cols.saturating_mul(1000) / n_cols;
    let overhead_ratio_permille = n_rows.saturating_sub(n_cols).saturating_mul(1000) / n_cols;

    DecoderPolicyFeatures {
        density_permille,
        rank_deficit_permille,
        inactivation_pressure_permille,
        overhead_ratio_permille,
        budget_exhausted: total_cells > POLICY_FEATURE_BUDGET_CELLS,
    }
}

fn policy_losses(features: DecoderPolicyFeatures, n_cols: usize) -> (u32, u32, u32) {
    let density = clamp_usize_to_u32(features.density_permille);
    let rank_deficit = clamp_usize_to_u32(features.rank_deficit_permille);
    let inactivation_pressure = clamp_usize_to_u32(features.inactivation_pressure_permille);
    let overhead = clamp_usize_to_u32(features.overhead_ratio_permille);

    let baseline_loss = 400u32
        .saturating_add(density.saturating_mul(3))
        .saturating_add(rank_deficit.saturating_mul(4))
        .saturating_add(inactivation_pressure.saturating_mul(2))
        .saturating_add(overhead);

    let high_support_loss = 700u32
        .saturating_add(density)
        .saturating_add(rank_deficit.saturating_mul(3))
        .saturating_add(inactivation_pressure)
        .saturating_add(overhead / 2);

    let block_schur_loss = if n_cols < BLOCK_SCHUR_MIN_COLS {
        u32::MAX
    } else {
        750u32
            .saturating_add(density / 2)
            .saturating_add(rank_deficit.saturating_mul(2))
            .saturating_add(inactivation_pressure)
            .saturating_add(overhead / 3)
    };

    (baseline_loss, high_support_loss, block_schur_loss)
}

#[cfg(test)]
thread_local! {
    static TEST_BYPASS_GOVERNANCE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

#[cfg(test)]
fn set_test_bypass_governance(bypass: bool) {
    TEST_BYPASS_GOVERNANCE.with(|cell| cell.set(bypass));
}

fn bypass_governance() -> bool {
    #[cfg(test)]
    {
        TEST_BYPASS_GOVERNANCE.with(std::cell::Cell::get)
    }
    #[cfg(not(test))]
    {
        false
    }
}

fn choose_runtime_decoder_policy(
    n_rows: usize,
    n_cols: usize,
    dense_nonzeros: usize,
    unsupported_cols: usize,
    inactivation_pressure_permille: usize,
) -> DecoderPolicyDecision {
    let features = compute_decoder_policy_features(
        n_rows,
        n_cols,
        dense_nonzeros,
        unsupported_cols,
        inactivation_pressure_permille,
    );
    let mut decision = choose_low_level_decoder_policy(features, n_rows, n_cols);
    let governance = decision_contract::evaluate_governance(&GovernanceSnapshot {
        n_rows,
        n_cols,
        density_permille: features.density_permille,
        rank_deficit_permille: features.rank_deficit_permille,
        inactivation_pressure_permille: features.inactivation_pressure_permille,
        overhead_ratio_permille: features.overhead_ratio_permille,
        budget_exhausted: features.budget_exhausted,
        baseline_loss: decision.baseline_loss,
        high_support_loss: decision.high_support_loss,
        block_schur_loss: decision.block_schur_loss,
    });
    if !bypass_governance() {
        match governance.chosen_action {
            "canary_hold" if matches!(decision.mode, DecoderPolicyMode::BlockSchurLowRank) => {
                decision.mode = DecoderPolicyMode::HighSupportFirst;
                decision.reason = "g7_expected_loss_canary_hold";
            }
            "rollback" if !matches!(decision.mode, DecoderPolicyMode::ConservativeBaseline) => {
                decision.mode = DecoderPolicyMode::ConservativeBaseline;
                decision.reason = "g7_expected_loss_rollback";
            }
            "fallback" if !matches!(decision.mode, DecoderPolicyMode::ConservativeBaseline) => {
                decision.mode = DecoderPolicyMode::ConservativeBaseline;
                decision.reason = "g7_deterministic_fallback_trigger";
            }
            _ => {}
        }
    }
    decision.governance = Some(governance);
    decision
}

fn choose_low_level_decoder_policy(
    features: DecoderPolicyFeatures,
    n_rows: usize,
    n_cols: usize,
) -> DecoderPolicyDecision {
    let (baseline_loss, high_support_loss, mut block_schur_loss) = policy_losses(features, n_cols);
    if features.budget_exhausted {
        return DecoderPolicyDecision {
            mode: DecoderPolicyMode::ConservativeBaseline,
            features,
            baseline_loss,
            high_support_loss,
            block_schur_loss,
            reason: "policy_budget_exhausted_conservative",
            governance: None,
        };
    }

    let hard_gate = n_cols >= HARD_REGIME_MIN_COLS
        && (features.density_permille >= HARD_REGIME_DENSITY_PERCENT.saturating_mul(10)
            || n_rows <= n_cols.saturating_add(HARD_REGIME_NEAR_SQUARE_EXTRA_ROWS));
    if !hard_gate {
        return DecoderPolicyDecision {
            mode: DecoderPolicyMode::ConservativeBaseline,
            features,
            baseline_loss,
            high_support_loss,
            block_schur_loss,
            reason: "expected_loss_conservative_gate",
            governance: None,
        };
    }

    let block_gate = n_cols >= BLOCK_SCHUR_MIN_COLS
        && features.density_permille >= BLOCK_SCHUR_MIN_DENSITY_PERCENT.saturating_mul(10)
        && n_cols > BLOCK_SCHUR_TRAILING_COLS;
    if !block_gate {
        block_schur_loss = u32::MAX;
    }
    let mode = if block_schur_loss < high_support_loss {
        DecoderPolicyMode::BlockSchurLowRank
    } else {
        DecoderPolicyMode::HighSupportFirst
    };

    DecoderPolicyDecision {
        mode,
        features,
        baseline_loss,
        high_support_loss,
        block_schur_loss,
        reason: "expected_loss_minimum",
        governance: None,
    }
}

const fn decoder_policy_mode_label(mode: DecoderPolicyMode) -> &'static str {
    match mode {
        DecoderPolicyMode::ConservativeBaseline => "conservative_baseline",
        DecoderPolicyMode::HighSupportFirst => "high_support_first",
        DecoderPolicyMode::BlockSchurLowRank => "block_schur_low_rank",
    }
}

fn apply_policy_decision_to_stats(stats: &mut DecodeStats, decision: DecoderPolicyDecision) {
    stats.policy_mode = Some(decoder_policy_mode_label(decision.mode));
    stats.policy_reason = Some(decision.reason);
    stats.policy_replay_ref = Some(POLICY_REPLAY_REF);
    stats.governance = decision.governance;
    stats.policy_density_permille = decision.features.density_permille;
    stats.policy_rank_deficit_permille = decision.features.rank_deficit_permille;
    stats.policy_inactivation_pressure_permille = decision.features.inactivation_pressure_permille;
    stats.policy_overhead_ratio_permille = decision.features.overhead_ratio_permille;
    stats.policy_budget_exhausted = decision.features.budget_exhausted;
    stats.policy_baseline_loss = decision.baseline_loss;
    stats.policy_high_support_loss = decision.high_support_loss;
    stats.policy_block_schur_loss = decision.block_schur_loss;
}

#[derive(Debug, Clone, Copy)]
struct DenseFactorCacheObservation {
    key: u64,
    result: DenseFactorCacheResult,
    reason: &'static str,
    reuse_eligible: bool,
    fingerprint_collision: bool,
    cache_entries: usize,
    cache_capacity: usize,
}

fn apply_dense_factor_cache_observation(
    stats: &mut DecodeStats,
    observation: DenseFactorCacheObservation,
) {
    stats.factor_cache_last_key = Some(observation.key);
    stats.factor_cache_last_reason = Some(observation.reason);
    stats.factor_cache_last_reuse_eligible = Some(observation.reuse_eligible);
    stats.factor_cache_entries = observation.cache_entries;
    stats.factor_cache_capacity = observation.cache_capacity;
    if observation.fingerprint_collision {
        stats.factor_cache_lookup_collisions += 1;
    }

    match observation.result {
        DenseFactorCacheResult::Hit => {
            stats.factor_cache_hits += 1;
        }
        DenseFactorCacheResult::MissInserted => {
            stats.factor_cache_misses += 1;
            stats.factor_cache_inserts += 1;
        }
        DenseFactorCacheResult::MissEvicted => {
            stats.factor_cache_misses += 1;
            stats.factor_cache_inserts += 1;
            stats.factor_cache_evictions += 1;
        }
    }
}

fn row_nonzero_count(a: &[Gf256], n_cols: usize, row: usize) -> usize {
    let row_off = row * n_cols;
    a[row_off..row_off + n_cols]
        .iter()
        .filter(|coef| !coef.is_zero())
        .count()
}

fn sparse_update_columns_if_beneficial(pivot_row: &[Gf256], n_cols: usize) -> Option<Vec<usize>> {
    if n_cols == 0 {
        return None;
    }

    // Equivalent threshold to should_use_sparse_row_update(pivot_nnz, n_cols).
    let threshold =
        n_cols.saturating_mul(HYBRID_SPARSE_COST_NUMERATOR) / HYBRID_SPARSE_COST_DENOMINATOR;

    if n_cols <= SMALL_ROW_DENSE_FASTPATH_COLS {
        // Very small rows are sensitive to per-pivot heap allocation overhead.
        // Use an allocation-free density pass; collect columns only if sparse.
        let mut sparse_nnz = 0usize;
        for coef in pivot_row.iter().take(n_cols) {
            if coef.is_zero() {
                continue;
            }
            sparse_nnz += 1;
            if sparse_nnz > threshold {
                return None;
            }
        }

        let mut cols = Vec::with_capacity(sparse_nnz.max(1));
        for (idx, coef) in pivot_row.iter().take(n_cols).enumerate() {
            if !coef.is_zero() {
                cols.push(idx);
            }
        }
        return Some(cols);
    }

    // For larger rows, one-pass collection avoids an extra scan on sparse pivots.
    let mut seen = 0usize;
    let mut cols = Vec::with_capacity((threshold + 1).min(n_cols).max(1));
    for (idx, coef) in pivot_row.iter().take(n_cols).enumerate() {
        if coef.is_zero() {
            continue;
        }
        seen += 1;
        if seen > threshold {
            return None;
        }
        cols.push(idx);
    }
    Some(cols)
}

fn select_hard_regime_plan(n_rows: usize, n_cols: usize, a: &[Gf256]) -> HardRegimePlan {
    let total_cells = n_rows.saturating_mul(n_cols);
    if n_cols < BLOCK_SCHUR_MIN_COLS || total_cells == 0 {
        return HardRegimePlan::Markowitz;
    }
    let nonzeros = matrix_nonzero_count(a);
    let dense_enough =
        nonzeros.saturating_mul(100) >= total_cells.saturating_mul(BLOCK_SCHUR_MIN_DENSITY_PERCENT);
    if !dense_enough || n_cols <= BLOCK_SCHUR_TRAILING_COLS {
        return HardRegimePlan::Markowitz;
    }
    let split_col = n_cols - BLOCK_SCHUR_TRAILING_COLS;
    HardRegimePlan::BlockSchurLowRank { split_col }
}

fn row_cross_block_nnz(
    a: &[Gf256],
    n_cols: usize,
    row: usize,
    split_col: usize,
    col: usize,
) -> usize {
    let row_off = row * n_cols;
    let row_slice = &a[row_off..row_off + n_cols];
    if col < split_col {
        row_slice[split_col..]
            .iter()
            .filter(|coef| !coef.is_zero())
            .count()
    } else {
        row_slice[..split_col]
            .iter()
            .filter(|coef| !coef.is_zero())
            .count()
    }
}

fn select_pivot_row(
    a: &[Gf256],
    n_rows: usize,
    n_cols: usize,
    col: usize,
    row_used: &[bool],
    hard_regime: bool,
    hard_plan: HardRegimePlan,
) -> Option<usize> {
    if !hard_regime {
        return (0..n_rows).find(|&row| !row_used[row] && !a[row * n_cols + col].is_zero());
    }

    let mut best: Option<(usize, usize, usize)> = None;
    for row in 0..n_rows {
        if row_used[row] || a[row * n_cols + col].is_zero() {
            continue;
        }
        let cross_block_nnz = match hard_plan {
            HardRegimePlan::Markowitz => 0,
            HardRegimePlan::BlockSchurLowRank { split_col } => {
                row_cross_block_nnz(a, n_cols, row, split_col, col)
            }
        };
        let nnz = row_nonzero_count(a, n_cols, row);
        match best {
            None => best = Some((row, cross_block_nnz, nnz)),
            Some((_best_row, best_cross, _best_nnz)) if cross_block_nnz < best_cross => {
                best = Some((row, cross_block_nnz, nnz));
            }
            Some((_best_row, best_cross, best_nnz))
                if cross_block_nnz == best_cross && nnz < best_nnz =>
            {
                best = Some((row, cross_block_nnz, nnz));
            }
            Some((best_row, best_cross, best_nnz))
                if cross_block_nnz == best_cross && nnz == best_nnz && row < best_row =>
            {
                best = Some((row, cross_block_nnz, nnz));
            }
            _ => {}
        }
    }

    best.map(|(row, _, _)| row)
}

// ============================================================================
// Inactivation decoder
// ============================================================================

/// Inactivation decoder for RaptorQ.
///
/// Decodes received symbols (source or repair) to recover intermediate
/// symbols, then extracts the original source data.
pub struct InactivationDecoder {
    params: SystematicParams,
    seed: u64,
    dense_factor_cache: parking_lot::Mutex<DenseFactorCache>,
}

impl InactivationDecoder {
    /// Create a new decoder for the given parameters.
    #[must_use]
    pub fn new(k: usize, symbol_size: usize, seed: u64) -> Self {
        let params = SystematicParams::for_source_block(k, symbol_size);
        Self {
            params,
            seed,
            dense_factor_cache: parking_lot::Mutex::new(DenseFactorCache::default()),
        }
    }

    /// Returns the encoding parameters.
    #[must_use]
    #[inline]
    pub const fn params(&self) -> &SystematicParams {
        &self.params
    }

    #[inline]
    const fn implicit_padding_rows(&self) -> usize {
        self.params.k_prime.saturating_sub(self.params.k)
    }

    #[inline]
    const fn minimum_received_symbols(&self) -> usize {
        self.params.l.saturating_sub(self.implicit_padding_rows())
    }

    fn validate_input(&self, symbols: &[ReceivedSymbol]) -> Result<(), DecodeError> {
        let k = self.params.k;
        let l = self.params.l;
        let symbol_size = self.params.symbol_size;
        let required = self.minimum_received_symbols();

        if symbols.len() < required {
            return Err(DecodeError::InsufficientSymbols {
                received: symbols.len(),
                required,
            });
        }

        for sym in symbols {
            if sym.data.len() != symbol_size {
                return Err(DecodeError::SymbolSizeMismatch {
                    expected: symbol_size,
                    actual: sym.data.len(),
                });
            }

            if sym.columns.len() != sym.coefficients.len() {
                return Err(DecodeError::SymbolEquationArityMismatch {
                    esi: sym.esi,
                    columns: sym.columns.len(),
                    coefficients: sym.coefficients.len(),
                });
            }

            for &column in &sym.columns {
                if column >= l {
                    return Err(DecodeError::ColumnIndexOutOfRange {
                        esi: sym.esi,
                        column,
                        max_valid: l,
                    });
                }
            }

            if sym.is_source {
                let esi = sym.esi as usize;
                if esi >= k {
                    return Err(DecodeError::SourceEsiOutOfRange {
                        esi: sym.esi,
                        max_valid: k,
                    });
                }
                if sym.columns.len() != 1
                    || sym.coefficients.len() != 1
                    || sym.columns[0] != esi
                    || sym.coefficients[0] != Gf256::ONE
                {
                    return Err(DecodeError::InvalidSourceSymbolEquation {
                        esi: sym.esi,
                        expected_column: esi,
                    });
                }
            }
        }

        Ok(())
    }

    fn verify_decoded_output(
        &self,
        symbols: &[ReceivedSymbol],
        intermediate: &[Vec<u8>],
    ) -> Result<(), DecodeError> {
        let symbol_size = self.params.symbol_size;
        // Reuse a single scratch buffer across rows to avoid per-symbol
        // heap allocation in decode hot paths.
        let mut reconstructed = vec![0u8; symbol_size];

        for sym in symbols {
            if sym.is_source
                && sym.columns.len() == 1
                && sym.coefficients.len() == 1
                && (sym.esi as usize) < self.params.k
                && sym.columns[0] == sym.esi as usize
                && sym.coefficients[0] == Gf256::ONE
            {
                let source_col = sym.columns[0];
                let expected = &intermediate[source_col];
                if let Some(byte_index) = first_mismatch_byte(expected, &sym.data) {
                    return Err(DecodeError::CorruptDecodedOutput {
                        esi: sym.esi,
                        byte_index,
                        expected: expected[byte_index],
                        actual: sym.data[byte_index],
                    });
                }
                continue;
            }

            reconstructed.fill(0);
            for (&column, &coefficient) in sym.columns.iter().zip(sym.coefficients.iter()) {
                if coefficient.is_zero() {
                    continue;
                }
                gf256_addmul_slice(&mut reconstructed, &intermediate[column], coefficient);
            }
            if let Some(byte_index) = first_mismatch_byte(&reconstructed, &sym.data) {
                return Err(DecodeError::CorruptDecodedOutput {
                    esi: sym.esi,
                    byte_index,
                    expected: reconstructed[byte_index],
                    actual: sym.data[byte_index],
                });
            }
        }

        Ok(())
    }

    /// Decode from received symbols.
    ///
    /// `symbols` must include the LDPC/HDPC constraint rows and enough received
    /// equations to solve the block. The decoder synthesizes the implicit zero
    /// LT rows for the padded systematic range `K..K'`, so callers do not need
    /// to supply them explicitly.
    /// Returns the decoded source symbols on success.
    pub fn decode(&self, symbols: &[ReceivedSymbol]) -> Result<DecodeResult, DecodeError> {
        let k = self.params.k;
        let symbol_size = self.params.symbol_size;

        self.validate_input(symbols)?;

        // Build decoder state
        let mut state = self.build_state(symbols);

        // Phase 1: Peeling
        Self::peel(&mut state);

        // Phase 2: Inactivation + Gaussian elimination
        self.inactivate_and_solve(&mut state)?;

        // Extract results
        let intermediate: Vec<Vec<u8>> = state
            .solved
            .into_iter()
            .map(|opt| opt.unwrap_or_else(|| vec![0u8; symbol_size]))
            .collect();
        self.verify_decoded_output(symbols, &intermediate)?;

        let source: Vec<Vec<u8>> = intermediate[..k].to_vec();

        Ok(DecodeResult {
            intermediate,
            source,
            stats: state.stats,
        })
    }

    /// Decode using the bounded wavefront pipeline.
    ///
    /// Instead of sequential assembly→peel→solve, this pipeline fuses
    /// assembly and peeling into bounded batches: symbols are assembled in
    /// chunks of `batch_size`, and after each chunk the peeling queue is
    /// drained. This reduces pipeline bubbles by overlapping assembly with
    /// peeling, so degree-1 equations discovered early are solved while
    /// remaining symbols are still being assembled.
    ///
    /// The solve phase (inactivation + Gaussian elimination) runs after
    /// all batches are processed, identical to the sequential path.
    ///
    /// Correctness: produces identical results to `decode()` because
    /// peeling order is deterministic (FIFO queue, same equation ordering)
    /// and the dense solve phase sees the same final state.
    ///
    /// `batch_size` controls the wavefront width. Smaller batches increase
    /// overlap but add per-batch overhead. A batch size of 0 means "use
    /// all symbols at once" (equivalent to sequential mode).
    pub fn decode_wavefront(
        &self,
        symbols: &[ReceivedSymbol],
        batch_size: usize,
    ) -> Result<DecodeResult, DecodeError> {
        let k = self.params.k;
        let symbol_size = self.params.symbol_size;

        self.validate_input(symbols)?;

        // A batch_size of 0 falls back to sequential (single batch = all symbols).
        let effective_batch = if batch_size == 0 {
            symbols.len()
        } else {
            batch_size
        };

        // Start from the same implicit K..K' padding rows that the sequential
        // decoder synthesizes so wavefront mode remains RFC-parity equivalent
        // on padded parameter sets.
        let mut state = self.build_state(&[]);
        state.equations.reserve(symbols.len());
        state.rhs.reserve(symbols.len());
        state.stats.wavefront_active = true;
        state.stats.wavefront_batch_size = effective_batch;

        // Wavefront: assemble symbols in bounded batches and peel after each.
        let mut total_overlap_peeled = 0usize;
        let mut batch_count = 0usize;
        let mut queue = VecDeque::new();
        let mut queued = vec![false; state.equations.len()];

        // The synthesized K..K' padding rows are immediately available and may
        // peel before any real symbols arrive. Apply that deterministic prefix
        // up front so subsequent batch catch-up sees the same reduced state as
        // the sequential decode path.
        for (idx, queued_flag) in queued.iter_mut().enumerate() {
            if !*queued_flag && active_degree_one_col(&state, &state.equations[idx]).is_some() {
                queue.push_back(idx);
                *queued_flag = true;
                state.stats.peel_queue_pushes += 1;
            }
        }
        state.stats.peel_frontier_peak = state.stats.peel_frontier_peak.max(queue.len());
        Self::peel_from_queue(&mut state, &mut queue, &mut queued);

        for chunk in symbols.chunks(effective_batch) {
            let base_eq_idx = state.equations.len();
            // Assembly: add this batch of symbols as equations.
            for sym in chunk {
                let eq = Equation::new(sym.columns.clone(), sym.coefficients.clone());
                state.equations.push(eq);
                state.rhs.push(sym.data.clone());
            }
            queued.resize(state.equations.len(), false);

            // Catch-up: apply already-peeled solutions to newly assembled equations.
            // This ensures new equations see the same reduced state they would in
            // the sequential path where all equations are present before peeling.
            for idx in base_eq_idx..state.equations.len() {
                let eq = &state.equations[idx];
                // Collect columns that have been solved and appear in this equation.
                let solved_terms: Vec<(usize, Gf256)> = eq
                    .terms
                    .iter()
                    .filter(|(col, coef)| !coef.is_zero() && state.solved[*col].is_some())
                    .copied()
                    .collect();
                for (col, eq_coef) in &solved_terms {
                    let solution = state.solved[*col].as_ref().expect("solution must exist");
                    gf256_addmul_slice(&mut state.rhs[idx], solution, *eq_coef);
                    if let Ok(pos) = state.equations[idx]
                        .terms
                        .binary_search_by_key(col, |(c, _)| *c)
                    {
                        state.equations[idx].terms.remove(pos);
                    }
                }
            }

            // Scan newly added equations for degree-1 candidates.
            for (idx, queued_flag) in queued.iter_mut().enumerate().skip(base_eq_idx) {
                if !*queued_flag && active_degree_one_col(&state, &state.equations[idx]).is_some() {
                    queue.push_back(idx);
                    *queued_flag = true;
                    state.stats.peel_queue_pushes += 1;
                }
            }
            state.stats.peel_frontier_peak = state.stats.peel_frontier_peak.max(queue.len());

            // Peel: drain the queue after this batch.
            let peeled_before = state.stats.peeled;
            Self::peel_from_queue(&mut state, &mut queue, &mut queued);
            let peeled_this_batch = state.stats.peeled - peeled_before;
            if batch_count > 0 {
                // Only count overlap peeling from non-first batches,
                // since the first batch has no prior assembly to overlap with.
                total_overlap_peeled += peeled_this_batch;
            }
            batch_count += 1;
        }

        state.stats.wavefront_batches = batch_count;
        state.stats.wavefront_overlap_peeled = total_overlap_peeled;

        // Phase 2: Inactivation + Gaussian elimination (same as sequential).
        self.inactivate_and_solve(&mut state)?;

        // Extract results.
        let intermediate: Vec<Vec<u8>> = state
            .solved
            .into_iter()
            .map(|opt| opt.unwrap_or_else(|| vec![0u8; symbol_size]))
            .collect();
        self.verify_decoded_output(symbols, &intermediate)?;

        let source: Vec<Vec<u8>> = intermediate[..k].to_vec();

        Ok(DecodeResult {
            intermediate,
            source,
            stats: state.stats,
        })
    }

    /// Peel from an existing queue, extending as new degree-1 equations are discovered.
    ///
    /// This is the core peeling loop factored out so it can be called
    /// incrementally by the wavefront pipeline after each assembly batch.
    fn peel_from_queue(state: &mut DecoderState, queue: &mut VecDeque<usize>, queued: &mut [bool]) {
        while let Some(eq_idx) = queue.pop_front() {
            state.stats.peel_queue_pops += 1;
            queued[eq_idx] = false;

            let Some(col) = active_degree_one_col(state, &state.equations[eq_idx]) else {
                continue;
            };

            // Solve this equation.
            let (_col, coef) = state.equations[eq_idx].terms[0];
            state.equations[eq_idx].used = true;

            let mut solution = std::mem::take(&mut state.rhs[eq_idx]);
            if coef != Gf256::ONE {
                let inv = coef.inv();
                crate::raptorq::gf256::gf256_mul_slice(&mut solution, inv);
            }

            state.active_cols.remove(&col);
            state.stats.peeled += 1;

            // Propagate to other equations.
            let active_cols = &state.active_cols;
            let solved = &state.solved;
            for (i, (eq, rhs)) in state
                .equations
                .iter_mut()
                .zip(state.rhs.iter_mut())
                .enumerate()
            {
                if eq.used {
                    continue;
                }
                let eq_coef = eq.coef(col);
                if eq_coef.is_zero() {
                    continue;
                }
                gf256_addmul_slice(rhs, &solution, eq_coef);
                if let Ok(pos) = eq.terms.binary_search_by_key(&col, |(c, _)| *c) {
                    eq.terms.remove(pos);
                }

                if !queued[i] && eq.degree() == 1 {
                    let next_col = eq.terms[0].0;
                    if active_cols.contains(&next_col) && solved[next_col].is_none() {
                        queue.push_back(i);
                        queued[i] = true;
                        state.stats.peel_queue_pushes += 1;
                    }
                }
            }

            state.stats.peel_frontier_peak = state.stats.peel_frontier_peak.max(queue.len());
            state.solved[col] = Some(solution);
        }
    }

    /// Decode from received symbols with proof artifact capture.
    ///
    /// Like `decode`, but also captures a proof artifact that explains
    /// the decode process for debugging and verification.
    ///
    /// # Arguments
    ///
    /// * `symbols` - Received symbols (at least L required)
    /// * `object_id` - Object ID for the proof artifact
    /// * `sbn` - Source block number for the proof artifact
    #[allow(clippy::result_large_err)]
    pub fn decode_with_proof(
        &self,
        symbols: &[ReceivedSymbol],
        object_id: ObjectId,
        sbn: u8,
    ) -> Result<DecodeResultWithProof, (DecodeError, DecodeProof)> {
        let k = self.params.k;
        let symbol_size = self.params.symbol_size;

        // Build proof configuration
        let config = DecodeConfig {
            object_id,
            sbn,
            k,
            s: self.params.s,
            h: self.params.h,
            l: self.params.l,
            symbol_size,
            seed: self.seed,
        };
        let mut proof_builder = DecodeProof::builder(config);

        // Capture received symbols summary
        let received = ReceivedSummary::from_received(symbols.iter().map(|s| (s.esi, s.is_source)));
        proof_builder.set_received(received);

        // Validate input
        if let Err(err) = self.validate_input(symbols) {
            proof_builder.set_failure(FailureReason::from(&err));
            return Err((err, proof_builder.build()));
        }

        // Build decoder state
        let mut state = self.build_state(symbols);

        // Phase 1: Peeling with proof capture
        Self::peel_with_proof(&mut state, proof_builder.peeling_mut());

        // Phase 2: Inactivation + Gaussian elimination with proof capture
        if let Err(err) =
            self.inactivate_and_solve_with_proof(&mut state, proof_builder.elimination_mut())
        {
            let reason = failure_reason_with_trace(&err, proof_builder.elimination_mut());
            proof_builder.set_failure(reason);
            return Err((err, proof_builder.build()));
        }

        // Extract results
        let intermediate: Vec<Vec<u8>> = state
            .solved
            .into_iter()
            .map(|opt| opt.unwrap_or_else(|| vec![0u8; symbol_size]))
            .collect();
        if let Err(err) = self.verify_decoded_output(symbols, &intermediate) {
            proof_builder.set_failure(FailureReason::from(&err));
            return Err((err, proof_builder.build()));
        }

        let source: Vec<Vec<u8>> = intermediate[..k].to_vec();

        // Mark success with a deterministic binding to the recovered payload.
        proof_builder.set_success(&source);

        Ok(DecodeResultWithProof {
            result: DecodeResult {
                intermediate,
                source,
                stats: state.stats,
            },
            proof: proof_builder.build(),
        })
    }

    /// Build initial decoder state from received symbols.
    ///
    /// The caller is responsible for including LDPC/HDPC constraint equations
    /// (with zero RHS) in the received symbols if needed. The decoder
    /// synthesizes the implicit zero LT rows for the padded systematic range
    /// `K..K'` so direct callers cannot accidentally omit them.
    fn build_state(&self, symbols: &[ReceivedSymbol]) -> DecoderState {
        let l = self.params.l;
        let symbol_size = self.params.symbol_size;

        let mut equations = Vec::with_capacity(symbols.len() + self.implicit_padding_rows());
        let mut rhs = Vec::with_capacity(symbols.len() + self.implicit_padding_rows());

        // Add received symbol equations
        for sym in symbols {
            let eq = Equation::new(sym.columns.clone(), sym.coefficients.clone());
            equations.push(eq);
            rhs.push(sym.data.clone());
        }

        // Systematic encoding includes K' LT rows. When K' > K the encoder
        // appends padded LT rows K..K' with an explicit zero RHS; synthesize
        // those rows here so the direct decoder path matches the encoder's
        // constraint system even when callers only provide real source symbols.
        for column in self.params.k..self.params.k_prime {
            equations.push(Equation::new(vec![column], vec![Gf256::ONE]));
            rhs.push(vec![0u8; symbol_size]);
        }

        let active_cols: BTreeSet<usize> = (0..l).collect();

        DecoderState {
            params: self.params.clone(),
            equations,
            rhs,
            solved: vec![None; l],
            active_cols,
            inactive_cols: BTreeSet::new(),
            stats: DecodeStats::default(),
        }
    }

    fn dense_factor_with_cache(
        &self,
        equations: &[Equation],
        dense_rows: &[usize],
        unsolved: &[usize],
    ) -> (Arc<DenseFactorArtifact>, DenseFactorCacheObservation) {
        let signature = DenseFactorSignature::from_equations(equations, dense_rows, unsolved);
        let cache_key = signature.fingerprint;
        let (lookup, cache_entries_at_lookup) = {
            let cache = self.dense_factor_cache.lock();
            (cache.lookup(&signature), cache.len())
        };

        if let DenseFactorCacheLookup::Hit(artifact) = lookup {
            return (
                artifact,
                DenseFactorCacheObservation {
                    key: cache_key,
                    result: DenseFactorCacheResult::Hit,
                    reason: "signature_match_reuse",
                    reuse_eligible: true,
                    fingerprint_collision: false,
                    cache_entries: cache_entries_at_lookup,
                    cache_capacity: DENSE_FACTOR_CACHE_CAPACITY,
                },
            );
        }

        let saw_fingerprint_collision =
            matches!(lookup, DenseFactorCacheLookup::MissFingerprintCollision);
        let artifact = Arc::new(DenseFactorArtifact::new(sparse_first_dense_columns(
            equations, dense_rows, unsolved,
        )));
        let (result, cache_entries) = {
            let mut cache = self.dense_factor_cache.lock();
            let result = cache.insert(signature, Arc::clone(&artifact));
            (result, cache.len())
        };
        let reason = if saw_fingerprint_collision {
            "fingerprint_collision_rebuild"
        } else {
            match result {
                DenseFactorCacheResult::Hit => "signature_match_reuse",
                DenseFactorCacheResult::MissInserted => "cache_miss_rebuild",
                DenseFactorCacheResult::MissEvicted => "cache_miss_evicted_oldest",
            }
        };
        (
            artifact,
            DenseFactorCacheObservation {
                key: cache_key,
                result,
                reason,
                reuse_eligible: false,
                fingerprint_collision: saw_fingerprint_collision,
                cache_entries,
                cache_capacity: DENSE_FACTOR_CACHE_CAPACITY,
            },
        )
    }

    /// Generate constraint symbols (LDPC + HDPC) with zero data.
    ///
    /// These should be included in the received symbols when decoding.
    /// The `decoding.rs` module handles this automatically; this method
    /// is provided for direct decoder testing.
    #[must_use]
    pub fn constraint_symbols(&self) -> Vec<ReceivedSymbol> {
        let s = self.params.s;
        let h = self.params.h;
        let symbol_size = self.params.symbol_size;
        let base_rows = s + h;

        // Build the constraint matrix (same as encoder uses)
        let constraints = ConstraintMatrix::build(&self.params, self.seed);

        let mut result = Vec::with_capacity(base_rows);

        // Extract the first S+H rows (LDPC + HDPC constraints)
        for row in 0..base_rows {
            let (columns, coefficients) = Self::constraint_row_equation(&constraints, row);
            result.push(ReceivedSymbol {
                esi: row as u32,
                is_source: false,
                columns,
                coefficients,
                data: vec![0u8; symbol_size],
            });
        }

        result
    }

    /// Extract a sparse equation from a constraint matrix row.
    fn constraint_row_equation(
        constraints: &ConstraintMatrix,
        row: usize,
    ) -> (Vec<usize>, Vec<Gf256>) {
        let mut columns = Vec::new();
        let mut coefficients = Vec::new();
        for col in 0..constraints.cols {
            let coeff = constraints.get(row, col);
            if !coeff.is_zero() {
                columns.push(col);
                coefficients.push(coeff);
            }
        }
        (columns, coefficients)
    }

    /// Phase 1: Peeling (belief propagation).
    ///
    /// Find degree-1 equations and solve them, propagating the solution
    /// to other equations.
    fn peel(state: &mut DecoderState) {
        Self::peel_impl(state, |_| {});
    }

    /// Phase 1: Peeling with proof trace capture.
    ///
    /// Like `peel`, but also records solved symbols to the proof trace.
    fn peel_with_proof(state: &mut DecoderState, trace: &mut PeelingTrace) {
        Self::peel_impl(state, |col| {
            trace.record_solved(col);
        });
    }

    fn peel_impl<F>(state: &mut DecoderState, mut on_solved: F)
    where
        F: FnMut(usize),
    {
        let mut queue = VecDeque::new();
        let mut queued = vec![false; state.equations.len()];
        for (idx, eq) in state.equations.iter().enumerate() {
            if active_degree_one_col(state, eq).is_some() {
                queue.push_back(idx);
                queued[idx] = true;
                state.stats.peel_queue_pushes += 1;
            }
        }
        state.stats.peel_frontier_peak = state.stats.peel_frontier_peak.max(queue.len());

        while let Some(eq_idx) = queue.pop_front() {
            state.stats.peel_queue_pops += 1;
            queued[eq_idx] = false;

            let Some(col) = active_degree_one_col(state, &state.equations[eq_idx]) else {
                continue;
            };

            // Solve this equation
            let (_col, coef) = state.equations[eq_idx].terms[0];
            state.equations[eq_idx].used = true;

            // Compute the solution: intermediate[col] = rhs[eq_idx] / coef
            let mut solution = std::mem::take(&mut state.rhs[eq_idx]);
            if coef != Gf256::ONE {
                let inv = coef.inv();
                crate::raptorq::gf256::gf256_mul_slice(&mut solution, inv);
            }

            state.active_cols.remove(&col);
            state.stats.peeled += 1;
            on_solved(col);

            // Propagate to other equations: subtract col's contribution
            let active_cols = &state.active_cols;
            let solved = &state.solved;
            for (i, eq) in state.equations.iter_mut().enumerate() {
                if eq.used {
                    continue;
                }
                let eq_coef = eq.coef(col);
                if eq_coef.is_zero() {
                    continue;
                }
                // rhs[i] -= eq_coef * solution
                gf256_addmul_slice(&mut state.rhs[i], &solution, eq_coef);
                // Remove the term from the equation.
                // Binary search is efficient since terms are sorted by column index.
                if let Ok(pos) = eq.terms.binary_search_by_key(&col, |(c, _)| *c) {
                    eq.terms.remove(pos);
                }

                if !queued[i] && !eq.used && eq.degree() == 1 {
                    let next_col = eq.terms[0].0;
                    if active_cols.contains(&next_col) && solved[next_col].is_none() {
                        queue.push_back(i);
                        queued[i] = true;
                        state.stats.peel_queue_pushes += 1;
                    }
                }
            }

            state.stats.peel_frontier_peak = state.stats.peel_frontier_peak.max(queue.len());

            // Move solution instead of cloning (avoids allocation)
            state.solved[col] = Some(solution);
        }
    }

    /// Phase 2: Inactivation + Gaussian elimination.
    #[allow(clippy::too_many_lines)]
    fn inactivate_and_solve(&self, state: &mut DecoderState) -> Result<(), DecodeError> {
        let symbol_size = self.params.symbol_size;

        // Collect remaining unsolved columns
        let unsolved: Vec<usize> = state
            .active_cols
            .iter()
            .filter(|&&col| state.solved[col].is_none())
            .copied()
            .collect();

        if unsolved.is_empty() {
            return Ok(());
        }
        state.stats.peeling_fallback_reason = Some("peeling_exhausted_to_dense_core");

        // Collect unused equations
        let unused_eqs: Vec<usize> = state
            .equations
            .iter()
            .enumerate()
            .filter_map(|(i, eq)| if eq.used { None } else { Some(i) })
            .collect();
        let (dense_rows, dropped_zero_rows) = build_dense_core_rows(state, &unused_eqs, &unsolved)?;
        state.stats.dense_core_dropped_rows += dropped_zero_rows;
        validate_dense_core_rhs_widths(state, &dense_rows, symbol_size)?;

        // Mark all remaining unsolved columns as inactive
        for &col in &unsolved {
            state.inactive_cols.insert(col);
            state.active_cols.remove(&col);
            state.stats.inactivated += 1;
        }

        // Reorder dense elimination columns deterministically and reuse cached
        // dense skeleton metadata when signatures match.
        let (dense_factor, cache_observation) =
            self.dense_factor_with_cache(&state.equations, &dense_rows, &unsolved);
        apply_dense_factor_cache_observation(&mut state.stats, cache_observation);
        let dense_cols = &dense_factor.dense_cols;
        let col_to_dense = &dense_factor.col_to_dense;

        // Build dense submatrix for Gaussian elimination
        // Rows = unused equations, Columns = unsolved columns
        let n_rows = dense_rows.len();
        let n_cols = dense_cols.len();
        let inactivation_pressure_permille =
            unsolved.len().saturating_mul(1000) / state.params.l.max(1);
        state.stats.dense_core_rows = n_rows;
        state.stats.dense_core_cols = n_cols;

        let mut b: Vec<Vec<u8>> = Vec::with_capacity(n_rows);

        if n_rows < n_cols {
            reactivate_unsolved_columns(state, &unsolved);
            return Err(singular_matrix_error(&unsolved, n_rows));
        }

        // Build flat row-major dense matrix A and RHS vector b.
        // Flat layout avoids per-row heap allocation and improves cache locality.
        // Move (take) RHS data from state instead of cloning to avoid O(n_rows * symbol_size)
        // heap allocation in this hot path.
        let total_cells = match n_rows.checked_mul(n_cols) {
            Some(total_cells) => total_cells,
            None => {
                let err = DecodeError::InsufficientSymbols {
                    received: n_rows,
                    required: n_cols,
                };
                reactivate_unsolved_columns(state, &unsolved);
                return Err(err);
            }
        };
        let mut a = vec![Gf256::ZERO; total_cells];
        let mut dense_nonzeros = 0usize;
        let mut dense_col_support = vec![0usize; n_cols];

        for (row, &eq_idx) in dense_rows.iter().enumerate() {
            let row_off = row * n_cols;
            for &(col, coef) in &state.equations[eq_idx].terms {
                if let Some(dense_col) = dense_col_index(col_to_dense, col) {
                    a[row_off + dense_col] = coef;
                    if !coef.is_zero() {
                        dense_nonzeros += 1;
                        dense_col_support[dense_col] += 1;
                    }
                }
            }
            b.push(std::mem::take(&mut state.rhs[eq_idx]));
        }
        let unsupported_cols = dense_col_support
            .iter()
            .filter(|&&support| support == 0)
            .count();
        let dense_rhs_snapshot = snapshot_dense_rhs(&b, symbol_size);

        let decision = choose_runtime_decoder_policy(
            n_rows,
            n_cols,
            dense_nonzeros,
            unsupported_cols,
            inactivation_pressure_permille,
        );
        apply_policy_decision_to_stats(&mut state.stats, decision);
        let mut hard_regime = !matches!(decision.mode, DecoderPolicyMode::ConservativeBaseline);
        let mut hard_plan = match decision.mode {
            DecoderPolicyMode::ConservativeBaseline | DecoderPolicyMode::HighSupportFirst => {
                HardRegimePlan::Markowitz
            }
            DecoderPolicyMode::BlockSchurLowRank => select_hard_regime_plan(n_rows, n_cols, &a),
        };
        if hard_regime {
            state.stats.hard_regime_activated = true;
            state.stats.hard_regime_branch = Some(hard_plan.label());
        } else if decision.reason == "policy_budget_exhausted_conservative" {
            state.stats.hard_regime_conservative_fallback_reason = Some(decision.reason);
        }

        let mut pivot_row = vec![usize::MAX; n_cols];
        loop {
            pivot_row.fill(usize::MAX);

            // Gaussian elimination with partial pivoting.
            // Pre-allocate a single pivot buffer to avoid per-column clones.
            let mut row_used = vec![false; n_rows];
            let mut pivot_buf = vec![Gf256::ZERO; n_cols];
            let mut pivot_rhs = vec![0u8; symbol_size];
            let mut gauss_ops = 0usize;
            let mut pivots_selected = 0usize;
            let mut markowitz_pivots = 0usize;
            let mut elimination_error = None;

            for col in 0..n_cols {
                let pivot =
                    select_pivot_row(&a, n_rows, n_cols, col, &row_used, hard_regime, hard_plan);
                let Some(prow) = pivot else {
                    elimination_error = Some(singular_matrix_error(dense_cols, col));
                    break;
                };

                pivot_row[col] = prow;
                row_used[prow] = true;
                pivots_selected += 1;
                if hard_regime && matches!(hard_plan, HardRegimePlan::Markowitz) {
                    markowitz_pivots += 1;
                }

                // Scale pivot row so a[prow][col] = 1
                let prow_off = prow * n_cols;
                let pivot_coef = a[prow_off + col];
                let inv = pivot_coef.inv();
                for value in &mut a[prow_off..prow_off + n_cols] {
                    *value *= inv;
                }
                crate::raptorq::gf256::gf256_mul_slice(&mut b[prow], inv);

                // Copy pivot row into reusable buffers (no heap allocation)
                pivot_buf[..n_cols].copy_from_slice(&a[prow_off..prow_off + n_cols]);
                pivot_rhs[..symbol_size].copy_from_slice(&b[prow]);
                let sparse_cols = sparse_update_columns_if_beneficial(&pivot_buf[..n_cols], n_cols);

                // Eliminate column in all other rows.
                for (row, rhs) in b.iter_mut().enumerate().take(n_rows) {
                    if row == prow {
                        continue;
                    }
                    let row_off = row * n_cols;
                    let factor = a[row_off + col];
                    if factor.is_zero() {
                        continue;
                    }
                    if let Some(cols) = sparse_cols.as_ref() {
                        for &c in cols {
                            a[row_off + c] += factor * pivot_buf[c];
                        }
                    } else {
                        for c in 0..n_cols {
                            a[row_off + c] += factor * pivot_buf[c];
                        }
                    }
                    gf256_addmul_slice(rhs, &pivot_rhs[..symbol_size], factor);
                    gauss_ops += 1;
                }
            }

            if elimination_error.is_none() {
                if let Some(row) = first_inconsistent_dense_row(&a, n_rows, n_cols, &b) {
                    elimination_error = Some(inconsistent_matrix_error(&dense_rows, row));
                }
            }

            // Record work performed in this attempt, even if we fallback or fail.
            state.stats.pivots_selected += pivots_selected;
            state.stats.markowitz_pivots += markowitz_pivots;
            state.stats.gauss_ops += gauss_ops;

            if let Some(err) = elimination_error {
                if !hard_regime {
                    hard_regime = true;
                    state.stats.hard_regime_activated = true;
                    state.stats.hard_regime_fallbacks += 1;
                    state.stats.hard_regime_conservative_fallback_reason =
                        Some("fallback_after_baseline_failure");
                    // Rebuild matrix BEFORE selecting hard-regime plan so that
                    // density metrics reflect the original matrix, not the
                    // partially-eliminated one.
                    rebuild_dense_matrix_from_equations(
                        &state.equations,
                        &dense_rows,
                        col_to_dense,
                        n_cols,
                        &mut a,
                    );
                    restore_dense_rhs(&mut b, &dense_rhs_snapshot, symbol_size);
                    hard_plan = select_hard_regime_plan(n_rows, n_cols, &a);
                    state.stats.hard_regime_branch = Some(hard_plan.label());
                    continue;
                }
                if matches!(hard_plan, HardRegimePlan::BlockSchurLowRank { .. }) {
                    hard_plan = HardRegimePlan::Markowitz;
                    state.stats.hard_regime_fallbacks += 1;
                    state.stats.hard_regime_conservative_fallback_reason =
                        Some("block_schur_failed_to_converge");
                    rebuild_dense_matrix_from_equations(
                        &state.equations,
                        &dense_rows,
                        col_to_dense,
                        n_cols,
                        &mut a,
                    );
                    restore_dense_rhs(&mut b, &dense_rhs_snapshot, symbol_size);
                    continue;
                }
                restore_dense_rows_into_state(state, &dense_rows, &dense_rhs_snapshot, symbol_size);
                reactivate_unsolved_columns(state, &unsolved);
                return Err(err);
            }
            break;
        }

        // Extract solutions: move RHS vectors instead of cloning
        for (dense_col, &col) in dense_cols.iter().enumerate() {
            let prow = pivot_row[dense_col];
            if prow < n_rows {
                state.solved[col] = Some(std::mem::take(&mut b[prow]));
            } else {
                state.solved[col] = Some(vec![0u8; symbol_size]);
            }
        }

        Ok(())
    }

    /// Phase 2: Inactivation + Gaussian elimination with proof trace capture.
    ///
    /// Like `inactivate_and_solve`, but also records inactivations, pivots,
    /// and row operations to the proof trace.
    #[allow(clippy::too_many_lines)]
    fn inactivate_and_solve_with_proof(
        &self,
        state: &mut DecoderState,
        trace: &mut EliminationTrace,
    ) -> Result<(), DecodeError> {
        // Each decode proof must describe only the current invocation, even if
        // a caller reuses a trace buffer across runs.
        *trace = EliminationTrace::default();
        let symbol_size = self.params.symbol_size;

        // Collect remaining unsolved columns
        let unsolved: Vec<usize> = state
            .active_cols
            .iter()
            .filter(|&&col| state.solved[col].is_none())
            .copied()
            .collect();

        if unsolved.is_empty() {
            return Ok(());
        }
        state.stats.peeling_fallback_reason = Some("peeling_exhausted_to_dense_core");

        // Collect unused equations
        let unused_eqs: Vec<usize> = state
            .equations
            .iter()
            .enumerate()
            .filter_map(|(i, eq)| if eq.used { None } else { Some(i) })
            .collect();
        let (dense_rows, dropped_zero_rows) = build_dense_core_rows(state, &unused_eqs, &unsolved)?;
        state.stats.dense_core_dropped_rows += dropped_zero_rows;
        validate_dense_core_rhs_widths(state, &dense_rows, symbol_size)?;

        // Mark all remaining unsolved columns as inactive
        for &col in &unsolved {
            state.inactive_cols.insert(col);
            state.active_cols.remove(&col);
            state.stats.inactivated += 1;
            // Record inactivation in proof trace
            trace.record_inactivation(col);
        }

        // Reorder dense elimination columns deterministically and reuse cached
        // dense skeleton metadata when signatures match.
        let (dense_factor, cache_observation) =
            self.dense_factor_with_cache(&state.equations, &dense_rows, &unsolved);
        apply_dense_factor_cache_observation(&mut state.stats, cache_observation);
        let dense_cols = &dense_factor.dense_cols;
        let col_to_dense = &dense_factor.col_to_dense;

        // Build dense submatrix for Gaussian elimination
        // Rows = unused equations, Columns = unsolved columns
        let n_rows = dense_rows.len();
        let n_cols = dense_cols.len();
        let inactivation_pressure_permille =
            unsolved.len().saturating_mul(1000) / state.params.l.max(1);
        state.stats.dense_core_rows = n_rows;
        state.stats.dense_core_cols = n_cols;

        let mut b: Vec<Vec<u8>> = Vec::with_capacity(n_rows);

        if n_rows < n_cols {
            reactivate_unsolved_columns(state, &unsolved);
            return Err(singular_matrix_error(&unsolved, n_rows));
        }

        // Build flat row-major dense matrix A and RHS vector b.
        // Move (take) RHS data from state instead of cloning to avoid O(n_rows * symbol_size)
        // heap allocation in this hot path.
        let total_cells = match n_rows.checked_mul(n_cols) {
            Some(total_cells) => total_cells,
            None => {
                let err = DecodeError::InsufficientSymbols {
                    received: n_rows,
                    required: n_cols,
                };
                reactivate_unsolved_columns(state, &unsolved);
                return Err(err);
            }
        };
        let mut a = vec![Gf256::ZERO; total_cells];
        let mut dense_nonzeros = 0usize;
        let mut dense_col_support = vec![0usize; n_cols];

        for (row, &eq_idx) in dense_rows.iter().enumerate() {
            let row_off = row * n_cols;
            for &(col, coef) in &state.equations[eq_idx].terms {
                if let Some(dense_col) = dense_col_index(col_to_dense, col) {
                    a[row_off + dense_col] = coef;
                    if !coef.is_zero() {
                        dense_nonzeros += 1;
                        dense_col_support[dense_col] += 1;
                    }
                }
            }
            b.push(std::mem::take(&mut state.rhs[eq_idx]));
        }
        let unsupported_cols = dense_col_support
            .iter()
            .filter(|&&support| support == 0)
            .count();
        let dense_rhs_snapshot = snapshot_dense_rhs(&b, symbol_size);

        trace.set_strategy(InactivationStrategy::AllAtOnce);
        let decision = choose_runtime_decoder_policy(
            n_rows,
            n_cols,
            dense_nonzeros,
            unsupported_cols,
            inactivation_pressure_permille,
        );
        apply_policy_decision_to_stats(&mut state.stats, decision);
        let mut hard_regime = !matches!(decision.mode, DecoderPolicyMode::ConservativeBaseline);
        let mut hard_plan = match decision.mode {
            DecoderPolicyMode::ConservativeBaseline | DecoderPolicyMode::HighSupportFirst => {
                HardRegimePlan::Markowitz
            }
            DecoderPolicyMode::BlockSchurLowRank => select_hard_regime_plan(n_rows, n_cols, &a),
        };
        if hard_regime {
            state.stats.hard_regime_activated = true;
            state.stats.hard_regime_branch = Some(hard_plan.label());
            trace.record_strategy_transition(
                InactivationStrategy::AllAtOnce,
                hard_plan.strategy(),
                "dense_or_near_square",
            );
        } else if decision.reason == "policy_budget_exhausted_conservative" {
            state.stats.hard_regime_conservative_fallback_reason = Some(decision.reason);
        }

        let mut pivot_row = vec![usize::MAX; n_cols];
        loop {
            pivot_row.fill(usize::MAX);
            let mut row_used = vec![false; n_rows];
            let mut pivot_buf = vec![Gf256::ZERO; n_cols];
            let mut pivot_rhs = vec![0u8; symbol_size];
            let mut gauss_ops = 0usize;
            let mut pivots_selected = 0usize;
            let mut markowitz_pivots = 0usize;
            let mut elimination_error = None;

            for col in 0..n_cols {
                let pivot =
                    select_pivot_row(&a, n_rows, n_cols, col, &row_used, hard_regime, hard_plan);
                let Some(prow) = pivot else {
                    elimination_error = Some(singular_matrix_error(dense_cols, col));
                    break;
                };

                pivot_row[col] = prow;
                row_used[prow] = true;
                pivots_selected += 1;
                if hard_regime && matches!(hard_plan, HardRegimePlan::Markowitz) {
                    markowitz_pivots += 1;
                }
                // Record pivot in proof trace (use original column index)
                trace.record_pivot(dense_cols[col], prow);

                // Scale pivot row so a[prow][col] = 1
                let prow_off = prow * n_cols;
                let pivot_coef = a[prow_off + col];
                let inv = pivot_coef.inv();
                for value in &mut a[prow_off..prow_off + n_cols] {
                    *value *= inv;
                }
                crate::raptorq::gf256::gf256_mul_slice(&mut b[prow], inv);

                // Copy pivot row into reusable buffers
                pivot_buf[..n_cols].copy_from_slice(&a[prow_off..prow_off + n_cols]);
                pivot_rhs[..symbol_size].copy_from_slice(&b[prow]);
                let sparse_cols = sparse_update_columns_if_beneficial(&pivot_buf[..n_cols], n_cols);

                // Eliminate column in all other rows.
                for (row, rhs) in b.iter_mut().enumerate().take(n_rows) {
                    if row == prow {
                        continue;
                    }
                    let row_off = row * n_cols;
                    let factor = a[row_off + col];
                    if factor.is_zero() {
                        continue;
                    }
                    if let Some(cols) = sparse_cols.as_ref() {
                        for &c in cols {
                            a[row_off + c] += factor * pivot_buf[c];
                        }
                    } else {
                        for c in 0..n_cols {
                            a[row_off + c] += factor * pivot_buf[c];
                        }
                    }
                    gf256_addmul_slice(rhs, &pivot_rhs[..symbol_size], factor);
                    gauss_ops += 1;
                    // Record row operation in proof trace
                    trace.record_row_op();
                }
            }

            if elimination_error.is_none() {
                if let Some(row) = first_inconsistent_dense_row(&a, n_rows, n_cols, &b) {
                    elimination_error = Some(inconsistent_matrix_error(&dense_rows, row));
                }
            }

            // Record work performed in this attempt, even if we fallback or fail.
            state.stats.pivots_selected += pivots_selected;
            state.stats.markowitz_pivots += markowitz_pivots;
            state.stats.gauss_ops += gauss_ops;

            if let Some(err) = elimination_error {
                if !hard_regime {
                    hard_regime = true;
                    state.stats.hard_regime_activated = true;
                    state.stats.hard_regime_fallbacks += 1;
                    state.stats.hard_regime_conservative_fallback_reason =
                        Some("fallback_after_baseline_failure");
                    // Rebuild matrix BEFORE selecting hard-regime plan so that
                    // density metrics reflect the original matrix, not the
                    // partially-eliminated one.
                    rebuild_dense_matrix_from_equations(
                        &state.equations,
                        &dense_rows,
                        col_to_dense,
                        n_cols,
                        &mut a,
                    );
                    restore_dense_rhs(&mut b, &dense_rhs_snapshot, symbol_size);
                    hard_plan = select_hard_regime_plan(n_rows, n_cols, &a);
                    state.stats.hard_regime_branch = Some(hard_plan.label());
                    trace.record_strategy_transition(
                        InactivationStrategy::AllAtOnce,
                        hard_plan.strategy(),
                        "fallback_after_baseline_failure",
                    );
                    trace.pivots = 0;
                    trace.pivot_events.clear();
                    trace.row_ops = 0;
                    trace.pivot_events_truncated = false;
                    continue;
                }
                if matches!(hard_plan, HardRegimePlan::BlockSchurLowRank { .. }) {
                    hard_plan = HardRegimePlan::Markowitz;
                    state.stats.hard_regime_fallbacks += 1;
                    state.stats.hard_regime_conservative_fallback_reason =
                        Some("block_schur_failed_to_converge");
                    trace.record_strategy_transition(
                        InactivationStrategy::BlockSchurLowRank,
                        InactivationStrategy::HighSupportFirst,
                        "block_schur_failed_to_converge",
                    );
                    trace.pivots = 0;
                    trace.pivot_events.clear();
                    trace.row_ops = 0;
                    trace.pivot_events_truncated = false;
                    rebuild_dense_matrix_from_equations(
                        &state.equations,
                        &dense_rows,
                        col_to_dense,
                        n_cols,
                        &mut a,
                    );
                    restore_dense_rhs(&mut b, &dense_rhs_snapshot, symbol_size);
                    continue;
                }
                restore_dense_rows_into_state(state, &dense_rows, &dense_rhs_snapshot, symbol_size);
                reactivate_unsolved_columns(state, &unsolved);
                return Err(err);
            }
            break;
        }

        // Extract solutions: move RHS vectors instead of cloning
        for (dense_col, &col) in dense_cols.iter().enumerate() {
            let prow = pivot_row[dense_col];
            if prow < n_rows {
                state.solved[col] = Some(std::mem::take(&mut b[prow]));
            } else {
                state.solved[col] = Some(vec![0u8; symbol_size]);
            }
        }

        Ok(())
    }

    /// Generate the RFC 6330 tuple-derived equation (columns + coefficients) for a repair symbol.
    ///
    /// This must stay in parity with `SystematicEncoder::repair_symbol` so that
    /// decoder row construction exactly matches encoder repair bytes.
    #[must_use]
    pub fn repair_equation(&self, esi: u32) -> (Vec<usize>, Vec<Gf256>) {
        self.params.rfc_repair_equation(esi)
    }

    /// Generate the equation (columns + coefficients) using RFC 6330 tuple rules.
    ///
    /// This method computes tuple parameters from RFC 6330 Section 5.3.5.4 and
    /// expands them into intermediate symbol indices using Section 5.3.5.3.
    ///
    /// This is kept as an explicit alias used by RFC conformance tests.
    #[must_use]
    pub fn repair_equation_rfc6330(&self, esi: u32) -> (Vec<usize>, Vec<Gf256>) {
        self.repair_equation(esi)
    }

    /// Generate equations for all K source symbols.
    ///
    /// In systematic encoding, source symbol i maps directly to intermediate
    /// symbol i with no additional connections. This matches the encoder's
    /// `build_lt_rows` which simply sets `intermediate[i] = source[i]`.
    ///
    /// Returns a vector of K equations, where index i is the equation for
    /// source ESI i.
    #[must_use]
    pub fn all_source_equations(&self) -> Vec<(Vec<usize>, Vec<Gf256>)> {
        let k = self.params.k;

        // Systematic encoding: source symbol i maps directly to intermediate[i]
        // No additional LT connections - the encoder's build_lt_rows just does
        // matrix.set(row, i, Gf256::ONE) for each source symbol.
        (0..k).map(|i| (vec![i], vec![Gf256::ONE])).collect()
    }

    /// Get the equation for a specific source symbol ESI.
    ///
    /// In systematic encoding, source symbol `esi` maps directly to
    /// intermediate symbol `esi` with coefficient 1.
    #[must_use]
    pub fn source_equation(&self, esi: u32) -> (Vec<usize>, Vec<Gf256>) {
        assert!((esi as usize) < self.params.k, "source ESI must be < K");
        // Systematic: source[esi] = intermediate[esi]
        (vec![esi as usize], vec![Gf256::ONE])
    }
}

fn first_mismatch_byte(expected: &[u8], actual: &[u8]) -> Option<usize> {
    expected
        .iter()
        .zip(actual.iter())
        .position(|(expected, actual)| expected != actual)
}

fn rebuild_dense_matrix_from_equations(
    equations: &[Equation],
    dense_rows: &[usize],
    col_to_dense: &DenseColIndexMap,
    n_cols: usize,
    a: &mut [Gf256],
) {
    a.fill(Gf256::ZERO);
    for (row, &eq_idx) in dense_rows.iter().enumerate() {
        let row_off = row * n_cols;
        for &(col, coef) in &equations[eq_idx].terms {
            if let Some(dense_col) = dense_col_index(col_to_dense, col) {
                a[row_off + dense_col] = coef;
            }
        }
    }
}

fn snapshot_dense_rhs(rows: &[Vec<u8>], symbol_size: usize) -> Vec<u8> {
    let mut snapshot = vec![0u8; rows.len().saturating_mul(symbol_size)];
    for (row_idx, row) in rows.iter().enumerate() {
        debug_assert_eq!(row.len(), symbol_size);
        let off = row_idx * symbol_size;
        snapshot[off..off + symbol_size].copy_from_slice(row);
    }
    snapshot
}

fn restore_dense_rhs(rows: &mut [Vec<u8>], snapshot: &[u8], symbol_size: usize) {
    debug_assert_eq!(snapshot.len(), rows.len().saturating_mul(symbol_size));
    for (row_idx, row) in rows.iter_mut().enumerate() {
        debug_assert_eq!(row.len(), symbol_size);
        let off = row_idx * symbol_size;
        row.copy_from_slice(&snapshot[off..off + symbol_size]);
    }
}

fn restore_dense_rows_into_state(
    state: &mut DecoderState,
    dense_rows: &[usize],
    snapshot: &[u8],
    symbol_size: usize,
) {
    debug_assert_eq!(snapshot.len(), dense_rows.len().saturating_mul(symbol_size));
    for (row_idx, &eq_idx) in dense_rows.iter().enumerate() {
        let off = row_idx * symbol_size;
        state.rhs[eq_idx] = snapshot[off..off + symbol_size].to_vec();
    }
}

fn reactivate_unsolved_columns(state: &mut DecoderState, unsolved: &[usize]) {
    for &col in unsolved {
        state.inactive_cols.remove(&col);
        state.active_cols.insert(col);
    }
}

// ============================================================================
// Helper: build ReceivedSymbol from raw data
// ============================================================================

impl ReceivedSymbol {
    /// Create a source symbol (ESI < K).
    #[must_use]
    pub fn source(esi: u32, data: Vec<u8>) -> Self {
        Self {
            esi,
            is_source: true,
            columns: vec![esi as usize],
            coefficients: vec![Gf256::ONE],
            data,
        }
    }

    /// Create a repair symbol with precomputed equation.
    #[must_use]
    pub fn repair(esi: u32, columns: Vec<usize>, coefficients: Vec<Gf256>, data: Vec<u8>) -> Self {
        Self {
            esi,
            is_source: false,
            columns,
            coefficients,
            data,
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    use insta::assert_json_snapshot;
    use serde_json::json;

    /// Test-only: checks whether sparse row update is beneficial.
    fn should_use_sparse_row_update(pivot_nnz: usize, n_cols: usize) -> bool {
        if n_cols == 0 {
            return false;
        }
        pivot_nnz.saturating_mul(HYBRID_SPARSE_COST_DENOMINATOR)
            <= n_cols.saturating_mul(HYBRID_SPARSE_COST_NUMERATOR)
    }

    /// Test-only: collects nonzero column indices from a pivot row.
    fn pivot_nonzero_columns(pivot_row: &[Gf256], n_cols: usize) -> Vec<usize> {
        let mut cols = Vec::with_capacity(n_cols.min(32));
        for (idx, coef) in pivot_row.iter().take(n_cols).enumerate() {
            if !coef.is_zero() {
                cols.push(idx);
            }
        }
        cols
    }

    use crate::raptorq::systematic::SystematicEncoder;
    use crate::raptorq::test_log_schema::{
        UnitDecodeStats, UnitGovernanceDecision, UnitLogEntry, validate_unit_log_json,
    };

    fn rfc_eq_context(
        scenario_id: &str,
        seed: u64,
        k: usize,
        symbol_size: usize,
        loss_pattern: &str,
        outcome: &str,
    ) -> String {
        format!(
            "scenario_id={scenario_id} seed={seed} k={k} symbol_size={symbol_size} \
             loss_pattern={loss_pattern} outcome={outcome} \
             artifact_path=artifacts/raptorq_b2_tuple_scenarios_v1.json \
             fixture_ref=RQ-B2-TUPLE-V1 \
             repro_cmd='rch exec -- cargo test -p asupersync --lib \
             repair_equation_rfc6330 -- --nocapture'"
        )
    }

    fn to_unit_decode_stats(k: usize, dropped: usize, stats: &DecodeStats) -> UnitDecodeStats {
        UnitDecodeStats {
            k,
            loss_pct: dropped.saturating_mul(100) / k.max(1),
            dropped,
            peeled: stats.peeled,
            inactivated: stats.inactivated,
            gauss_ops: stats.gauss_ops,
            pivots: stats.pivots_selected,
            peel_queue_pushes: stats.peel_queue_pushes,
            peel_queue_pops: stats.peel_queue_pops,
            peel_frontier_peak: stats.peel_frontier_peak,
            dense_core_rows: stats.dense_core_rows,
            dense_core_cols: stats.dense_core_cols,
            dense_core_dropped_rows: stats.dense_core_dropped_rows,
            fallback_reason: stats
                .hard_regime_conservative_fallback_reason
                .or(stats.peeling_fallback_reason)
                .unwrap_or("none")
                .to_string(),
            hard_regime_activated: stats.hard_regime_activated,
            hard_regime_branch: stats.hard_regime_branch.unwrap_or("none").to_string(),
            hard_regime_fallbacks: stats.hard_regime_fallbacks,
            conservative_fallback_reason: stats
                .hard_regime_conservative_fallback_reason
                .unwrap_or("none")
                .to_string(),
            governance: stats.governance.as_ref().map(UnitGovernanceDecision::from),
        }
    }

    fn emit_decoder_unit_log(
        scenario_id: &str,
        seed: u64,
        parameter_set: &str,
        outcome: &str,
        repro_command: &str,
        stats: Option<UnitDecodeStats>,
    ) -> String {
        let mut entry = UnitLogEntry::new(
            scenario_id,
            seed,
            parameter_set,
            "replay:rq-track-c-decoder-unit-v1",
            repro_command,
            outcome,
        )
        .with_artifact_path("artifacts/raptorq_track_c_decoder_unit_v1.json");
        if let Some(stats) = stats {
            entry = entry.with_decode_stats(stats);
        }

        let json = entry.to_json().expect("serialize decoder unit log entry");
        let violations = validate_unit_log_json(&json);
        let context = entry.to_context_string();
        assert!(
            violations.is_empty(),
            "{context}: unit log schema violations: {violations:?}"
        );
        json
    }

    fn decode_stats_snapshot(
        scenario: &str,
        k: usize,
        symbol_size: usize,
        seed: u64,
        dropped: usize,
        received_symbols: usize,
        result: &DecodeResult,
    ) -> serde_json::Value {
        json!({
            "scenario": scenario,
            "k": k,
            "symbol_size": symbol_size,
            "seed": seed,
            "received_symbols": received_symbols,
            "decoded_source_symbols": result.source.len(),
            "intermediate_symbols": result.intermediate.len(),
            "stats": serde_json::to_value(to_unit_decode_stats(k, dropped, &result.stats))
                .expect("serialize decode stats snapshot"),
        })
    }

    #[test]
    fn dense_col_index_map_handles_sparse_columns() {
        let unsolved = vec![2, 7, 11];
        let col_to_dense = build_dense_col_index_map(&unsolved);

        assert_eq!(dense_col_index(&col_to_dense, 2), Some(0));
        assert_eq!(dense_col_index(&col_to_dense, 7), Some(1));
        assert_eq!(dense_col_index(&col_to_dense, 11), Some(2));
        assert_eq!(dense_col_index(&col_to_dense, 3), None);
        assert_eq!(dense_col_index(&col_to_dense, 99), None);
    }

    #[test]
    fn sparse_first_dense_columns_orders_by_support_then_column() {
        let equations = vec![
            Equation::new(vec![7, 11], vec![Gf256::ONE, Gf256::ONE]),
            Equation::new(vec![2, 7], vec![Gf256::ONE, Gf256::ONE]),
            Equation::new(vec![7], vec![Gf256::ONE]),
            Equation::new(vec![2], vec![Gf256::ONE]),
        ];
        let dense_rows = vec![0, 1, 2, 3];
        let unsolved = vec![7, 2, 11];

        let ordered = sparse_first_dense_columns(&equations, &dense_rows, &unsolved);

        // supports: col 11 -> 1, col 2 -> 2, col 7 -> 3
        assert_eq!(ordered, vec![11, 2, 7]);
    }

    #[test]
    fn sparse_first_dense_columns_sorted_fast_path_matches_expected() {
        let equations = vec![
            Equation::new(vec![7, 11], vec![Gf256::ONE, Gf256::ONE]),
            Equation::new(vec![2, 7], vec![Gf256::ONE, Gf256::ONE]),
            Equation::new(vec![7], vec![Gf256::ONE]),
            Equation::new(vec![2], vec![Gf256::ONE]),
        ];
        let dense_rows = vec![0, 1, 2, 3];
        let unsolved = vec![2, 7, 11];

        let ordered = sparse_first_dense_columns(&equations, &dense_rows, &unsolved);

        // supports: col 11 -> 1, col 2 -> 2, col 7 -> 3
        assert_eq!(ordered, vec![11, 2, 7]);
    }

    #[test]
    fn dense_col_index_map_uses_direct_representation_for_compact_range() {
        let unsolved = vec![1, 2, 4];
        let map = build_dense_col_index_map(&unsolved);

        assert!(matches!(map, DenseColIndexMap::Direct(_)));
        assert_eq!(dense_col_index(&map, 1), Some(0));
        assert_eq!(dense_col_index(&map, 2), Some(1));
        assert_eq!(dense_col_index(&map, 4), Some(2));
        assert_eq!(dense_col_index(&map, 3), None);
    }

    #[test]
    fn dense_col_index_map_uses_sorted_pairs_for_sparse_high_columns() {
        let unsolved = vec![2, 7, 10_000];
        let map = build_dense_col_index_map(&unsolved);

        assert!(matches!(map, DenseColIndexMap::SortedPairs(_)));
        assert_eq!(dense_col_index(&map, 2), Some(0));
        assert_eq!(dense_col_index(&map, 7), Some(1));
        assert_eq!(dense_col_index(&map, 10_000), Some(2));
        assert_eq!(dense_col_index(&map, 9_999), None);
    }

    #[test]
    fn dense_factor_signature_detects_equation_changes() {
        let equations_a = vec![Equation::new(vec![0, 1], vec![Gf256::ONE, Gf256::new(7)])];
        let equations_b = vec![Equation::new(vec![0, 1], vec![Gf256::ONE, Gf256::new(9)])];
        let dense_rows = vec![0];
        let unsolved = vec![0, 1];

        let sig_a = DenseFactorSignature::from_equations(&equations_a, &dense_rows, &unsolved);
        let sig_b = DenseFactorSignature::from_equations(&equations_b, &dense_rows, &unsolved);

        assert_ne!(sig_a, sig_b);
    }

    #[test]
    fn dense_factor_cache_requires_strict_signature_match() {
        let equations_a = vec![Equation::new(vec![0, 1], vec![Gf256::ONE, Gf256::new(7)])];
        let equations_b = vec![Equation::new(vec![0, 1], vec![Gf256::ONE, Gf256::new(9)])];
        let dense_rows = vec![0];
        let unsolved = vec![0, 1];

        let sig_a = DenseFactorSignature::from_equations(&equations_a, &dense_rows, &unsolved);
        let sig_b = DenseFactorSignature::from_equations(&equations_b, &dense_rows, &unsolved);

        let mut cache = DenseFactorCache::default();
        assert_eq!(
            cache.insert(
                sig_a.clone(),
                Arc::new(DenseFactorArtifact::new(vec![1, 0]))
            ),
            DenseFactorCacheResult::MissInserted
        );
        assert_eq!(
            cache.lookup(&sig_a),
            DenseFactorCacheLookup::Hit(Arc::new(DenseFactorArtifact::new(vec![1, 0])))
        );
        assert_eq!(cache.lookup(&sig_b), DenseFactorCacheLookup::MissNoEntry);
    }

    #[test]
    fn dense_factor_cache_detects_fingerprint_collision() {
        let equations_a = vec![Equation::new(vec![0, 1], vec![Gf256::ONE, Gf256::new(7)])];
        let equations_b = vec![Equation::new(vec![0, 1], vec![Gf256::ONE, Gf256::new(9)])];
        let dense_rows = vec![0];
        let unsolved = vec![0, 1];

        let sig_a = DenseFactorSignature::from_equations(&equations_a, &dense_rows, &unsolved);
        let mut sig_b = DenseFactorSignature::from_equations(&equations_b, &dense_rows, &unsolved);
        sig_b.fingerprint = sig_a.fingerprint;

        let mut cache = DenseFactorCache::default();
        assert_eq!(
            cache.insert(sig_a, Arc::new(DenseFactorArtifact::new(vec![1, 0]))),
            DenseFactorCacheResult::MissInserted
        );
        assert_eq!(
            cache.lookup(&sig_b),
            DenseFactorCacheLookup::MissFingerprintCollision
        );
    }

    #[test]
    fn dense_factor_cache_evicts_oldest_entry_at_capacity() {
        let mut cache = DenseFactorCache::default();
        let mut first_signature = None;

        for idx in 0..=DENSE_FACTOR_CACHE_CAPACITY {
            let signature = DenseFactorSignature {
                fingerprint: idx as u64,
                unsolved: vec![idx],
                row_offsets: vec![1],
                row_terms_flat: vec![(idx, 1)],
            };
            if idx == 0 {
                first_signature = Some(signature.clone());
            }
            let expected = if idx + 1 > DENSE_FACTOR_CACHE_CAPACITY {
                DenseFactorCacheResult::MissEvicted
            } else {
                DenseFactorCacheResult::MissInserted
            };
            assert_eq!(
                cache.insert(signature, Arc::new(DenseFactorArtifact::new(vec![idx]))),
                expected
            );
        }

        assert_eq!(cache.len(), DENSE_FACTOR_CACHE_CAPACITY);
        assert_eq!(
            cache.lookup(&first_signature.expect("first signature recorded")),
            DenseFactorCacheLookup::MissNoEntry
        );
    }

    #[test]
    fn hybrid_cost_model_prefers_sparse_for_low_support() {
        assert!(should_use_sparse_row_update(3, 8));
        assert!(should_use_sparse_row_update(6, 10));
        assert!(!should_use_sparse_row_update(7, 10));
        assert!(!should_use_sparse_row_update(1, 0));
    }

    #[test]
    fn pivot_nonzero_columns_returns_stable_sorted_positions() {
        let row = vec![
            Gf256::ZERO,
            Gf256::ONE,
            Gf256::ZERO,
            Gf256::ONE,
            Gf256::ONE,
            Gf256::ZERO,
        ];
        let cols = pivot_nonzero_columns(&row, row.len());
        assert_eq!(cols, vec![1, 3, 4]);
    }

    #[test]
    fn sparse_update_columns_if_beneficial_matches_threshold() {
        // For n_cols=10 and ratio 3/5, sparse path should accept up to 6 non-zero entries.
        let row_sparse = vec![
            Gf256::ONE,
            Gf256::ONE,
            Gf256::ZERO,
            Gf256::ONE,
            Gf256::ZERO,
            Gf256::ONE,
            Gf256::ONE,
            Gf256::ONE,
            Gf256::ZERO,
            Gf256::ZERO,
        ];
        let row_dense = vec![
            Gf256::ONE,
            Gf256::ONE,
            Gf256::ONE,
            Gf256::ONE,
            Gf256::ONE,
            Gf256::ONE,
            Gf256::ONE,
            Gf256::ZERO,
            Gf256::ZERO,
            Gf256::ZERO,
        ];

        let sparse_cols = sparse_update_columns_if_beneficial(&row_sparse, 10)
            .expect("row_sparse should take sparse update path");
        assert_eq!(sparse_cols, vec![0, 1, 3, 5, 6, 7]);
        assert!(sparse_update_columns_if_beneficial(&row_dense, 10).is_none());
    }

    fn make_source_data(k: usize, symbol_size: usize) -> Vec<Vec<u8>> {
        (0..k)
            .map(|i| {
                (0..symbol_size)
                    .map(|j| ((i * 37 + j * 13 + 7) % 256) as u8)
                    .collect()
            })
            .collect()
    }

    /// Helper to create received symbols for source data using proper LT equations.
    fn make_received_source(
        decoder: &InactivationDecoder,
        source: &[Vec<u8>],
    ) -> Vec<ReceivedSymbol> {
        let source_eqs = decoder.all_source_equations();
        source
            .iter()
            .enumerate()
            .map(|(i, data)| {
                let (cols, coefs) = source_eqs[i].clone();
                ReceivedSymbol {
                    esi: i as u32,
                    is_source: true,
                    columns: cols,
                    coefficients: coefs,
                    data: data.clone(),
                }
            })
            .collect()
    }

    /// Build repair symbol bytes by XOR-folding encoder intermediate symbols.
    fn build_repair_from_intermediate(
        encoder: &SystematicEncoder,
        columns: &[usize],
        symbol_size: usize,
    ) -> Vec<u8> {
        let mut out = vec![0u8; symbol_size];
        for &col in columns {
            for (dst, src) in out.iter_mut().zip(encoder.intermediate_symbol(col)) {
                *dst ^= *src;
            }
        }
        out
    }

    #[test]
    fn decode_all_source_symbols() {
        let k = 8;
        let symbol_size = 32;
        let seed = 42u64;

        let source = make_source_data(k, symbol_size);
        let decoder = InactivationDecoder::new(k, symbol_size, seed);

        // Start with constraint symbols (LDPC + HDPC with zero data)
        let mut received = decoder.constraint_symbols();

        // Add all source symbols with proper LT equations
        received.extend(make_received_source(&decoder, &source));

        // Add some repair symbols to reach L
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let l = decoder.params().l;
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let result = decoder.decode(&received).expect("decode should succeed");

        // Verify source symbols match
        for (i, original) in source.iter().enumerate() {
            assert_eq!(&result.source[i], original, "source symbol {i} mismatch");
        }
    }

    #[test]
    fn decode_mixed_source_and_repair() {
        let k = 8;
        let symbol_size = 32;
        let seed = 42u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        // Start with constraint symbols
        let mut received = decoder.constraint_symbols();

        // Get proper source equations
        let source_eqs = decoder.all_source_equations();

        // First half source symbols with proper LT equations
        for i in 0..(k / 2) {
            let (cols, coefs) = source_eqs[i].clone();
            received.push(ReceivedSymbol {
                esi: i as u32,
                is_source: true,
                columns: cols,
                coefficients: coefs,
                data: source[i].clone(),
            });
        }

        // Fill with repair symbols
        for esi in (k as u32)..(l as u32 + k as u32 / 2) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let result = decoder.decode(&received).expect("decode should succeed");

        for (i, original) in source.iter().enumerate() {
            assert_eq!(&result.source[i], original, "source symbol {i} mismatch");
        }
    }

    #[test]
    fn decode_repair_only() {
        let k = 4;
        let symbol_size = 16;
        let seed = 99u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        // Start with constraint symbols
        let mut received = decoder.constraint_symbols();

        // Receive only repair symbols (need at least L)
        for esi in (k as u32)..(k as u32 + l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let result = decoder.decode(&received).expect("decode should succeed");

        for (i, original) in source.iter().enumerate() {
            assert_eq!(&result.source[i], original, "source symbol {i} mismatch");
        }
    }

    #[test]
    fn decode_repair_only_hits_dense_factor_cache_on_second_run() {
        let k = 4;
        let symbol_size = 16;
        let seed = 99u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        for esi in (k as u32)..(k as u32 + l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let first = decoder
            .decode(&received)
            .expect("first decode should succeed");
        let second = decoder
            .decode(&received)
            .expect("second decode should succeed");

        assert!(
            first.stats.factor_cache_misses >= 1,
            "first decode should populate dense-factor cache"
        );
        assert!(
            second.stats.factor_cache_hits >= 1,
            "second decode should hit dense-factor cache"
        );
        assert_eq!(
            first.stats.factor_cache_last_reason,
            Some("cache_miss_rebuild")
        );
        assert_eq!(
            second.stats.factor_cache_last_reason,
            Some("signature_match_reuse")
        );
        assert_eq!(first.stats.factor_cache_last_reuse_eligible, Some(false));
        assert_eq!(second.stats.factor_cache_last_reuse_eligible, Some(true));
        assert_eq!(
            first.stats.factor_cache_last_key, second.stats.factor_cache_last_key,
            "repeated burst decode should probe the same structural cache key",
        );
        assert_eq!(
            second.stats.factor_cache_capacity,
            DENSE_FACTOR_CACHE_CAPACITY
        );
        assert!(
            second.stats.factor_cache_entries <= second.stats.factor_cache_capacity,
            "cache occupancy must remain bounded by configured capacity"
        );
    }

    #[test]
    fn decode_burst_loss_payload_recovers_with_repair_overhead() {
        let k = 8;
        let symbol_size = 32;
        let seed = 2026u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut payload = make_received_source(&decoder, &source);
        for esi in (k as u32)..((k + l + 8) as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            payload.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        // Deterministic contiguous burst drop in payload symbols.
        payload.drain(3..7);

        let mut received = decoder.constraint_symbols();
        received.extend(payload);
        assert!(
            received.len() >= l,
            "burst-loss scenario must still provide at least L equations"
        );

        let first = decoder
            .decode(&received)
            .expect("burst-loss decode should recover source symbols");
        let second = InactivationDecoder::new(k, symbol_size, seed)
            .decode(&received)
            .expect("burst-loss replay decode should recover source symbols");

        assert_eq!(first.source, source);
        assert_eq!(second.source, source);
        assert_eq!(
            first.source, second.source,
            "replay should be deterministic"
        );
        assert_eq!(first.stats.peeled, second.stats.peeled);
        assert_eq!(first.stats.inactivated, second.stats.inactivated);
    }

    #[test]
    fn decode_statistics_output_scrubbed() {
        let k = 8;
        let symbol_size = 32;

        let happy_seed = 42u64;
        let happy_source = make_source_data(k, symbol_size);
        let happy_encoder = SystematicEncoder::new(&happy_source, symbol_size, happy_seed).unwrap();
        let happy_decoder = InactivationDecoder::new(k, symbol_size, happy_seed);
        let happy_l = happy_decoder.params().l;

        let mut happy_received = happy_decoder.constraint_symbols();
        happy_received.extend(make_received_source(&happy_decoder, &happy_source));
        for esi in (k as u32)..(happy_l as u32) {
            let (cols, coefs) = happy_decoder.repair_equation(esi);
            let repair_data = happy_encoder.repair_symbol(esi);
            happy_received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }
        let happy_result = happy_decoder
            .decode(&happy_received)
            .expect("happy-path decode should succeed");

        let degraded_seed = 2026u64;
        let degraded_source = make_source_data(k, symbol_size);
        let degraded_encoder =
            SystematicEncoder::new(&degraded_source, symbol_size, degraded_seed).unwrap();
        let degraded_decoder = InactivationDecoder::new(k, symbol_size, degraded_seed);
        let degraded_l = degraded_decoder.params().l;

        let mut degraded_payload = make_received_source(&degraded_decoder, &degraded_source);
        for esi in (k as u32)..((k + degraded_l + 8) as u32) {
            let (cols, coefs) = degraded_decoder.repair_equation(esi);
            let repair_data = degraded_encoder.repair_symbol(esi);
            degraded_payload.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }
        degraded_payload.drain(3..7);

        let mut degraded_received = degraded_decoder.constraint_symbols();
        degraded_received.extend(degraded_payload);
        let degraded_result = degraded_decoder
            .decode(&degraded_received)
            .expect("degraded decode should recover source symbols");

        assert_json_snapshot!(
            "decode_statistics_output_scrubbed",
            json!({
                "happy_path": decode_stats_snapshot(
                    "happy_path",
                    k,
                    symbol_size,
                    happy_seed,
                    0,
                    happy_received.len(),
                    &happy_result,
                ),
                "degraded_burst_loss": decode_stats_snapshot(
                    "degraded_burst_loss",
                    k,
                    symbol_size,
                    degraded_seed,
                    4,
                    degraded_received.len(),
                    &degraded_result,
                ),
            })
        );
    }

    #[test]
    fn decode_corrupted_repair_symbol_reports_corrupt_output() {
        let k = 8;
        let symbol_size = 32;
        let seed = 0u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        received.extend(make_received_source(&decoder, &source));
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let tampered = received
            .iter_mut()
            .find(|sym| !sym.is_source && sym.esi >= k as u32)
            .expect("must include at least one repair symbol");
        tampered.data[0] ^= 0x5A;

        let err = decoder
            .decode(&received)
            .expect_err("corrupted repair symbol must fail");
        assert!(
            matches!(err, DecodeError::SingularMatrix { .. })
                || matches!(err, DecodeError::CorruptDecodedOutput { .. }),
            "expected corruption or inconsistency, got: {err:?}"
        );
    }

    #[test]
    fn decode_with_proof_corrupted_repair_symbol_reports_failure_reason() {
        let k = 8;
        let symbol_size = 32;
        let seed = 0u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        received.extend(make_received_source(&decoder, &source));
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let tampered = received
            .iter_mut()
            .find(|sym| !sym.is_source && sym.esi >= k as u32)
            .expect("must include at least one repair symbol");
        tampered.data[0] ^= 0xA5;

        let (err, proof) = decoder
            .decode_with_proof(&received, ObjectId::new_for_test(9090), 0)
            .expect_err("corrupted repair symbol should fail with proof witness");
        assert!(
            matches!(err, DecodeError::SingularMatrix { .. })
                || matches!(err, DecodeError::CorruptDecodedOutput { .. }),
            "expected corruption or inconsistency, got: {err:?}"
        );
        assert!(
            matches!(
                proof.outcome,
                crate::raptorq::proof::ProofOutcome::Failure {
                    reason: FailureReason::SingularMatrix { .. }
                }
            ) || matches!(
                proof.outcome,
                crate::raptorq::proof::ProofOutcome::Failure {
                    reason: FailureReason::CorruptDecodedOutput { .. }
                }
            ),
            "expected corruption or inconsistency in proof"
        );
    }

    #[test]
    fn decode_wavefront_corrupted_repair_symbol_matches_direct_and_proof_failure() {
        let k = 8;
        let symbol_size = 32;
        let seed = 1u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        received.extend(make_received_source(&decoder, &source));
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let tampered = received
            .iter_mut()
            .find(|sym| !sym.is_source && sym.esi >= k as u32)
            .expect("must include at least one repair symbol");
        tampered.data[0] ^= 0x3C;

        let direct = decoder
            .decode(&received)
            .expect_err("corrupted repair symbol must fail in direct decode");
        let wavefront = decoder
            .decode_wavefront(&received, 3)
            .expect_err("corrupted repair symbol must fail in wavefront decode");
        let (proof_err, proof) = decoder
            .decode_with_proof(&received, ObjectId::new_for_test(9191), 0)
            .expect_err("corrupted repair symbol must fail in proof decode");

        assert_eq!(
            direct, wavefront,
            "wavefront decode must report the same failure as direct decode"
        );
        assert_eq!(
            direct, proof_err,
            "proof decode must report the same failure as direct decode"
        );
        assert!(
            matches!(direct, DecodeError::SingularMatrix { .. })
                || matches!(direct, DecodeError::CorruptDecodedOutput { .. }),
            "expected corruption or inconsistency, got: {direct:?}"
        );
        assert!(
            matches!(
                proof.outcome,
                crate::raptorq::proof::ProofOutcome::Failure {
                    reason: FailureReason::SingularMatrix { .. }
                }
            ) || matches!(
                proof.outcome,
                crate::raptorq::proof::ProofOutcome::Failure {
                    reason: FailureReason::CorruptDecodedOutput { .. }
                }
            ),
            "expected corruption or inconsistency in proof"
        );
    }

    #[test]
    fn decode_insufficient_symbols_fails() {
        let k = 8;
        let symbol_size = 32;
        let seed = 42u64;

        let source = make_source_data(k, symbol_size);
        let decoder = InactivationDecoder::new(k, symbol_size, seed);

        // Only provide a couple source symbols - not enough to solve
        let source_eqs = decoder.all_source_equations();
        let received: Vec<ReceivedSymbol> = (0..2)
            .map(|i| {
                let (cols, coefs) = source_eqs[i].clone();
                ReceivedSymbol {
                    esi: i as u32,
                    is_source: true,
                    columns: cols,
                    coefficients: coefs,
                    data: source[i].clone(),
                }
            })
            .collect();

        let err = decoder.decode(&received).unwrap_err();
        assert!(matches!(err, DecodeError::InsufficientSymbols { .. }));

        let dropped = k.saturating_sub(received.len());
        let parameter_set = format!("k={k},symbol_size={symbol_size},dropped={dropped}");
        let log_json = emit_decoder_unit_log(
            "RQ-C-LOG-FAIL-INSUFFICIENT-001",
            seed,
            &parameter_set,
            "decode_failure",
            "rch exec -- cargo test -p asupersync --lib raptorq::decoder::tests::decode_insufficient_symbols_fails -- --nocapture",
            None,
        );
        assert!(
            log_json.contains("\"scenario_id\":\"RQ-C-LOG-FAIL-INSUFFICIENT-001\""),
            "failure log must retain deterministic scenario id"
        );
        assert!(
            log_json
                .contains("\"artifact_path\":\"artifacts/raptorq_track_c_decoder_unit_v1.json\""),
            "failure log must include artifact pointer"
        );
    }

    #[test]
    fn decode_sources_only_auto_synthesizes_padded_lt_rows() {
        let k = 50;
        let symbol_size = 32;
        let seed = 77u64;

        let source = make_source_data(k, symbol_size);
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        assert!(
            decoder.params().k_prime > k,
            "test requires a padded systematic parameter set"
        );

        let mut received = decoder.constraint_symbols();
        received.extend(make_received_source(&decoder, &source));

        let result = decoder
            .decode(&received)
            .expect("decoder should synthesize K..K' zero LT rows");

        for (idx, original) in source.iter().enumerate() {
            assert_eq!(
                &result.source[idx], original,
                "source symbol {idx} mismatch after synthesized padding rows"
            );
        }
    }

    #[test]
    fn wavefront_decode_sources_only_auto_synthesizes_padded_lt_rows() {
        let k = 50;
        let symbol_size = 32;
        let seed = 79u64;

        let source = make_source_data(k, symbol_size);
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        assert!(
            decoder.params().k_prime > k,
            "test requires a padded systematic parameter set"
        );

        let mut received = decoder.constraint_symbols();
        received.extend(make_received_source(&decoder, &source));

        let sequential = decoder
            .decode(&received)
            .expect("sequential decoder should synthesize K..K' zero LT rows");

        for &batch_size in &[1, 7, received.len()] {
            let wavefront = decoder
                .decode_wavefront(&received, batch_size)
                .unwrap_or_else(|_| panic!("wavefront decode batch_size={batch_size}"));
            assert_eq!(
                wavefront.source, sequential.source,
                "wavefront decode must match sequential decode for padded K..K' rows"
            );
        }
    }

    #[test]
    fn systematic_index_table_sources_only_decode_succeeds_across_representative_k_values() {
        let symbol_size = 8;
        let representative_k_values = [1usize, 2, 3, 4, 5, 8, 16, 31, 32, 33, 63, 64];

        for &k in &representative_k_values {
            let seed = 10_000u64 + k as u64;
            let source = make_source_data(k, symbol_size);
            let decoder = InactivationDecoder::new(k, symbol_size, seed);

            let mut received = decoder.constraint_symbols();
            received.extend(make_received_source(&decoder, &source));

            let decoded = decoder
                .decode(&received)
                .unwrap_or_else(|_| panic!("sources-only decode must succeed for k={k}"));

            assert_eq!(
                decoded.source, source,
                "systematic-table decode mismatch for k={k}"
            );
        }
    }

    #[test]
    fn extra_repair_symbols_do_not_reduce_decode_success_rate() {
        let k = 12;
        let symbol_size = 16;
        let seed = 0x5EED_0204u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut baseline = decoder.constraint_symbols();
        for esi in (k as u32)..(k as u32 + l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            baseline.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let baseline_decoded = decoder
            .decode(&baseline)
            .expect("repair-only baseline decode must succeed");

        let mut with_extra_repair = baseline.clone();
        for esi in (k as u32 + l as u32)..(k as u32 + l as u32 + 4) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            with_extra_repair.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let extra_decoded = decoder
            .decode(&with_extra_repair)
            .expect("adding valid repair symbols must not break decode success");

        assert_eq!(
            extra_decoded.source, baseline_decoded.source,
            "extra repair symbols must not change recovered source output"
        );

        let wavefront_extra = decoder
            .decode_wavefront(&with_extra_repair, 3)
            .expect("wavefront decode must remain successful with extra repair symbols");
        assert_eq!(
            wavefront_extra.source, baseline_decoded.source,
            "wavefront decode must recover the same output after extra repair symbols are added"
        );
    }

    #[test]
    fn decode_rejects_source_esi_in_padded_range() {
        let k = 50;
        let symbol_size = 32;
        let seed = 91u64;

        let source = make_source_data(k, symbol_size);
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        assert!(
            decoder.params().k_prime > k,
            "test requires a padded systematic parameter set"
        );

        let mut received = decoder.constraint_symbols();
        received.extend(make_received_source(&decoder, &source));
        received.push(ReceivedSymbol::source(k as u32, vec![0xA5; symbol_size]));

        let err = decoder.decode(&received).unwrap_err();
        assert_eq!(
            err,
            DecodeError::SourceEsiOutOfRange {
                esi: k as u32,
                max_valid: k,
            }
        );
        assert!(err.is_unrecoverable());
    }

    #[test]
    fn decode_symbol_equation_arity_mismatch_fails() {
        let k = 8;
        let symbol_size = 32;
        let seed = 42u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        received.extend(make_received_source(&decoder, &source));
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        received[0].columns.push(0);
        let esi = received[0].esi;
        let columns = received[0].columns.len();
        let coefficients = received[0].coefficients.len();

        let err = decoder.decode(&received).unwrap_err();
        assert_eq!(
            err,
            DecodeError::SymbolEquationArityMismatch {
                esi,
                columns,
                coefficients
            }
        );
    }

    #[test]
    fn decode_with_proof_symbol_equation_arity_mismatch_reports_failure_reason() {
        let k = 8;
        let symbol_size = 32;
        let seed = 43u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        received.extend(make_received_source(&decoder, &source));
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        received[0].columns.push(0);
        let esi = received[0].esi;
        let columns = received[0].columns.len();
        let coefficients = received[0].coefficients.len();

        let (err, proof) = decoder
            .decode_with_proof(&received, ObjectId::new_for_test(4242), 0)
            .unwrap_err();
        assert_eq!(
            err,
            DecodeError::SymbolEquationArityMismatch {
                esi,
                columns,
                coefficients
            }
        );
        assert!(matches!(
            proof.outcome,
            crate::raptorq::proof::ProofOutcome::Failure {
                reason: FailureReason::SymbolEquationArityMismatch {
                    esi: e,
                    columns: c,
                    coefficients: coef_count
                }
            } if e == esi && c == columns && coef_count == coefficients
        ));
    }

    #[test]
    fn decode_column_index_out_of_range_fails_unrecoverably() {
        let k = 8;
        let symbol_size = 32;
        let seed = 44u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        received.extend(make_received_source(&decoder, &source));
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let esi = received[0].esi;
        let invalid_column = l;
        received[0].columns[0] = invalid_column;

        let err = decoder.decode(&received).unwrap_err();
        assert_eq!(
            err,
            DecodeError::ColumnIndexOutOfRange {
                esi,
                column: invalid_column,
                max_valid: l
            }
        );
        assert!(err.is_unrecoverable());
        assert!(!err.is_recoverable());
    }

    #[test]
    fn decode_with_proof_column_index_out_of_range_reports_failure_reason() {
        let k = 8;
        let symbol_size = 32;
        let seed = 45u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        received.extend(make_received_source(&decoder, &source));
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let esi = received[1].esi;
        let invalid_column = l + 2;
        received[1].columns[0] = invalid_column;

        let (err, proof) = decoder
            .decode_with_proof(&received, ObjectId::new_for_test(5252), 0)
            .unwrap_err();
        assert_eq!(
            err,
            DecodeError::ColumnIndexOutOfRange {
                esi,
                column: invalid_column,
                max_valid: l
            }
        );
        assert!(matches!(
            proof.outcome,
            crate::raptorq::proof::ProofOutcome::Failure {
                reason: FailureReason::ColumnIndexOutOfRange {
                    esi: e,
                    column,
                    max_valid
                }
            } if e == esi && column == invalid_column && max_valid == l
        ));
    }

    #[test]
    fn decode_deterministic() {
        let k = 6;
        let symbol_size = 24;
        let seed = 77u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        // Build received symbols: constraints + source + repair
        let mut received = decoder.constraint_symbols();
        received.extend(make_received_source(&decoder, &source));

        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        // Decode twice
        let result1 = decoder.decode(&received).unwrap();
        let result2 = decoder.decode(&received).unwrap();

        // Results must be identical
        assert_eq!(result1.source, result2.source);
        assert_eq!(result1.stats.peeled, result2.stats.peeled);
        assert_eq!(result1.stats.inactivated, result2.stats.inactivated);
        assert_eq!(
            result1.stats.peel_queue_pushes, result2.stats.peel_queue_pushes,
            "peel queue push accounting must be deterministic"
        );
        assert_eq!(
            result1.stats.peel_queue_pops, result2.stats.peel_queue_pops,
            "peel queue pop accounting must be deterministic"
        );
        assert_eq!(
            result1.stats.dense_core_rows, result2.stats.dense_core_rows,
            "dense-core row extraction must be deterministic"
        );
        assert_eq!(
            result1.stats.dense_core_cols, result2.stats.dense_core_cols,
            "dense-core column extraction must be deterministic"
        );

        let parameter_set = format!("k={k},symbol_size={symbol_size},dropped=0");
        let log_json = emit_decoder_unit_log(
            "RQ-C-LOG-SUCCESS-DET-001",
            seed,
            &parameter_set,
            "ok",
            "rch exec -- cargo test -p asupersync --lib raptorq::decoder::tests::decode_deterministic -- --nocapture",
            Some(to_unit_decode_stats(k, 0, &result1.stats)),
        );
        assert!(
            log_json.contains("\"outcome\":\"ok\""),
            "success log should preserve deterministic outcome marker"
        );
        assert!(
            log_json.contains("\"repro_command\":\"rch exec --"),
            "success log must keep remote replay command"
        );
    }

    #[test]
    fn stats_track_peeling_and_inactivation() {
        // Use k=8 for more robust coverage (k=4 with certain seeds can cause
        // singular matrices due to sparse LT equation coverage)
        let k = 8;
        let symbol_size = 32;
        let seed = 42u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        // Start with constraint symbols (LDPC + HDPC with zero data)
        let mut received = decoder.constraint_symbols();

        // Add all source symbols with proper LT equations
        received.extend(make_received_source(&decoder, &source));

        // Add repair symbols to provide enough equations for full coverage
        for esi in (k as u32)..(l as u32 + 2) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let result = decoder.decode(&received).unwrap();

        // At least some peeling should occur (LDPC/HDPC constraints + some equations)
        // Note: with proper LT equations, peeling behavior may vary
        assert!(
            result.stats.peeled > 0 || result.stats.inactivated > 0,
            "expected some peeling or inactivation"
        );
        assert!(
            result.stats.peel_queue_pushes >= result.stats.peel_queue_pops,
            "queue pushes should dominate or equal pops"
        );
        assert!(
            result.stats.peel_frontier_peak > 0,
            "peeling queue should observe non-zero frontier depth"
        );
        if result.stats.inactivated > 0 {
            assert!(
                result.stats.dense_core_cols > 0,
                "dense core should contain unsolved columns when inactivation occurs"
            );
            assert_eq!(
                result.stats.peeling_fallback_reason,
                Some("peeling_exhausted_to_dense_core"),
                "fallback reason should be explicit when we transition to dense core"
            );
        }
    }

    #[test]
    fn repair_equation_rfc6330_deterministic() {
        let k = 8;
        let symbol_size = 32;
        let seed = 42u64;
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let (c1, k1) = decoder.repair_equation_rfc6330(17);
        let (c2, k2) = decoder.repair_equation_rfc6330(17);
        let context = rfc_eq_context(
            "RQ-B2-DECODER-EQ-DET-001",
            seed,
            k,
            symbol_size,
            "none",
            "deterministic_replay",
        );
        assert_eq!(c1, c2, "{context} column replay mismatch");
        assert_eq!(k1, k2, "{context} coefficient replay mismatch");
    }

    #[test]
    fn repair_equation_rfc6330_indices_within_bounds() {
        let k = 10;
        let symbol_size = 32;
        let seed = 7u64;
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let params = decoder.params();
        let upper = params.w + params.p;
        let context = rfc_eq_context(
            "RQ-B2-DECODER-EQ-BOUNDS-001",
            seed,
            k,
            symbol_size,
            "none",
            "index_bounds",
        );
        for esi in 0..32u32 {
            let (cols, coefs) = decoder.repair_equation_rfc6330(esi);
            assert_eq!(
                cols.len(),
                coefs.len(),
                "{context} len mismatch for esi={esi}"
            );
            assert!(!cols.is_empty(), "{context} empty row for esi={esi}");
            assert!(
                cols.iter().all(|col| *col < upper),
                "{context} out-of-range column for esi={esi}"
            );
        }
    }

    #[test]
    fn repair_equation_rfc6330_includes_pi_domain_entries() {
        let k = 12;
        let symbol_size = 64;
        let seed = 99u64;
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let params = decoder.params();
        let w = params.w;
        let mut saw_pi = false;
        for esi in 0..128u32 {
            let (cols, _) = decoder.repair_equation_rfc6330(esi);
            if cols.iter().any(|c| *c >= w) {
                saw_pi = true;
                break;
            }
        }
        let context = rfc_eq_context(
            "RQ-B2-DECODER-EQ-PI-001",
            seed,
            k,
            symbol_size,
            "none",
            "pi_domain_coverage",
        );
        assert!(saw_pi, "{context} expected PI-domain index in sample");
    }

    #[test]
    fn repair_equation_rfc6330_matches_systematic_params_helper() {
        let scenarios = [
            ("RQ-C1-PARITY-001", 8usize, 32usize, 42u64),
            ("RQ-C1-PARITY-002", 16usize, 64usize, 77u64),
            ("RQ-C1-PARITY-003", 32usize, 128usize, 1234u64),
        ];

        for (scenario_id, k, symbol_size, seed) in scenarios {
            let decoder = InactivationDecoder::new(k, symbol_size, seed);
            let params = SystematicParams::for_source_block(k, symbol_size);
            for esi in 0..64u32 {
                let decoder_eq = decoder.repair_equation_rfc6330(esi);
                let shared_eq = params.rfc_repair_equation(esi);
                let context = rfc_eq_context(
                    scenario_id,
                    seed,
                    k,
                    symbol_size,
                    "none",
                    "decoder_params_parity",
                );
                assert_eq!(
                    decoder_eq, shared_eq,
                    "{context} decoder/params equation mismatch for esi={esi}"
                );
            }
        }
    }

    #[test]
    fn decode_roundtrip_with_rfc_tuple_repair_equations() {
        let k = 8;
        let symbol_size = 32;
        let seed = 42u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed)
            .expect("RQ-C1-E2E-001 encoder setup should succeed");
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        // Start with constraint symbols + systematic source symbols.
        let mut received = decoder.constraint_symbols();
        received.extend(make_received_source(&decoder, &source));

        // Add RFC tuple-driven repair equations and synthesize repair bytes directly
        // from intermediate symbols to validate decoder-side equation reconstruction.
        for esi in (k as u32)..(l as u32) {
            let (columns, coefficients) = decoder.repair_equation_rfc6330(esi);
            let repair_data = build_repair_from_intermediate(&encoder, &columns, symbol_size);
            received.push(ReceivedSymbol::repair(
                esi,
                columns,
                coefficients,
                repair_data,
            ));
        }

        let result = decoder.decode(&received).unwrap_or_else(|err| {
            let context = rfc_eq_context(
                "RQ-C1-E2E-001",
                seed,
                k,
                symbol_size,
                "none",
                "decode_failed",
            );
            panic!("{context} unexpected decode failure: {err:?}");
        });

        for (i, original) in source.iter().enumerate() {
            let context = rfc_eq_context(
                "RQ-C1-E2E-001",
                seed,
                k,
                symbol_size,
                "none",
                "roundtrip_compare",
            );
            assert_eq!(
                &result.source[i], original,
                "{context} source symbol mismatch at index {i}"
            );
        }
    }

    #[test]
    fn verify_decoded_output_detects_corruption_witness() {
        let k = 6;
        let symbol_size = 16;
        let seed = 46u64;
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let source = make_source_data(k, symbol_size);
        let received = make_received_source(&decoder, &source);

        let mut intermediate = vec![vec![0u8; symbol_size]; decoder.params().l];
        for (idx, src) in source.iter().enumerate() {
            intermediate[idx] = src.clone();
        }
        intermediate[0][0] ^= 0xA5;

        let err = decoder
            .verify_decoded_output(&received, &intermediate)
            .expect_err("corruption guard should reject inconsistent reconstruction");
        assert!(matches!(
            err,
            DecodeError::CorruptDecodedOutput {
                esi: 0,
                byte_index: 0,
                ..
            }
        ));
        assert!(err.is_unrecoverable());
    }

    #[test]
    fn failure_classification_is_explicit() {
        assert!(
            DecodeError::InsufficientSymbols {
                received: 1,
                required: 2
            }
            .is_recoverable()
        );
        assert!(DecodeError::SingularMatrix { row: 3 }.is_recoverable());
        assert!(
            DecodeError::SymbolSizeMismatch {
                expected: 8,
                actual: 7
            }
            .is_unrecoverable()
        );
        assert!(
            DecodeError::ColumnIndexOutOfRange {
                esi: 1,
                column: 99,
                max_valid: 12
            }
            .is_unrecoverable()
        );
        assert!(
            DecodeError::SourceEsiOutOfRange {
                esi: 12,
                max_valid: 8
            }
            .is_unrecoverable()
        );
        assert!(
            DecodeError::InvalidSourceSymbolEquation {
                esi: 3,
                expected_column: 3
            }
            .is_unrecoverable()
        );
        assert!(
            DecodeError::CorruptDecodedOutput {
                esi: 1,
                byte_index: 0,
                expected: 1,
                actual: 2
            }
            .is_unrecoverable()
        );
    }

    fn make_rank_deficient_state(
        params: &SystematicParams,
        symbol_size: usize,
        left_col: usize,
        right_col: usize,
    ) -> DecoderState {
        let equation = Equation::new(vec![left_col, right_col], vec![Gf256::ONE, Gf256::ONE]);
        let active_cols = [left_col, right_col].into_iter().collect();
        DecoderState {
            params: params.clone(),
            equations: vec![equation.clone(), equation],
            rhs: vec![vec![0x11; symbol_size], vec![0x22; symbol_size]],
            solved: vec![None; params.l],
            active_cols,
            inactive_cols: BTreeSet::new(),
            stats: DecodeStats::default(),
        }
    }

    fn make_underdetermined_dense_core_state(
        params: &SystematicParams,
        symbol_size: usize,
        left_col: usize,
        right_col: usize,
    ) -> DecoderState {
        let equation = Equation::new(vec![left_col, right_col], vec![Gf256::ONE, Gf256::ONE]);
        let active_cols = [left_col, right_col].into_iter().collect();
        DecoderState {
            params: params.clone(),
            equations: vec![equation],
            rhs: vec![vec![0x11; symbol_size]],
            solved: vec![None; params.l],
            active_cols,
            inactive_cols: BTreeSet::new(),
            stats: DecodeStats::default(),
        }
    }

    fn make_reordered_underdetermined_dense_core_state(
        params: &SystematicParams,
        symbol_size: usize,
        left_col: usize,
        middle_col: usize,
        right_col: usize,
    ) -> DecoderState {
        let eq_left_middle =
            Equation::new(vec![left_col, middle_col], vec![Gf256::ONE, Gf256::ONE]);
        let eq_middle_right =
            Equation::new(vec![middle_col, right_col], vec![Gf256::ONE, Gf256::ONE]);
        let active_cols = [left_col, middle_col, right_col].into_iter().collect();
        DecoderState {
            params: params.clone(),
            equations: vec![eq_left_middle, eq_middle_right],
            rhs: vec![vec![0x11; symbol_size], vec![0x22; symbol_size]],
            solved: vec![None; params.l],
            active_cols,
            inactive_cols: BTreeSet::new(),
            stats: DecodeStats::default(),
        }
    }

    fn make_pivot_tie_break_state(
        params: &SystematicParams,
        symbol_size: usize,
        left_col: usize,
        right_col: usize,
    ) -> DecoderState {
        let eq_left = Equation::new(vec![left_col], vec![Gf256::ONE]);
        let eq_mix = Equation::new(vec![left_col, right_col], vec![Gf256::ONE, Gf256::ONE]);
        let eq_right = Equation::new(vec![right_col], vec![Gf256::ONE]);
        let active_cols = [left_col, right_col].into_iter().collect();
        DecoderState {
            params: params.clone(),
            equations: vec![eq_left, eq_mix, eq_right],
            rhs: vec![
                vec![0x10; symbol_size],
                vec![0x30; symbol_size],
                vec![0x20; symbol_size],
            ],
            solved: vec![None; params.l],
            active_cols,
            inactive_cols: BTreeSet::new(),
            stats: DecodeStats::default(),
        }
    }

    fn make_inconsistent_overdetermined_state(
        params: &SystematicParams,
        symbol_size: usize,
        left_col: usize,
        right_col: usize,
    ) -> DecoderState {
        let eq_left = Equation::new(vec![left_col], vec![Gf256::ONE]);
        let eq_right = Equation::new(vec![right_col], vec![Gf256::ONE]);
        let eq_mix = Equation::new(vec![left_col, right_col], vec![Gf256::ONE, Gf256::ONE]);
        let active_cols = [left_col, right_col].into_iter().collect();
        DecoderState {
            params: params.clone(),
            equations: vec![eq_left, eq_right, eq_mix],
            rhs: vec![
                vec![0x10; symbol_size],
                vec![0x20; symbol_size],
                vec![0x31; symbol_size], // 0x10 ^ 0x20 = 0x30 => contradiction
            ],
            solved: vec![None; params.l],
            active_cols,
            inactive_cols: BTreeSet::new(),
            stats: DecodeStats::default(),
        }
    }

    fn make_dense_core_prunable_state(
        params: &SystematicParams,
        symbol_size: usize,
        left_col: usize,
        right_col: usize,
        empty_rhs_byte: u8,
    ) -> DecoderState {
        let eq_left = Equation::new(vec![left_col], vec![Gf256::ONE]);
        let eq_right = Equation::new(vec![right_col], vec![Gf256::ONE]);
        let eq_empty = Equation {
            terms: Vec::new(),
            used: false,
        };
        let active_cols = [left_col, right_col].into_iter().collect();
        DecoderState {
            params: params.clone(),
            equations: vec![eq_left, eq_right, eq_empty],
            rhs: vec![
                vec![0x10; symbol_size],
                vec![0x20; symbol_size],
                vec![empty_rhs_byte; symbol_size],
            ],
            solved: vec![None; params.l],
            active_cols,
            inactive_cols: BTreeSet::new(),
            stats: DecodeStats::default(),
        }
    }

    fn make_hard_regime_dense_state(
        params: &SystematicParams,
        symbol_size: usize,
        start_col: usize,
        width: usize,
    ) -> DecoderState {
        let cols: Vec<usize> = (start_col..start_col + width).collect();
        let mut equations = Vec::with_capacity(width);
        let mut rhs = Vec::with_capacity(width);

        // Upper-triangular dense system:
        // row i references cols[i..], so the matrix is full-rank while still dense.
        for i in 0..width {
            let row_cols = cols[i..].to_vec();
            let row_coefs = vec![Gf256::ONE; row_cols.len()];
            equations.push(Equation::new(row_cols, row_coefs));
            rhs.push(vec![(i as u8) + 1; symbol_size]);
        }

        DecoderState {
            params: params.clone(),
            equations,
            rhs,
            solved: vec![None; params.l],
            active_cols: cols.into_iter().collect(),
            inactive_cols: BTreeSet::new(),
            stats: DecodeStats::default(),
        }
    }

    fn make_block_schur_rank_deficient_state(
        params: &SystematicParams,
        symbol_size: usize,
        start_col: usize,
        width: usize,
    ) -> DecoderState {
        let cols: Vec<usize> = (start_col..start_col + width).collect();
        let mut equations = Vec::with_capacity(width);
        let mut rhs = Vec::with_capacity(width);

        for i in 0..width {
            equations.push(Equation::new(cols.clone(), vec![Gf256::ONE; cols.len()]));
            let rhs_byte = ((i % 255) as u8).saturating_add(1);
            rhs.push(vec![rhs_byte; symbol_size]);
        }

        DecoderState {
            params: params.clone(),
            equations,
            rhs,
            solved: vec![None; params.l],
            active_cols: cols.into_iter().collect(),
            inactive_cols: BTreeSet::new(),
            stats: DecodeStats::default(),
        }
    }

    #[test]
    fn singular_matrix_reports_original_column_id() {
        let decoder = InactivationDecoder::new(8, 16, 123);
        let params = decoder.params().clone();
        let mut state = make_rank_deficient_state(&params, 16, 3, 7);

        let err = decoder.inactivate_and_solve(&mut state).unwrap_err();
        assert_eq!(
            err,
            DecodeError::SingularMatrix { row: 7 },
            "rank-deficient failure should report original unsolved column id"
        );
    }

    #[test]
    fn underdetermined_dense_core_reports_singular_error() {
        let decoder = InactivationDecoder::new(8, 16, 512);
        let params = decoder.params().clone();
        let mut state = make_underdetermined_dense_core_state(&params, 16, 3, 7);

        let err = decoder.inactivate_and_solve(&mut state).unwrap_err();
        assert_eq!(
            err,
            DecodeError::SingularMatrix { row: 7 },
            "dense-core underdetermined systems should be classified as rank-deficient"
        );
    }

    #[test]
    fn underdetermined_dense_core_reports_witness_in_natural_unsolved_order() {
        let decoder = InactivationDecoder::new(8, 16, 5121);
        let params = decoder.params().clone();
        let mut state = make_reordered_underdetermined_dense_core_state(&params, 16, 3, 7, 9);

        let err = decoder.inactivate_and_solve(&mut state).unwrap_err();
        assert_eq!(
            err,
            DecodeError::SingularMatrix { row: 9 },
            "early underdetermined failure should report a witness the proof trace can explain"
        );
    }

    #[test]
    fn singular_matrix_with_proof_keeps_deterministic_attempt_history() {
        let decoder = InactivationDecoder::new(8, 16, 321);
        let params = decoder.params().clone();
        let mut state = make_rank_deficient_state(&params, 16, 3, 7);
        let mut trace = EliminationTrace::default();

        let err = decoder
            .inactivate_and_solve_with_proof(&mut state, &mut trace)
            .unwrap_err();
        assert_eq!(err, DecodeError::SingularMatrix { row: 7 });
        assert_eq!(
            trace
                .pivot_events
                .iter()
                .map(|ev| ev.col)
                .collect::<Vec<_>>(),
            vec![3],
            "pivot history should be deterministic across rank-deficient failure"
        );
    }

    #[test]
    fn underdetermined_dense_core_with_proof_reports_singular_error() {
        let decoder = InactivationDecoder::new(8, 16, 513);
        let params = decoder.params().clone();
        let mut state = make_underdetermined_dense_core_state(&params, 16, 3, 7);
        let mut trace = EliminationTrace::default();

        let err = decoder
            .inactivate_and_solve_with_proof(&mut state, &mut trace)
            .unwrap_err();
        assert_eq!(
            err,
            DecodeError::SingularMatrix { row: 7 },
            "proof path should keep the same rank-deficiency classification"
        );
        assert!(
            trace.pivot_events.is_empty(),
            "no pivots should be recorded when the dense core is underdetermined up front"
        );
        assert_eq!(
            trace.inactive_cols,
            vec![3, 7],
            "proof trace should preserve deterministic inactivation order"
        );
        assert_eq!(trace.inactivated, 2);
    }

    #[test]
    fn underdetermined_dense_core_with_proof_keeps_witness_in_inactive_col_order() {
        let decoder = InactivationDecoder::new(8, 16, 5131);
        let params = decoder.params().clone();
        let mut state = make_reordered_underdetermined_dense_core_state(&params, 16, 3, 7, 9);
        let mut trace = EliminationTrace::default();

        let err = decoder
            .inactivate_and_solve_with_proof(&mut state, &mut trace)
            .unwrap_err();
        assert_eq!(err, DecodeError::SingularMatrix { row: 9 });
        assert_eq!(
            trace.inactive_cols,
            vec![3, 7, 9],
            "proof trace should expose the same column ordering used for the underdetermined witness"
        );
        assert!(trace.pivot_events.is_empty());
    }

    #[test]
    fn underdetermined_dense_core_with_proof_resets_stale_trace_state() {
        let decoder = InactivationDecoder::new(8, 16, 514);
        let params = decoder.params().clone();
        let mut state = make_underdetermined_dense_core_state(&params, 16, 3, 7);
        let mut trace = EliminationTrace::default();
        trace.set_strategy(InactivationStrategy::BlockSchurLowRank);
        trace.record_inactivation(99);
        trace.record_pivot(88, 0);
        trace.record_row_op();

        let err = decoder
            .inactivate_and_solve_with_proof(&mut state, &mut trace)
            .unwrap_err();
        assert_eq!(err, DecodeError::SingularMatrix { row: 7 });
        assert_eq!(
            trace.strategy,
            InactivationStrategy::AllAtOnce,
            "proof helper should not leak prior strategy state into a new decode"
        );
        assert_eq!(
            trace.inactive_cols,
            vec![3, 7],
            "only the current decode's inactivations should remain in the trace"
        );
        assert_eq!(trace.inactivated, 2);
        assert!(
            trace.pivot_events.is_empty(),
            "stale pivot events must be cleared before recording a new decode"
        );
        assert_eq!(trace.row_ops, 0);
        assert!(
            trace.strategy_transitions.is_empty(),
            "stale strategy transitions must not leak across proof invocations"
        );
        assert!(!trace.inactive_cols_truncated);
        assert!(!trace.pivot_events_truncated);
        assert!(!trace.strategy_transitions_truncated);
    }

    #[test]
    fn proof_and_non_proof_dense_core_fallback_stats_stay_aligned() {
        let decoder = InactivationDecoder::new(8, 16, 514);
        let params = decoder.params().clone();

        let mut plain_state = make_underdetermined_dense_core_state(&params, 16, 3, 7);
        let plain_err = decoder.inactivate_and_solve(&mut plain_state).unwrap_err();

        let mut proof_state = make_underdetermined_dense_core_state(&params, 16, 3, 7);
        let mut trace = EliminationTrace::default();
        let proof_err = decoder
            .inactivate_and_solve_with_proof(&mut proof_state, &mut trace)
            .unwrap_err();

        assert_eq!(plain_err, proof_err);
        assert_eq!(
            plain_state.stats.peeling_fallback_reason,
            Some("peeling_exhausted_to_dense_core")
        );
        assert_eq!(
            proof_state.stats.peeling_fallback_reason, plain_state.stats.peeling_fallback_reason,
            "proof capture must not change dense-core fallback telemetry"
        );
    }

    #[test]
    fn underdetermined_dense_failure_restores_decoder_state_before_rhs_take() {
        let decoder = InactivationDecoder::new(8, 16, 3200);
        let params = decoder.params().clone();
        let mut state = make_underdetermined_dense_core_state(&params, 16, 3, 7);
        let initial_rhs = state.rhs.clone();
        let initial_active = state.active_cols.clone();

        let err = decoder.inactivate_and_solve(&mut state).unwrap_err();
        assert_eq!(err, DecodeError::SingularMatrix { row: 7 });
        assert_eq!(state.rhs, initial_rhs);
        assert_eq!(state.active_cols, initial_active);
        assert!(state.inactive_cols.is_empty());
    }

    #[test]
    fn underdetermined_dense_failure_with_proof_restores_decoder_state_before_rhs_take() {
        let decoder = InactivationDecoder::new(8, 16, 3200);
        let params = decoder.params().clone();
        let mut state = make_underdetermined_dense_core_state(&params, 16, 3, 7);
        let initial_rhs = state.rhs.clone();
        let initial_active = state.active_cols.clone();
        let mut trace = EliminationTrace::default();

        let err = decoder
            .inactivate_and_solve_with_proof(&mut state, &mut trace)
            .unwrap_err();
        assert_eq!(err, DecodeError::SingularMatrix { row: 7 });
        assert_eq!(state.rhs, initial_rhs);
        assert_eq!(state.active_cols, initial_active);
        assert!(state.inactive_cols.is_empty());
        assert_eq!(trace.inactive_cols, vec![3, 7]);
    }

    #[test]
    fn dense_failure_restores_decoder_state_after_early_termination() {
        let decoder = InactivationDecoder::new(8, 16, 3201);
        let params = decoder.params().clone();
        let mut state = make_rank_deficient_state(&params, 16, 3, 7);
        let initial_rhs = state.rhs.clone();
        let initial_active = state.active_cols.clone();

        let err = decoder.inactivate_and_solve(&mut state).unwrap_err();
        assert_eq!(err, DecodeError::SingularMatrix { row: 7 });
        assert_eq!(
            state.rhs, initial_rhs,
            "dense-failure cleanup must restore RHS rows taken into the dense core"
        );
        assert_eq!(
            state.active_cols, initial_active,
            "dense-failure cleanup must reactivate unsolved columns for postmortem inspection"
        );
        assert!(
            state.inactive_cols.is_empty(),
            "dense-failure cleanup must not leak inactive-column bookkeeping"
        );
    }

    #[test]
    fn dense_failure_with_proof_restores_decoder_state_after_early_termination() {
        let decoder = InactivationDecoder::new(8, 16, 3202);
        let params = decoder.params().clone();
        let mut state = make_rank_deficient_state(&params, 16, 3, 7);
        let initial_rhs = state.rhs.clone();
        let initial_active = state.active_cols.clone();
        let mut trace = EliminationTrace::default();

        let err = decoder
            .inactivate_and_solve_with_proof(&mut state, &mut trace)
            .unwrap_err();
        assert_eq!(err, DecodeError::SingularMatrix { row: 7 });
        assert_eq!(
            state.rhs, initial_rhs,
            "proof dense-failure cleanup must restore RHS rows taken into the dense core"
        );
        assert_eq!(
            state.active_cols, initial_active,
            "proof dense-failure cleanup must reactivate unsolved columns for postmortem inspection"
        );
        assert!(
            state.inactive_cols.is_empty(),
            "proof dense-failure cleanup must not leak inactive-column bookkeeping"
        );
    }

    #[test]
    fn dense_core_rhs_width_drift_fails_closed_before_plain_snapshot() {
        let decoder = InactivationDecoder::new(8, 16, 3203);
        let params = decoder.params().clone();
        let mut state = make_rank_deficient_state(&params, 16, 3, 7);
        let initial_rhs = state.rhs.clone();
        let initial_active = state.active_cols.clone();
        state.rhs[0].truncate(15);

        let err = decoder.inactivate_and_solve(&mut state).unwrap_err();
        assert_eq!(
            err,
            DecodeError::SymbolSizeMismatch {
                expected: 16,
                actual: 15,
            },
            "dense-core RHS width drift must fail closed instead of panicking during snapshot"
        );
        assert_eq!(state.rhs[0].len(), 15);
        assert_eq!(state.rhs[1], initial_rhs[1]);
        assert_eq!(state.active_cols, initial_active);
        assert!(state.inactive_cols.is_empty());
    }

    #[test]
    fn dense_core_rhs_width_drift_fails_closed_before_proof_snapshot() {
        let decoder = InactivationDecoder::new(8, 16, 3204);
        let params = decoder.params().clone();
        let mut state = make_rank_deficient_state(&params, 16, 3, 7);
        let initial_rhs = state.rhs.clone();
        let initial_active = state.active_cols.clone();
        let mut trace = EliminationTrace::default();
        state.rhs[0].truncate(15);

        let err = decoder
            .inactivate_and_solve_with_proof(&mut state, &mut trace)
            .unwrap_err();
        assert_eq!(
            err,
            DecodeError::SymbolSizeMismatch {
                expected: 16,
                actual: 15,
            },
            "proof dense-core RHS width drift must fail closed instead of panicking during snapshot"
        );
        assert_eq!(state.rhs[0].len(), 15);
        assert_eq!(state.rhs[1], initial_rhs[1]);
        assert_eq!(state.active_cols, initial_active);
        assert!(state.inactive_cols.is_empty());
        assert_eq!(trace.inactive_cols, vec![3, 7]);
        assert_eq!(trace.inactivated, 2);
        assert!(trace.pivot_events.is_empty());
    }

    #[test]
    fn failure_reason_captures_attempted_pivot_columns() {
        let mut elimination = EliminationTrace::default();
        elimination.record_pivot(3, 0);
        elimination.record_pivot(9, 1);

        let reason =
            failure_reason_with_trace(&DecodeError::SingularMatrix { row: 11 }, &elimination);
        assert_eq!(
            reason,
            FailureReason::SingularMatrix {
                row: 11,
                attempted_cols: vec![3, 9],
            }
        );
    }

    #[test]
    fn pivot_tie_break_prefers_lowest_available_row_deterministically() {
        let decoder = InactivationDecoder::new(8, 1, 999);
        let params = decoder.params().clone();

        let mut state_one = make_pivot_tie_break_state(&params, 1, 3, 7);
        let mut trace_one = EliminationTrace::default();
        decoder
            .inactivate_and_solve_with_proof(&mut state_one, &mut trace_one)
            .expect("tie-break test state should be solvable");

        assert_eq!(
            trace_one
                .pivot_events
                .iter()
                .map(|ev| (ev.col, ev.row))
                .collect::<Vec<_>>(),
            vec![(3, 0), (7, 1)],
            "pivot order should be deterministic and prefer lowest available row"
        );
        assert_eq!(state_one.solved[3], Some(vec![0x10]));
        assert_eq!(state_one.solved[7], Some(vec![0x20]));

        let mut state_two = make_pivot_tie_break_state(&params, 1, 3, 7);
        let mut trace_two = EliminationTrace::default();
        decoder
            .inactivate_and_solve_with_proof(&mut state_two, &mut trace_two)
            .expect("second solve should match first solve");

        assert_eq!(
            trace_one.pivot_events, trace_two.pivot_events,
            "pivot trace should be stable across repeated runs"
        );
    }

    #[test]
    fn inconsistent_overdetermined_system_reports_singular_error() {
        let decoder = InactivationDecoder::new(8, 16, 111);
        let params = decoder.params().clone();
        let mut state = make_inconsistent_overdetermined_state(&params, 16, 3, 7);

        let err = decoder.inactivate_and_solve(&mut state).unwrap_err();
        assert_eq!(
            err,
            DecodeError::SingularMatrix { row: 2 },
            "contradictory overdetermined system should fail deterministically at witness row"
        );
    }

    #[test]
    fn inconsistent_overdetermined_with_proof_preserves_attempt_history() {
        let decoder = InactivationDecoder::new(8, 16, 222);
        let params = decoder.params().clone();
        let mut state = make_inconsistent_overdetermined_state(&params, 16, 3, 7);
        let mut trace = EliminationTrace::default();

        let err = decoder
            .inactivate_and_solve_with_proof(&mut state, &mut trace)
            .unwrap_err();
        assert_eq!(err, DecodeError::SingularMatrix { row: 2 });
        assert_eq!(
            trace
                .pivot_events
                .iter()
                .map(|ev| ev.col)
                .collect::<Vec<_>>(),
            vec![3, 7],
            "inconsistent-system witness should preserve full pivot-attempt history"
        );
    }

    #[test]
    fn dense_core_extraction_drops_redundant_zero_rows() {
        let decoder = InactivationDecoder::new(8, 16, 6060);
        let params = decoder.params().clone();
        let mut state = make_dense_core_prunable_state(&params, 16, 3, 7, 0x00);

        decoder
            .inactivate_and_solve(&mut state)
            .expect("state with redundant zero row should be solvable");
        assert_eq!(
            state.stats.dense_core_rows, 2,
            "dense core should only include rows with unsolved-column signal"
        );
        assert_eq!(
            state.stats.dense_core_cols, 2,
            "dense core should preserve unsolved column width"
        );
        assert_eq!(
            state.stats.dense_core_dropped_rows, 1,
            "one redundant zero-information row should be dropped"
        );
    }

    #[test]
    fn dense_core_inconsistent_constant_row_reports_equation_witness() {
        let decoder = InactivationDecoder::new(8, 16, 6161);
        let params = decoder.params().clone();
        let mut state = make_dense_core_prunable_state(&params, 16, 3, 7, 0x01);

        let err = decoder.inactivate_and_solve(&mut state).unwrap_err();
        assert_eq!(
            err,
            DecodeError::SingularMatrix { row: 2 },
            "inconsistent constant row should report deterministic original equation index"
        );
    }

    #[test]
    fn baseline_failure_triggers_deterministic_hard_regime_fallback() {
        let decoder = InactivationDecoder::new(8, 1, 4242);
        let params = decoder.params().clone();
        let mut state = make_rank_deficient_state(&params, 1, 3, 7);

        let err = decoder.inactivate_and_solve(&mut state).unwrap_err();
        assert_eq!(err, DecodeError::SingularMatrix { row: 7 });
        assert!(
            state.stats.hard_regime_activated,
            "fallback should activate hard regime deterministically"
        );
        assert_eq!(
            state.stats.hard_regime_fallbacks, 1,
            "exactly one fallback transition is expected"
        );
        assert!(
            state.stats.markowitz_pivots <= state.stats.pivots_selected,
            "hard-regime pivot accounting should remain internally consistent"
        );
    }

    #[test]
    fn proof_trace_records_fallback_transition_reason() {
        let decoder = InactivationDecoder::new(8, 1, 4343);
        let params = decoder.params().clone();
        let mut state = make_rank_deficient_state(&params, 1, 3, 7);
        let mut trace = EliminationTrace::default();

        let err = decoder
            .inactivate_and_solve_with_proof(&mut state, &mut trace)
            .unwrap_err();
        assert_eq!(err, DecodeError::SingularMatrix { row: 7 });
        assert_eq!(
            trace.strategy,
            InactivationStrategy::HighSupportFirst,
            "proof trace should expose fallback strategy"
        );
        assert_eq!(
            trace.strategy_transitions.len(),
            1,
            "fallback should record one strategy transition"
        );
        assert_eq!(
            trace.strategy_transitions[0].reason, "fallback_after_baseline_failure",
            "transition reason should be deterministic and triage-friendly"
        );
        assert_eq!(
            trace
                .pivot_events
                .iter()
                .map(|ev| ev.col)
                .collect::<Vec<_>>(),
            vec![3],
            "fallback proof should preserve the deterministic pivot-attempt witness"
        );
    }

    #[test]
    fn hard_regime_activation_is_deterministic_and_observable() {
        set_test_bypass_governance(true);
        let decoder = InactivationDecoder::new(8, 1, 3030);
        let params = decoder.params().clone();

        let mut state_one = make_hard_regime_dense_state(&params, 1, 4, 8);
        let mut trace_one = EliminationTrace::default();
        decoder
            .inactivate_and_solve_with_proof(&mut state_one, &mut trace_one)
            .expect("hard regime state should be solvable");

        assert!(
            state_one.stats.hard_regime_activated,
            "hard-regime transition should be observable in decode stats"
        );
        assert_eq!(
            state_one.stats.markowitz_pivots, 8,
            "all hard-regime pivots should use deterministic Markowitz selector"
        );
        assert_eq!(
            trace_one.strategy,
            InactivationStrategy::HighSupportFirst,
            "proof trace must expose hard-regime strategy"
        );
        assert_eq!(
            trace_one.strategy_transitions.len(),
            1,
            "hard regime should record a single strategy transition"
        );
        assert_eq!(
            trace_one.strategy_transitions[0].reason, "dense_or_near_square",
            "transition reason should be deterministic and triage-friendly"
        );

        let mut state_two = make_hard_regime_dense_state(&params, 1, 4, 8);
        let mut trace_two = EliminationTrace::default();
        decoder
            .inactivate_and_solve_with_proof(&mut state_two, &mut trace_two)
            .expect("repeated hard regime solve should succeed");

        assert_eq!(
            state_one.stats.markowitz_pivots, state_two.stats.markowitz_pivots,
            "hard-regime pivot counts should be stable across runs"
        );
        assert_eq!(
            trace_one.pivot_events, trace_two.pivot_events,
            "hard-regime pivot event ordering must be deterministic"
        );
        assert_eq!(
            trace_one.strategy_transitions, trace_two.strategy_transitions,
            "hard-regime strategy transition history must be deterministic"
        );
    }

    #[test]
    fn hard_regime_plan_selects_block_schur_for_dense_large_core() {
        let n_rows = 12;
        let n_cols = 12;
        let dense = vec![Gf256::ONE; n_rows * n_cols];
        let plan = select_hard_regime_plan(n_rows, n_cols, &dense);
        assert_eq!(
            plan,
            HardRegimePlan::BlockSchurLowRank { split_col: 8 },
            "dense 12x12 system should select deterministic block-schur plan"
        );
    }

    #[test]
    fn block_schur_failure_falls_back_to_markowitz_with_reason() {
        set_test_bypass_governance(true);
        let decoder = InactivationDecoder::new(32, 1, 7070);
        let params = decoder.params().clone();
        let mut state = make_block_schur_rank_deficient_state(&params, 1, 4, 12);
        let mut trace = EliminationTrace::default();

        let err = decoder
            .inactivate_and_solve_with_proof(&mut state, &mut trace)
            .expect_err("rank-deficient block-schur candidate should fail deterministically");
        assert!(matches!(err, DecodeError::SingularMatrix { .. }));
        assert!(
            state.stats.hard_regime_activated,
            "dense rank-deficient system should activate hard regime"
        );
        assert_eq!(
            state.stats.hard_regime_branch,
            Some("block_schur_low_rank"),
            "stats should expose deterministic accelerated branch selection"
        );
        assert_eq!(
            state.stats.hard_regime_conservative_fallback_reason,
            Some("block_schur_failed_to_converge"),
            "stats should expose deterministic conservative fallback reason"
        );
        assert_eq!(
            state.stats.hard_regime_fallbacks, 1,
            "block-schur attempt should perform exactly one conservative fallback"
        );
        assert!(
            trace.strategy_transitions.iter().any(|transition| {
                transition.from == InactivationStrategy::BlockSchurLowRank
                    && transition.to == InactivationStrategy::HighSupportFirst
                    && transition.reason == "block_schur_failed_to_converge"
            }),
            "proof trace should record deterministic branch fallback transition"
        );
    }

    #[test]
    fn block_schur_fallback_preserves_non_pivot_truncation_flags() {
        set_test_bypass_governance(true);
        let decoder = InactivationDecoder::new(300, 1, 7171);
        let params = decoder.params().clone();
        let mut state = make_block_schur_rank_deficient_state(
            &params,
            1,
            4,
            crate::raptorq::proof::MAX_PIVOT_EVENTS + 1,
        );
        let mut trace = EliminationTrace::default();

        let err = decoder
            .inactivate_and_solve_with_proof(&mut state, &mut trace)
            .expect_err("wide rank-deficient block-schur candidate should fail deterministically");
        assert!(matches!(err, DecodeError::SingularMatrix { .. }));
        assert!(
            trace.inactive_cols_truncated,
            "large inactivation witness must stay marked truncated after fallback cleanup"
        );
        assert!(
            !trace.pivot_events_truncated,
            "clearing pivot history for retry should only reset the pivot-events truncation flag"
        );
        assert!(
            !trace.strategy_transitions_truncated,
            "single fallback transition should remain non-truncated"
        );
    }

    #[test]
    fn normal_regime_keeps_basic_pivot_strategy() {
        let decoder = InactivationDecoder::new(8, 1, 99);
        let params = decoder.params().clone();
        let mut state = make_pivot_tie_break_state(&params, 1, 3, 7);

        decoder
            .inactivate_and_solve(&mut state)
            .expect("normal regime test state should solve");

        assert!(
            !state.stats.hard_regime_activated,
            "small systems should stay on the baseline inactivation strategy"
        );
        assert_eq!(
            state.stats.markowitz_pivots, 0,
            "baseline strategy should not report Markowitz pivots"
        );
    }

    #[test]
    fn normal_regime_proof_trace_keeps_all_at_once_strategy() {
        let decoder = InactivationDecoder::new(8, 1, 100);
        let params = decoder.params().clone();
        let mut state = make_pivot_tie_break_state(&params, 1, 3, 7);
        let mut trace = EliminationTrace::default();

        decoder
            .inactivate_and_solve_with_proof(&mut state, &mut trace)
            .expect("normal regime proof solve should succeed");

        assert_eq!(
            trace.strategy,
            InactivationStrategy::AllAtOnce,
            "normal regime should stay on baseline strategy"
        );
        assert!(
            trace.strategy_transitions.is_empty(),
            "normal regime must not emit strategy transitions"
        );
    }

    #[test]
    fn policy_metadata_is_recorded_for_conservative_mode() {
        let decoder = InactivationDecoder::new(8, 1, 101);
        let params = decoder.params().clone();
        let mut state = make_pivot_tie_break_state(&params, 1, 3, 7);

        decoder
            .inactivate_and_solve(&mut state)
            .expect("conservative-mode state should solve");

        assert_eq!(state.stats.policy_mode, Some("conservative_baseline"));
        assert_eq!(
            state.stats.policy_reason,
            Some("expected_loss_conservative_gate")
        );
        assert_eq!(state.stats.policy_replay_ref, Some(POLICY_REPLAY_REF));
        assert!(state.stats.policy_baseline_loss > 0);
        assert!(state.stats.policy_high_support_loss > 0);
        let governance = state
            .stats
            .governance
            .expect("governance telemetry must be recorded");
        assert_eq!(
            governance.replay_ref,
            decision_contract::G7_DECISION_REPLAY_REF
        );
        assert_eq!(
            governance
                .state_posterior_permille
                .iter()
                .map(|&value| u32::from(value))
                .sum::<u32>(),
            1000
        );
    }

    #[test]
    fn policy_metadata_is_recorded_for_aggressive_mode() {
        set_test_bypass_governance(true);
        let decoder = InactivationDecoder::new(32, 1, 8080);
        let params = decoder.params().clone();
        let mut state = make_block_schur_rank_deficient_state(&params, 1, 2, 15);

        let _err = decoder.inactivate_and_solve(&mut state).unwrap_err();

        assert!(
            matches!(
                state.stats.policy_mode,
                Some("high_support_first" | "block_schur_low_rank")
            ),
            "dense state should log an aggressive policy mode"
        );
        assert_eq!(state.stats.policy_reason, Some("expected_loss_minimum"));
        assert_eq!(state.stats.policy_replay_ref, Some(POLICY_REPLAY_REF));
        assert!(state.stats.policy_density_permille >= 350);
        let governance = state
            .stats
            .governance
            .expect("governance telemetry must be recorded");
        assert!(matches!(
            governance.chosen_action,
            "continue" | "canary_hold" | "rollback" | "fallback"
        ));
        assert!(governance.confidence_score <= 1000);
    }

    #[test]
    fn decoder_policy_budget_exhaustion_forces_conservative_baseline() {
        let n_rows = 65;
        let n_cols = 65;
        let dense = vec![Gf256::ONE; n_rows * n_cols];
        let decision = choose_runtime_decoder_policy(n_rows, n_cols, dense.len(), 0, 700);
        assert_eq!(decision.mode, DecoderPolicyMode::ConservativeBaseline);
        assert_eq!(decision.reason, "policy_budget_exhausted_conservative");
        assert!(decision.features.budget_exhausted);
        assert!(
            decision
                .governance
                .is_some_and(|telemetry| telemetry.deterministic_fallback_triggered)
        );
    }

    #[test]
    fn decoder_policy_prefers_aggressive_strategy_for_dense_high_pressure() {
        set_test_bypass_governance(true);
        let n_rows = 16;
        let n_cols = 16;
        let dense = vec![Gf256::ONE; n_rows * n_cols];
        let decision = choose_runtime_decoder_policy(n_rows, n_cols, dense.len(), 0, 850);
        assert!(
            matches!(
                decision.mode,
                DecoderPolicyMode::HighSupportFirst | DecoderPolicyMode::BlockSchurLowRank
            ),
            "dense/high-pressure matrix should avoid conservative baseline"
        );
    }

    #[test]
    fn decoder_policy_prefers_conservative_for_sparse_low_pressure() {
        let n_rows = 24;
        let n_cols = 16;
        let mut sparse = vec![Gf256::ZERO; n_rows * n_cols];
        for idx in 0..n_cols {
            sparse[idx * n_cols + idx] = Gf256::ONE;
        }

        let one = choose_runtime_decoder_policy(n_rows, n_cols, n_cols, 0, 40);
        let two = choose_runtime_decoder_policy(n_rows, n_cols, n_cols, 0, 40);
        assert_eq!(one, two, "policy decision should be deterministic");
        assert_eq!(one.mode, DecoderPolicyMode::ConservativeBaseline);
        assert_eq!(one.reason, "expected_loss_conservative_gate");
        assert!(
            one.governance.is_some(),
            "G7 governance telemetry must be present"
        );
    }

    // ── all_source_equations / source_equation coverage (br-3narc.2.7) ──

    #[test]
    fn all_source_equations_returns_identity_map() {
        let k = 8;
        let decoder = InactivationDecoder::new(k, 32, 42);
        let equations = decoder.all_source_equations();

        assert_eq!(equations.len(), k, "should return exactly K equations");
        for (i, (cols, coefs)) in equations.iter().enumerate() {
            assert_eq!(cols, &[i], "source equation {i} should map to column {i}");
            assert_eq!(
                coefs,
                &[Gf256::ONE],
                "source equation {i} should have unit coefficient"
            );
        }
    }

    #[test]
    fn source_equation_matches_all_source_equations() {
        let k = 12;
        let decoder = InactivationDecoder::new(k, 16, 99);
        let all = decoder.all_source_equations();

        for esi in 0..k as u32 {
            let single = decoder.source_equation(esi);
            assert_eq!(
                single, all[esi as usize],
                "source_equation({esi}) must match all_source_equations()[{esi}]"
            );
        }
    }

    #[test]
    #[should_panic(expected = "source ESI must be < K")]
    fn source_equation_panics_on_esi_ge_k() {
        let k = 4;
        let decoder = InactivationDecoder::new(k, 16, 42);
        let _ = decoder.source_equation(k as u32); // ESI == K should panic
    }

    // ── Duplicate ESI handling (br-3narc.2.7) ──

    #[test]
    fn decode_with_duplicate_source_esi_produces_defined_outcome() {
        // Feeding the same ESI twice gives the decoder redundant equations.
        // It should either succeed (if the extra equation is linearly dependent)
        // or fail with SingularMatrix (if it introduces inconsistency).
        // It must NOT panic.
        let k = 8;
        let symbol_size = 32;
        let seed = 42u64;
        let source: Vec<Vec<u8>> = (0..k)
            .map(|i| {
                (0..symbol_size)
                    .map(|j| ((i * 37 + j * 13 + 7) % 256) as u8)
                    .collect()
            })
            .collect();

        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        // Add all source symbols
        for (i, data) in source.iter().enumerate() {
            received.push(ReceivedSymbol::source(i as u32, data.clone()));
        }
        // Duplicate: add source symbol 0 again
        received.push(ReceivedSymbol::source(0, source[0].clone()));

        // Add repair to reach L
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        // Must not panic; outcome is either Ok or a well-formed error
        let result = decoder.decode(&received);
        match result {
            Ok(decoded_symbols) => {
                assert_eq!(
                    decoded_symbols.source, source,
                    "decode with duplicate ESI should recover correct source"
                );
            }
            Err(e) => {
                // Redundant duplicate equations can still expose a rank-deficient witness,
                // but they should not be flattened into a raw underprovisioning error.
                assert!(
                    matches!(e, DecodeError::SingularMatrix { .. }),
                    "unexpected error type with duplicate ESI: {e:?}"
                );
            }
        }
    }

    // ── Zero-data source symbols (br-3narc.2.7) ──

    #[test]
    fn decode_all_zeros_source_data() {
        let k = 8;
        let symbol_size = 32;
        let seed = 42u64;

        let source: Vec<Vec<u8>> = (0..k).map(|_| vec![0u8; symbol_size]).collect();
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        for (i, data) in source.iter().enumerate() {
            received.push(ReceivedSymbol::source(i as u32, data.clone()));
        }
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let result = decoder
            .decode(&received)
            .expect("all-zeros source should decode");
        assert_eq!(result.source, source, "decoded all-zeros must match");
    }

    // ── Intermediate symbol reconstruction invariant (br-3narc.2.7) ──

    #[test]
    fn intermediate_symbols_match_encoder_after_decode() {
        let k = 8;
        let symbol_size = 32;
        let seed = 42u64;

        let source: Vec<Vec<u8>> = (0..k)
            .map(|i| {
                (0..symbol_size)
                    .map(|j| ((i * 37 + j * 13 + 7) % 256) as u8)
                    .collect()
            })
            .collect();

        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        for (i, data) in source.iter().enumerate() {
            received.push(ReceivedSymbol::source(i as u32, data.clone()));
        }
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let result = decoder.decode(&received).expect("decode should succeed");

        // Every intermediate symbol from decode must match the encoder's
        assert_eq!(result.intermediate.len(), l);
        for i in 0..l {
            assert_eq!(
                result.intermediate[i],
                encoder.intermediate_symbol(i),
                "intermediate symbol {i}/{l} must match encoder"
            );
        }
    }

    // ── Peeling + Gaussian coverage invariant (br-3narc.2.7) ──

    #[test]
    fn stats_peeled_plus_inactivated_covers_all_columns() {
        let k = 8;
        let symbol_size = 32;
        let seed = 42u64;

        let source: Vec<Vec<u8>> = (0..k)
            .map(|i| {
                (0..symbol_size)
                    .map(|j| ((i * 37 + j * 13 + 7) % 256) as u8)
                    .collect()
            })
            .collect();

        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        for (i, data) in source.iter().enumerate() {
            received.push(ReceivedSymbol::source(i as u32, data.clone()));
        }
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let result = decoder.decode(&received).expect("decode should succeed");
        assert_eq!(
            result.stats.peeled + result.stats.inactivated,
            l,
            "peeled + inactivated must equal L ({l})"
        );
    }

    // ========================================================================
    // F8: Wavefront decode pipeline tests
    // ========================================================================

    #[test]
    fn wavefront_decode_matches_sequential() {
        // Verify that wavefront decode produces identical source symbols
        // to sequential decode for a variety of batch sizes.
        let k = 16;
        let symbol_size = 64;
        let seed = 0xF8_0001u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);

        let mut received = decoder.constraint_symbols();
        for esi in 0..(k as u32) {
            received.push(ReceivedSymbol::source(esi, source[esi as usize].clone()));
        }
        // Add a few repair symbols for robustness.
        for esi in (k as u32)..(k as u32 + 4) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let sequential = decoder.decode(&received).expect("sequential decode");

        for batch_size in [1, 2, 4, 8, 16, 0] {
            let wavefront = decoder
                .decode_wavefront(&received, batch_size)
                .unwrap_or_else(|_| panic!("wavefront decode batch_size={batch_size}"));

            for (i, (seq_sym, wf_sym)) in sequential
                .source
                .iter()
                .zip(wavefront.source.iter())
                .enumerate()
            {
                assert_eq!(
                    seq_sym, wf_sym,
                    "source symbol {i} mismatch at batch_size={batch_size}"
                );
            }

            assert!(wavefront.stats.wavefront_active);
            assert_eq!(
                wavefront.stats.wavefront_batch_size,
                if batch_size == 0 {
                    received.len()
                } else {
                    batch_size
                }
            );
            assert!(wavefront.stats.wavefront_batches > 0);
        }
    }

    #[test]
    fn wavefront_decode_with_loss_matches_sequential() {
        // Verify wavefront correctness under symbol loss (repair-only decode).
        let k = 8;
        let symbol_size = 32;
        let seed = 0xF8_0002u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        let mut received = decoder.constraint_symbols();
        // Only repair symbols — no source symbols.
        for esi in (k as u32)..(k as u32 + l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let sequential = decoder.decode(&received).expect("sequential decode");

        for batch_size in [1, 4, 8] {
            let wavefront = decoder
                .decode_wavefront(&received, batch_size)
                .unwrap_or_else(|_| panic!("wavefront batch_size={batch_size}"));

            for (i, (seq_sym, wf_sym)) in sequential
                .source
                .iter()
                .zip(wavefront.source.iter())
                .enumerate()
            {
                assert_eq!(
                    seq_sym, wf_sym,
                    "source symbol {i} mismatch at batch_size={batch_size} (repair-only)"
                );
            }
        }
    }

    #[test]
    fn wavefront_overlap_peeling_is_tracked() {
        // With batch_size=1, each symbol is assembled and peeled individually.
        // Some peeling should happen during assembly batches (overlap).
        let k = 16;
        let symbol_size = 64;
        let seed = 0xF8_0003u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);

        let mut received = decoder.constraint_symbols();
        for esi in 0..(k as u32) {
            received.push(ReceivedSymbol::source(esi, source[esi as usize].clone()));
        }
        for esi in (k as u32)..(k as u32 + 4) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let wavefront = decoder
            .decode_wavefront(&received, 1)
            .expect("wavefront batch_size=1");

        assert!(wavefront.stats.wavefront_active);
        assert_eq!(wavefront.stats.wavefront_batch_size, 1);
        assert_eq!(wavefront.stats.wavefront_batches, received.len());
        // With source symbols fed one at a time, some should peel during
        // the assembly batches (overlap region).
        // We don't assert a specific count since it depends on equation structure.
        assert!(
            wavefront.stats.peeled > 0,
            "some symbols should peel in wavefront mode"
        );
    }

    #[test]
    fn wavefront_sequential_fallback_batch_zero() {
        // batch_size=0 should behave identically to sequential decode.
        let k = 8;
        let symbol_size = 32;
        let seed = 0xF8_0004u64;

        let source = make_source_data(k, symbol_size);
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);

        let mut received = decoder.constraint_symbols();
        for esi in 0..(k as u32) {
            received.push(ReceivedSymbol::source(esi, source[esi as usize].clone()));
        }
        for esi in (k as u32)..(k as u32 + 2) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let sequential = decoder.decode(&received).expect("sequential");
        let wavefront = decoder
            .decode_wavefront(&received, 0)
            .expect("wavefront batch_size=0");

        assert_eq!(sequential.source, wavefront.source);
        assert!(wavefront.stats.wavefront_active);
        assert_eq!(wavefront.stats.wavefront_batches, 1);
        assert_eq!(wavefront.stats.wavefront_batch_size, received.len());
    }
}